diff --git a/CHANGELOG.md b/CHANGELOG.md index f28a149..0d885c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and ### Added +- MCP `2026-07-28` stateless request metadata, mandatory `server/discover`, modern result decoration, and dual-era protocol tests. +- JSON Schema 2020-12 tool validation with deterministic tool discovery and modern-only cache metadata. +- Standard `resources/templates/list` discovery with modern concrete-resource separation and legacy catalog compatibility. +- Wire-level request ID presence and type validation across stdio and HTTP transports. - Distributed worker-to-orchestrator callbacks for step events, lease renewals, and terminal results. - Redis-backed distributed ownership leases with persisted `traces.current_attempt` and `traces.terminal_reason` state. - Worker-side session attachment and stable distributed callback propagation for existing Appium sessions. @@ -22,6 +26,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and ### Changed +- Streamable HTTP now validates modern `MCP-Protocol-Version`, `Mcp-Method`, and `Mcp-Name` headers while retaining `2025-11-25` and `2025-06-18` initialize compatibility. +- Tool call results now include native `structuredContent`, and modern HTTP no longer exposes GET streams or accepts client response envelopes. +- Modern Streamable HTTP rejects client notifications and uses request connection closure for cancellation. +- Resource reads now use current MCP `-32602` not-found and `-32603` internal error semantics instead of generic legacy server errors. - Distributed dispatch now reserves an execution attempt before RPC dispatch and promotes that reserved attempt to `running` only after worker acceptance. - Watchdog handling now distinguishes plan timeout from ownership-lease expiry and prevents stale callbacks from overwriting active or terminal traces. - Worker registration now uses a routable advertise address instead of hard-coded `localhost`. diff --git a/MCP_2026_07_28_ALIGNMENT.md b/MCP_2026_07_28_ALIGNMENT.md new file mode 100644 index 0000000..686325b --- /dev/null +++ b/MCP_2026_07_28_ALIGNMENT.md @@ -0,0 +1,90 @@ +# MCP 2026-07-28 升级说明 + +本仓库已按官方 Current 版本 `2026-07-28` 完成核心 server/transport 对齐,并继续兼容 initialize-based legacy 客户端。官方参考: + +- [MCP 2026-07-28 Specification](https://modelcontextprotocol.io/specification/2026-07-28) +- [2026-07-28 Changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog) +- [Versioning and Compatibility](https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning) +- [Streamable HTTP](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http) +- [Server Discovery](https://modelcontextprotocol.io/specification/2026-07-28/server/discover) +- [Base Protocol](https://modelcontextprotocol.io/specification/2026-07-28/basic/index) +- [Resources](https://modelcontextprotocol.io/specification/2026-07-28/server/resources) +- [Tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) + +## 协议变化摘要 + +| 变化 | `2025-11-25` 及更早 | `2026-07-28` | 本仓库实现 | +| --- | --- | --- | --- | +| 生命周期 | `initialize` + `notifications/initialized` | 无握手、逐请求无状态 | 双时代兼容 | +| 版本/能力 | 初始化时协商 | 每个 request 的 `params._meta` | 强制验证两个必填 namespaced 字段 | +| 服务发现 | 依赖 initialize capabilities | `server/discover` 为服务端必选 | 已实现并返回全部支持版本 | +| 成功结果 | `resultType` 可缺失 | 每个结果必须声明 `resultType` | 现代结果统一补 `complete` | +| Request ID | 旧集成可能混淆 `null` 与 omitted | 仅 string/integer,且不得为 `null` | 三个 transport 统一保留 presence 并校验类型 | +| 服务身份 | initialize 的 `serverInfo` | 推荐每个 result 的 `_meta` | 现代结果统一补 namespaced `serverInfo` | +| HTTP | POST,可选 GET/SSE 和 session | 仅 POST,无 GET stream/session id | `/mcp` GET 返回 405,POST 无 session 状态 | +| HTTP 镜像头 | 仅协议版本 | 另需 `Mcp-Method`;指定方法需 `Mcp-Name` | 校验缺失、编码和 header/body 一致性 | +| 工具/资源缓存 | 无统一字段 | list/template-list/read 支持 `ttlMs`、`cacheScope` | 目录使用 public,授权相关 resource read 使用 private | +| 资源模板 | 可被旧集成混入 `resources/list` | 参数化 URI 由 `resources/templates/list` 返回 | Modern 分离 concrete resources 与 URI templates,legacy 保持原结果 | +| Tool schema | dialect 行为不统一 | 默认且至少支持 JSON Schema 2020-12 | 显式声明并使用 2020-12 校验器 | +| Tool result | structured object 限制较多 | `structuredContent` 可为任意 JSON | 同时返回 text 与原生 structured JSON | + +## 当前支持矩阵 + +- Modern:`2026-07-28`,通过每个 request 的 `_meta` 选择,无 initialize。 +- Legacy:`2025-11-25` 和 `2025-06-18`,继续通过 initialize 选择。 +- `server/discover` 返回上述三个版本,顺序为 modern 优先。 +- Modern 方法:`server/discover`、`tools/list`、`tools/call`、`resources/list`、`resources/templates/list`、`resources/read`,以及 stdio cancellation 处理。 +- Modern `resources/list` 当前返回空 concrete resource 集合;三个参数化 Appium URI 由 `resources/templates/list` 返回。 +- Legacy 的 `ping`、`notifications/initialized` 与现有兼容方法保持可用,但在 modern `_meta` 下返回 method not found。 +- Modern Streamable HTTP 不接收 client notification;取消正在执行的 HTTP 请求应关闭该请求的响应流,`notifications/cancelled` 仅保留给 stdio。 +- `/jsonrpc` 继续作为非标准 compatibility endpoint;标准 MCP HTTP endpoint 是 `/mcp`。 + +## Modern Request 要求 + +每个 JSON-RPC request 的 `params._meta` 必须包含: + +```json +{ + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {} +} +``` + +`io.modelcontextprotocol/clientInfo` 可选,但建议每次提供。HTTP 同时要求: + +- `Content-Type: application/json` +- `Accept: application/json, text/event-stream` +- `MCP-Protocol-Version` 与 body protocol version 一致 +- `Mcp-Method` 与 JSON-RPC `method` 一致 +- `tools/call`、`resources/read`、`prompts/get` 的 `Mcp-Name` 与 `params.name` / `params.uri` 一致 +- 不安全 ASCII、非 ASCII 或首尾空白的 `Mcp-Name` 使用 `=?base64?{Base64}?=` sentinel + +关键错误映射: + +- Header 缺失、格式错误或与 body 不一致:HTTP 400 / JSON-RPC `-32020` +- Modern 必填 `_meta` 字段缺失:HTTP 400 / JSON-RPC `-32602` +- 请求版本不支持:HTTP 400 / JSON-RPC `-32022`,data 包含 `supported` 和 `requested` +- Modern RPC 未实现:HTTP 404 / JSON-RPC `-32601` +- Resource 不存在或对调用方不可见:JSON-RPC `-32602`;后端读取失败:JSON-RPC `-32603` + +## 实现位置 + +- `internal/gateway/mcp/protocol.go`:版本、逐请求 metadata、discover、现代 result/cache decoration 与标准错误。 +- `internal/gateway/jsonrpc/modern.go`:modern/legacy 分类与 modern 方法边界。 +- `internal/gateway/mcphttp/handler.go`:双时代 Streamable HTTP、标准头和状态码。 +- `internal/gateway/mcp/tools.go`:确定性排序和 JSON Schema 2020-12 预编译校验。 +- `internal/gateway/mcp/handler.go`:legacy-compatible 基础结果与 `structuredContent`。 + +## 验证 + +```bash +go test ./internal/gateway/mcp ./internal/gateway/jsonrpc ./internal/gateway/mcphttp -count=1 +go test ./... -count=1 +go vet ./... +``` + +测试覆盖 modern discovery、逐请求 metadata、unsupported-version retry data、legacy 回归、request ID 校验、HTTP header mismatch、Base64 sentinel、modern 404、HTTP notification rejection、resource/template 分离、resource error codes、结果装饰、确定性 tool ordering,以及 `unevaluatedProperties` 的 JSON Schema 2020-12 行为。 + +## 非阻塞扩展项 + +Prompts、subscriptions/listen、sampling、elicitation、MCP Apps、Tasks 等仍是未声明的可选 capability,不影响当前 tools/resources server 对 `2026-07-28` 核心协议的支持。后续增加任何 capability 时,应同时加入 discover capability 声明、逐请求 client capability 检查及对应 conformance tests。 diff --git a/MCP_ALIGNMENT_HANDOFF.md b/MCP_ALIGNMENT_HANDOFF.md new file mode 100644 index 0000000..136d9f1 --- /dev/null +++ b/MCP_ALIGNMENT_HANDOFF.md @@ -0,0 +1,68 @@ +# MCP Alignment Handoff + +Updated: 2026-08-06 + +This handoff records the current MCP alignment state in `/Users/stellajen/Documents/workspace/mcp_for_appium_v1` on branch `v1-work`. + +## Current Status + +The original P0 legacy alignment is complete, including request/notification classification, silent notification responses, cancellation, legacy `ping`, and `/mcp` Streamable HTTP support. + +The follow-up implementation now targets the official Current MCP revision `2026-07-28` while preserving dual-era compatibility: + +- Modern `2026-07-28` requests use stateless per-request `_meta` and do not initialize. +- Legacy `2025-11-25` and `2025-06-18` clients continue to use initialize semantics. +- `server/discover` advertises all three supported versions and the implemented tools/resources capabilities. +- Successful modern results receive `resultType: complete` and namespaced server identity metadata. +- Modern Streamable HTTP validates `MCP-Protocol-Version`, `Mcp-Method`, and method-specific `Mcp-Name`, including Base64 sentinel decoding. +- Modern HTTP removes GET streams and session IDs, maps header mismatch to `400/-32020`, unsupported versions to `400/-32022`, and unknown methods to `404/-32601`. +- Modern HTTP rejects client notifications because cancellation is represented by closing the request response stream; stdio cancellation remains supported. +- Modern tool and resource results receive method-specific cache metadata while legacy result shapes remain unchanged; tool ordering is deterministic. +- Modern parameterized resources are exposed through `resources/templates/list`; `resources/list` reports the currently enumerable concrete set while legacy callers retain the historical catalog shape. +- Resource reads map missing or caller-invisible URIs to `-32602` and backend failures to `-32603`, replacing the old generic `-32000` path. +- Shared JSON-RPC decoding distinguishes omitted IDs from explicit JSON null and accepts only string or integer request IDs. +- Tool schemas are explicitly advertised and validated as JSON Schema 2020-12. +- Tool calls now expose native results through `structuredContent` in addition to text content. + +The detailed protocol and compatibility summary is in `MCP_2026_07_28_ALIGNMENT.md`. + +## Primary Implementation Areas + +- `internal/gateway/mcp/protocol.go` +- `internal/gateway/mcp/handler.go` +- `internal/gateway/mcp/tools.go` +- `internal/gateway/jsonrpc/modern.go` +- `internal/gateway/jsonrpc/handler.go` +- `internal/gateway/mcphttp/handler.go` +- `README.md` + +## Test Coverage + +Targeted tests cover: + +- mandatory modern discovery over shared JSON-RPC and Streamable HTTP +- required request metadata and unsupported-version retry data +- result decoration and server identity +- legacy initialize, ping, notifications, and client response compatibility +- modern HTTP method/name/version header consistency +- Base64 sentinel decoding +- modern HTTP client response and notification rejection +- modern method-not-found HTTP 404 behavior +- modern concrete-resource and resource-template separation +- current resource-not-found and internal error codes +- explicit-null and non-integral request ID rejection +- cache metadata and deterministic tool order +- JSON Schema 2020-12 `unevaluatedProperties` behavior + +## Remaining Optional Work + +The server does not declare optional Prompts, subscriptions/listen, sampling, elicitation, MCP Apps, or Tasks capabilities. Adding one later requires capability advertisement, request-local client capability checks where applicable, transport behavior, and conformance tests. + +Tool `title`, annotations, icons, and outputSchema remain optional metadata improvements. They are not required for the implemented tools/resources core server surface. + +## Validation Commands + +```bash +GOCACHE=/tmp/mcp-for-appium-go-cache go test ./... -count=1 +GOCACHE=/tmp/mcp-for-appium-go-cache go vet ./... +``` diff --git a/README.md b/README.md index ed2033a..4895ceb 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # MCP Mobile Worker - Appium 自动化测试平台 > **发布阶段**: `v0.x` 预发布 -> **当前实现口径**: `v4.4` 需求/设计基线 +> **当前实现口径**: `v4.4` 需求/设计基线 + MCP `2026-07-28` alignment > **协议支持**: 标准 MCP (Model Context Protocol) + JSON-RPC + gRPC + WebSocket + HTTP 辅助端点 ## 概述 @@ -10,9 +10,10 @@ MCP Mobile Worker 是一个面向 AI Agent 的统一移动测试执行平台, ### 当前发布定位 -- ✅ **标准 MCP 协议支持**:实现 Anthropic MCP 标准(协议版本 2024-11-05) +- ✅ **标准 MCP 协议支持**:支持最新 `2026-07-28` 无状态协议,并兼容 `2025-11-25` / `2025-06-18` initialize-based 客户端 - ✅ **stdio 传输模式**:通过 `gateway --stdio` 启动,支持 Claude Desktop 配置 -- ✅ **MCP Tools 注册表**:26 个工具(会话/执行/元素/手势/实用/Device Farm/调试)暴露给 LLM +- ✅ **Streamable HTTP 传输模式**:通过 `/mcp` 提供标准 MCP HTTP endpoint +- ✅ **MCP Tools 注册表**:内置 26 个工具;启用 `gateway.disable_adb_shell_tool` 后对外暴露 25 个 - ✅ **HTTP 辅助能力**:保留健康检查、指标与浏览器 WebSocket subscription token 签发端点 - ✅ **当前 GA 候选模式**:`monolith` - ⚠️ **distributed**:功能已补齐 ownership lease、结果回传、worker 恢复、stale-result protection 与端到端回归,但首个稳定版仍明确按 `experimental` 管理 @@ -22,6 +23,7 @@ MCP Mobile Worker 是一个面向 AI Agent 的统一移动测试执行平台, - 推荐运行模式:`monolith` - `distributed`:**experimental**,`v1.0.0` 首个稳定版仍不作为生产 GA 入口模式 - Gateway 的 HTTP 与 `stdio` 入口当前都以 `monolith` 为正式支持模式 +- Gateway 尚未连接外部 orchestrator;standalone orchestrator/worker 当前用于 distributed 集成验证和后续部署接线 - JSON-RPC 预留方法 `replay` `subscribe` `unsubscribe` 当前仍未实现 ### 功能矩阵 @@ -31,7 +33,8 @@ MCP Mobile Worker 是一个面向 AI Agent 的统一移动测试执行平台, | `monolith` 执行模式 | `GA candidate` | 当前推荐的正式运行模式 | | `distributed` 执行模式 | `experimental` | 已具备结果回传、lease、worker 恢复与 distributed E2E,但首个稳定版仍按实验特性发布 | | MCP `stdio` | `GA candidate` | 可供 Claude Desktop 等 MCP 客户端发现和调用 | -| HTTP JSON-RPC | `GA candidate` | 主链路可用 | +| MCP Streamable HTTP `/mcp` | `GA candidate` | `2026-07-28` 仅使用 POST,并校验 `MCP-Protocol-Version`、`Mcp-Method` 与按方法要求的 `Mcp-Name`;同时保留 legacy initialize 路径 | +| HTTP JSON-RPC `/jsonrpc` | `compatibility` | 向后兼容入口,非标准 MCP Streamable HTTP transport | | HTTP 辅助端点 | `GA candidate` | 用于 `/healthz`、`/metrics` 与浏览器 WebSocket token 签发 | | WebSocket 事件订阅 | `GA candidate` | 浏览器需先换短时 subscription token,trace 订阅已校验持久化 ownership | | `replay` / `subscribe` / `unsubscribe` JSON-RPC 方法 | `planned` | schema 预留,尚未实现 | @@ -41,7 +44,35 @@ MCP Mobile Worker 是一个面向 AI Agent 的统一移动测试执行平台, ### 快速开始 -#### 1. 本地开发:作为 MCP Server 使用(Claude Desktop 集成) +#### 1. 准备依赖、配置和 PostgreSQL Schema + +本地运行 `gateway` 需要: + +- `go.mod` 声明的 Go `1.24.5` 或兼容工具链 +- PostgreSQL 和 Redis +- 已创建且可执行 `HeadBucket` / `PutObject` 的 S3 或 S3-compatible bucket + +`gateway` 会在监听端口前检查 PostgreSQL、Redis 和 S3 bucket;缺少可访问的 bucket 时会直接启动失败。 +实际创建和执行移动会话时,还需要 Appium 2 可执行文件,或一个可访问的 Appium server;仅执行协议发现和健康检查时不要求 Appium 已启动。 + +```bash +cp config.example.yaml config.yaml +mkdir -p bin +go build -o ./bin/gateway ./cmd/gateway + +export DATABASE_URL='postgres://postgres:postgres@127.0.0.1:5432/mcp_mobile_worker?sslmode=disable' +psql "$DATABASE_URL" -f internal/storage/postgres/migrations/001_init.sql +psql "$DATABASE_URL" -f internal/storage/postgres/migrations/002_audit_logs.sql +psql "$DATABASE_URL" -f internal/storage/postgres/migrations/003_reserved_slot.sql +psql "$DATABASE_URL" -f internal/storage/postgres/migrations/004_pat_tokens.sql +psql "$DATABASE_URL" -f internal/storage/postgres/migrations/005_hmac_keys.sql +psql "$DATABASE_URL" -f internal/storage/postgres/migrations/006_trace_execution_state.sql +psql "$DATABASE_URL" -f internal/storage/postgres/migrations/007_trace_session_ownership.sql +``` + +迁移说明见 [PostgreSQL Migrations](./internal/storage/postgres/migrations/README.md)。 + +#### 2. 本地开发:作为 MCP Server 使用(Claude Desktop 集成) 在 Claude Desktop 配置文件中添加: @@ -49,10 +80,10 @@ MCP Mobile Worker 是一个面向 AI Agent 的统一移动测试执行平台, { "mcpServers": { "appium-mobile-testing": { - "command": "/path/to/gateway", + "command": "/path/to/repo/bin/gateway", "args": ["--stdio"], "env": { - "CONFIG_PATH": "/path/to/config.yaml" + "CONFIG_PATH": "/path/to/repo/config.yaml" } } } @@ -63,41 +94,61 @@ MCP Mobile Worker 是一个面向 AI Agent 的统一移动测试执行平台, - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json` - Windows: `%APPDATA%\Claude\claude_desktop_config.json` -#### 2. 本地开发:作为 HTTP 服务使用 +#### 3. 本地开发:作为 HTTP 服务使用 ```bash # 启动 HTTP 服务器模式(默认,本地调试可使用明文 HTTP) -./gateway --config config.yaml +./bin/gateway --config config.yaml -# 访问 JSON-RPC 端点 -curl -X POST http://localhost:8080/jsonrpc \ +# MCP 2026-07-28 无状态发现(现代协议不再调用 initialize) +curl -X POST http://localhost:8080/mcp \ + -H "Accept: application/json, text/event-stream" \ -H "Content-Type: application/json" \ + -H "MCP-Protocol-Version: 2026-07-28" \ + -H "Mcp-Method: server/discover" \ -d '{ "jsonrpc": "2.0", - "method": "tools/list", - "params": {}, + "method": "server/discover", + "params": { + "_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": {"name": "local-test", "version": "1.0.0"} + } + }, "id": 1 }' -``` -#### 3. 初始化 PostgreSQL Schema +# 每个现代请求都重复携带版本和客户端能力,不依赖此前连接状态 +curl -X POST http://localhost:8080/mcp \ + -H "Accept: application/json, text/event-stream" \ + -H "Content-Type: application/json" \ + -H "MCP-Protocol-Version: 2026-07-28" \ + -H "Mcp-Method: tools/list" \ + -d '{ + "jsonrpc": "2.0", + "method": "tools/list", + "params": { + "_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {} + } + }, + "id": 2 + }' -在首次启动 `gateway` 或 `orchestrator` 之前,先应用仓库自带的 schema migration: +# 本项目当前支持的 tools/call 和 resources/read 还必须发送与 params.name/params.uri 一致的 Mcp-Name +# legacy 客户端仍可先 initialize,并使用 2025-11-25 或 2025-06-18 的 MCP-Protocol-Version -```bash -export DATABASE_URL='postgres://postgres:postgres@127.0.0.1:5432/mcp_mobile_worker?sslmode=disable' -psql "$DATABASE_URL" -f internal/storage/postgres/migrations/001_init.sql -psql "$DATABASE_URL" -f internal/storage/postgres/migrations/002_audit_logs.sql -psql "$DATABASE_URL" -f internal/storage/postgres/migrations/003_reserved_slot.sql -psql "$DATABASE_URL" -f internal/storage/postgres/migrations/004_pat_tokens.sql -psql "$DATABASE_URL" -f internal/storage/postgres/migrations/005_hmac_keys.sql -psql "$DATABASE_URL" -f internal/storage/postgres/migrations/006_trace_execution_state.sql -psql "$DATABASE_URL" -f internal/storage/postgres/migrations/007_trace_session_ownership.sql +# 兼容旧集成的 JSON-RPC endpoint 仍保留 +curl -X POST http://localhost:8080/jsonrpc \ + -H "Content-Type: application/json" \ + -d '{"jsonrpc":"2.0","method":"tools/list","params":{},"id":1}' ``` -迁移目录说明见: +本地示例默认关闭鉴权;启用 PAT、OIDC 或 HMAC 后,上述 HTTP 请求还需要携带对应凭据。 -- [internal/storage/postgres/migrations/README.md](./internal/storage/postgres/migrations/README.md) +#### 4. 验证 如需做完整的 migration 回放验证,可以直接运行: @@ -111,11 +162,12 @@ go run ./cmd/migration_replay_check go test ./internal/integration -count=1 -v ``` -这条集成测试会自动拉起: +完整 integration package 会自动拉起: - embedded PostgreSQL - miniredis - fake Appium HTTP server +- fake S3-compatible HTTP endpoint(artifact 场景) 并真实覆盖: @@ -127,7 +179,7 @@ go test ./internal/integration -count=1 -v 如需运行 distributed 端到端链路验证,可以直接运行: ```bash -go test ./internal/integration -run TestDistributedFlowEndToEnd -count=1 -v +go test ./internal/integration -run TestDistributedStartExecuteTraceEndFlow -count=1 -v ``` ### 生产部署默认建议 @@ -136,12 +188,13 @@ go test ./internal/integration -run TestDistributedFlowEndToEnd -count=1 -v - 内部 RPC 推荐至少使用 `tls`,不要把 `insecure` 当成生产默认 - 浏览器 WebSocket 应走短时 subscription token,不应直接暴露长期 PAT / OIDC Bearer - 生产推荐配置请以 [config.production.example.yaml](./config.production.example.yaml) 为基线,本地联调用 [config.example.yaml](./config.example.yaml) 做显式降级 +- 生产示例仍包含占位域名、证书、token 和数据库 DSN;部署前必须替换 secret,并为 PostgreSQL、Redis 与 S3 配置符合环境要求的传输加密和访问控制 ### MCP Tools 列表 通过 MCP 协议可用的工具: -- 共 **26** 个工具(截至 2026-03-23) +- 内置注册表共 **26** 个工具,定义来自 `internal/gateway/mcp/tools/*.json` - 核心会话/执行工具:`startSession` `executePlan` `endSession` `cancelPlan` `getTrace` - 交互式元素工具:`findElement` `clickElement` `sendKeysToElement` `clearElement` `getElementText` `getElementAttribute` `isElementDisplayed` - 手势工具:`tap` `swipe` `longPress` `pressBack` `hideKeyboard` @@ -152,8 +205,8 @@ go test ./internal/integration -run TestDistributedFlowEndToEnd -count=1 -v 补充说明: -- 上述 **26 个** 名称是当前实际可发现的 MCP tools -- 运维可通过 `gateway.disable_adb_shell_tool=true` 完全移除 `adbShell` 的发现与调用入口 +- 本地示例默认可发现上述 **26 个** MCP tools +- 运维可通过 `gateway.disable_adb_shell_tool=true` 完全移除 `adbShell`;生产示例默认启用该开关,因此暴露 **25 个** - JSON-RPC schema 中还保留了 `replay` `subscribe` `unsubscribe` 三个方法名,但它们当前 **未实现**,不计入可用 MCP tools 集 ### Device Farm 参数缓存说明(run_api 模式) @@ -185,6 +238,7 @@ go test ./internal/integration -run TestDistributedFlowEndToEnd -count=1 -v - [Release Notes v1.0.0 Draft](./RELEASE_NOTES_v1.0.0.md) - [v1.0.0 Release Checklist](./v1.0.0_release_checklist.md) - [Security Policy](./SECURITY.md) +- [MCP 2026-07-28 升级说明](./MCP_2026_07_28_ALIGNMENT.md) - [MIT License](./LICENSE) ### 许可证 @@ -195,68 +249,40 @@ go test ./internal/integration -run TestDistributedFlowEndToEnd -count=1 -v ```mermaid flowchart TD - %% ========= Ingress ========= - A[Client
REST / JSON-RPC] --> B[Gateway] - A2[Client
WebSocket] --> WS[WS Hub] - - subgraph G1[Gateway] - B --> B1[Auth 中间件
HMAC / OIDC / PAT] - B1 --> B2[RateLimit / 配额探测] - B2 --> B3{Idempotency-Key 命中?} - B3 -- 是 --> B3r[返回缓存结果] - B3 -- 否 --> B4[Schema 校验
JSON-RPC/REST] - B4 --> B5[路由: /sessions /plans:execute /cancel ...] + MCP["MCP client"] -->|"POST /mcp"| G["Gateway"] + STDIO["Local MCP client"] -->|"stdio"| G + COMPAT["Compatibility client"] -->|"POST /jsonrpc"| G + BROWSER["Browser client"] -->|"POST /api/ws/traces/{traceId}/subscription-token"| G + BROWSER -->|"WS /ws/plan-events"| WS["WebSocket Hub"] + + G -->|"protected HTTP routes"| AUTH["Optional PAT / OIDC / HMAC"] + + subgraph MONO["GA candidate: monolith"] + AUTH --> O["Embedded Orchestrator"] + G -->|"stdio direct"| O + O --> Q["Redis Streams queue"] + Q --> D["Dispatcher"] + D --> E["Local plan executor"] + E --> A["Appium or Device Farm remote access"] end - %% ========= Orchestrator ========= - B5 --> O[Orchestrator] - subgraph O1[Orchestrator] - O --> O0[DAO / Cache / S3 Client 就绪检查] - O0 --> O1a[CreateTrace / 事务] - O1a --> O2[EventsPublisher
插入事件(PlanQueued)] - O2 --> O3[Dispatcher
写入 Redis Streams 分片] - O3 --> O4[WorkerRegistry.Assign
选择合适 Worker/ADF] - O4 --> O5{ADF 租赁超时?} - O5 -- 是 --> O5f[Fallback=本地执行
事件 phase=fallback] - O5 -- 否 --> O6[派发作业给 Worker] + subgraph DIST["Experimental: standalone distributed stack"] + SO["Standalone Orchestrator"] --> DQ["Redis Streams dispatcher"] + DQ -->|"ExecutePlan gRPC"| W["Worker with capacity admission"] + W --> WA["Appium"] + W -->|"events, lease renewal, completion gRPC"| SO end - %% ========= Worker 执行 ========= - O6 --> W[Worker] - subgraph W1[Worker] - W --> W0[并发控制器 Acquire] - W0 --> W1a[Appium Client
会话建立/恢复] - W1a --> W2[执行计划步骤循环] - subgraph STEP[Step 执行] - direction TB - S1[定位策略矩阵
and/near→视觉兜底] --> S2[动作执行] - S2 --> S3[可选验证/失败截图] - S3 --> S4[emit PlanEvent
非阻塞/背压保护] - end - W2 --> STEP --> W3[心跳/指标上报] - W3 --> W4{取消/超时?} - W4 -- 是 --> W4c[停止≤1s;最终事件=PlanCanceled] - W4 -- 否 --> W5[完成/失败;最终事件=PlanFinished/Failed] - W5 --> W6[并发控制器 Release] - end - - %% ========= 事件与制品 ========= - W4c -->|事件流| EDB[(Postgres
Traces/Events)] - W5 -->|事件流| EDB - W -->|Screenshot/Logs 大文件| S3[S3 对象存储] - S3 -.-> O7[CompleteArtifactUpload
ETag/SHA256 校验] - - %% ========= 发布与补偿 ========= - EDB --> PUB[EventsPublisher
广播触发] - PUB --> WS - WS -->|实时 at-most-once| A2[Client WS 订阅者] - EDB --> A3[GetEvents(sinceId)
(A2A 补偿)] - - %% ========= 观测与链路 ========= - B & O & W --> M[Metrics / Prometheus] - B & O & W --> T[OTEL Tracing] - classDef faded fill:#f7f7f7,stroke:#bbb,color:#333; - - %% notes - class S3,T,M faded + O --> PG[("PostgreSQL sessions, traces, events, audit")] + SO --> PG + O --> R[("Redis cache, leases, PubSub")] + SO --> R + O --> S3["S3 screenshot artifacts"] + O --> EP["EventsPublisher"] + SO --> EP + EP -->|"durable events"| PG + EP -->|"best-effort PubSub"| R + R --> WS ``` + +当前 gateway 不会把 HTTP 或 stdio 请求转发给 standalone orchestrator,因此图中的 distributed stack 不是现有 gateway 的可选后端。事件先持久化到 PostgreSQL,再 best-effort 发布到 Redis PubSub;WebSocket 是实时 at-most-once 通道,历史事件通过 `getTrace` 读取,而不是旧 A2A REST 路由。`/metrics` 当前与 gateway 共用监听端口,`telemetry.metrics_port` 尚未创建独立 listener;gateway 和 orchestrator 初始化 OTEL tracing,worker 当前使用结构化日志。 diff --git a/USAGE_EXAMPLES.md b/USAGE_EXAMPLES.md index d8873a9..c997c3e 100644 --- a/USAGE_EXAMPLES.md +++ b/USAGE_EXAMPLES.md @@ -258,12 +258,12 @@ curl -X POST http://localhost:8080/jsonrpc \ ./gateway --stdio --config config.yaml ``` -### 发送 JSON-RPC 请求 +### 发送 MCP 2026-07-28 JSON-RPC 请求 在 stdin 中输入(一行): ```json -{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}},"id":1} +{"jsonrpc":"2.0","method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"test-client","version":"1.0.0"}}},"id":1} ``` 按回车发送。 @@ -273,9 +273,11 @@ curl -X POST http://localhost:8080/jsonrpc \ 从 stdout 读取响应: ```json -{"jsonrpc":"2.0","result":{"protocolVersion":"2024-11-05","capabilities":{"tools":{"listChanged":false},"resources":{"subscribe":true,"listChanged":false}},"serverInfo":{"name":"MCP Mobile Worker","version":"1.0.0"}},"id":1} +{"jsonrpc":"2.0","result":{"resultType":"complete","supportedVersions":["2026-07-28","2025-11-25","2025-06-18"],"capabilities":{"tools":{"listChanged":false},"resources":{"subscribe":false,"listChanged":false}},"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"MCP Mobile Worker","version":"1.0.0"}},"instructions":"Use tools/list to discover Appium operations and resources/templates/list to discover trace URI patterns.","ttlMs":3600000,"cacheScope":"public"},"id":1} ``` +Legacy 客户端仍可发送 `initialize`,并协商 `2025-11-25` 或 `2025-06-18`。 + ### 完整测试脚本 创建文件 `test_stdio.sh`: @@ -290,8 +292,8 @@ GATEWAY_PID=$! # 等待启动 sleep 2 -# 发送 initialize 请求 -echo '{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}},"id":1}' | \ +# 发送现代 server/discover 请求 +echo '{"jsonrpc":"2.0","method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"test","version":"1.0"}}},"id":1}' | \ ./gateway --stdio --config config.yaml # 清理 diff --git a/cmd/gateway/main.go b/cmd/gateway/main.go index 059c32b..7cad495 100644 --- a/cmd/gateway/main.go +++ b/cmd/gateway/main.go @@ -4,16 +4,20 @@ import ( "context" "encoding/json" "flag" + "io" "log" "net/http" "os" "os/signal" + "strings" "syscall" "time" "mcp_for_appium/internal/config" "mcp_for_appium/internal/gateway/capabilities" + "mcp_for_appium/internal/gateway/httpinput" "mcp_for_appium/internal/gateway/jsonrpc" + "mcp_for_appium/internal/gateway/mcphttp" "mcp_for_appium/internal/gateway/rest" "mcp_for_appium/internal/gateway/stdio" "mcp_for_appium/internal/gateway/websocket" @@ -31,7 +35,11 @@ import ( func main() { // Parse command line flags stdioMode := flag.Bool("stdio", false, "Run in stdio mode for MCP protocol") - configPath := flag.String("config", "config.yaml", "Path to config file") + defaultConfigPath := strings.TrimSpace(os.Getenv("CONFIG_PATH")) // Honor the documented environment variable while still allowing the command-line flag to override it. + if defaultConfigPath == "" { // Fall back to the repository-default path only when the environment does not select one. + defaultConfigPath = "config.yaml" // Preserve existing local startup behavior for deployments that do not set CONFIG_PATH. + } + configPath := flag.String("config", defaultConfigPath, "Path to config file") // Use the environment-derived default while retaining explicit --config precedence. flag.Parse() // 加载配置文件 @@ -44,8 +52,12 @@ func main() { } // 初始化日志与遥测 - telemetry.InitLogger(cfg.Telemetry.LogLevel, cfg.Telemetry.LogFile) // Initialize structured logging with optional file sink. - log.SetOutput(telemetry.StdLogWriter()) // Mirror standard-library logs into the configured log destinations. + consoleWriter := io.Writer(os.Stdout) // Keep HTTP-mode structured logs on the ordinary process console by default. + if *stdioMode { // Reserve stdout exclusively for JSON-RPC frames whenever the stdio transport is selected. + consoleWriter = os.Stderr // Route every structured startup and service log to stderr before dependencies initialize. + } + telemetry.InitLoggerWithConsole(cfg.Telemetry.LogLevel, cfg.Telemetry.LogFile, consoleWriter) // Initialize structured logging on a transport-safe console with the optional file sink. + log.SetOutput(telemetry.StdLogWriter()) // Mirror standard-library logs into the configured log destinations. shutdownTracer := telemetry.InitTracer("gateway", cfg.Telemetry.OTLPEndpoint) defer func() { _ = shutdownTracer(context.Background()) @@ -163,6 +175,7 @@ func runHTTPMode(cfg *config.Config) { jsonrpcHandler := jsonrpc.NewHandler(orchSvc, capSvc) restRouter := rest.NewRouter(orchSvc) subscriptionTokenStore := websocket.NewSubscriptionTokenStore(redisCache, cfg.WebSocket.SubscriptionTokenTTL) // Construct the shared Redis-backed subscription-token store so the browser helper endpoint and WebSocket handshake validation use the same authority. + subscriptionTokenStore.SetAuditRecorder(postgres.NewAuditRecorder(pgDAO)) // Record token creation and WebSocket authorization through the append-only PostgreSQL audit sink. restRouter.SetSubscriptionTokenStore(subscriptionTokenStore) // Inject the shared token store into the trimmed HTTP helper router so browser clients can mint short-lived subscription tokens. authMiddleware, err := buildGatewayAuthMiddleware(ctx, cfg, pgDAO, redisCache) // Construct the optional gateway auth middleware once so JSON-RPC and REST can share the same auth pipeline. if err != nil { // Stop startup when a configured auth source cannot be initialized safely. @@ -171,13 +184,15 @@ func runHTTPMode(cfg *config.Config) { wsHub := websocket.NewHub(redisCache) go wsHub.Run(ctx) - protectedMux := http.NewServeMux() // Isolate auth-protected routes so health, metrics, and WebSocket can keep their dedicated exposure rules. - protectedMux.Handle("/jsonrpc", jsonrpcHandler) // Register the JSON-RPC endpoint inside the protected route subtree. - restRouter.RegisterRoutes(protectedMux) // Register the remaining browser helper endpoint that issues short-lived WebSocket subscription tokens. - protectedHandler := http.Handler(protectedMux) // Seed the protected subtree handler with the raw mux before optional auth wrapping. - if authMiddleware != nil { // Wrap the protected subtree only when at least one auth validator is active. + protectedMux := http.NewServeMux() // Isolate auth-protected routes so health, metrics, and WebSocket can keep their dedicated exposure rules. + protectedMux.Handle("/jsonrpc", jsonrpcHandler) // Register the JSON-RPC compatibility endpoint inside the protected route subtree. + protectedMux.Handle("/mcp", mcphttp.NewHandler(jsonrpcHandler, cfg.Gateway.AllowedOrigins)) // Register the standard MCP Streamable HTTP endpoint beside the compatibility endpoint. + restRouter.RegisterRoutes(protectedMux) // Register the remaining browser helper endpoint that issues short-lived WebSocket subscription tokens. + protectedHandler := http.Handler(protectedMux) // Seed the protected subtree handler with the raw mux before optional auth wrapping. + if authMiddleware != nil { // Wrap the protected subtree only when at least one auth validator is active. protectedHandler = authMiddleware.Handle(protectedHandler) // Enforce HMAC/OIDC/PAT auth for JSON-RPC and REST requests. } + protectedHandler = httpinput.LimitBody(protectedHandler, httpinput.MaxRequestBodyBytes) // Enforce the request-size ceiling before authentication reads or hashes any protected body. mux := http.NewServeMux() // Build the public root mux that combines protected APIs with public operational endpoints. mux.Handle("/", protectedHandler) // Mount the protected subtree under "/" so JSON-RPC and REST remain reachable through their existing paths. diff --git a/cmd/gateway/main_test.go b/cmd/gateway/main_test.go index 11d326c..cdb2858 100644 --- a/cmd/gateway/main_test.go +++ b/cmd/gateway/main_test.go @@ -4,6 +4,8 @@ package main import ( "net/http" "testing" + + "mcp_for_appium/internal/config" ) // TestHealthHTTPStatusReturnsServiceUnavailableForDown verifies that /healthz uses HTTP 503 when the orchestrator reports a down state. @@ -14,6 +16,18 @@ func TestHealthHTTPStatusReturnsServiceUnavailableForDown(t *testing.T) { } } +// TestNewGatewayHTTPServerConfiguresDefensiveTimeouts verifies that the gateway listener cannot retain slow or idle connections indefinitely. +func TestNewGatewayHTTPServerConfiguresDefensiveTimeouts(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{Port: 8080}} // Build the minimal gateway configuration needed by the HTTP server constructor. + server := newGatewayHTTPServer(cfg, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) // Construct the production server around one inert handler. + if server.ReadHeaderTimeout <= 0 || server.ReadTimeout <= 0 || server.WriteTimeout <= 0 || server.IdleTimeout <= 0 { // Require every slow-client lifecycle phase to have a finite deadline. + t.Fatalf("expected defensive HTTP timeouts, got header=%v read=%v write=%v idle=%v", server.ReadHeaderTimeout, server.ReadTimeout, server.WriteTimeout, server.IdleTimeout) // Surface every configured deadline for quick diagnosis. + } + if server.MaxHeaderBytes <= 0 { // Require an explicit header-memory ceiling in addition to connection deadlines. + t.Fatalf("expected positive MaxHeaderBytes, got %d", server.MaxHeaderBytes) // Surface a missing or invalid header limit. + } +} + // TestHealthHTTPStatusReturnsOKForNonDownStates verifies that healthy and degraded health payloads remain HTTP 200 so operators can still inspect degraded nodes. func TestHealthHTTPStatusReturnsOKForNonDownStates(t *testing.T) { healthyStatus := healthHTTPStatus(map[string]interface{}{"status": "healthy"}) // Map one healthy payload through the gateway helper used by /healthz. diff --git a/cmd/gateway/security.go b/cmd/gateway/security.go index 01bcbd6..b4cfd82 100644 --- a/cmd/gateway/security.go +++ b/cmd/gateway/security.go @@ -35,7 +35,11 @@ func buildGatewayAuthMiddleware(ctx context.Context, cfg *config.Config, pgDAO * return nil, err // Preserve the PAT construction failure so startup can stop with the precise root cause. } - return gatewaymiddleware.NewAuthMiddleware(hmacValidator, oidcValidator, patValidator), nil // Build the combined gateway auth middleware, or nil when no validator is active. + authMiddleware := gatewaymiddleware.NewAuthMiddleware(hmacValidator, oidcValidator, patValidator) // Build the combined gateway auth middleware, or nil when no validator is active. + if authMiddleware != nil { // Attach audit persistence only when protected-route authentication is active. + authMiddleware.SetAuditRecorder(postgres.NewAuditRecorder(pgDAO)) // Record every authentication success and failure through the shared append-only PostgreSQL sink. + } + return authMiddleware, nil // Return the fully wired middleware after validator and optional audit construction succeeds. } // buildGatewayHMACValidator constructs the optional HMAC validator from the configured static or PostgreSQL-backed key source. @@ -107,7 +111,7 @@ func buildGatewayOIDCValidator(ctx context.Context, cfg *config.Config) (*auth.O return nil, nil // Return nil so the caller knows OIDC auth is inactive rather than partially initialized. } - return auth.NewOIDCValidator(ctx, issuerURL, audience) // Build the OIDC validator with the canonical v4.4 issuer and audience fields. + return auth.NewOIDCValidator(ctx, issuerURL, audience, strings.TrimSpace(cfg.Auth.OIDC.JWKSURLOverride)) // Build the OIDC validator with discovery or the configured explicit JWKS endpoint. } // buildGatewayPATValidator constructs the optional PAT validator from the configured static or PostgreSQL-backed token source. @@ -152,8 +156,16 @@ func buildGatewayPATValidator(cfg *config.Config, pgDAO *postgres.DAO) (*auth.PA // newGatewayHTTPServer constructs the runtime HTTP server with TLS defaults aligned to the gateway config. func newGatewayHTTPServer(cfg *config.Config, handler http.Handler) *http.Server { - server := &http.Server{Addr: ":" + strconv.Itoa(cfg.Gateway.Port), Handler: handler} // Construct the server once so the caller can decide whether to run it in TLS or plaintext mode. - if cfg.Gateway.EnableTLS { // Apply an explicit TLS floor only when HTTPS is enabled for the gateway listener. + server := &http.Server{ // Construct the bounded server once so the caller can decide whether to run it in TLS or plaintext mode. + Addr: ":" + strconv.Itoa(cfg.Gateway.Port), // Bind the configured gateway port on every available interface as before. + Handler: handler, // Route accepted requests through tracing and the gateway mux supplied by the caller. + ReadHeaderTimeout: 5 * time.Second, // Bound slow or incomplete request headers before any application handler runs. + ReadTimeout: 30 * time.Second, // Bound request-body reads so slow clients cannot retain connections indefinitely. + WriteTimeout: 10 * time.Minute, // Bound complete response handling while leaving room for the documented synchronous plan wait. + IdleTimeout: 2 * time.Minute, // Reclaim inactive keep-alive connections after a predictable idle window. + MaxHeaderBytes: 1 << 20, // Cap aggregate request headers at one mebibyte to constrain parsing memory. + } + if cfg.Gateway.EnableTLS { // Apply an explicit TLS floor only when HTTPS is enabled for the gateway listener. server.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} // Enforce TLS 1.2+ so the gateway does not negotiate deprecated protocol versions. } diff --git a/cmd/orchestrator/main.go b/cmd/orchestrator/main.go index 7cce1ed..022252a 100644 --- a/cmd/orchestrator/main.go +++ b/cmd/orchestrator/main.go @@ -5,6 +5,7 @@ import ( "log" "os" "os/signal" + "strings" "syscall" "time" @@ -19,8 +20,11 @@ import ( // main is the entry point for this binary. func main() { - // 加载配置 - cfg, err := config.Load("config.yaml") + configPath := strings.TrimSpace(os.Getenv("CONFIG_PATH")) // Honor the same deployment-level config override used by the gateway process. + if configPath == "" { // Preserve local startup behavior when no environment override is supplied. + configPath = "config.yaml" // Use the repository-default configuration file. + } + cfg, err := config.Load(configPath) // Load the resolved configuration path before startup validation or dependency creation. if err != nil { log.Fatalf("failed to load config: %v", err) } diff --git a/cmd/worker/main.go b/cmd/worker/main.go index 6db94c1..6d028f2 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -7,6 +7,7 @@ import ( "net" "os" "os/signal" + "strings" "syscall" "time" @@ -21,7 +22,11 @@ import ( // main is the entry point for this binary. func main() { - cfg, err := config.Load("config.yaml") + configPath := strings.TrimSpace(os.Getenv("CONFIG_PATH")) // Honor the shared deployment-level configuration override. + if configPath == "" { // Preserve local startup behavior when no environment override is supplied. + configPath = "config.yaml" // Use the repository-default configuration file. + } + cfg, err := config.Load(configPath) // Load the resolved configuration path before worker startup validation. if err != nil { log.Fatalf("failed to load config: %v", err) } @@ -54,11 +59,16 @@ func main() { } defer orchClient.Close() + concurrency := cfg.Worker.Concurrency // Resolve worker admission capacity before constructing or advertising the gRPC service. + if concurrency <= 0 { // Preserve the documented default when configuration omits or supplies an invalid capacity. + concurrency = 4 // Use four authoritative worker execution slots by default. + } + // --- gRPC server (receives ExecutePlan / CancelPlan from orchestrator) --- - workerSvc := worker.NewGRPCServer(cfg.Worker.AppiumURL, cfg.Orchestrator.StepTimeout, cfg.Orchestrator.AutoWaitMax, workerID, orchClient, leaseRenewEvery(cfg.Worker.HeartbeatInterval)) // Construct the distributed worker handler with orchestrator callbacks, stable identity, and a lease-renewal cadence derived from worker heartbeats. - workerSvc.SetAppiumReadyFunc(appiumSupervisor.EnsureReady) // Reuse the same worker-owned Appium supervisor before every plan so local Appium is auto-started again if it goes away after startup. - grpcServerOptions, err := rpc.NewServerOptions(cfg.RPC.Security) // Build the worker gRPC server options that match the configured internal RPC transport mode and shared-token enforcement. - if err != nil { // Stop immediately when the configured internal RPC security settings cannot be turned into a gRPC server safely. + workerSvc := worker.NewGRPCServer(cfg.Worker.AppiumURL, cfg.Orchestrator.StepTimeout, cfg.Orchestrator.AutoWaitMax, workerID, orchClient, leaseRenewEvery(cfg.Worker.HeartbeatInterval), concurrency) // Construct the distributed worker with the same authoritative capacity advertised during registration. + workerSvc.SetAppiumReadyFunc(appiumSupervisor.EnsureReady) // Reuse the same worker-owned Appium supervisor before every plan so local Appium is auto-started again if it goes away after startup. + grpcServerOptions, err := rpc.NewServerOptions(cfg.RPC.Security) // Build the worker gRPC server options that match the configured internal RPC transport mode and shared-token enforcement. + if err != nil { // Stop immediately when the configured internal RPC security settings cannot be turned into a gRPC server safely. log.Fatalf("failed to initialize worker gRPC security: %v", err) // Surface the gRPC security wiring failure before the listener starts. } grpcSrv := grpc.NewServer(grpcServerOptions...) // Construct the worker gRPC server with the configured transport credentials and shared-token interceptor. @@ -75,11 +85,6 @@ func main() { }() logger.Info("worker gRPC server started", "port", cfg.Worker.GRPCPort) - concurrency := cfg.Worker.Concurrency - if concurrency == 0 { - concurrency = 4 - } - regCtx, regCancel := context.WithTimeout(context.Background(), 10*time.Second) defer regCancel() @@ -123,10 +128,13 @@ func heartbeatLoop(ctx context.Context, client *rpc.OrchestratorClient, workerID case <-ctx.Done(): return case <-ticker.C: - if _, err := client.Heartbeat(ctx, &rpc.HeartbeatRequest{ + heartbeatCtx, heartbeatCancel := context.WithTimeout(ctx, 5*time.Second) // Bound each heartbeat independently so one stalled RPC cannot halt future liveness reports forever. + _, err := client.Heartbeat(heartbeatCtx, &rpc.HeartbeatRequest{ // Report authoritative admitted-run load through the bounded RPC context. WorkerID: workerID, ActiveLoad: svc.ActiveLoad(), - }); err != nil { + }) + heartbeatCancel() // Release the per-heartbeat timer immediately after the RPC returns. + if err != nil { // Log this heartbeat failure and allow the next ticker iteration to retry. logger.Error("heartbeat failed", "worker_id", workerID, "error", err) } } diff --git a/go.mod b/go.mod index c814849..45b25bf 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( github.com/jackc/pgx/v5 v5.7.6 github.com/prometheus/client_golang v1.23.2 github.com/redis/go-redis/v9 v9.17.0 + github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 github.com/xeipuuv/gojsonschema v1.2.0 go.opentelemetry.io/otel v1.38.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0 diff --git a/go.sum b/go.sum index 2a9c3d5..b4b44c8 100644 --- a/go.sum +++ b/go.sum @@ -57,6 +57,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/fergusstrange/embedded-postgres v1.34.0 h1:c6RKhPKFsLVU+Tdxsx8q0UxCHsvZZ/iShAnljRBXs6s= github.com/fergusstrange/embedded-postgres v1.34.0/go.mod h1:w0YvnCgf19o6tskInrOOACtnqfVlOvluz3hlNLY7tRk= github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= @@ -110,6 +112,8 @@ github.com/redis/go-redis/v9 v9.17.0 h1:K6E+ZlYN95KSMmZeEQPbU/c++wfmEvfFB17yEAq/ github.com/redis/go-redis/v9 v9.17.0/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= diff --git a/internal/audit/recorder.go b/internal/audit/recorder.go new file mode 100644 index 0000000..c522ea2 --- /dev/null +++ b/internal/audit/recorder.go @@ -0,0 +1,91 @@ +// recorder.go defines the repository-wide structured security audit event and pluggable recording contract. +package audit + +import ( + "context" + "net" + "net/http" + "strings" + "time" +) + +// Event captures actor, credential, tenant, action, resource, outcome, request, and metadata fields required for one append-only security audit record. +type Event struct { + ProjectID string + SessionID string + TraceID string + ActorID string + ActorType string + AuthScheme string + CredentialID string + TenantID string + Action string + ResourceType string + ResourceID string + Result string + Reason string + SourceIP string + RequestID string + CreatedAt time.Time + Metadata map[string]interface{} +} + +// Recorder appends structured audit events to one authoritative sink. +type Recorder interface { + Record(ctx context.Context, event Event) error +} + +// RecorderFunc adapts one function into the Recorder interface. +type RecorderFunc func(ctx context.Context, event Event) error + +type requestContextKey struct{} + +// RequestContext stores sanitized gateway request correlation fields for downstream audit producers. +type RequestContext struct { + RequestID string + SourceIP string +} + +// Record invokes the adapted audit function with the supplied event. +func (f RecorderFunc) Record(ctx context.Context, event Event) error { + return f(ctx, event) // Delegate recording to the wrapped function so tests and lightweight integrations can inject a sink directly. +} + +// WithRequestContext attaches sanitized request correlation metadata for downstream audit events such as WebSocket token issuance. +func WithRequestContext(ctx context.Context, requestContext RequestContext) context.Context { + return context.WithValue(ctx, requestContextKey{}, requestContext) // Preserve request correlation without attaching headers, credentials, or body data. +} + +// RequestContextFrom returns sanitized request correlation metadata when an upstream gateway middleware attached it. +func RequestContextFrom(ctx context.Context) (RequestContext, bool) { + if ctx == nil { // Reject nil contexts defensively because context.Value cannot be called safely on nil. + return RequestContext{}, false // Report that no request metadata is available. + } + requestContext, ok := ctx.Value(requestContextKey{}).(RequestContext) // Read the exact private context key type used by WithRequestContext. + return requestContext, ok // Return the stored metadata together with an explicit presence marker. +} + +// RequestSourceIP extracts one normalized peer IP from an HTTP request without trusting forwarding headers implicitly. +func RequestSourceIP(r *http.Request) string { + if r == nil { // Return an empty source when no request metadata exists. + return "" // Avoid dereferencing a nil request in failure-path audit code. + } + host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)) // Parse the ordinary host:port peer address supplied by net/http. + if err == nil { // Return only the host when the peer address includes a valid port. + return strings.TrimSpace(host) // Normalize the extracted peer IP before persistence. + } + return strings.TrimSpace(r.RemoteAddr) // Preserve a port-less test or proxy peer address without trusting caller-controlled headers. +} + +// ErrorReason returns one stable internal error code for audit classification or a generic failure marker for untyped errors. +func ErrorReason(err error, codeLookup func(error) (string, bool)) string { + if err == nil { // Successful operations have no failure reason. + return "" // Keep success audit records free of misleading reason text. + } + if codeLookup != nil { // Prefer a caller-supplied stable error-code extractor when available. + if code, ok := codeLookup(err); ok && strings.TrimSpace(code) != "" { // Record only a non-empty stable code. + return strings.TrimSpace(code) // Avoid persisting wrapped backend error text in the audit record. + } + } + return "unclassified_failure" // Use a stable generic marker for failures without a repository error code. +} diff --git a/internal/auth/context.go b/internal/auth/context.go index fd9a707..6cd1acf 100644 --- a/internal/auth/context.go +++ b/internal/auth/context.go @@ -10,10 +10,11 @@ var subjectKey = contextKey{} // Subject represents the authenticated entity. type Subject struct { - ID string - Type string // "pat", "oidc", "hmac" - TenantID string - Scopes []string + ID string + Type string // "pat", "oidc", "hmac" + CredentialID string + TenantID string + Scopes []string } // WithSubject returns a new context with the subject. diff --git a/internal/auth/hmac.go b/internal/auth/hmac.go index f197e25..b07ad7a 100644 --- a/internal/auth/hmac.go +++ b/internal/auth/hmac.go @@ -70,22 +70,17 @@ func (v *HMACValidator) Verify(ctx context.Context, sig string, method string, p return nil, errors.New(errors.CodeUnauthenticated, "timestamp out of window") // Surface stale or far-future requests as standard authentication failures. } - if v.nonceStore != nil { // Enforce nonce uniqueness only when the caller supplied a store because replay protection requires shared state. - nonceKey := "nonce:" + strings.TrimSpace(keyID) + ":" + strings.TrimSpace(nonce) // Scope the replay marker by key ID so distinct credentials can reuse the same nonce safely. - acquired, _, err := v.nonceStore.CheckAndSet(ctx, nonceKey, "1", v.nonceTTL) // Store the replay marker with the configured nonce TTL so duplicates inside the validity window are rejected. - if err != nil { // Stop immediately when replay protection storage fails because the signature cannot be trusted safely without it. - return nil, errors.Wrap(errors.CodeInternal, "failed to check nonce", err) // Surface nonce-store failures as internal errors because the caller cannot fix server-side replay storage issues. - } - if !acquired { // Reject duplicate nonce usage because replay protection has already observed this signed request fingerprint recently. - return nil, errors.New(errors.CodeNonceDuplicate, "nonce reused") // Surface replayed requests through the dedicated nonce-duplicate error code. - } - } - keyMaterial, err := v.keyLookup(ctx, strings.TrimSpace(keyID)) // Resolve the authoritative HMAC key material so runtime validation can enforce status and validity windows. if err != nil { // Stop immediately when the HMAC key ID is unknown or the lookup source fails. + if errors.IsCode(err, errors.CodeStoreRead) || errors.IsCode(err, errors.CodeStoreConn) { // Preserve source availability failures instead of misclassifying them as bad credentials. + return nil, err // Let the HTTP layer fail closed with a server error while keeping backend details private. + } return nil, errors.Wrap(errors.CodeUnauthenticated, "key not found", err) // Preserve the source failure while returning the stable unauthenticated code. } - if strings.EqualFold(strings.TrimSpace(keyMaterial.Status), "revoked") || strings.EqualFold(strings.TrimSpace(keyMaterial.Status), "retired") { // Reject revoked or retired keys before signature comparison because those keys must no longer authenticate traffic. + if keyMaterial == nil { // Reject a lookup that succeeds without authoritative key material because signature verification cannot proceed safely. + return nil, errors.New(errors.CodeUnauthenticated, "key not found") // Fail closed without dereferencing a nil lookup result. + } + if !strings.EqualFold(strings.TrimSpace(keyMaterial.Status), "active") { // Accept only the explicit active lifecycle state so unknown or future states fail closed. return nil, errors.New(errors.CodeUnauthenticated, "hmac key is not active") // Surface inactive keys as standard authentication failures. } if keyMaterial.NotBefore != nil && requestTime.Before(keyMaterial.NotBefore.UTC()) { // Reject requests signed before the key validity window begins. @@ -109,12 +104,23 @@ func (v *HMACValidator) Verify(ctx context.Context, sig string, method string, p return nil, errors.New(errors.CodeUnauthenticated, "invalid signature") // Surface mismatched HMAC digests as standard authentication failures. } + if v.nonceStore != nil { // Consume replay state only after the key and signature prove that the caller holds the shared secret. + nonceKey := "nonce:" + strings.TrimSpace(keyID) + ":" + strings.TrimSpace(nonce) // Scope the replay marker by key ID so distinct credentials can reuse the same nonce safely. + acquired, _, err := v.nonceStore.CheckAndSet(ctx, nonceKey, "1", v.nonceTTL) // Store the authenticated replay marker with the configured expiry. + if err != nil { // Stop when replay storage cannot enforce uniqueness for the otherwise valid request. + return nil, errors.Wrap(errors.CodeInternal, "failed to check nonce", err) // Fail closed because accepting without shared replay state would weaken the signature contract. + } + if !acquired { // Reject duplicate nonce usage because a prior authenticated request already consumed this marker. + return nil, errors.New(errors.CodeNonceDuplicate, "nonce reused") // Surface replayed requests through the dedicated nonce-duplicate error code. + } + } + subjectID := strings.TrimSpace(keyMaterial.SubjectID) // Normalize the authoritative subject ID so downstream handlers receive a stable principal identifier. if subjectID == "" { // Fall back to the key ID only when the source does not supply a distinct subject identifier. subjectID = strings.TrimSpace(keyMaterial.KeyID) // Preserve a stable authenticated subject identifier even for legacy static HMAC setups without explicit subject data. } - return &Subject{ID: subjectID, Type: "hmac", TenantID: strings.TrimSpace(keyMaterial.TenantID)}, nil // Return the authenticated HMAC subject for downstream tenant-aware request handling. + return &Subject{ID: subjectID, Type: "hmac", CredentialID: strings.TrimSpace(keyMaterial.KeyID), TenantID: strings.TrimSpace(keyMaterial.TenantID)}, nil // Return the authenticated HMAC subject with its safe key identifier for downstream authorization and audit. } // canonicalizeQuery normalizes one raw HTTP query string into the deterministic encoding used by the canonical HMAC request format. diff --git a/internal/auth/hmac_test.go b/internal/auth/hmac_test.go index 5472db1..7165fc0 100644 --- a/internal/auth/hmac_test.go +++ b/internal/auth/hmac_test.go @@ -68,6 +68,23 @@ func TestHMACValidatorRejectsDuplicateNonce(t *testing.T) { } } +// TestHMACValidatorInvalidSignatureDoesNotConsumeNonce verifies that unauthenticated traffic cannot exhaust replay-protection keys. +func TestHMACValidatorInvalidSignatureDoesNotConsumeNonce(t *testing.T) { + nonceStore := &memoryNonceStore{} // Share one observable nonce store across the invalid and valid verification attempts. + validator := NewHMACValidator(func(_ context.Context, keyID string) (*HMACKeyMaterial, error) { // Build one validator over a deterministic active key. + return &HMACKeyMaterial{KeyID: keyID, SubjectID: "subject-1", Secret: "super-secret", Status: "active"}, nil // Return the authoritative key expected by the valid signature. + }, nonceStore, 5*time.Minute, 15*time.Minute) // Enable replay protection so nonce consumption order is exercised. + + signatureTimestamp := fmt.Sprintf("%d", time.Now().UTC().Unix()) // Capture one current timestamp shared by both attempts. + if _, err := validator.Verify(context.Background(), "invalid-signature", "POST", "/mcp", "", `{}`, signatureTimestamp, "nonce-safe", "key-1"); !errors.IsCode(err, errors.CodeUnauthenticated) { // Submit one invalid signature using the target nonce. + t.Fatalf("expected invalid signature rejection, got %v", err) // Surface unexpected validation or replay classifications. + } + validSignature := mustComputeTestSignature(t, "super-secret", "POST", "/mcp", "", `{}`, signatureTimestamp, "nonce-safe", "key-1") // Compute the valid signature over the same nonce and request fields. + if _, err := validator.Verify(context.Background(), validSignature, "POST", "/mcp", "", `{}`, signatureTimestamp, "nonce-safe", "key-1"); err != nil { // Retry with proof of key possession. + t.Fatalf("expected valid signature to consume unused nonce, got %v", err) // Prove the invalid request did not reserve the replay marker. + } +} + // mustComputeTestSignature computes the canonical HMAC signature used by the tests and fails the test immediately when canonicalization fails. func mustComputeTestSignature(t *testing.T, secret string, method string, path string, rawQuery string, body string, timestamp string, nonce string, keyID string) string { t.Helper() // Mark this helper so any failure points at the calling test rather than the helper body. diff --git a/internal/auth/oidc.go b/internal/auth/oidc.go index 0f3eb3b..e3e55a4 100644 --- a/internal/auth/oidc.go +++ b/internal/auth/oidc.go @@ -1,3 +1,4 @@ +// oidc.go validates OIDC ID tokens through issuer discovery or an explicitly configured JWKS endpoint. package auth import ( @@ -14,16 +15,21 @@ type OIDCValidator struct { verifier *oidc.IDTokenVerifier } -// NewOIDCValidator executes this operation. -func NewOIDCValidator(ctx context.Context, issuerURL string, audience string) (*OIDCValidator, error) { +// NewOIDCValidator constructs an issuer- and audience-validating token verifier, optionally bypassing discovery with one explicit JWKS URL. +func NewOIDCValidator(ctx context.Context, issuerURL string, audience string, jwksURLOverride ...string) (*OIDCValidator, error) { + config := &oidc.Config{ // Build the verifier policy once so discovery and explicit-JWKS paths enforce the same audience. + ClientID: strings.TrimSpace(audience), // Require every accepted token to target the configured gateway audience. + } + if len(jwksURLOverride) > 0 && strings.TrimSpace(jwksURLOverride[0]) != "" { // Select the explicit JWKS source only when the caller configured a non-empty override. + keySet := oidc.NewRemoteKeySet(ctx, strings.TrimSpace(jwksURLOverride[0])) // Build the caching remote key set against the operator-selected JWKS endpoint. + verifier := oidc.NewVerifier(strings.TrimSpace(issuerURL), keySet, config) // Continue enforcing the configured issuer even when discovery is bypassed. + return &OIDCValidator{verifier: verifier}, nil // Return the explicit-JWKS validator without contacting the issuer discovery endpoint during startup. + } + provider, err := oidc.NewProvider(ctx, issuerURL) if err != nil { return nil, err } - - config := &oidc.Config{ - ClientID: audience, - } verifier := provider.Verifier(config) return &OIDCValidator{ @@ -34,6 +40,9 @@ func NewOIDCValidator(ctx context.Context, issuerURL string, audience string) (* // Validate executes this operation. func (v *OIDCValidator) Validate(ctx context.Context, rawToken string) (*Subject, error) { + if v == nil || v.verifier == nil { // Reject validation through an uninitialized OIDC verifier instead of panicking. + return nil, errors.New(errors.CodeUnauthenticated, "oidc validator is not configured") // Surface the startup wiring defect through the stable auth contract. + } // Remove Bearer prefix if present if strings.HasPrefix(rawToken, "Bearer ") { rawToken = strings.TrimPrefix(rawToken, "Bearer ") @@ -53,11 +62,15 @@ func (v *OIDCValidator) Validate(ctx context.Context, rawToken string) (*Subject if err := idToken.Claims(&claims); err != nil { return nil, errors.Wrap(errors.CodeUnauthenticated, "failed to parse claims", err) } + if strings.TrimSpace(claims.Sub) == "" { // Require the standard subject claim because downstream ownership cannot authorize an anonymous token. + return nil, errors.New(errors.CodeUnauthenticated, "oidc token subject is missing") // Reject otherwise valid tokens that cannot identify one principal. + } return &Subject{ - ID: claims.Sub, - Type: "oidc", - TenantID: claims.Tenant, - Scopes: claims.Scopes, + ID: strings.TrimSpace(claims.Sub), // Preserve the validated OIDC subject as the application principal. + Type: "oidc", // Identify the authentication scheme for authorization and audit consumers. + CredentialID: strings.TrimSpace(claims.Sub), // Use the subject as the safe credential identifier because no token secret or raw JWT is persisted. + TenantID: strings.TrimSpace(claims.Tenant), // Preserve the optional tenant claim for ownership checks. + Scopes: claims.Scopes, // Preserve validated token scopes for downstream authorization. }, nil } diff --git a/internal/auth/oidc_test.go b/internal/auth/oidc_test.go new file mode 100644 index 0000000..7d1b05c --- /dev/null +++ b/internal/auth/oidc_test.go @@ -0,0 +1,21 @@ +// oidc_test.go verifies OIDC validator construction for explicit JWKS overrides without issuer discovery. +package auth + +import ( + "context" + "testing" +) + +// TestNewOIDCValidatorUsesJWKSOverrideWithoutDiscovery verifies that an explicit key endpoint avoids a startup request to issuer discovery. +func TestNewOIDCValidatorUsesJWKSOverrideWithoutDiscovery(t *testing.T) { + validator, err := NewOIDCValidator(context.Background(), "https://issuer.invalid", "gateway-audience", "https://keys.invalid/jwks.json") // Construct against non-routable endpoints so any eager discovery request would fail the test. + if err != nil { // Reject construction failures because remote JWKS retrieval should remain lazy until token verification. + t.Fatalf("expected explicit JWKS validator construction to succeed, got %v", err) // Surface accidental issuer-discovery calls or invalid override wiring. + } + if validator == nil || validator.verifier == nil { // Require a usable verifier even though no provider discovery object is created. + t.Fatalf("expected explicit JWKS verifier, got %#v", validator) // Surface incomplete construction directly. + } + if validator.provider != nil { // Require the override path to bypass discovery rather than silently ignoring the supplied endpoint. + t.Fatal("expected explicit JWKS path to omit discovery provider") // Surface regressions that would make the config field ineffective. + } +} diff --git a/internal/auth/pat.go b/internal/auth/pat.go index 760ce74..54ac827 100644 --- a/internal/auth/pat.go +++ b/internal/auth/pat.go @@ -4,6 +4,7 @@ package auth import ( "context" "crypto/sha256" + "crypto/subtle" "encoding/hex" "encoding/json" "strings" @@ -49,18 +50,24 @@ func (v *PATValidator) Validate(ctx context.Context, token string) (*Subject, er record, err := v.lookup(ctx, tokenID) // Resolve the authoritative PAT metadata by token ID so validation can enforce status, expiry, and secret hash. if err != nil { // Stop immediately when the PAT ID is unknown or the lookup source fails. + if errors.IsCode(err, errors.CodeStoreRead) || errors.IsCode(err, errors.CodeStoreConn) { // Preserve source availability failures instead of misclassifying them as bad credentials. + return nil, err // Let the HTTP layer fail closed with a server error while keeping backend details private. + } return nil, errors.Wrap(errors.CodeUnauthenticated, "token not found", err) // Preserve the source failure while returning the stable unauthenticated code. } - if strings.EqualFold(strings.TrimSpace(record.Status), "revoked") { // Reject revoked PATs before the secret hash comparison because revoked credentials must never authenticate again. - return nil, errors.New(errors.CodeUnauthenticated, "token revoked") // Surface revoked PATs as standard authentication failures. + if record == nil { // Reject a lookup that succeeds without authoritative PAT metadata because validation cannot continue safely. + return nil, errors.New(errors.CodeUnauthenticated, "token not found") // Fail closed without dereferencing a nil lookup result. + } + if !strings.EqualFold(strings.TrimSpace(record.Status), "active") { // Accept only the explicit active lifecycle state so unknown, revoked, or future states fail closed. + return nil, errors.New(errors.CodeUnauthenticated, "token is not active") // Surface every inactive PAT through one stable authentication failure. } if record.ExpiresAt != nil && time.Now().UTC().After(record.ExpiresAt.UTC()) { // Reject expired PATs before the secret hash comparison because expired credentials must never authenticate again. return nil, errors.New(errors.CodeTokenExpired, "token expired") // Surface PAT expiry distinctly so callers can distinguish expiry from bad secrets. } - secretHash := sha256.Sum256([]byte(secret)) // Hash the presented secret exactly once so it can be compared against the stored authoritative digest. - encodedHash := hex.EncodeToString(secretHash[:]) // Normalize the presented secret hash into the same lowercase hex format stored by the source of truth. - if encodedHash != strings.TrimSpace(record.SecretHash) { // Reject mismatched secret digests because the presented PAT secret does not match the authoritative record. + secretHash := sha256.Sum256([]byte(secret)) // Hash the presented secret exactly once so it can be compared against the stored authoritative digest. + encodedHash := hex.EncodeToString(secretHash[:]) // Normalize the presented secret hash into the same lowercase hex format stored by the source of truth. + if subtle.ConstantTimeCompare([]byte(encodedHash), []byte(strings.TrimSpace(record.SecretHash))) != 1 { // Compare equal-length hexadecimal digests without data-dependent early exit. return nil, errors.New(errors.CodeUnauthenticated, "invalid token secret") // Surface secret mismatches as standard authentication failures. } @@ -70,7 +77,7 @@ func (v *PATValidator) Validate(ctx context.Context, token string) (*Subject, er subjectID = record.TokenID // Preserve a stable authenticated subject identifier even for legacy static PAT records that do not store subject IDs explicitly. } - return &Subject{ID: subjectID, Type: "pat", TenantID: strings.TrimSpace(record.TenantID), Scopes: scopes}, nil // Return the authenticated PAT subject for downstream tenant-aware request handling. + return &Subject{ID: subjectID, Type: "pat", CredentialID: strings.TrimSpace(record.TokenID), TenantID: strings.TrimSpace(record.TenantID), Scopes: scopes}, nil // Return the authenticated PAT subject with its safe token identifier for downstream authorization and audit. } // splitPATToken parses one PAT bearer token in the repository wire format and returns the token ID plus secret components. diff --git a/internal/config/loader.go b/internal/config/loader.go index ed6460c..3dd92b4 100644 --- a/internal/config/loader.go +++ b/internal/config/loader.go @@ -15,9 +15,14 @@ import ( // Load reads configuration from file and environment variables. func Load(path string) (*Config, error) { - cfg := &Config{} + cfg := &Config{} // Allocate one zero-value config before tagged defaults and external sources are layered in precedence order. - // 1. Load from file if exists + // 1. Apply tagged defaults before decoding so explicit false, zero, and empty values in YAML remain authoritative. + if err := applyDefaults(cfg); err != nil { // Seed omitted fields without overwriting values supplied by later sources. + return nil, err // Preserve the precise default parsing failure for startup diagnostics. + } + + // 2. Load from file if exists if path != "" { f, err := os.Open(path) if err == nil { @@ -31,15 +36,6 @@ func Load(path string) (*Config, error) { } } - // 2. Apply defaults (if zero values need to be overwritten by non-zero defaults) - // Note: In this implementation, we rely on struct tags or explicit setting if needed. - // Since Go zero values are 0/false/"", we might want to set defaults before loading file? - // Actually, the struct tags `default:"..."` are not automatically handled by standard json/yaml. - // We will implement a simple default setter based on tags. - if err := applyDefaults(cfg); err != nil { - return nil, err - } - // 3. Apply Environment Overrides if err := applyEnvOverrides(cfg); err != nil { return nil, err diff --git a/internal/config/loader_test.go b/internal/config/loader_test.go index 0f9fe22..73b7b07 100644 --- a/internal/config/loader_test.go +++ b/internal/config/loader_test.go @@ -61,3 +61,22 @@ func TestLoadAppliesDefaultsAndEnvOverrides(t *testing.T) { t.Fatal("expected gateway disable_adb_shell_tool override to be true") // Surface the unexpected flag value so operator feature-gate regressions are obvious. } } + +// TestLoadPreservesExplicitFalse verifies that YAML false overrides a tagged true default instead of being replaced after decoding. +func TestLoadPreservesExplicitFalse(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.yaml") // Allocate one isolated file path for the explicit-false configuration fixture. + configYAML := "gateway:\n port: 18080\nstorage:\n postgres:\n dsn: postgres://postgres:postgres@127.0.0.1:5432/mcp_mobile_worker?sslmode=disable\nauth:\n enable_pat: false\n pat_static_tokens:\n legacy-token: hash|tenant-1|active\n" // Supply a legacy static source while explicitly disabling its legacy activation flag. + if err := os.WriteFile(configPath, []byte(configYAML), 0o644); err != nil { // Persist the fixture for the production YAML loader. + t.Fatalf("failed to write explicit-false config: %v", err) // Surface setup failure before configuration assertions run. + } + cfg, err := Load(configPath) // Load defaults, then the explicit YAML value, then compatibility normalization. + if err != nil { // Fail when the otherwise valid configuration cannot be loaded. + t.Fatalf("expected explicit-false config to load, got %v", err) // Surface unexpected validation or precedence failures. + } + if cfg.Auth.EnablePAT { // Require the explicit YAML false to remain authoritative over the default true tag. + t.Fatal("expected auth.enable_pat to remain false") // Surface the security-sensitive defaulting regression directly. + } + if cfg.Auth.PAT.Mode != "disabled" { // Require compatibility normalization to respect the preserved false flag. + t.Fatalf("expected legacy PAT mode disabled, got %q", cfg.Auth.PAT.Mode) // Surface accidental authentication activation. + } +} diff --git a/internal/errors/codes.go b/internal/errors/codes.go index 46d9cfd..6c1880c 100644 --- a/internal/errors/codes.go +++ b/internal/errors/codes.go @@ -1,6 +1,7 @@ package errors import ( + stdErrors "errors" "fmt" "net/http" @@ -112,8 +113,8 @@ func WrapPreservingCode(msg string, err error) *Error { // MapToGRPC maps an internal error to a gRPC status error. func MapToGRPC(err error) error { - e, ok := err.(*Error) - if !ok { + var e *Error // Allocate a typed target so wrapped and joined repository errors preserve their transport classification. + if !stdErrors.As(err, &e) { // Search the complete error chain instead of requiring the repository error at the outermost layer. return status.Error(codes.Unknown, err.Error()) } @@ -148,8 +149,8 @@ func MapToGRPC(err error) error { // MapToHTTP maps an internal error to an HTTP status code. func MapToHTTP(err error) int { - e, ok := err.(*Error) - if !ok { + var e *Error // Allocate a typed target so wrapped and joined repository errors preserve their HTTP classification. + if !stdErrors.As(err, &e) { // Search the complete error chain instead of requiring the repository error at the outermost layer. return http.StatusInternalServerError } @@ -186,14 +187,13 @@ type JSONRPCError struct { // MapToJSONRPC maps an internal error to a JSON-RPC error. func MapToJSONRPC(err error) *JSONRPCError { - e, ok := err.(*Error) - if !ok { - return &JSONRPCError{ // Return unknown error types with raw text for direct diagnostics. + var e *Error // Allocate a typed target so wrapped and joined repository errors preserve their JSON-RPC classification. + if !stdErrors.As(err, &e) { // Search the complete error chain instead of requiring the repository error at the outermost layer. + return &JSONRPCError{ // Return unknown error types with a stable classification and no wrapped backend text. Code: -32603, // Use JSON-RPC internal error code for non-standard error wrappers. Message: "Internal error", - Data: map[string]interface{}{ // Return structured data instead of plain string for consistency with MCP. - "internalCode": "", // Leave code empty when no standardized internal code is available. - "rawError": err.Error(), // Preserve original/native error for clients. + Data: map[string]interface{}{ // Return only the stable internal classification for programmatic handling. + "internalCode": string(CodeInternal), // Classify untyped server failures without exposing their raw text. }, } } @@ -214,20 +214,19 @@ func MapToJSONRPC(err error) *JSONRPCError { code = -32603 // Internal error } - return &JSONRPCError{ // Return mapped JSON-RPC error with internal and raw details. + return &JSONRPCError{ // Return the mapped JSON-RPC error with only its stable internal classification. Code: code, // Keep mapped transport-level JSON-RPC code. Message: e.Message, // Keep concise business-facing message. - Data: map[string]interface{}{ // Include both stable internal code and full wrapped chain. + Data: map[string]interface{}{ // Include the stable internal code without exposing the wrapped cause chain. "internalCode": string(e.Code), // Expose standardized internal code for programmatic handling. - "rawError": e.Error(), // Expose full wrapped error string for debugging/root-cause analysis. }, } } // CodeOf extracts the internal error code, if present. func CodeOf(err error) (ErrorCode, bool) { - e, ok := err.(*Error) - if !ok { + var e *Error // Allocate a typed target so wrapped and joined errors expose their first repository classification. + if !stdErrors.As(err, &e) { // Search the complete error chain instead of requiring the repository error at the outermost layer. return "", false } return e.Code, true diff --git a/internal/errors/codes_test.go b/internal/errors/codes_test.go index 15a4546..78b3b32 100644 --- a/internal/errors/codes_test.go +++ b/internal/errors/codes_test.go @@ -28,6 +28,9 @@ func TestMapToJSONRPCIncludesInternalCode(t *testing.T) { if data["internalCode"] != string(CodePlanInvalid) { // Fail the test when the internal code is lost during JSON-RPC mapping. t.Fatalf("expected internal code %q, got %#v", CodePlanInvalid, data["internalCode"]) // Surface the unexpected internal code so machine-handling regressions are obvious. } + if _, exists := data["rawError"]; exists { // Reject reintroduction of wrapped backend diagnostics into externally visible JSON-RPC data. + t.Fatalf("expected rawError to be omitted, got %#v", data["rawError"]) // Surface the unsafe field immediately when sanitization regresses. + } } // TestIsCodeMatchesWrappedErrors verifies that the convenience helper recognizes wrapped repository errors by their standardized code. diff --git a/internal/gateway/httpinput/body.go b/internal/gateway/httpinput/body.go new file mode 100644 index 0000000..067d26f --- /dev/null +++ b/internal/gateway/httpinput/body.go @@ -0,0 +1,72 @@ +// body.go centralizes bounded HTTP request-body reading and strict single-document JSON decoding for gateway transports. +package httpinput + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" +) + +const MaxRequestBodyBytes int64 = 1 << 20 // MaxRequestBodyBytes limits protected gateway request bodies to one mebibyte. + +// LimitBody rejects declared oversized requests and wraps accepted bodies with net/http's streaming size guard before authentication or dispatch. +func LimitBody(next http.Handler, maxBytes int64) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Wrap the downstream route so every body reader observes the same byte ceiling. + if r.ContentLength > maxBytes { // Reject a known oversized body before authentication spends work reading or hashing it. + http.Error(w, "request body too large", http.StatusRequestEntityTooLarge) // Return the standard HTTP status without reflecting request content. + return // Stop before invoking authentication or application handlers for the oversized request. + } + if r.Body != nil { // Install the streaming guard only when the request actually carries a body reader. + r.Body = http.MaxBytesReader(w, r.Body, maxBytes) // Convert reads beyond the configured ceiling into a typed MaxBytesError. + } + next.ServeHTTP(w, r) // Forward the bounded request to authentication and protocol dispatch. + }) +} + +// DecodeSingleJSON decodes exactly one JSON value, preserves integral identifiers as json.Number, and rejects trailing documents. +func DecodeSingleJSON(body io.Reader, destination interface{}) error { + if body == nil { // Reject a missing reader because every JSON transport request requires one document. + return errors.New("request body is required") // Return a stable parse failure without dereferencing a nil reader. + } + decoder := json.NewDecoder(body) // Create one streaming decoder over the already bounded request body. + decoder.UseNumber() // Preserve JSON integer text so request identifiers do not lose precision through float64 conversion. + if err := decoder.Decode(destination); err != nil { // Decode the sole expected JSON document into the transport envelope. + return err // Preserve syntax, type, and request-size failures for transport-specific mapping. + } + var trailing interface{} // Allocate a generic sink used only to detect a second JSON document after the first value. + if err := decoder.Decode(&trailing); err != io.EOF { // Require only optional whitespace and EOF after the first decoded document. + if err == nil { // Distinguish a successfully decoded second document from malformed trailing bytes. + return errors.New("request body must contain exactly one JSON value") // Reject concatenated JSON documents deterministically. + } + return err // Preserve malformed trailing-data diagnostics for the protocol parse-error response. + } + return nil // Confirm that one complete JSON value and no additional document were supplied. +} + +// ReadAndRestoreBody reads at most maxBytes from a request body and restores the exact bytes for downstream decoding after HMAC verification. +func ReadAndRestoreBody(r *http.Request, maxBytes int64) ([]byte, error) { + if r == nil { // Reject a missing request because there is no body stream to clone safely. + return nil, errors.New("request is required") // Return a deterministic error instead of panicking on a nil request. + } + if r.Body == nil { // Treat body-less requests as an empty signed payload. + return nil, nil // Preserve empty-body semantics without installing an unnecessary reader. + } + limitedBody := io.LimitReader(r.Body, maxBytes+1) // Read one sentinel byte beyond the limit so direct middleware use also detects oversized bodies. + body, err := io.ReadAll(limitedBody) // Materialize the bounded payload once for HMAC hashing and downstream replay. + if err != nil { // Preserve typed MaxBytesError values emitted by an outer net/http guard. + return nil, err // Return the body-read failure without restoring a partial and unverifiable payload. + } + if int64(len(body)) > maxBytes { // Detect oversized bodies when the middleware is invoked without the outer LimitBody wrapper. + return nil, &http.MaxBytesError{Limit: maxBytes} // Return the standard typed size error so callers can map it to HTTP 413. + } + r.Body = io.NopCloser(bytes.NewReader(body)) // Restore the exact accepted bytes so the protocol handler sees the signed payload unchanged. + return body, nil // Return the accepted payload bytes for canonical HMAC calculation. +} + +// IsBodyTooLarge reports whether an error chain contains net/http's request-body size sentinel. +func IsBodyTooLarge(err error) bool { + var sizeError *http.MaxBytesError // Allocate a typed target used by errors.As across wrapped authentication and parsing failures. + return errors.As(err, &sizeError) // Recognize direct and repository-wrapped body-limit failures consistently. +} diff --git a/internal/gateway/httpinput/body_test.go b/internal/gateway/httpinput/body_test.go new file mode 100644 index 0000000..3fe6d02 --- /dev/null +++ b/internal/gateway/httpinput/body_test.go @@ -0,0 +1,45 @@ +// body_test.go verifies gateway request-body size enforcement, strict JSON framing, and HMAC-safe body restoration. +package httpinput + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestLimitBodyRejectsDeclaredOversize verifies that known oversized requests stop before downstream authentication or dispatch. +func TestLimitBodyRejectsDeclaredOversize(t *testing.T) { + called := false // Track downstream execution so the test can prove early rejection rather than only checking the status. + handler := LimitBody(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { // Wrap one sentinel handler with the production body limiter. + called = true // Record any unsafe downstream invocation after the oversized body declaration. + w.WriteHeader(http.StatusNoContent) // Return a distinct status if the limiter accidentally forwards the request. + }), 4) + request := httptest.NewRequest(http.MethodPost, "/jsonrpc", strings.NewReader("12345")) // Build a five-byte request against a four-byte ceiling. + recorder := httptest.NewRecorder() // Capture the limiter response for status assertions. + handler.ServeHTTP(recorder, request) // Execute the oversized request through the production limiter. + if recorder.Code != http.StatusRequestEntityTooLarge { // Require the standard HTTP 413 transport classification. + t.Fatalf("expected status %d, got %d", http.StatusRequestEntityTooLarge, recorder.Code) // Surface the unexpected status for quick diagnosis. + } + if called { // Reject any downstream invocation because authentication must not read known oversized payloads. + t.Fatal("expected oversized request to stop before downstream handler") // Surface an ordering regression in the gateway middleware stack. + } +} + +// TestDecodeSingleJSONRejectsTrailingDocument verifies that concatenated JSON values cannot smuggle a second request past transport validation. +func TestDecodeSingleJSONRejectsTrailingDocument(t *testing.T) { + var destination map[string]interface{} // Allocate a generic destination matching the first valid JSON object. + err := DecodeSingleJSON(strings.NewReader(`{"first":true}{"second":true}`), &destination) // Decode two concatenated documents through the strict production helper. + if err == nil { // Reject successful decoding because only one top-level document is allowed per request. + t.Fatal("expected trailing JSON document to be rejected") // Surface framing regressions that could create parser differentials. + } +} + +// TestReadAndRestoreBodyEnforcesLimit verifies that direct HMAC body cloning cannot allocate beyond its configured ceiling. +func TestReadAndRestoreBodyEnforcesLimit(t *testing.T) { + request := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader("12345")) // Build a body one byte beyond the direct clone limit. + _, err := ReadAndRestoreBody(request, 4) // Exercise the production body clone without an outer MaxBytesReader. + if !IsBodyTooLarge(err) { // Require a typed size error so auth can map it to HTTP 413. + t.Fatalf("expected body-too-large error, got %v", err) // Surface accidental generic authentication classification. + } +} diff --git a/internal/gateway/jsonrpc/handler.go b/internal/gateway/jsonrpc/handler.go index d6b8197..b1639e9 100644 --- a/internal/gateway/jsonrpc/handler.go +++ b/internal/gateway/jsonrpc/handler.go @@ -1,14 +1,19 @@ package jsonrpc import ( + "bytes" "context" "encoding/json" + "math" + "math/big" "net/http" + "sync" "time" "mcp_for_appium/internal/config" "mcp_for_appium/internal/errors" "mcp_for_appium/internal/gateway/capabilities" + "mcp_for_appium/internal/gateway/httpinput" "mcp_for_appium/internal/gateway/mcp" "mcp_for_appium/internal/orchestrator" "mcp_for_appium/internal/storage/postgres" @@ -16,31 +21,39 @@ import ( ) type Handler struct { - orch *orchestrator.Service - mcpHandler *mcp.MCPHandler - capService *capabilities.Service - validator *Validator + orch *orchestrator.Service + mcpHandler *mcp.MCPHandler + capService *capabilities.Service + validator *Validator + inflightMu sync.Mutex + inflightRequests map[string]*inflightRequest } -// NewHandler executes this operation. +type inflightRequest struct { + cancel context.CancelFunc +} + +// NewHandler constructs a JSON-RPC protocol handler with MCP dispatch, capability discovery, schema validation, and request cancellation tracking. func NewHandler(orch *orchestrator.Service, capSvc *capabilities.Service) *Handler { adbShellEnabled := true // Default to the historical tool surface when no capability service is supplied. if capSvc != nil { // Read operator-shaped capability flags when discovery service wiring is available. adbShellEnabled = capSvc.ADBShellToolEnabled() // Reuse the capability service as the single gateway-level source of truth for adbShell exposure. } return &Handler{ - orch: orch, - mcpHandler: mcp.NewMCPHandlerWithConfig(orch, config.GatewayConfig{DisableADBShellTool: !adbShellEnabled}), - capService: capSvc, - validator: NewValidator(), + orch: orch, // Preserve the orchestrator dependency for legacy direct methods and MCP tool execution. + mcpHandler: mcp.NewMCPHandlerWithConfig(orch, config.GatewayConfig{DisableADBShellTool: !adbShellEnabled}), // Construct the MCP handler with the gateway-shaped tool surface. + capService: capSvc, // Preserve the capability service for direct describeCapabilities requests. + validator: NewValidator(), // Create the JSON-RPC schema validator used before dispatching schema-covered methods. + inflightRequests: make(map[string]*inflightRequest), // Initialize the cancellation registry so transports can register active request ids immediately. } } type Request struct { - JSONRPC string `json:"jsonrpc"` - Method string `json:"method"` - Params json.RawMessage `json:"params"` - ID interface{} `json:"id"` + JSONRPC string `json:"jsonrpc"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` + ID interface{} `json:"id"` + IDPresent bool `json:"-"` // IDPresent distinguishes an omitted notification id from an explicitly invalid JSON null id. } type Response struct { @@ -50,9 +63,155 @@ type Response struct { ID interface{} `json:"id"` } -// ProcessRequest processes a JSON-RPC request and returns the result or error -// This method is used by both HTTP and stdio transports +// UnmarshalJSON decodes one JSON-RPC request while retaining whether the wire envelope explicitly included the id member. +func (r *Request) UnmarshalJSON(data []byte) error { + type requestAlias Request // Disable recursive UnmarshalJSON calls while preserving the request field tags. + var decoded requestAlias // Hold the ordinarily decoded request fields before the id-presence marker is attached. + decoder := json.NewDecoder(bytes.NewReader(data)) // Decode from the exact custom-unmarshal input while controlling number representation. + decoder.UseNumber() // Preserve numeric request identifiers as their original JSON text instead of lossy float64 values. + if err := decoder.Decode(&decoded); err != nil { // Decode the request envelope with precision-preserving numeric semantics. + return err // Preserve the syntax or field decoding failure for the transport's parse-error response. + } + var fields map[string]json.RawMessage // Decode top-level members separately so an omitted id can be distinguished from JSON null. + if err := json.Unmarshal(data, &fields); err != nil { // Reuse JSON object decoding rather than inferring presence from a nil interface value. + return err // Preserve the object decoding failure for the transport's parse-error response. + } + *r = Request(decoded) // Copy the decoded JSON-RPC fields into the caller's request value. + _, r.IDPresent = fields["id"] // Record exact wire-level id presence so notification classification can reject explicit null. + return nil // Confirm that both request values and presence metadata were decoded successfully. +} + +// IsNotification reports whether one decoded JSON-RPC message is a notification that carries a method and completely omits the id member. +func IsNotification(req *Request) bool { + return req != nil && req.Method != "" && req.ID == nil && !req.IDPresent // Treat only method-bearing messages with no wire id member as notifications so explicit null remains invalid. +} + +// IsRequest reports whether one decoded JSON-RPC message carries a method and a valid string or integer request id. +func IsRequest(req *Request) bool { + return req != nil && req.Method != "" && validRequestID(req.ID) // Accept only MCP's string-or-integer id domain so malformed IDs cannot be dispatched as requests. +} + +// validRequestID reports whether one decoded or programmatically constructed value is a JSON string or mathematically integral JSON number. +func validRequestID(id interface{}) bool { + switch value := id.(type) { // Recognize decoder-produced numbers and common integer types used by internal tests and callers. + case string: + return true // Accept every JSON string, including an empty string, because MCP places no additional content restriction on string IDs. + case json.Number: + if !json.Valid([]byte(value.String())) { // Reject programmatically constructed json.Number values that are not valid standalone JSON numbers. + return false // Prevent malformed numeric text from entering response serialization or cancellation keys. + } + var integer big.Int // Allocate an arbitrary-precision integer so JSON-RPC ids are not limited to int64 or uint64. + _, ok := integer.SetString(value.String(), 10) // Require an exact base-10 integer literal with no fraction or exponent syntax. + return ok // Accept every valid arbitrary-size integer literal while preserving its exact wire representation. + case float64: + return !math.IsNaN(value) && !math.IsInf(value, 0) && math.Trunc(value) == value // Accept programmatic finite floats only when they represent a mathematical integer. + case float32: + floatValue := float64(value) // Promote the programmatic float for standard finite and truncation checks. + return !math.IsNaN(floatValue) && !math.IsInf(floatValue, 0) && math.Trunc(floatValue) == floatValue // Reject fractional or non-JSON float values. + case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + return true // Accept native integer types used by programmatic callers before JSON serialization. + default: + return false // Reject nil, null, booleans, arrays, objects, and every non-integral or unsupported identifier type. + } +} + +// RegisterInFlightRequest records one cancellable request id and returns a cleanup function that removes only that exact registry entry. +func (h *Handler) RegisterInFlightRequest(id interface{}, cancel context.CancelFunc) func() { + key, ok := requestIDKey(id) // Normalize the JSON-RPC id once so requests decoded through different Go numeric types still share the same cancellation key. + if h == nil || !ok || cancel == nil { // Skip registration when the handler, request id, or cancel hook is unavailable. + return func() {} // Return a no-op cleanup so callers can always defer the returned function safely. + } + + entry := &inflightRequest{cancel: cancel} // Allocate one entry pointer so cleanup can avoid deleting a newer request that reused the same id later. + h.inflightMu.Lock() // Lock the in-flight registry before mutating the shared request map. + if h.inflightRequests == nil { // Lazily initialize the map so zero-value handlers used in tests still avoid nil-map panics. + h.inflightRequests = make(map[string]*inflightRequest) // Allocate the registry map before storing the new request entry. + } + h.inflightRequests[key] = entry // Store the request cancel hook under the normalized JSON-RPC request id. + h.inflightMu.Unlock() // Release the registry lock before returning to request execution. + + return func() { h.unregisterInFlightRequest(key, entry) } // Return exact-entry cleanup so completed requests stop being cancellable without racing newer duplicate ids. +} + +// CancelInFlightRequest cancels the request matching id and reports whether an active request was found. +func (h *Handler) CancelInFlightRequest(id interface{}) bool { + key, ok := requestIDKey(id) // Normalize the cancellation request id using the same key function as registration. + if h == nil || !ok { // Treat missing handlers and malformed ids as benign unmatched cancellation notifications. + return false // Report no match so callers can log the late or invalid cancellation without surfacing a protocol error. + } + + h.inflightMu.Lock() // Lock the registry while reading and removing the matching in-flight entry. + entry, found := h.inflightRequests[key] // Read the active request entry for the normalized id. + if found { // Remove matched entries before invoking cancellation so repeated notifications stay idempotent. + delete(h.inflightRequests, key) // Delete the matched request from the registry so later cancellations do not repeat the same cancel call. + } + h.inflightMu.Unlock() // Release the registry lock before calling user code through the cancel function. + + if !found { // Treat late or unknown cancellation requests as benign no-ops. + return false // Report no match so callers can include the outcome in low-noise observability. + } + entry.cancel() // Cancel the in-flight request context so downstream handlers can stop work promptly. + return true // Report that one active request was cancelled. +} + +// unregisterInFlightRequest removes one registry entry only when it still points at the same request entry. +func (h *Handler) unregisterInFlightRequest(key string, entry *inflightRequest) { + if h == nil || entry == nil { // Ignore invalid cleanup calls because callers defer cleanup across several error paths. + return // Nothing can be removed safely without both a handler and the exact entry pointer. + } + + h.inflightMu.Lock() // Lock the registry before checking whether the entry is still current for this key. + if h.inflightRequests[key] == entry { // Delete only the original entry so duplicate request ids cannot be removed by an older cleanup. + delete(h.inflightRequests, key) // Remove the completed request from the cancellation registry. + } + h.inflightMu.Unlock() // Release the registry lock after the conditional cleanup is complete. +} + +// requestIDKey converts a JSON-RPC id into a stable map key and rejects nil or JSON null identifiers. +func requestIDKey(id interface{}) (string, bool) { + if id == nil { // Reject nil ids because notifications have no request id and therefore cannot be registered or cancelled. + return "", false // Report that no usable cancellation key exists for the provided id. + } + + encoded, err := json.Marshal(id) // Serialize the id through JSON so numeric ids decoded as int or float64 normalize to the same wire representation. + if err != nil { // Reject ids that cannot be represented as JSON because they are not valid JSON-RPC request identifiers. + return "", false // Report that no usable cancellation key exists for the malformed id. + } + key := string(encoded) // Use the compact JSON representation as the registry key so string and numeric ids remain distinct. + if key == "null" { // Reject explicit JSON null ids because this codebase treats nil ids as notifications. + return "", false // Report that null is not a usable cancellation key. + } + return key, true // Return the normalized id key so registration and cancellation can address the same request. +} + +// handleCancelledNotification decodes one MCP cancellation notification and cancels a matching in-flight request when present. +func (h *Handler) handleCancelledNotification(ctx context.Context, params json.RawMessage) (interface{}, error) { + logger := telemetry.WithContext(ctx) // Build context-enriched logging so cancellation observations carry request trace metadata when available. + var p struct { + RequestID interface{} `json:"requestId"` + Reason string `json:"reason"` + } + + decoder := json.NewDecoder(bytes.NewReader(params)) // Decode cancellation metadata from its exact raw JSON representation. + decoder.UseNumber() // Preserve a large numeric requestId so it matches the original in-flight request key exactly. + if err := decoder.Decode(&p); err != nil { // Decode the MCP cancellation payload so the original request id can be matched against the registry. + return nil, &mcp.MCPError{Code: -32602, Message: "Invalid params", Data: "failed to decode notifications/cancelled params"} // Return invalid-params for malformed cancellation payloads while transports suppress notification responses. + } + if p.RequestID == nil { // Reject cancellation payloads that omit requestId because no registry lookup can be performed. + return nil, &mcp.MCPError{Code: -32602, Message: "Invalid params", Data: "notifications/cancelled requestId is required"} // Return invalid-params so request-style misuse receives a stable protocol error. + } + + matched := h.CancelInFlightRequest(p.RequestID) // Cancel the matching registered request when it is still active. + logger.Info("mcp cancelled notification received", "request_id", p.RequestID, "reason", p.Reason, "matched", matched) // Record both matched and late cancellations without surfacing protocol errors for benign races. + return nil, nil // Cancellation notifications do not produce MCP result payloads. +} + +// ProcessRequest dispatches one JSON-RPC request or notification and returns the handler result for request-style calls. func (h *Handler) ProcessRequest(ctx context.Context, req *Request) (interface{}, error) { + if req == nil { // Reject nil messages before logging because there is no method or id to safely inspect. + return nil, &mcp.MCPError{Code: -32600, Message: "Invalid Request"} // Return the JSON-RPC invalid-request error instead of panicking on malformed internal calls. + } + logger := telemetry.WithContext(ctx) // Build context-enriched logger so per-request logs carry trace ids when available. startedAt := time.Now() // Capture dispatch start timestamp for duration reporting. logger.Info("jsonrpc process begin", "method", req.Method, "id", req.ID) // Log every JSON-RPC method entry for step-by-step tracing. @@ -60,6 +219,14 @@ func (h *Handler) ProcessRequest(ctx context.Context, req *Request) (interface{} var result interface{} var err error + if !IsRequest(req) && !IsNotification(req) { // Reject messages that are neither requests nor notifications because the dispatcher only handles method-bearing calls. + return nil, &mcp.MCPError{Code: -32600, Message: "Invalid Request"} // Return the JSON-RPC invalid-request error so transports expose stable protocol semantics. + } + modern, eraErr := validateRequestEra(req) // Classify this message from its own params._meta instead of relying on transport or connection state. + if eraErr != nil { // Reject malformed metadata, unavailable versions, and methods removed from the modern protocol before dispatch. + return nil, eraErr // Preserve the exact modern MCP error code and retry metadata for the transport response. + } + if h.validator != nil { if vErr := h.validator.Validate(req.Method, req.Params); vErr != nil { return nil, vErr @@ -68,14 +235,28 @@ func (h *Handler) ProcessRequest(ctx context.Context, req *Request) (interface{} switch req.Method { // ===== MCP Protocol Methods ===== + case "server/discover": + result, err = h.mcpHandler.Discover(req.Params) // Return mandatory modern discovery metadata through the same MCP handler used by other server features. case "initialize": result, err = h.mcpHandler.Initialize(ctx, req.Params) + case "notifications/initialized": + logger.Info("mcp initialized notification received", "method", req.Method) // Record the lifecycle notification at low noise because clients are expected to send it after initialize. + case "notifications/cancelled": + result, err = h.handleCancelledNotification(ctx, req.Params) // Resolve the cancellation notification through the in-flight registry shared by all transports. + case "ping": + result = map[string]interface{}{} // Return the minimal MCP ping payload so clients can verify liveness without invoking business logic. case "tools/list": result, err = h.mcpHandler.ToolsList(ctx, req.Params) case "tools/call": result, err = h.mcpHandler.ToolsCall(ctx, req.Params) case "resources/list": - result, err = h.mcpHandler.ResourcesList(ctx, req.Params) + if modern { // Separate concrete modern resources from the URI templates historically returned to legacy clients. + result, err = h.mcpHandler.ModernResourcesList(ctx, req.Params) // Return the current caller's concrete resource set using the modern protocol shape. + } else { + result, err = h.mcpHandler.ResourcesList(ctx, req.Params) // Preserve the repository's historical template-like resources/list response for legacy clients. + } + case "resources/templates/list": + result, err = h.mcpHandler.ResourcesTemplatesList(ctx, req.Params) // Return parameterized Appium resources through the standard resource-template method. case "resources/read": result, err = h.mcpHandler.ResourcesRead(ctx, req.Params) @@ -384,6 +565,10 @@ func (h *Handler) ProcessRequest(ctx context.Context, req *Request) (interface{} case "replay", "subscribe", "unsubscribe": return nil, errors.New(errors.CodeStepUnsupported, "method not implemented: "+req.Method) default: + if IsNotification(req) { // Silently ignore unknown notifications because JSON-RPC notifications must not elicit protocol errors on the wire. + logger.Info("jsonrpc notification ignored", "method", req.Method) // Record the ignored notification at low noise so operators can still trace unexpected client traffic. + break + } return nil, &mcp.MCPError{ Code: -32601, Message: "Method not found", @@ -391,29 +576,65 @@ func (h *Handler) ProcessRequest(ctx context.Context, req *Request) (interface{} } if err != nil { + if IsNotification(req) { // Downgrade notification failures to info logging because transports intentionally suppress notification responses. + logger.Info("jsonrpc notification failed", "method", req.Method, "id", req.ID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Preserve observability for failed notifications without introducing error-level noise. + return nil, err + } logger.Error("jsonrpc process failed", "method", req.Method, "id", req.ID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Log method failures with latency and root error. return nil, err } + if modern && IsRequest(req) { // Add current-protocol result fields only to successful modern requests, never legacy responses or notifications. + result, err = mcp.DecorateModernResult(req.Method, result) // Normalize the method result and attach method-specific current-protocol metadata. + if err != nil { // Surface an internal protocol error when a handler produced a non-object modern result. + logger.Error("jsonrpc modern result decoration failed", "method", req.Method, "id", req.ID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Record the server-side result-shape defect with request context. + return nil, err // Prevent a non-compliant success payload from reaching any transport. + } + } logger.Info("jsonrpc process done", "method", req.Method, "id", req.ID, "duration_ms", time.Since(startedAt).Milliseconds()) // Log successful completion with total dispatch latency. return result, nil } -// ServeHTTP implements http.Handler for HTTP-based JSON-RPC +// ServeHTTP implements the compatibility HTTP JSON-RPC transport while suppressing responses for notifications. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - var req Request - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if r.ContentLength > httpinput.MaxRequestBodyBytes { // Reject known oversized compatibility requests before reading or decoding their payload. + h.writeErrorStatus(w, http.StatusRequestEntityTooLarge, nil, -32600, "Invalid Request", "request body too large") // Return HTTP 413 with a sanitized JSON-RPC envelope. + return // Stop request processing after the declared-size rejection. + } + r.Body = http.MaxBytesReader(w, r.Body, httpinput.MaxRequestBodyBytes) // Enforce the compatibility transport's body ceiling even without the outer gateway middleware. + var req Request // Allocate the JSON-RPC request envelope before strict single-document decoding. + if err := httpinput.DecodeSingleJSON(r.Body, &req); err != nil { // Decode exactly one bounded JSON value and reject concatenated request documents. + if httpinput.IsBodyTooLarge(err) { // Map the typed body-limit failure to its transport-level status before ordinary parse errors. + h.writeErrorStatus(w, http.StatusRequestEntityTooLarge, nil, -32600, "Invalid Request", "request body too large") // Return HTTP 413 with a sanitized JSON-RPC envelope. + return // Stop request processing after the size rejection. + } h.writeError(w, nil, -32700, "Parse error", nil) return } if req.JSONRPC != "2.0" { + if IsNotification(&req) { // Suppress invalid-version notification responses because JSON-RPC notifications must not receive reply envelopes. + w.WriteHeader(http.StatusNoContent) // Return HTTP 204 so the compatibility endpoint closes the exchange without a JSON-RPC body. + return + } h.writeError(w, req.ID, -32600, "Invalid Request", nil) return } - ctx := r.Context() - result, err := h.ProcessRequest(ctx, &req) + ctx := r.Context() // Start from the HTTP request context so client disconnects and server shutdown still cancel work. + if IsRequest(&req) { // Register only request-style messages because notifications have no response id to cancel later. + requestCtx, cancel := context.WithCancel(ctx) // Create a cancellable child context that notifications/cancelled can trigger through the in-flight registry. + cleanup := h.RegisterInFlightRequest(req.ID, cancel) // Record the request id before dispatch so concurrent HTTP cancellation notifications can find it. + defer cleanup() // Remove the request from the registry once dispatch completes or errors. + defer cancel() // Release context resources after dispatch even when no cancellation notification arrives. + ctx = requestCtx // Pass the cancellable child context into downstream handlers. + } + result, err := h.ProcessRequest(ctx, &req) // Dispatch the request or notification through the shared JSON-RPC protocol handler. + + if IsNotification(&req) { // Suppress notification responses because JSON-RPC notifications are fire-and-forget messages. + w.WriteHeader(http.StatusNoContent) // Return HTTP 204 so the compatibility endpoint completes cleanly without emitting a response object. + return + } if err != nil { // Check if it's an MCP error @@ -449,7 +670,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // writeError executes this operation. func (h *Handler) writeError(w http.ResponseWriter, id interface{}, code int, msg string, data interface{}) { - h.writeResponse(w, Response{ + h.writeResponse(w, Response{ // Preserve the historical HTTP 200 envelope for ordinary compatibility JSON-RPC errors. JSONRPC: "2.0", Error: &errors.JSONRPCError{ Code: code, @@ -460,8 +681,27 @@ func (h *Handler) writeError(w http.ResponseWriter, id interface{}, code int, ms }) } +// writeErrorStatus writes one JSON-RPC error envelope using an explicit HTTP transport status for pre-dispatch limits such as oversized bodies. +func (h *Handler) writeErrorStatus(w http.ResponseWriter, status int, id interface{}, code int, msg string, data interface{}) { + h.writeResponseStatus(w, status, Response{ // Serialize the supplied protocol error with the transport-level rejection status. + JSONRPC: "2.0", // Identify the response envelope as JSON-RPC 2.0. + Error: &errors.JSONRPCError{ // Attach the supplied stable error classification and sanitized data. + Code: code, // Preserve the caller-selected JSON-RPC error code. + Message: msg, // Preserve the caller-selected public error message. + Data: data, // Preserve only the caller-selected safe diagnostic payload. + }, + ID: id, // Echo the request identifier when decoding reached it, or null for pre-envelope failures. + }) +} + // writeResponse executes this operation. func (h *Handler) writeResponse(w http.ResponseWriter, resp Response) { - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(resp) + h.writeResponseStatus(w, http.StatusOK, resp) // Preserve the compatibility transport's historical HTTP 200 response status. +} + +// writeResponseStatus serializes one JSON-RPC response with an explicit HTTP status. +func (h *Handler) writeResponseStatus(w http.ResponseWriter, status int, resp Response) { + w.Header().Set("Content-Type", "application/json") // Mark every compatibility response as JSON before writing its status. + w.WriteHeader(status) // Emit the explicit transport status before serializing the response envelope. + _ = json.NewEncoder(w).Encode(resp) // Encode the response while ignoring late network write failures after headers are committed. } diff --git a/internal/gateway/jsonrpc/handler_test.go b/internal/gateway/jsonrpc/handler_test.go index 5a4e441..e6d70d2 100644 --- a/internal/gateway/jsonrpc/handler_test.go +++ b/internal/gateway/jsonrpc/handler_test.go @@ -15,6 +15,45 @@ import ( mcperrors "mcp_for_appium/internal/gateway/mcp" ) +// TestServeHTTPRejectsOversizedBody verifies that the compatibility transport applies the shared request-body ceiling when mounted directly. +func TestServeHTTPRejectsOversizedBody(t *testing.T) { + handler := NewHandler(nil, nil) // Construct the protocol handler without application dependencies. + request := httptest.NewRequest(http.MethodPost, "/jsonrpc", strings.NewReader(strings.Repeat("x", (1<<20)+1))) // Build a body one byte larger than the shared ceiling. + recorder := httptest.NewRecorder() // Capture the explicit HTTP size rejection. + handler.ServeHTTP(recorder, request) // Execute the oversized request through the direct compatibility handler. + if recorder.Code != http.StatusRequestEntityTooLarge { // Require HTTP 413 instead of an ordinary JSON-RPC HTTP 200 parse envelope. + t.Fatalf("expected status %d, got %d", http.StatusRequestEntityTooLarge, recorder.Code) // Surface incorrect transport mapping for the size limit. + } +} + +// TestServeHTTPRejectsTrailingJSONDocument verifies that the compatibility transport accepts exactly one request document per body. +func TestServeHTTPRejectsTrailingJSONDocument(t *testing.T) { + handler := NewHandler(nil, nil) // Construct the protocol handler without application dependencies. + request := httptest.NewRequest(http.MethodPost, "/jsonrpc", strings.NewReader(`{"jsonrpc":"2.0","method":"ping","id":1}{"jsonrpc":"2.0","method":"ping","id":2}`)) // Build two concatenated valid JSON-RPC requests. + recorder := httptest.NewRecorder() // Capture the compatibility parse-error response. + handler.ServeHTTP(recorder, request) // Execute the concatenated documents through strict decoding. + if recorder.Code != http.StatusOK { // Preserve compatibility HTTP 200 while requiring a JSON-RPC parse error body. + t.Fatalf("expected compatibility status %d, got %d", http.StatusOK, recorder.Code) // Surface accidental transport behavior drift. + } + if !strings.Contains(recorder.Body.String(), `"code":-32700`) { // Require the JSON-RPC parse-error classification in the response envelope. + t.Fatalf("expected parse error response, got %s", recorder.Body.String()) // Surface accidental dispatch or malformed error serialization. + } +} + +// TestServeHTTPEchoesLargeNumericIDExactly verifies that compatibility JSON-RPC decoding never rounds request identifiers through float64. +func TestServeHTTPEchoesLargeNumericIDExactly(t *testing.T) { + handler := NewHandler(nil, nil) // Construct the protocol-only handler because ping does not require application dependencies. + request := httptest.NewRequest(http.MethodPost, "/jsonrpc", strings.NewReader(`{"jsonrpc":"2.0","method":"ping","id":9007199254740993}`)) // Send the first integer above IEEE-754's exact range so any float64 conversion becomes visible. + recorder := httptest.NewRecorder() // Capture the serialized response identifier for exact textual comparison. + handler.ServeHTTP(recorder, request) // Execute the request through strict body decoding and the custom request unmarshaler. + if recorder.Code != http.StatusOK { // Preserve the compatibility transport's successful HTTP status. + t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, recorder.Code, recorder.Body.String()) // Surface transport and body details on failure. + } + if !strings.Contains(recorder.Body.String(), `"id":9007199254740993`) { // Require exact wire-value echoing instead of the rounded adjacent integer. + t.Fatalf("expected exact large numeric id in response, got %s", recorder.Body.String()) // Surface the serialized response for precision diagnosis. + } +} + // TestProcessRequestReturnsCapabilities verifies that the direct JSON-RPC describeCapabilities method delegates to the capability service. func TestProcessRequestReturnsCapabilities(t *testing.T) { handler := NewHandler(nil, capabilities.NewService(config.GatewayConfig{})) // Construct one handler with no orchestrator dependency because describeCapabilities only depends on the capability service. @@ -59,8 +98,8 @@ func TestValidatorRejectsInvalidStartSessionPayload(t *testing.T) { // TestProcessRequestReturnsMethodNotFoundMCPError verifies that unknown methods still map to the MCP-compatible method-not-found error shape. func TestProcessRequestReturnsMethodNotFoundMCPError(t *testing.T) { - handler := NewHandler(nil, nil) // Construct one handler with no orchestrator dependency because unknown-method dispatch exits before any service call. - request := &Request{JSONRPC: "2.0", Method: "methodThatDoesNotExist", Params: json.RawMessage(`{}`)} // Build one direct unknown-method request so the fallback dispatch path can be exercised directly. + handler := NewHandler(nil, nil) // Construct one handler with no orchestrator dependency because unknown-method dispatch exits before any service call. + request := &Request{JSONRPC: "2.0", Method: "methodThatDoesNotExist", Params: json.RawMessage(`{}`), ID: "req-unknown"} // Build one direct unknown-method request with an id so the fallback request path is exercised instead of notification semantics. if _, err := handler.ProcessRequest(context.Background(), request); err == nil { // Execute the production JSON-RPC fallback path for one unknown method. t.Fatal("expected unknown method to fail") // Surface the missing failure because clients depend on stable method-not-found behavior. @@ -69,6 +108,295 @@ func TestProcessRequestReturnsMethodNotFoundMCPError(t *testing.T) { } } +// TestProcessRequestSilentlyIgnoresUnknownNotification verifies that unsupported notifications are consumed without surfacing a protocol error. +func TestProcessRequestSilentlyIgnoresUnknownNotification(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler with no orchestrator dependency because the test exercises only notification classification and fallback behavior. + request := &Request{JSONRPC: "2.0", Method: "methodThatDoesNotExist", Params: json.RawMessage(`{}`)} // Build one unknown notification without an id so the notification-ignore path is exercised directly. + + result, err := handler.ProcessRequest(context.Background(), request) // Execute the production fallback dispatch path for one unsupported notification. + if err != nil { // Fail when unsupported notifications unexpectedly surface protocol errors to the shared handler boundary. + t.Fatalf("expected unknown notification to be ignored, got error: %v", err) // Surface the unexpected error so notification regressions are obvious. + } + if result != nil { // Fail when unsupported notifications unexpectedly produce one result payload. + t.Fatalf("expected unknown notification to return nil result, got %#v", result) // Surface the unexpected payload so notification regressions are obvious. + } +} + +// TestProcessRequestAcceptsInitializedNotification verifies that the MCP initialized lifecycle notification is accepted silently. +func TestProcessRequestAcceptsInitializedNotification(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler without orchestrator dependencies because the initialized notification is pure protocol bookkeeping. + request := &Request{JSONRPC: "2.0", Method: "notifications/initialized", Params: json.RawMessage(`{}`)} // Build one initialized notification payload with no id so notification semantics are exercised directly. + + result, err := handler.ProcessRequest(context.Background(), request) // Execute the production notification dispatch path directly at the JSON-RPC handler boundary. + if err != nil { // Fail when the initialized notification unexpectedly returns a protocol error. + t.Fatalf("expected initialized notification to succeed, got error: %v", err) // Surface the unexpected error so lifecycle-handshake regressions are obvious. + } + if result != nil { // Fail when the notification unexpectedly produces a result payload because notifications must not carry responses. + t.Fatalf("expected initialized notification to return nil result, got %#v", result) // Surface the unexpected payload so notification regressions are obvious. + } + if !IsNotification(request) { // Fail when the shared message classifier no longer recognizes initialized as a notification. + t.Fatal("expected initialized message to be classified as notification") // Surface the classifier regression because transports depend on it to suppress responses. + } +} + +// TestProcessRequestCancelledNotificationCancelsInflightRequest verifies that notifications/cancelled cancels one matching registered request. +func TestProcessRequestCancelledNotificationCancelsInflightRequest(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler without orchestrator dependencies because this test exercises only protocol-level cancellation bookkeeping. + requestCtx, cancel := context.WithCancel(context.Background()) // Create one cancellable context that represents an active request registered by a transport. + cleanup := handler.RegisterInFlightRequest("req-cancel", cancel) // Register the request id exactly as a transport would before dispatching work. + defer cleanup() // Ensure the registry is cleaned even if the cancellation assertion fails. + request := &Request{JSONRPC: "2.0", Method: "notifications/cancelled", Params: json.RawMessage(`{"requestId":"req-cancel","reason":"client timeout"}`)} // Build one cancellation notification that targets the registered request id. + + result, err := handler.ProcessRequest(context.Background(), request) // Execute the production cancellation notification dispatch path. + if err != nil { // Fail when a valid cancellation notification unexpectedly returns a protocol error. + t.Fatalf("expected cancellation notification to succeed, got error: %v", err) // Surface the unexpected error so cancellation regressions are obvious. + } + if result != nil { // Fail when the notification unexpectedly produces a result payload. + t.Fatalf("expected cancellation notification to return nil result, got %#v", result) // Surface the unexpected payload so notification regressions are obvious. + } + select { // Check the request context synchronously because CancelInFlightRequest invokes the cancel function before returning. + case <-requestCtx.Done(): // Observe the cancelled request context to prove the registry invoked the registered cancel function. + default: + t.Fatal("expected cancellation notification to cancel registered request") // Surface the missing cancellation because clients depend on request-id cancellation semantics. + } +} + +// TestProcessRequestCancelledNotificationPreservesLargeNumericID verifies that cancellation lookup uses the same exact json.Number representation as request decoding. +func TestProcessRequestCancelledNotificationPreservesLargeNumericID(t *testing.T) { + handler := NewHandler(nil, nil) // Construct the protocol handler whose in-flight registry is under test. + requestCtx, cancel := context.WithCancel(context.Background()) // Create one observable cancellation target for the large numeric id. + cleanup := handler.RegisterInFlightRequest(json.Number("9007199254740993"), cancel) // Register the exact integer text preserved by request decoding. + defer cleanup() // Remove any unmatched entry if the test exits before cancellation succeeds. + notification := &Request{JSONRPC: "2.0", Method: "notifications/cancelled", Params: json.RawMessage(`{"requestId":9007199254740993,"reason":"client timeout"}`)} // Send the same large integer through cancellation-param decoding. + if _, err := handler.ProcessRequest(context.Background(), notification); err != nil { // Process the notification through the production cancellation path. + t.Fatalf("expected large-id cancellation notification to succeed, got error: %v", err) // Surface decode or key-normalization regressions. + } + select { + case <-requestCtx.Done(): + // The exact large numeric key matched and invoked the registered cancellation function. + default: + t.Fatal("expected large numeric request id to match the inflight cancellation key") // Surface silent numeric rounding or representation mismatch. + } +} + +// TestProcessRequestCancelledNotificationIgnoresLateRequest verifies that cancellation for an already-completed request is a benign no-op. +func TestProcessRequestCancelledNotificationIgnoresLateRequest(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler without orchestrator dependencies because this test exercises only late-cancellation handling. + request := &Request{JSONRPC: "2.0", Method: "notifications/cancelled", Params: json.RawMessage(`{"requestId":"missing-request","reason":"late"}`)} // Build one cancellation notification for a request id that is not registered. + + result, err := handler.ProcessRequest(context.Background(), request) // Execute the production cancellation notification dispatch path for the missing request id. + if err != nil { // Fail when late cancellation unexpectedly surfaces a protocol error. + t.Fatalf("expected late cancellation notification to be ignored, got error: %v", err) // Surface the unexpected error so benign cancellation races remain supported. + } + if result != nil { // Fail when late cancellation unexpectedly produces a result payload. + t.Fatalf("expected late cancellation notification to return nil result, got %#v", result) // Surface the unexpected payload so notification regressions are obvious. + } +} + +// TestProcessRequestReturnsPingResult verifies that the MCP ping method returns the required empty object payload. +func TestProcessRequestReturnsPingResult(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler without orchestrator dependencies because ping is a pure protocol liveness method. + request := &Request{JSONRPC: "2.0", Method: "ping", Params: json.RawMessage(`{}`), ID: 9} // Build one ping request with an id so request semantics are exercised directly. + + result, err := handler.ProcessRequest(context.Background(), request) // Execute the production ping dispatch path directly at the JSON-RPC handler boundary. + if err != nil { // Fail when ping unexpectedly returns a protocol error. + t.Fatalf("expected ping to succeed, got error: %v", err) // Surface the unexpected error so liveness regressions are obvious. + } + payload, ok := result.(map[string]interface{}) // Decode the generic ping result so the empty-object response shape can be asserted directly. + if !ok { // Fail when ping no longer returns a structured object payload. + t.Fatalf("expected ping response map, got %#v", result) // Surface the unexpected payload type so liveness regressions are obvious. + } + if len(payload) != 0 { // Fail when ping no longer returns the required empty object payload. + t.Fatalf("expected empty ping response, got %#v", payload) // Surface the unexpected payload content so liveness regressions are obvious. + } + if !IsRequest(request) { // Fail when the shared message classifier no longer recognizes ping with an id as a request. + t.Fatal("expected ping message to be classified as request") // Surface the classifier regression because transports depend on it to emit responses. + } +} + +// TestRequestClassificationRejectsInvalidIDs verifies that explicit null and fractional request IDs are not mistaken for notifications or valid MCP requests. +func TestRequestClassificationRejectsInvalidIDs(t *testing.T) { + var nullIDRequest Request // Allocate one request that will be populated through the production custom JSON decoder. + if err := json.Unmarshal([]byte(`{"jsonrpc":"2.0","method":"tools/list","params":{},"id":null}`), &nullIDRequest); err != nil { // Decode an explicitly null id so wire presence can be asserted. + t.Fatalf("expected null-id envelope to decode, got %v", err) // Surface unexpected JSON decoding failures before classification assertions. + } + if !nullIDRequest.IDPresent || IsRequest(&nullIDRequest) || IsNotification(&nullIDRequest) { // Require explicit null to remain distinguishable from an omitted notification id. + t.Fatalf("expected explicit null id to be invalid, got %#v", nullIDRequest) // Surface all decoded request fields and presence metadata. + } + handler := NewHandler(nil, nil) // Construct one protocol-only handler because invalid request classification stops before method dispatch. + _, err := handler.ProcessRequest(context.Background(), &nullIDRequest) // Process the malformed request through the shared JSON-RPC boundary. + mcpErr, ok := err.(*mcperrors.MCPError) // Inspect the typed invalid-request error returned by classification. + if !ok || mcpErr.Code != -32600 { // Require the standard JSON-RPC Invalid Request code. + t.Fatalf("expected explicit null id error -32600, got %#v", err) // Surface the unexpected error type or code. + } + fractionalRequest := &Request{JSONRPC: "2.0", Method: "tools/list", Params: json.RawMessage(`{}`), ID: 1.5, IDPresent: true} // Build a programmatic request with a non-integral numeric id. + if IsRequest(fractionalRequest) || IsNotification(fractionalRequest) { // Reject fractional numbers from both valid message categories. + t.Fatalf("expected fractional id to be invalid, got %#v", fractionalRequest) // Surface the malformed request on classifier regression. + } +} + +// TestProcessRequestPreservesLegacyProgressMetadata verifies that a generic _meta.progressToken does not accidentally select modern protocol semantics. +func TestProcessRequestPreservesLegacyProgressMetadata(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler without an orchestrator because tools/list reads only embedded metadata. + params := json.RawMessage(`{"_meta":{"progressToken":"legacy-progress"}}`) // Build a legacy MCP request that uses the cross-era progress metadata member only. + request := &Request{JSONRPC: "2.0", Method: "tools/list", Params: params, ID: 91} // Build one initialization-era tool discovery request with generic metadata. + + result, err := handler.ProcessRequest(context.Background(), request) // Execute era classification and normal legacy tool discovery. + if err != nil { // Fail when progress metadata is mistaken for incomplete modern metadata. + t.Fatalf("expected legacy progress metadata to remain valid, got %v", err) // Surface the misclassification diagnostic. + } + resultObject, ok := result.(map[string]interface{}) // Read the undecorated legacy tool list result. + if !ok { // Require the ordinary object response shape. + t.Fatalf("expected legacy tools/list result object, got %#v", result) // Surface malformed legacy output. + } + if _, modernResult := resultObject["resultType"]; modernResult { // Ensure generic legacy metadata did not trigger modern result decoration. + t.Fatalf("expected legacy result without resultType, got %#v", resultObject) // Surface accidental modern-era selection. + } + if _, modernCache := resultObject["ttlMs"]; modernCache { // Ensure cache metadata introduced by current MCP is not emitted to initialization-era clients. + t.Fatalf("expected legacy result without ttlMs, got %#v", resultObject) // Surface accidental current-protocol cache leakage. + } +} + +// TestProcessRequestReturnsModernDiscovery verifies mandatory server discovery and result decoration directly on the shared stdio-compatible dispatch path. +func TestProcessRequestReturnsModernDiscovery(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler without business dependencies because discovery is pure protocol metadata. + params := json.RawMessage(`{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"stdio-test","version":"1.0.0"}}}`) // Build complete request-local modern metadata as a stdio client would send it. + request := &Request{JSONRPC: "2.0", Method: "server/discover", Params: params, ID: "discover"} // Build the mandatory discovery probe with an id so it receives one result. + + result, err := handler.ProcessRequest(context.Background(), request) // Execute discovery through the transport-independent JSON-RPC dispatcher. + if err != nil { // Fail when a complete modern discovery probe is rejected. + t.Fatalf("expected modern discovery to succeed, got %v", err) // Surface the protocol failure for metadata or dispatch debugging. + } + resultObject, ok := result.(map[string]interface{}) // Read the decorated discovery object returned to both stdio and HTTP transports. + if !ok { // Reject any non-object result because modern MCP success values require object results. + t.Fatalf("expected discovery result object, got %#v", result) // Surface the malformed result shape. + } + if resultObject["resultType"] != mcperrors.ResultTypeComplete { // Require the current protocol's explicit final-result discriminator. + t.Fatalf("expected complete resultType, got %#v", resultObject["resultType"]) // Surface the missing or incorrect discriminator. + } + supportedVersions, ok := resultObject["supportedVersions"].([]interface{}) // Read the JSON-normalized preference-ordered version list. + if !ok || len(supportedVersions) != 3 || supportedVersions[0] != mcperrors.CurrentProtocolVersion { // Require current plus two supported legacy revisions with modern first. + t.Fatalf("expected dual-era supported versions, got %#v", resultObject["supportedVersions"]) // Surface the negotiation metadata on regression. + } + resultMetadata, ok := resultObject["_meta"].(map[string]interface{}) // Read response-local server identity metadata added by the shared decorator. + if !ok || resultMetadata[mcperrors.ServerInfoMetaKey] == nil { // Require identity without relying on a previous initialize exchange. + t.Fatalf("expected modern serverInfo metadata, got %#v", resultObject["_meta"]) // Surface the malformed metadata object. + } +} + +// TestProcessRequestDecoratesModernToolsList verifies that shared dispatch adds current result fields while retaining deterministic catalog cache metadata. +func TestProcessRequestDecoratesModernToolsList(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler without an orchestrator because tools/list reads only embedded metadata. + params := json.RawMessage(`{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}`) // Build the minimum complete modern metadata object. + request := &Request{JSONRPC: "2.0", Method: "tools/list", Params: params, ID: 10} // Build one stateless tool discovery request. + + result, err := handler.ProcessRequest(context.Background(), request) // Execute tools/list through the same path used by stdio. + if err != nil { // Fail when valid modern tool discovery is rejected. + t.Fatalf("expected modern tools/list to succeed, got %v", err) // Surface the unexpected protocol or catalog error. + } + resultObject, ok := result.(map[string]interface{}) // Read the JSON-normalized and decorated result object. + if !ok { // Reject any non-object tool list response. + t.Fatalf("expected tools/list result object, got %#v", result) // Surface the malformed payload. + } + if resultObject["resultType"] != mcperrors.ResultTypeComplete || resultObject["cacheScope"] != mcperrors.CacheScopePublic { // Require completion and public cache semantics. + t.Fatalf("expected decorated public tools/list result, got %#v", resultObject) // Surface the entire compact result for field diagnosis. + } + if resultObject["ttlMs"] != mcperrors.CatalogCacheTTLMS { // Require the integer cache duration injected after modern result normalization. + t.Fatalf("expected tools/list ttlMs %d, got %#v", mcperrors.CatalogCacheTTLMS, resultObject["ttlMs"]) // Surface the actual cache duration. + } + tools, ok := resultObject["tools"].([]interface{}) // Read the normalized tool array returned to clients. + if !ok || len(tools) == 0 { // Require at least one discovered tool after registry construction. + t.Fatalf("expected non-empty modern tool catalog, got %#v", resultObject["tools"]) // Surface malformed or empty discovery data. + } +} + +// TestProcessRequestSeparatesModernResourcesAndTemplates verifies that current clients receive concrete resources and parameterized URI templates from their standard distinct methods. +func TestProcessRequestSeparatesModernResourcesAndTemplates(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one protocol-only handler because both resource catalog methods use static metadata. + params := json.RawMessage(`{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}`) // Build the minimum complete modern request metadata reused by both catalog requests. + resourcesRequest := &Request{JSONRPC: "2.0", Method: "resources/list", Params: params, ID: 14} // Request the concrete resource set through the current protocol method. + + resourcesResult, err := handler.ProcessRequest(context.Background(), resourcesRequest) // Execute modern resources/list through era-aware shared dispatch. + if err != nil { // Fail when the required resource-list method is rejected. + t.Fatalf("expected modern resources/list to succeed, got %v", err) // Surface the unexpected protocol or dispatch error. + } + resourcesObject, ok := resourcesResult.(map[string]interface{}) // Read the decorated concrete resource result. + if !ok { // Reject malformed non-object modern results. + t.Fatalf("expected resources/list result object, got %#v", resourcesResult) // Surface the actual result type and value. + } + resources, ok := resourcesObject["resources"].([]interface{}) // Read the JSON-normalized concrete resource array. + if !ok || len(resources) != 0 { // Require an explicit empty set because this server cannot enumerate caller-specific IDs. + t.Fatalf("expected empty concrete resource list, got %#v", resourcesObject["resources"]) // Surface placeholder leakage or a malformed array. + } + + templatesRequest := &Request{JSONRPC: "2.0", Method: "resources/templates/list", Params: params, ID: 15} // Request the parameterized URI catalog through its standard modern method. + templatesResult, err := handler.ProcessRequest(context.Background(), templatesRequest) // Execute template discovery through modern dispatch and result decoration. + if err != nil { // Fail when the implemented template-list method is rejected. + t.Fatalf("expected modern resources/templates/list to succeed, got %v", err) // Surface the unexpected protocol or dispatch error. + } + templatesObject, ok := templatesResult.(map[string]interface{}) // Read the decorated resource-template result. + if !ok { // Reject malformed non-object modern results. + t.Fatalf("expected resource templates result object, got %#v", templatesResult) // Surface the actual result type and value. + } + templates, ok := templatesObject["resourceTemplates"].([]interface{}) // Read the JSON-normalized standard template array. + if !ok || len(templates) != 3 { // Require all three Appium URI patterns under the standard field. + t.Fatalf("expected 3 resource templates, got %#v", templatesObject["resourceTemplates"]) // Surface missing or malformed template discovery data. + } + firstTemplate, ok := templates[0].(map[string]interface{}) // Inspect one normalized entry for the protocol-defined URI field. + if !ok || firstTemplate["uriTemplate"] == nil { // Require a standard resource template rather than a placeholder concrete URI. + t.Fatalf("expected uriTemplate in modern template entry, got %#v", templates[0]) // Surface the malformed template object. + } + if _, hasLegacyURI := firstTemplate["uri"]; hasLegacyURI { // Prevent the historical non-standard field from leaking into modern template discovery. + t.Fatalf("expected modern template without legacy uri field, got %#v", firstTemplate) // Surface the incompatible field on regression. + } + if templatesObject["ttlMs"] != mcperrors.CatalogCacheTTLMS || templatesObject["cacheScope"] != mcperrors.CacheScopePublic { // Require the cache controls mandated for resource-template lists. + t.Fatalf("expected public template cache metadata, got %#v", templatesObject) // Surface the full decorated object for cache-policy diagnosis. + } +} + +// TestProcessRequestRejectsMissingModernCapabilities verifies that every modern request declares client capabilities even when the object is empty. +func TestProcessRequestRejectsMissingModernCapabilities(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one protocol-only handler because validation stops before discovery. + params := json.RawMessage(`{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}`) // Omit the required clientCapabilities metadata key deliberately. + request := &Request{JSONRPC: "2.0", Method: "server/discover", Params: params, ID: 11} // Build a modern discovery probe whose metadata is incomplete. + + _, err := handler.ProcessRequest(context.Background(), request) // Execute validation through the shared stdio-compatible path. + mcpErr, ok := err.(*mcperrors.MCPError) // Inspect the typed protocol failure returned before dispatch. + if !ok || mcpErr.Code != -32602 { // Require the current protocol's malformed-request error code. + t.Fatalf("expected missing capabilities error -32602, got %#v", err) // Surface the unexpected error type or code. + } +} + +// TestProcessRequestRejectsUnsupportedModernVersion verifies that stateless clients receive retryable supported and requested version data. +func TestProcessRequestRejectsUnsupportedModernVersion(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one protocol-only handler because version selection occurs before discovery. + params := json.RawMessage(`{"_meta":{"io.modelcontextprotocol/protocolVersion":"1900-01-01","io.modelcontextprotocol/clientCapabilities":{}}}`) // Request one unavailable protocol revision with otherwise-complete metadata. + request := &Request{JSONRPC: "2.0", Method: "server/discover", Params: params, ID: 12} // Build the standard discovery probe used for stdio era and version detection. + + _, err := handler.ProcessRequest(context.Background(), request) // Execute request-local version validation. + mcpErr, ok := err.(*mcperrors.MCPError) // Inspect the typed retryable protocol error. + if !ok || mcpErr.Code != mcperrors.ErrorCodeUnsupportedVersion { // Require the exact specification-reserved version error. + t.Fatalf("expected unsupported version error %d, got %#v", mcperrors.ErrorCodeUnsupportedVersion, err) // Surface the unexpected failure. + } + errorData, ok := mcpErr.Data.(map[string]interface{}) // Read the retry metadata supplied with the version error. + if !ok || errorData["requested"] != "1900-01-01" || errorData["supported"] == nil { // Require both the rejected value and available alternatives. + t.Fatalf("expected retryable version data, got %#v", mcpErr.Data) // Surface incomplete negotiation metadata. + } +} + +// TestProcessRequestRejectsLegacyPingUnderModernMetadata verifies that legacy liveness remains available only to initialization-based clients. +func TestProcessRequestRejectsLegacyPingUnderModernMetadata(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one protocol-only handler because modern method gating precedes business dispatch. + params := json.RawMessage(`{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}`) // Build complete modern stateless metadata. + request := &Request{JSONRPC: "2.0", Method: "ping", Params: params, ID: 13} // Invoke the lifecycle method removed by the current MCP revision. + + _, err := handler.ProcessRequest(context.Background(), request) // Execute modern method gating directly. + mcpErr, ok := err.(*mcperrors.MCPError) // Inspect the standard unknown-method response. + if !ok || mcpErr.Code != -32601 { // Require ping to be absent from the current method surface. + t.Fatalf("expected modern ping method-not-found, got %#v", err) // Surface accidental legacy leakage into modern semantics. + } +} + // TestProcessRequestRejectsADBShellWhenDisabled verifies that the JSON-RPC MCP bridge hides and rejects adbShell when the gateway kill switch is active. func TestProcessRequestRejectsADBShellWhenDisabled(t *testing.T) { handler := NewHandler(nil, capabilities.NewService(config.GatewayConfig{DisableADBShellTool: true})) // Construct one handler with adbShell disabled so the JSON-RPC-to-MCP bridge can be asserted directly. @@ -112,3 +440,19 @@ func TestServeHTTPRejectsInvalidRequestVersion(t *testing.T) { t.Fatalf("expected invalid request body, got %s", recorder.Body.String()) // Surface the unexpected body so HTTP mapping regressions are obvious. } } + +// TestServeHTTPSuppressesInitializedNotificationResponse verifies that the compatibility HTTP transport consumes notifications without emitting JSON-RPC bodies. +func TestServeHTTPSuppressesInitializedNotificationResponse(t *testing.T) { + handler := NewHandler(nil, nil) // Construct one handler without orchestrator dependencies because initialized is pure protocol lifecycle traffic. + request := httptest.NewRequest(http.MethodPost, "/jsonrpc", strings.NewReader(`{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}`)) // Build one HTTP notification payload without an id so the transport suppression path is exercised directly. + recorder := httptest.NewRecorder() // Capture the HTTP exchange so the transport status and body can be asserted directly. + + handler.ServeHTTP(recorder, request) // Execute the initialized notification through the production HTTP compatibility transport. + + if recorder.Code != http.StatusNoContent { // Fail when the compatibility transport no longer suppresses notification response bodies. + t.Fatalf("expected HTTP 204 for notification, got %d", recorder.Code) // Surface the unexpected transport status so notification regressions are obvious. + } + if recorder.Body.Len() != 0 { // Fail when the compatibility transport still emits a JSON-RPC body for notifications. + t.Fatalf("expected empty notification body, got %q", recorder.Body.String()) // Surface the unexpected body so notification regressions are obvious. + } +} diff --git a/internal/gateway/jsonrpc/modern.go b/internal/gateway/jsonrpc/modern.go new file mode 100644 index 0000000..04de1de --- /dev/null +++ b/internal/gateway/jsonrpc/modern.go @@ -0,0 +1,33 @@ +// modern.go classifies dual-era JSON-RPC messages and constrains MCP 2026-07-28 requests to the modern methods implemented by this server. +package jsonrpc + +import "mcp_for_appium/internal/gateway/mcp" + +// validateRequestEra validates per-request metadata when present and reports whether dispatch must use modern MCP 2026-07-28 semantics. +func validateRequestEra(req *Request) (bool, error) { + metadata, err := mcp.ParseRequestMetadata(req.Params) // Inspect only params._meta so method-specific payload decoding remains inside each handler. + if err != nil { // Reject malformed metadata before any business method sees untrusted request state. + return false, err // Preserve the protocol-specific invalid-params diagnostic created by the metadata parser. + } + modern := metadata.ProtocolFieldsPresent || req.Method == "server/discover" // Treat namespaced protocol fields and mandatory discovery as modern while allowing legacy progressToken metadata. + if !modern { // Preserve existing initialization-based and compatibility JSON-RPC behavior when metadata is absent. + return false, nil // Report legacy semantics without imposing modern version or capability requirements. + } + if err := mcp.ValidateModernRequestMetadata(metadata); err != nil { // Require complete stateless context on every modern request, including discovery. + return false, err // Return malformed or unsupported-version errors before method dispatch. + } + if !supportsModernMethod(req.Method) { // Reject legacy lifecycle and repository-specific direct methods from the modern protocol surface. + return false, &mcp.MCPError{Code: -32601, Message: "Method not found"} // Use the standard unknown-method response required for unimplemented modern RPCs. + } + return true, nil // Confirm that dispatch and result decoration must follow modern stateless semantics. +} + +// supportsModernMethod reports whether this server implements one method under MCP 2026-07-28 semantics. +func supportsModernMethod(method string) bool { + switch method { // Enumerate only current core methods with production handlers in this repository. + case "server/discover", "tools/list", "tools/call", "resources/list", "resources/templates/list", "resources/read", "notifications/cancelled": + return true // Permit discovery, tools, resources, and stdio cancellation under modern semantics. + default: + return false // Exclude removed lifecycle methods and every unimplemented modern feature. + } +} diff --git a/internal/gateway/mcp/handler.go b/internal/gateway/mcp/handler.go index 1211bb3..fcdd842 100644 --- a/internal/gateway/mcp/handler.go +++ b/internal/gateway/mcp/handler.go @@ -10,6 +10,7 @@ import ( "mcp_for_appium/internal/config" "mcp_for_appium/internal/devicefarm" + internalerrors "mcp_for_appium/internal/errors" "mcp_for_appium/internal/orchestrator" "mcp_for_appium/internal/storage/postgres" "mcp_for_appium/internal/telemetry" @@ -46,7 +47,7 @@ func NewMCPHandlerWithConfig(orch *orchestrator.Service, gatewayCfg config.Gatew } } -// Initialize handles the MCP initialize request +// Initialize negotiates initialization-based MCP clients while deliberately excluding the stateless 2026-07-28 revision that removed this method. func (h *MCPHandler) Initialize(ctx context.Context, params json.RawMessage) (interface{}, error) { var p struct { ProtocolVersion string `json:"protocolVersion"` @@ -57,39 +58,28 @@ func (h *MCPHandler) Initialize(ctx context.Context, params json.RawMessage) (in } `json:"clientInfo"` } - if err := json.Unmarshal(params, &p); err != nil { + if err := json.Unmarshal(params, &p); err != nil { // Decode the legacy handshake fields before choosing one initialization-based protocol revision. return nil, &MCPError{ - Code: -32602, - Message: "Invalid params", - Data: err.Error(), + Code: -32602, // Use the standard invalid-params error for a malformed initialize payload. + Message: "Invalid params", // Keep the legacy error message stable for existing clients. + Data: err.Error(), // Preserve the JSON decoding diagnostic for client troubleshooting. } } - // Return server capabilities - return map[string]interface{}{ - "protocolVersion": "2024-11-05", - "capabilities": map[string]interface{}{ - "tools": map[string]interface{}{ - "listChanged": false, // Tools don't change dynamically - }, - "resources": map[string]interface{}{ - "subscribe": false, // Advertise no MCP resource subscriptions because this server does not implement resources/subscribe today. - "listChanged": false, - }, - }, - "serverInfo": map[string]interface{}{ - "name": "MCP Mobile Worker", - "version": "1.0.0", - }, + protocolVersion := NegotiateLegacyProtocolVersion(p.ProtocolVersion) // Select a supported legacy revision without ever advertising modern stateless semantics through initialize. + return map[string]interface{}{ // Return the initialization result shape required by legacy MCP clients. + "protocolVersion": protocolVersion, // Echo the selected initialization-based revision for subsequent legacy requests. + "capabilities": ServerCapabilities(), // Advertise the same implemented tool and resource features exposed by modern discovery. + "serverInfo": ServerInfo(), // Identify the server implementation using the shared cross-era metadata source. }, nil } -// ToolsList handles the tools/list request +// ToolsList returns the complete deterministic tool catalog; modern result decoration adds current-protocol result and cache metadata. func (h *MCPHandler) ToolsList(ctx context.Context, params json.RawMessage) (interface{}, error) { - tools := h.registry.List() + tools := h.registry.List() // Read the deterministic registry snapshot used by both legacy and modern clients. - return map[string]interface{}{ - "tools": tools, + return map[string]interface{}{ // Return the legacy-compatible base shape before era-specific result decoration runs. + "tools": tools, // Expose every enabled tool in deterministic name order. }, nil } @@ -115,14 +105,17 @@ func (h *MCPHandler) ToolsCall(ctx context.Context, params json.RawMessage) (int // Validate tool exists and arguments if err := h.registry.Validate(p.Name, p.Arguments); err != nil { logger.Error("mcp tools/call validate failed", "tool", p.Name, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Log schema/validation failures as explicit step failures. - return nil, err + if mcpErr, ok := err.(*MCPError); ok && mcpErr.Code == -32602 { // Return caller-correctable tool input failures through the MCP tool-result contract. + return newToolErrorResult(p.Name, err), nil // Mark invalid arguments with isError instead of turning them into a JSON-RPC protocol failure. + } + return nil, err // Preserve unknown-tool and internal registry defects as protocol-level JSON-RPC errors. } // Route to the appropriate business method result, err := h.executeTool(ctx, p.Name, p.Arguments) if err != nil { logger.Error("mcp tools/call execute failed", "tool", p.Name, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Log tool execution failures with elapsed time. - return nil, normalizeToolError(p.Name, err) // Normalize per-tool errors into structured MCP payloads. + return newToolErrorResult(p.Name, err), nil // Return business and downstream failures as normal MCP tool results marked with isError. } // Wrap result in MCP format @@ -133,7 +126,8 @@ func (h *MCPHandler) ToolsCall(ctx context.Context, params json.RawMessage) (int "text": formatToolResult(p.Name, result), }, }, - "isError": false, + "structuredContent": result, // Preserve the native tool result as arbitrary JSON for clients that prefer structured outputs. + "isError": false, // Mark the completed tool execution as successful for both modern and legacy clients. } logger.Info("mcp tools/call done", "tool", p.Name, "duration_ms", time.Since(startedAt).Milliseconds()) // Log successful tool completion with elapsed time. return response, nil // Return standard MCP response and nil error. @@ -142,32 +136,35 @@ func (h *MCPHandler) ToolsCall(ctx context.Context, params json.RawMessage) (int // internalCodePattern matches internal error markers like [E.CONFIG.MISSING] inside wrapped error strings. var internalCodePattern = regexp.MustCompile(`\[(E\.[A-Z0-9._]+)\]`) // Compile once to avoid per-request regex allocations. -// normalizeToolError executes this operation. -func normalizeToolError(toolName string, err error) error { - if mcpErr, ok := err.(*MCPError); ok { // Reuse existing MCP error objects produced by handler methods. - rawError := stringifyErrorData(mcpErr.Data, err) // Preserve the most specific raw error text for users and debugging. - data := map[string]interface{}{ // Return structured data so clients can render richer diagnostics. - "interface": "tools/call", // Identify the failed interface category for consumers. - "tool": toolName, // Identify the exact failing tool for quick triage. - "rawError": rawError, // Keep original downstream/native error message if available. - "internalCode": extractInternalCode(rawError), // Parse standardized internal code when present. - "hint": toolFailureHint(toolName, rawError), // Add actionable hint without hiding source error. - } - mcpErr.Data = data // Overwrite flat string data with structured details while keeping top-level MCP code/message. - return mcpErr // Return same MCPError instance to preserve code/message semantics. - } - - // Convert non-MCP errors to MCP server errors with full context. - return &MCPError{ // Wrap unknown error types so clients still receive consistent diagnostic fields. - Code: -32000, // Use server error code for unexpected tool execution failures. - Message: "Tool execution failed", - Data: map[string]interface{}{ - "interface": "tools/call", // Mark this as a tool-call execution failure. - "tool": toolName, // Include tool name for routing/debugging on client side. - "rawError": err.Error(), // Preserve original error text from lower layers. - "internalCode": extractInternalCode(err.Error()), // Extract internal code when wrapped text includes it. - "hint": toolFailureHint(toolName, err.Error()), // Provide lightweight next-step guidance. +// newToolErrorResult converts one input, business, or downstream failure into the normal MCP tools/call result shape without exposing wrapped backend details. +func newToolErrorResult(toolName string, err error) map[string]interface{} { + publicMessage := "Tool execution failed" // Start with a stable diagnostic for untyped failures whose text may contain sensitive backend data. + rawDiagnostic := err.Error() // Retain the full server-side diagnostic only for code extraction and predefined hint selection. + if mcpErr, ok := err.(*MCPError); ok { // Reuse protocol handler classifications when a tool path already supplied one. + publicMessage = mcpErr.Message // Expose the concise MCP message while keeping its potentially sensitive data private. + rawDiagnostic = stringifyErrorData(mcpErr.Data, err) // Use detailed data only to derive a stable internal code and remediation hint. + } + internalCode := extractInternalCode(rawDiagnostic) // Recover an embedded repository code from wrapped MCP diagnostics when present. + if code, ok := internalerrors.CodeOf(err); ok { // Prefer a directly typed repository code over text extraction when available. + internalCode = string(code) // Preserve the stable machine-readable classification without returning the wrapped cause. + } + hint := toolFailureHint(toolName, rawDiagnostic) // Select a predefined actionable hint from the private diagnostic. + structuredContent := map[string]interface{}{ // Build a machine-readable failure payload containing only sanitized fields. + "interface": "tools/call", // Identify the protocol interface that completed with an application-level failure. + "tool": toolName, // Identify the selected tool without reflecting any argument values. + "message": publicMessage, // Return the concise public classification supplied by the tool layer. + "internalCode": internalCode, // Return the stable internal code when one could be determined. + "hint": hint, // Return a safe remediation hint that does not quote the backend error. + } + return map[string]interface{}{ // Return a successful JSON-RPC result whose MCP-level outcome is explicitly an error. + "content": []map[string]interface{}{ // Provide a text fallback for clients that do not consume structuredContent. + { + "type": "text", // Identify the fallback content block as plain text. + "text": fmt.Sprintf("%s failed: %s", toolName, publicMessage), // Summarize the tool failure without including raw downstream data. + }, }, + "structuredContent": structuredContent, // Preserve the sanitized machine-readable failure details for modern clients. + "isError": true, // Mark the normal tools/call result as a failed tool execution per the MCP contract. } } @@ -218,7 +215,7 @@ func toolFailureHint(toolName string, raw string) string { case strings.Contains(lower, "exec: \"adb\": executable file not found"): return "Install Android platform-tools and ensure adb is in PATH." } - return fmt.Sprintf("Inspect rawError for %s and fix the upstream dependency/configuration.", toolName) // Provide a deterministic fallback hint. + return fmt.Sprintf("Inspect server logs for %s and fix the upstream dependency or configuration.", toolName) // Provide a deterministic fallback without promising raw backend details in the client response. } // executeTool routes tool calls to business logic @@ -749,36 +746,59 @@ func (h *MCPHandler) handleHealthCheck(ctx context.Context, arguments json.RawMe return h.orch.HealthCheck(ctx), nil } -// ResourcesList handles the resources/list request -func (h *MCPHandler) ResourcesList(ctx context.Context, params json.RawMessage) (interface{}, error) { - // Define available resources - resources := []map[string]interface{}{ +// ResourcesList returns the historical template-like resource catalog retained for initialization-era client compatibility. +func (h *MCPHandler) ResourcesList(_ context.Context, _ json.RawMessage) (interface{}, error) { + resources := make([]map[string]interface{}, 0, 3) // Allocate the fixed legacy catalog while preserving JSON array output when templates are transformed. + for _, resource := range appiumResourceTemplates() { // Convert each standard resource template into the non-standard shape returned by earlier repository versions. + resource["uri"] = resource["uriTemplate"] // Preserve the historical uri field so existing initialization-era clients do not lose catalog entries. + delete(resource, "uriTemplate") // Remove the modern template field because legacy consumers expect the old resource object shape. + resources = append(resources, resource) // Append the transformed request-local map without mutating any shared catalog state. + } + return map[string]interface{}{ // Return the legacy-compatible base shape without modern cache or result metadata. + "resources": resources, // Expose each historical parameterized Appium resource under its old field name. + }, nil +} + +// ModernResourcesList returns the concrete resources currently enumerable for a modern caller, which is empty because this server resolves only ID-parameterized resources. +func (h *MCPHandler) ModernResourcesList(_ context.Context, _ json.RawMessage) (interface{}, error) { + resources := make([]map[string]interface{}, 0) // Allocate an explicit empty array because no trace or session IDs can be enumerated without caller-supplied identifiers. + return map[string]interface{}{ // Return the standard resources/list base shape before modern cache and result decoration. + "resources": resources, // Report the empty concrete resource set while directing clients to resources/templates/list for URI patterns. + }, nil +} + +// ResourcesTemplatesList returns the standard parameterized Appium resource templates used to construct artifacts, traces, and session URIs. +func (h *MCPHandler) ResourcesTemplatesList(_ context.Context, _ json.RawMessage) (interface{}, error) { + return map[string]interface{}{ // Return the standard template-list base shape before era-specific result decoration. + "resourceTemplates": appiumResourceTemplates(), // Expose all supported URI templates under the protocol-defined result field. + }, nil +} + +// appiumResourceTemplates returns a new static catalog of parameterized resource definitions so callers may transform entries without shared mutation. +func appiumResourceTemplates() []map[string]interface{} { + return []map[string]interface{}{ // Allocate request-local maps because legacy compatibility rewrites the URI field in place. { - "uri": "mcp://appium/artifacts/{traceId}", - "name": "Test Artifacts", - "description": "获取测试执行产生的工件(截图、日志等)", - "mimeType": "application/json", + "uriTemplate": "mcp://appium/artifacts/{traceId}", // Define the trace identifier placeholder using the MCP resource-template field. + "name": "Test Artifacts", // Provide a stable programmatic display name for artifact data. + "description": "获取测试执行产生的工件(截图、日志等)", // Explain that this template resolves screenshots, logs, and related run artifacts. + "mimeType": "application/json", // Declare that resolved artifact content is serialized JSON text. }, { - "uri": "mcp://appium/traces/{traceId}", - "name": "Execution Trace", - "description": "获取测试执行的详细追踪记录", - "mimeType": "application/json", + "uriTemplate": "mcp://appium/traces/{traceId}", // Define the trace identifier placeholder for detailed execution history. + "name": "Execution Trace", // Provide a stable programmatic display name for trace data. + "description": "获取测试执行的详细追踪记录", // Explain that this template resolves detailed test execution traces. + "mimeType": "application/json", // Declare that resolved trace content is serialized JSON text. }, { - "uri": "mcp://appium/sessions/{sessionId}", - "name": "Session Info", - "description": "获取会话详细信息", - "mimeType": "application/json", + "uriTemplate": "mcp://appium/sessions/{sessionId}", // Define the Appium session identifier placeholder for session metadata. + "name": "Session Info", // Provide a stable programmatic display name for session data. + "description": "获取会话详细信息", // Explain that this template resolves detailed Appium session information. + "mimeType": "application/json", // Declare that resolved session content is serialized JSON text. }, } - - return map[string]interface{}{ - "resources": resources, - }, nil } -// ResourcesRead handles the resources/read request +// ResourcesRead resolves one Appium resource URI and returns JSON text whose modern decoration uses a short private cache lifetime. func (h *MCPHandler) ResourcesRead(ctx context.Context, params json.RawMessage) (interface{}, error) { var p struct { URI string `json:"uri"` @@ -807,21 +827,21 @@ func (h *MCPHandler) ResourcesRead(ctx context.Context, params json.RawMessage) case "artifacts": artifacts, err := h.orch.GetArtifacts(ctx, id) if err != nil { - return nil, &MCPError{Code: -32000, Message: "Failed to get artifacts", Data: err.Error()} + return nil, newResourceReadError(p.URI, "get artifacts", err) // Map missing and internal artifact failures to current resource error semantics. } content = map[string]interface{}{"traceId": id, "artifacts": artifacts} case "traces": trace, events, err := h.orch.GetTrace(ctx, id) if err != nil { - return nil, &MCPError{Code: -32000, Message: "Failed to get trace", Data: err.Error()} + return nil, newResourceReadError(p.URI, "get trace", err) // Map missing and internal trace failures to current resource error semantics. } content = map[string]interface{}{"trace": trace, "events": events} case "sessions": sess, err := h.orch.GetSession(ctx, id) if err != nil { - return nil, &MCPError{Code: -32000, Message: "Failed to get session", Data: err.Error()} + return nil, newResourceReadError(p.URI, "get session", err) // Map missing and internal session failures to current resource error semantics. } var caps interface{} if sess.Capabilities != nil { @@ -843,15 +863,41 @@ func (h *MCPHandler) ResourcesRead(ctx context.Context, params json.RawMessage) } text, _ := json.MarshalIndent(content, "", " ") - return map[string]interface{}{ - "contents": []map[string]interface{}{ + return newResourceReadResult(p.URI, string(text)), nil // Build the legacy-compatible resource payload before modern private cache metadata is attached. +} + +// newResourceReadError maps unavailable or unauthorized resources to Invalid Params and all other backend failures to the standard JSON-RPC internal error. +func newResourceReadError(uri string, operation string, err error) *MCPError { + if internalerrors.IsCode(err, internalerrors.CodeTraceNotFound) || internalerrors.IsCode(err, internalerrors.CodeSessionNotFound) || internalerrors.IsCode(err, internalerrors.CodePermissionDenied) { // Treat unavailable and unauthorized caller-scoped resources identically to avoid disclosing their existence. + return &MCPError{ // Return the exact current-protocol resource-not-found error family. + Code: -32602, // Use Invalid Params because MCP 2026-07-28 retired the legacy resource-not-found server code. + Message: "Resource not found", // Give clients the canonical resource availability diagnostic. + Data: map[string]interface{}{ // Include only the requested identifier so clients can correct or discard the stale URI. + "uri": uri, // Echo the unavailable resource URI without exposing backend or authorization details. + }, + } + } + return &MCPError{ // Return a standard internal failure for storage, decoding, and other server-side resource errors. + Code: -32603, // Use JSON-RPC Internal error instead of allocating a forbidden legacy MCP server code. + Message: "Failed to read resource", // Identify the failed protocol operation without incorrectly reporting absence. + Data: map[string]interface{}{ // Preserve stable request context while keeping backend diagnostics in server logs only. + "uri": uri, // Identify the resource whose backend read failed. + "operation": operation, // Identify the internal read stage that returned the error. + }, + } +} + +// newResourceReadResult builds one legacy-compatible JSON text resource response for subsequent era-specific result decoration. +func newResourceReadResult(uri string, text string) map[string]interface{} { + return map[string]interface{}{ // Return one resource payload without adding fields unknown to initialization-era clients. + "contents": []map[string]interface{}{ // Provide the standard MCP resource contents array even though one URI resolves to one document. { - "uri": p.URI, - "mimeType": "application/json", - "text": string(text), + "uri": uri, // Echo the exact resource identifier that produced this content. + "mimeType": "application/json", // Identify the text payload as a serialized JSON document. + "text": text, // Return the preformatted JSON document as MCP text resource content. }, }, - }, nil + } } // parseResourceURI parses mcp://appium/{resource}/{id} into resource type and id diff --git a/internal/gateway/mcp/mcp_test.go b/internal/gateway/mcp/mcp_test.go index 41537bd..f5a1752 100644 --- a/internal/gateway/mcp/mcp_test.go +++ b/internal/gateway/mcp/mcp_test.go @@ -4,9 +4,11 @@ package mcp import ( "context" "encoding/json" + "strings" "testing" "mcp_for_appium/internal/config" + internalerrors "mcp_for_appium/internal/errors" ) // expectedToolCatalogSize stores the current embedded MCP tool count so catalog drift is detected immediately in unit tests. @@ -29,7 +31,7 @@ func mustMCPError(t *testing.T, err error, expectedCode int) *MCPError { return mcpErr // Return the typed MCP error so callers can assert message and data fields without repeating the type assertion. } -// TestMCPHandlerInitializeReturnsServerCapabilities verifies that initialize returns the expected protocol version, capabilities, and server metadata. +// TestMCPHandlerInitializeReturnsServerCapabilities verifies that an unknown legacy initialize version receives the historical fallback, capabilities, and server metadata. func TestMCPHandlerInitializeReturnsServerCapabilities(t *testing.T) { handler := NewMCPHandler(nil) // Construct one handler without an orchestrator because initialize is pure protocol metadata. params := json.RawMessage(`{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}`) // Build one representative initialize payload that matches the MCP handshake shape. @@ -42,8 +44,8 @@ func TestMCPHandlerInitializeReturnsServerCapabilities(t *testing.T) { if !ok { // Reject non-map results because initialize must return a structured MCP response object. t.Fatalf("expected initialize response map, got %T", result) // Surface the actual response type so protocol regressions are easy to diagnose. } - if resultMap["protocolVersion"] != "2024-11-05" { // Assert the wire protocol version so clients can rely on a stable MCP handshake target. - t.Fatalf("expected protocolVersion 2024-11-05, got %#v", resultMap["protocolVersion"]) // Surface the actual version so handshake regressions are easy to diagnose. + if resultMap["protocolVersion"] != "2025-06-18" { // Assert the historical fallback used only for unknown initialization-era protocol versions. + t.Fatalf("expected protocolVersion 2025-06-18, got %#v", resultMap["protocolVersion"]) // Surface the actual version so handshake regressions are easy to diagnose. } capabilities, ok := resultMap["capabilities"].(map[string]interface{}) // Extract the capabilities map so tool and resource support can be asserted precisely. if !ok { // Reject malformed capabilities because MCP clients rely on this shape during negotiation. @@ -70,6 +72,11 @@ func TestToolRegistryCatalogAndValidation(t *testing.T) { if len(tools) != expectedToolCatalogSize { // Assert the current embedded tool count so catalog drift is detected immediately. t.Fatalf("expected %d tools, got %d", expectedToolCatalogSize, len(tools)) // Surface the actual count so catalog regressions are easy to diagnose. } + for index := 1; index < len(tools); index++ { // Compare every adjacent pair to enforce deterministic lexicographic discovery order. + if tools[index-1].Name >= tools[index].Name { // Reject duplicates and unstable ordering because clients cache the serialized catalog. + t.Fatalf("expected tools sorted by name, found %q before %q", tools[index-1].Name, tools[index].Name) // Surface the first offending pair for catalog debugging. + } + } requiredToolNames := map[string]bool{ // Define representative tools across the major capability areas so the registry assertion is broader than a raw count. "startSession": false, @@ -98,6 +105,9 @@ func TestToolRegistryCatalogAndValidation(t *testing.T) { if tool.InputSchema == nil { // Reject nil schemas because MCP clients depend on per-tool input-schema metadata. t.Fatal("expected startSession input schema") // Stop immediately because schema validation assertions depend on an actual schema. } + if tool.InputSchema["$schema"] != JSONSchema202012 { // Require tools/list to declare the current MCP default JSON Schema dialect explicitly. + t.Fatalf("expected JSON Schema 2020-12 declaration, got %#v", tool.InputSchema["$schema"]) // Surface the advertised dialect when schema alignment regresses. + } validArgs := json.RawMessage(`{"projectId":"test-project","w3cCapsJson":{"platformName":"iOS"}}`) // Build one minimal valid payload for the startSession schema. if err := registry.Validate("startSession", validArgs); err != nil { // Validate the minimal payload through the production schema path. @@ -111,6 +121,36 @@ func TestToolRegistryCatalogAndValidation(t *testing.T) { } } +// TestCompileToolInputSchemaSupportsDraft202012 verifies validation of a keyword whose cross-subschema behavior requires the MCP-mandated 2020-12 dialect. +func TestCompileToolInputSchemaSupportsDraft202012(t *testing.T) { + tool := Tool{ // Build one isolated schema fixture that uses 2020-12 unevaluatedProperties semantics. + Name: "draft2020Test", // Assign a safe unique name used only to construct the local schema resource URI. + InputSchema: map[string]interface{}{ // Compose an object across allOf while disallowing properties left unevaluated afterward. + "$schema": JSONSchema202012, // Explicitly select the current MCP default dialect for this regression fixture. + "type": "object", // Require the validated tool arguments to use an object shape. + "allOf": []interface{}{ // Evaluate the declared property inside a composed subschema. + map[string]interface{}{ // Define the one permitted property within the allOf branch. + "properties": map[string]interface{}{ // Mark name as evaluated when it satisfies the nested declaration. + "name": map[string]interface{}{"type": "string"}, // Require the permitted name value to be a string. + }, + "required": []interface{}{"name"}, // Require the permitted property so the accepted fixture is meaningful. + }, + }, + "unevaluatedProperties": false, // Reject properties not evaluated by the composed 2020-12 schema. + }, + } + compiledSchema, err := compileToolInputSchema(tool) // Compile the fixture through the production dialect-pinned compiler. + if err != nil { // Fail when the server cannot compile a valid 2020-12 tool schema. + t.Fatalf("expected JSON Schema 2020-12 compilation to succeed, got %v", err) // Surface the compiler diagnostic for dependency or dialect regressions. + } + if err := compiledSchema.Validate(map[string]interface{}{"name": "appium"}); err != nil { // Validate an object whose only property is evaluated inside allOf. + t.Fatalf("expected composed 2020-12 schema to accept evaluated property, got %v", err) // Surface unexpected rejection of valid arguments. + } + if err := compiledSchema.Validate(map[string]interface{}{"name": "appium", "extra": true}); err == nil { // Validate an object containing one property left unevaluated by allOf. + t.Fatal("expected 2020-12 unevaluatedProperties to reject extra property") // Prove the modern dialect keyword is enforced rather than silently ignored. + } +} + // TestNewMCPHandlerWithConfigRemovesADBShell verifies that the gateway-level adbShell disable flag removes the tool from MCP discovery and invocation. func TestNewMCPHandlerWithConfigRemovesADBShell(t *testing.T) { handler := NewMCPHandlerWithConfig(nil, config.GatewayConfig{DisableADBShellTool: true}) // Construct one MCP handler with adbShell explicitly disabled so discovery and call-path shaping can be asserted directly. @@ -145,17 +185,36 @@ func TestMCPHandlerToolsCallRejectsUnknownTool(t *testing.T) { } } -// TestMCPHandlerToolsCallRejectsInvalidArguments verifies that schema-invalid tool arguments fail before handler execution begins. -func TestMCPHandlerToolsCallRejectsInvalidArguments(t *testing.T) { +// TestMCPHandlerToolsCallReturnsInputErrorResult verifies that schema-invalid tool arguments use the MCP isError result contract instead of a JSON-RPC error. +func TestMCPHandlerToolsCallReturnsInputErrorResult(t *testing.T) { handler := NewMCPHandler(nil) // Construct one handler without an orchestrator because validation failures stop before business logic is reached. params := json.RawMessage(`{"name":"findElement","arguments":{"sessionId":"session-1"}}`) // Build one invalid findElement payload that omits required strategy and selector fields. - mcpErr := mustMCPError(t, func() error { // Execute the real tools/call path and capture the validation failure for structured assertions. - _, err := handler.ToolsCall(context.Background(), params) // Invoke the production tools/call entry point with the invalid payload. - return err // Return the error so the shared MCP assertion helper can inspect it. - }(), -32602) - if mcpErr.Message != "Schema validation failed" { // Assert the stable schema-validation message so clients can classify input failures consistently. - t.Fatalf("expected schema validation failure message, got %q", mcpErr.Message) // Surface the actual message so validation regressions are easy to diagnose. + result, err := handler.ToolsCall(context.Background(), params) // Invoke the production tools/call entry point with the invalid payload. + if err != nil { // Reject protocol-level errors because schema failures must complete as tool results. + t.Fatalf("expected MCP tool error result, got protocol error: %v", err) // Surface accidental JSON-RPC error regressions directly. + } + resultMap, ok := result.(map[string]interface{}) // Assert the standard MCP tool-result object shape before inspecting its error marker. + if !ok { // Reject non-object results because tools/call must return a structured result. + t.Fatalf("expected tool result map, got %T", result) // Surface the unexpected result type for quick protocol diagnosis. + } + if isError, ok := resultMap["isError"].(bool); !ok || !isError { // Require the explicit MCP application-error marker on schema failures. + t.Fatalf("expected isError=true, got %#v", resultMap["isError"]) // Surface the malformed marker so clients do not silently treat the call as successful. + } +} + +// TestNewToolErrorResultDoesNotExposeRawCause verifies that tool-result failures preserve stable codes without returning sensitive wrapped diagnostics. +func TestNewToolErrorResultDoesNotExposeRawCause(t *testing.T) { + result := newToolErrorResult("startSession", internalerrors.New(internalerrors.CodeStoreRead, "password=secret-value")) // Build one typed failure whose private message would be unsafe to return. + encodedResult, err := json.Marshal(result) // Serialize the complete client-visible result so every nested field is checked together. + if err != nil { // Fail when the generated tool result cannot be encoded as JSON. + t.Fatalf("expected tool error result to marshal, got %v", err) // Surface malformed result values introduced by future changes. + } + if strings.Contains(string(encodedResult), "secret-value") { // Reject any nested reflection of the private downstream diagnostic. + t.Fatalf("expected sensitive cause to be omitted, got %s", encodedResult) // Surface the unsafe response payload for immediate remediation. + } + if !strings.Contains(string(encodedResult), string(internalerrors.CodeStoreRead)) { // Require the stable machine-readable code to remain available after sanitization. + t.Fatalf("expected internal code %s, got %s", internalerrors.CodeStoreRead, encodedResult) // Surface loss of programmatic error classification. } } @@ -178,6 +237,12 @@ func TestMCPHandlerResourcesListReturnsExpectedCatalog(t *testing.T) { if len(resources) != 3 { // Assert the documented resource count so catalog drift is detected immediately. t.Fatalf("expected 3 resources, got %d", len(resources)) // Surface the actual count so catalog regressions are easy to diagnose. } + if _, hasTTL := resultMap["ttlMs"]; hasTTL { // Keep the era-neutral handler result compatible with initialization-era resource clients. + t.Fatalf("expected base resources/list result without modern ttlMs, got %#v", resultMap) // Surface accidental current-protocol leakage into legacy output. + } + if _, hasScope := resultMap["cacheScope"]; hasScope { // Keep authorization-aware cache controls in modern result decoration only. + t.Fatalf("expected base resources/list result without modern cacheScope, got %#v", resultMap) // Surface accidental current-protocol leakage into legacy output. + } expectedURIs := map[string]bool{ // Define the documented MCP resource templates so the catalog assertion is order-independent. "mcp://appium/artifacts/{traceId}": false, @@ -213,6 +278,39 @@ func TestMCPHandlerResourcesReadRejectsInvalidURI(t *testing.T) { } } +// TestDecorateModernResourceReadResultUsesPrivateCache verifies that modern user-specific resource content cannot be shared across authorization contexts. +func TestDecorateModernResourceReadResultUsesPrivateCache(t *testing.T) { + baseResult := newResourceReadResult("mcp://appium/traces/trace-1", `{"trace":"value"}`) // Build the era-neutral resource payload without requiring an orchestrator or database. + decorated, err := DecorateModernResult("resources/read", baseResult) // Apply the production current-protocol result policy for a resource read. + if err != nil { // Fail when a valid resource object cannot be decorated. + t.Fatalf("expected modern resource decoration to succeed, got %v", err) // Surface unexpected normalization or result-shape failures. + } + result, ok := decorated.(map[string]interface{}) // Read the normalized modern result object for cache assertions. + if !ok { // Reject non-object output because all modern MCP successful results must be objects. + t.Fatalf("expected decorated resource result object, got %#v", decorated) // Surface the malformed modern result. + } + if result["ttlMs"] != ResourceCacheTTLMS { // Require the short resource freshness window injected after JSON normalization. + t.Fatalf("expected resource ttlMs %d, got %#v", ResourceCacheTTLMS, result["ttlMs"]) // Surface the actual cache duration on regression. + } + if result["cacheScope"] != CacheScopePrivate { // Require caller-isolated caching for potentially authorized test data. + t.Fatalf("expected private resource cache scope, got %#v", result["cacheScope"]) // Surface unsafe public scope regressions immediately. + } +} + +// TestNewResourceReadErrorUsesCurrentProtocolCodes verifies that unavailable resources and backend failures use the JSON-RPC codes required by current MCP. +func TestNewResourceReadErrorUsesCurrentProtocolCodes(t *testing.T) { + notFoundCause := internalerrors.New(internalerrors.CodeTraceNotFound, "trace not found") // Build one repository-standard missing resource error without a database dependency. + notFound := newResourceReadError("mcp://appium/traces/missing", "get trace", notFoundCause) // Map the missing trace through the production resource error helper. + if notFound.Code != -32602 || notFound.Message != "Resource not found" { // Require the current resource-not-found code and stable message. + t.Fatalf("expected resource not found -32602, got %#v", notFound) // Surface the complete malformed protocol error. + } + internalCause := internalerrors.New(internalerrors.CodeStoreRead, "database unavailable") // Build one backend read failure that must not be reported as a missing URI. + internalFailure := newResourceReadError("mcp://appium/traces/trace-1", "get trace", internalCause) // Map the backend failure through the same production helper. + if internalFailure.Code != -32603 || internalFailure.Message != "Failed to read resource" { // Require the standard JSON-RPC internal error rather than a legacy server code. + t.Fatalf("expected resource internal error -32603, got %#v", internalFailure) // Surface the complete malformed protocol error. + } +} + // TestParseResourceURI verifies the resource URI parser for valid and invalid MCP resource identifiers. func TestParseResourceURI(t *testing.T) { testCases := []struct { diff --git a/internal/gateway/mcp/protocol.go b/internal/gateway/mcp/protocol.go new file mode 100644 index 0000000..e4f593a --- /dev/null +++ b/internal/gateway/mcp/protocol.go @@ -0,0 +1,199 @@ +// protocol.go defines MCP 2026-07-28 request metadata, discovery, result decoration, and dual-era version compatibility primitives. +package mcp + +import ( + "encoding/json" + "strings" +) + +const ( + CurrentProtocolVersion = "2026-07-28" // CurrentProtocolVersion identifies the modern stateless MCP revision implemented by this server. + LatestLegacyProtocolVersion = "2025-11-25" // LatestLegacyProtocolVersion identifies the newest initialization-based MCP revision accepted by this server. + LegacyProtocolVersion = "2025-06-18" // LegacyProtocolVersion preserves compatibility with the repository's previously advertised MCP revision. + JSONSchema202012 = "https://json-schema.org/draft/2020-12/schema" // JSONSchema202012 identifies the minimum JSON Schema dialect required by current MCP. + ProtocolVersionMetaKey = "io.modelcontextprotocol/protocolVersion" // ProtocolVersionMetaKey carries the protocol revision on every modern request. + ClientCapabilitiesMetaKey = "io.modelcontextprotocol/clientCapabilities" // ClientCapabilitiesMetaKey carries request-relevant client capabilities on every modern request. + ClientInfoMetaKey = "io.modelcontextprotocol/clientInfo" // ClientInfoMetaKey optionally identifies the client implementation on a modern request. + ServerInfoMetaKey = "io.modelcontextprotocol/serverInfo" // ServerInfoMetaKey identifies this server in each modern successful result. + ResultTypeComplete = "complete" // ResultTypeComplete identifies a successful result that needs no additional client input. + CacheScopePublic = "public" // CacheScopePublic allows clients to reuse server-wide protocol metadata across callers. + CacheScopePrivate = "private" // CacheScopePrivate limits cached user-specific data to the same authorization context. + DiscoveryCacheTTLMS = 3600000 // DiscoveryCacheTTLMS allows one hour of caching for stable server identity and capabilities. + CatalogCacheTTLMS = 300000 // CatalogCacheTTLMS allows five minutes of caching for static tool and resource catalogs. + ResourceCacheTTLMS = 30000 // ResourceCacheTTLMS allows thirty seconds of caching for mutable Appium resource reads. + ErrorCodeHeaderMismatch = -32020 // ErrorCodeHeaderMismatch identifies missing, malformed, or body-inconsistent modern HTTP headers. + ErrorCodeUnsupportedVersion = -32022 // ErrorCodeUnsupportedVersion identifies a modern request for a protocol revision this server cannot process. +) + +// RequestMetadata captures the modern MCP protocol fields decoded from one request's params._meta object. +type RequestMetadata struct { + Present bool // Present reports whether the request included a params._meta object. + ProtocolFieldsPresent bool // ProtocolFieldsPresent reports whether _meta contains modern namespaced version, capability, or identity fields. + ProtocolVersion string // ProtocolVersion is the exact MCP revision requested for this operation. + ClientCapabilities map[string]interface{} // ClientCapabilities contains only capabilities explicitly declared for this request. + ClientCapabilitiesPresent bool // ClientCapabilitiesPresent distinguishes an omitted required field from a present empty object. + ClientInfo map[string]interface{} // ClientInfo optionally identifies the requesting client implementation. +} + +// SupportedProtocolVersions returns a new preference-ordered slice containing every modern and legacy MCP revision this server implements. +func SupportedProtocolVersions() []string { + return []string{CurrentProtocolVersion, LatestLegacyProtocolVersion, LegacyProtocolVersion} // Return a fresh slice so callers cannot mutate the server's advertised version set. +} + +// NegotiateLegacyProtocolVersion preserves a supported legacy request version and otherwise falls back to the repository's previous 2025-06-18 behavior. +func NegotiateLegacyProtocolVersion(requested string) string { + switch requested { // Select only initialization-based revisions because modern MCP removed the initialize handshake. + case LatestLegacyProtocolVersion, LegacyProtocolVersion: + return requested // Echo a mutually supported legacy revision so the client can continue with its requested semantics. + default: + return LegacyProtocolVersion // Preserve the historical fallback for older or unknown initialization-based clients. + } +} + +// ServerInfo returns a new MCP implementation descriptor for inclusion in legacy handshakes and modern result metadata. +func ServerInfo() map[string]interface{} { + return map[string]interface{}{ // Allocate a fresh map so result decoration never shares mutable metadata across requests. + "name": "MCP Mobile Worker", // Identify the server product consistently across protocol eras. + "version": "1.0.0", // Identify the current server implementation release for diagnostics. + } +} + +// ServerCapabilities returns the MCP tool and resource capabilities implemented by this server without advertising unsupported subscriptions. +func ServerCapabilities() map[string]interface{} { + return map[string]interface{}{ // Allocate one request-local capabilities object because clients may retain or transform the response. + "tools": map[string]interface{}{ // Advertise the tool server feature implemented by tools/list and tools/call. + "listChanged": false, // State that this process does not emit tool catalog change notifications. + }, + "resources": map[string]interface{}{ // Advertise the resource server feature implemented by resource list, template list, and read methods. + "subscribe": false, // State that this server does not implement resource subscriptions. + "listChanged": false, // State that this process does not emit resource catalog change notifications. + }, + } +} + +// ParseRequestMetadata decodes params._meta without interpreting a missing metadata object as a modern request. +func ParseRequestMetadata(params json.RawMessage) (RequestMetadata, error) { + metadata := RequestMetadata{} // Start with legacy-compatible absence until an explicit _meta member is found. + if len(params) == 0 || string(params) == "null" { // Accept omitted or null params as metadata-free input for legacy methods that allow them. + return metadata, nil // Return the absent metadata marker without changing legacy dispatch behavior. + } + + var paramsObject map[string]json.RawMessage // Decode only the top-level params members needed to locate _meta. + if err := json.Unmarshal(params, ¶msObject); err != nil { // Reject non-object or malformed params before protocol metadata can be trusted. + return metadata, &MCPError{Code: -32602, Message: "Invalid params", Data: "params must be a JSON object"} // Return the modern required invalid-params code with a stable diagnostic. + } + rawMetadata, present := paramsObject["_meta"] // Read the standard metadata member while leaving method-specific parameters untouched. + if !present { // Preserve legacy semantics when the request carries no modern metadata marker. + return metadata, nil // Return a non-modern classification so dual-era dispatch can use initialization-based behavior. + } + metadata.Present = true // Record the metadata object without assuming legacy progress metadata selects modern protocol semantics. + + var metadataObject map[string]json.RawMessage // Decode namespaced metadata keys while preserving unknown extension metadata. + if err := json.Unmarshal(rawMetadata, &metadataObject); err != nil || metadataObject == nil { // Require _meta to be a concrete JSON object rather than null, array, or scalar. + return metadata, &MCPError{Code: -32602, Message: "Invalid params", Data: "params._meta must be a JSON object"} // Reject malformed request metadata with the protocol-required invalid-params code. + } + + if rawVersion, exists := metadataObject[ProtocolVersionMetaKey]; exists { // Decode the required protocol version only when the namespaced key is present. + metadata.ProtocolFieldsPresent = true // Distinguish modern protocol metadata from legacy _meta members such as progressToken. + if err := json.Unmarshal(rawVersion, &metadata.ProtocolVersion); err != nil { // Require the protocol version value to be a JSON string. + return metadata, &MCPError{Code: -32602, Message: "Invalid params", Data: ProtocolVersionMetaKey + " must be a string"} // Return an actionable type diagnostic for malformed metadata. + } + } + if rawCapabilities, exists := metadataObject[ClientCapabilitiesMetaKey]; exists { // Decode the required capability object while preserving an explicitly empty declaration. + metadata.ProtocolFieldsPresent = true // Mark an empty capability declaration as a modern protocol-era signal. + metadata.ClientCapabilitiesPresent = true // Record field presence independently from decoded map contents so null remains invalid. + if err := json.Unmarshal(rawCapabilities, &metadata.ClientCapabilities); err != nil { // Require capabilities to use the MCP object shape. + return metadata, &MCPError{Code: -32602, Message: "Invalid params", Data: ClientCapabilitiesMetaKey + " must be an object"} // Return an actionable type diagnostic for malformed capabilities. + } + } + if rawClientInfo, exists := metadataObject[ClientInfoMetaKey]; exists { // Decode optional implementation metadata only when the client supplies it. + metadata.ProtocolFieldsPresent = true // Treat optional modern identity alone as a modern signal that still requires both mandatory fields. + if err := json.Unmarshal(rawClientInfo, &metadata.ClientInfo); err != nil || metadata.ClientInfo == nil { // Require optional clientInfo to be a non-null object when present. + return metadata, &MCPError{Code: -32602, Message: "Invalid params", Data: ClientInfoMetaKey + " must be an object"} // Reject malformed optional identity metadata consistently. + } + } + + return metadata, nil // Return all recognized modern metadata for stateless validation and dispatch. +} + +// ValidateModernRequestMetadata enforces the version and capability fields required on every MCP 2026-07-28 request. +func ValidateModernRequestMetadata(metadata RequestMetadata) error { + if !metadata.Present { // Reject modern methods that omit the per-request metadata object entirely. + return &MCPError{Code: -32602, Message: "Invalid params", Data: "params._meta is required for modern MCP requests"} // Use the protocol-required malformed-request error. + } + if strings.TrimSpace(metadata.ProtocolVersion) == "" { // Reject missing and empty protocol version values before attempting version selection. + return &MCPError{Code: -32602, Message: "Invalid params", Data: ProtocolVersionMetaKey + " is required"} // Name the exact missing metadata key for client remediation. + } + if metadata.ProtocolVersion != CurrentProtocolVersion { // Process only the modern revision through per-request metadata semantics. + return NewUnsupportedProtocolVersionError(metadata.ProtocolVersion) // Return the protocol-defined version error with retryable supported versions. + } + if !metadata.ClientCapabilitiesPresent || metadata.ClientCapabilities == nil { // Require a concrete object even when the request needs no optional client capability. + return &MCPError{Code: -32602, Message: "Invalid params", Data: ClientCapabilitiesMetaKey + " is required and must be an object"} // Reject absent or null capabilities with the required malformed-request error. + } + return nil // Confirm that this request contains all state needed for independent modern processing. +} + +// NewUnsupportedProtocolVersionError creates the protocol-defined retryable error for a modern request using an unavailable revision. +func NewUnsupportedProtocolVersionError(requested string) *MCPError { + return &MCPError{ // Build the exact modern MCP error shape clients use for version retry selection. + Code: ErrorCodeUnsupportedVersion, // Use the specification-reserved UnsupportedProtocolVersion code. + Message: "Unsupported protocol version", // Use the canonical protocol error message. + Data: map[string]interface{}{ // Include both values required for a deterministic client retry decision. + "supported": SupportedProtocolVersions(), // Advertise modern and legacy revisions implemented by this dual-era server. + "requested": requested, // Echo the unavailable request revision for diagnostics. + }, + } +} + +// DecorateModernResult converts one successful method result to an object and adds current-protocol completion, caching, and server identity metadata. +func DecorateModernResult(method string, result interface{}) (interface{}, error) { + encodedResult, err := json.Marshal(result) // Normalize typed maps and structs into the JSON object representation required by MCP results. + if err != nil { // Reject server values that cannot be represented on the JSON-RPC wire. + return nil, &MCPError{Code: -32603, Message: "Internal error", Data: "failed to encode MCP result"} // Surface a standard internal error without leaking serialization internals. + } + var resultObject map[string]interface{} // Decode the normalized result into a mutable object for protocol field insertion. + if err := json.Unmarshal(encodedResult, &resultObject); err != nil || resultObject == nil { // Require all modern MCP success payloads to be JSON objects. + return nil, &MCPError{Code: -32603, Message: "Internal error", Data: "MCP result must be a JSON object"} // Reject invalid server result shapes before sending a non-compliant response. + } + if _, exists := resultObject["resultType"]; !exists { // Preserve extension or input-required result types already selected by a method. + resultObject["resultType"] = ResultTypeComplete // Mark ordinary successful method results as final and complete. + } + applyModernCacheMetadata(method, resultObject) // Add only the cache policy defined for this modern method while leaving legacy method results unchanged. + resultMetadata, ok := resultObject["_meta"].(map[string]interface{}) // Preserve existing response metadata when the method already supplied an object. + if !ok { // Replace absent or malformed metadata with a valid request-local object. + resultMetadata = make(map[string]interface{}) // Allocate the result metadata container required for server identity insertion. + } + resultMetadata[ServerInfoMetaKey] = ServerInfo() // Identify the server on this response without relying on prior connection state. + resultObject["_meta"] = resultMetadata // Attach the completed metadata object to the modern result. + return resultObject, nil // Return the compliant modern MCP success object to the shared transport. +} + +// applyModernCacheMetadata adds the current protocol's method-specific freshness and authorization-scope controls to one successful result object. +func applyModernCacheMetadata(method string, resultObject map[string]interface{}) { + var ttlMS int // Hold the method-specific freshness window in milliseconds until a cacheable method is selected. + var scope string // Hold the method-specific cache sharing boundary until a cacheable method is selected. + switch method { // Select cache policy from the operation because result payloads do not otherwise identify their source method. + case "server/discover": + ttlMS = DiscoveryCacheTTLMS // Cache stable server identity and capability discovery for one hour. + scope = CacheScopePublic // Share discovery metadata because it does not vary by caller or authorization. + case "tools/list", "resources/list", "resources/templates/list": + ttlMS = CatalogCacheTTLMS // Cache static tool and resource catalogs for five minutes. + scope = CacheScopePublic // Share catalogs because this server does not filter them by caller. + case "resources/read": + ttlMS = ResourceCacheTTLMS // Limit mutable Appium resource reuse to thirty seconds. + scope = CacheScopePrivate // Restrict trace and session data to the same authorization context. + default: + return // Leave non-cacheable operations without cache metadata so clients do not retain dynamic command results. + } + resultObject["ttlMs"] = ttlMS // Advertise the selected freshness duration on the modern successful result. + resultObject["cacheScope"] = scope // Advertise whether the cached result may be shared across authorization contexts. +} + +// Discover returns current server versions, capabilities, and usage guidance for the mandatory modern discovery method. +func (h *MCPHandler) Discover(_ json.RawMessage) (interface{}, error) { + return map[string]interface{}{ // Build the stable discovery payload before shared result decoration adds current-protocol metadata. + "supportedVersions": SupportedProtocolVersions(), // Advertise every revision implemented by this dual-era endpoint in preference order. + "capabilities": ServerCapabilities(), // Advertise only the server features currently implemented by this repository. + "instructions": "Use tools/list to discover Appium operations and resources/templates/list to discover trace URI patterns.", // Give clients concise, stable guidance for selecting the next operation. + }, nil +} diff --git a/internal/gateway/mcp/tools.go b/internal/gateway/mcp/tools.go index ba4e5ee..fe28095 100644 --- a/internal/gateway/mcp/tools.go +++ b/internal/gateway/mcp/tools.go @@ -4,10 +4,11 @@ import ( "embed" "encoding/json" "path/filepath" + "sort" "mcp_for_appium/internal/errors" - "github.com/xeipuuv/gojsonschema" + "github.com/santhosh-tekuri/jsonschema/v6" ) //go:embed tools/*.json @@ -22,57 +23,84 @@ type Tool struct { // ToolRegistry holds all available MCP tools type ToolRegistry struct { - tools map[string]Tool + tools map[string]Tool // tools stores each advertised MCP definition by its unique tool name. + schemas map[string]*jsonschema.Schema // schemas stores one precompiled JSON Schema 2020-12 validator per tool name. } -// NewToolRegistry creates and initializes the tool registry +// NewToolRegistry loads every embedded tool definition, compiles its input schema as JSON Schema 2020-12, and panics when the built-in catalog is invalid. func NewToolRegistry() *ToolRegistry { - registry := &ToolRegistry{ - tools: make(map[string]Tool), + registry := &ToolRegistry{ // Allocate both catalog maps before reading the embedded tool definitions. + tools: make(map[string]Tool), // Store tool metadata used by discovery and name lookup. + schemas: make(map[string]*jsonschema.Schema), // Store compiled validators so calls do not recompile schemas per request. } - if err := registry.registerBuiltinTools(); err != nil { - // Log error but don't fail initialization — return empty registry - // In production, consider panic or return error from constructor - panic("failed to load MCP tools: " + err.Error()) + if err := registry.registerBuiltinTools(); err != nil { // Treat an invalid embedded catalog as a build or deployment defect rather than serving partial discovery data. + panic("failed to load MCP tools: " + err.Error()) // Stop startup so tools/list and tools/call can never disagree about available schemas. } - return registry + return registry // Return the complete immutable-after-startup registry to the MCP handler. } -// registerBuiltinTools loads all tool definitions from embedded JSON files +// registerBuiltinTools decodes every embedded JSON tool, declares the MCP-default 2020-12 dialect, and stores its precompiled validator. func (r *ToolRegistry) registerBuiltinTools() error { - entries, err := toolsFS.ReadDir("tools") - if err != nil { - return err + entries, err := toolsFS.ReadDir("tools") // Enumerate the embedded tool directory bundled into the gateway binary. + if err != nil { // Propagate embed filesystem failures because no trustworthy catalog can be constructed. + return err // Return the original read failure to the startup panic with full context. } - for _, entry := range entries { - if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" { - continue + for _, entry := range entries { // Process each embedded directory entry exactly once during registry construction. + if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" { // Ignore nested directories and non-JSON support files. + continue // Skip entries that cannot define one MCP tool document. } - raw, err := toolsFS.ReadFile("tools/" + entry.Name()) - if err != nil { - return err + raw, err := toolsFS.ReadFile("tools/" + entry.Name()) // Read the complete embedded tool definition by its relative path. + if err != nil { // Abort registry construction when one advertised tool cannot be read. + return err // Return the embed read failure so startup cannot expose a partial catalog. } - var tool Tool - if err := json.Unmarshal(raw, &tool); err != nil { - return err + var tool Tool // Allocate the strongly typed MCP tool definition for this file. + if err := json.Unmarshal(raw, &tool); err != nil { // Decode metadata and inputSchema from the embedded JSON document. + return err // Reject malformed built-in JSON before the server starts accepting requests. + } + if tool.InputSchema == nil { // Require every advertised tool to provide the MCP-mandated input schema object. + return errors.New(errors.CodeSchemaInvalid, "tool "+tool.Name+" has no inputSchema") // Return a structured startup error naming the invalid tool definition. + } + if _, declared := tool.InputSchema["$schema"]; !declared { // Make the current MCP default dialect explicit in tools/list output and compilation. + tool.InputSchema["$schema"] = JSONSchema202012 // Declare JSON Schema 2020-12 for every existing schema that omitted an explicit dialect. + } + compiledSchema, err := compileToolInputSchema(tool) // Compile the schema once so unsupported 2020-12 keywords fail during startup rather than invocation. + if err != nil { // Abort registry construction when one input schema is invalid under the required dialect. + return err // Return the compiler diagnostic so the malformed tool can be corrected before deployment. } - r.tools[tool.Name] = tool + r.tools[tool.Name] = tool // Store the dialect-annotated definition used by deterministic tools/list responses. + r.schemas[tool.Name] = compiledSchema // Store the matching validator used by tools/call argument validation. } - return nil + return nil // Report that every embedded definition and validator loaded successfully. } -// List returns all registered tools +// compileToolInputSchema compiles one tool input schema with JSON Schema 2020-12 as the explicit default dialect and performs no network loading. +func compileToolInputSchema(tool Tool) (*jsonschema.Schema, error) { + compiler := jsonschema.NewCompiler() // Create an isolated compiler so one tool cannot resolve references into another tool implicitly. + compiler.DefaultDraft(jsonschema.Draft2020) // Pin schemas without $schema to the minimum dialect required by current MCP. + schemaURL := "https://mcp-for-appium.invalid/tools/" + tool.Name + "/input-schema.json" // Assign a deterministic non-routable base URI for local reference resolution. + if err := compiler.AddResource(schemaURL, tool.InputSchema); err != nil { // Register the in-memory schema document without performing any network request. + return nil, errors.Wrap(errors.CodeSchemaInvalid, "failed to register input schema for "+tool.Name, err) // Add the tool name while preserving the compiler failure. + } + compiledSchema, err := compiler.Compile(schemaURL) // Compile and meta-validate the tool schema against its declared 2020-12 dialect. + if err != nil { // Return a structured startup failure when the schema itself is invalid. + return nil, errors.Wrap(errors.CodeSchemaInvalid, "failed to compile input schema for "+tool.Name, err) // Add the tool name so catalog defects are immediately actionable. + } + return compiledSchema, nil // Return the immutable validator reused by every invocation of this tool. +} + +// List returns all registered tools sorted lexicographically by name for deterministic client and prompt caching. func (r *ToolRegistry) List() []Tool { - tools := make([]Tool, 0, len(r.tools)) - for _, tool := range r.tools { - tools = append(tools, tool) + tools := make([]Tool, 0, len(r.tools)) // Preallocate the exact catalog capacity while retaining a zero-length append target. + for _, tool := range r.tools { // Copy each map value because Go map iteration order is intentionally unstable. + tools = append(tools, tool) // Append the complete tool definition to the request-local result slice. } - return tools + sort.Slice(tools, func(i int, j int) bool { return tools[i].Name < tools[j].Name }) // Sort by the protocol-unique name so unchanged catalogs serialize in a stable order. + return tools // Return the deterministic catalog snapshot without exposing the registry map itself. } // Get retrieves a tool by name @@ -81,51 +109,40 @@ func (r *ToolRegistry) Get(name string) (Tool, bool) { return tool, exists } -// Validate validates tool arguments against the schema +// Validate rejects unknown tools, malformed argument JSON, and instances that fail the tool's precompiled JSON Schema 2020-12 validator. func (r *ToolRegistry) Validate(toolName string, arguments json.RawMessage) error { - tool, exists := r.Get(toolName) - if !exists { - return &MCPError{ - Code: -32601, - Message: "Tool not found: " + toolName, + _, exists := r.Get(toolName) // Confirm that discovery and invocation refer to the same enabled tool catalog. + if !exists { // Reject names omitted from the live registry, including operator-disabled tools. + return &MCPError{ // Return an MCP method-level not-found error before decoding untrusted arguments. + Code: -32601, // Preserve the repository's established tool-not-found code. + Message: "Tool not found: " + toolName, // Name the unavailable tool for client correction. } } - // Validate JSON structure - var args interface{} - if err := json.Unmarshal(arguments, &args); err != nil { - return &MCPError{ - Code: -32602, - Message: "Invalid arguments JSON", - Data: err.Error(), - } - } - schemaLoader := gojsonschema.NewGoLoader(tool.InputSchema) - docLoader := gojsonschema.NewBytesLoader(arguments) - schema, err := gojsonschema.NewSchema(schemaLoader) - if err != nil { - return &MCPError{ - Code: -32602, - Message: "Invalid tool schema", - Data: err.Error(), + var args interface{} // Decode arguments into the generic JSON value model expected by the schema validator. + if err := json.Unmarshal(arguments, &args); err != nil { // Reject malformed JSON before schema evaluation. + return &MCPError{ // Return the standard invalid-params family used by existing MCP clients. + Code: -32602, // Identify malformed tool arguments as invalid parameters. + Message: "Invalid arguments JSON", // Distinguish JSON decoding failure from schema constraint failure. + Data: err.Error(), // Preserve the decoder location and syntax diagnostic. } } - res, err := schema.Validate(docLoader) - if err != nil { - return &MCPError{ - Code: -32602, - Message: "Schema validation error", - Data: err.Error(), + schema, exists := r.schemas[toolName] // Read the validator compiled from the same definition returned by tools/list. + if !exists || schema == nil { // Treat registry divergence as an internal server defect rather than accepting unchecked input. + return &MCPError{ // Return a standard internal error because clients cannot repair a missing server validator. + Code: -32603, // Identify catalog-validator divergence as a JSON-RPC internal error. + Message: "Internal error", // Avoid misclassifying a server setup defect as client input failure. + Data: "tool schema unavailable", // Provide a concise operator-facing diagnostic without exposing implementation details. } } - if !res.Valid() { - return &MCPError{ - Code: -32602, - Message: "Schema validation failed", - Data: errors.New(errors.CodeSchemaInvalid, res.Errors()[0].String()).Error(), + if err := schema.Validate(args); err != nil { // Evaluate the complete argument value with JSON Schema 2020-12 semantics. + return &MCPError{ // Preserve the stable MCP error shape expected by existing invalid-argument tests and clients. + Code: -32602, // Identify schema constraint violations as invalid parameters. + Message: "Schema validation failed", // Keep the established client-facing classification unchanged. + Data: errors.New(errors.CodeSchemaInvalid, err.Error()).Error(), // Wrap the detailed validator path in the repository's schema error code. } } - return nil + return nil // Confirm that the selected tool exists and all supplied arguments satisfy its advertised schema. } // MCPError represents an MCP protocol error diff --git a/internal/gateway/mcphttp/handler.go b/internal/gateway/mcphttp/handler.go new file mode 100644 index 0000000..a297be2 --- /dev/null +++ b/internal/gateway/mcphttp/handler.go @@ -0,0 +1,451 @@ +// handler.go implements dual-era MCP Streamable HTTP with stateless 2026-07-28 validation and initialization-based legacy compatibility. +package mcphttp + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "mime" + "net/http" + "net/url" + "strconv" + "strings" + "unicode/utf8" + + internalerrors "mcp_for_appium/internal/errors" + "mcp_for_appium/internal/gateway/httpinput" + "mcp_for_appium/internal/gateway/jsonrpc" + "mcp_for_appium/internal/gateway/mcp" +) + +const ( + protocolVersionHeader = "MCP-Protocol-Version" // protocolVersionHeader is the HTTP header carrying the negotiated MCP protocol version. + methodHeader = "Mcp-Method" // methodHeader mirrors the JSON-RPC method for modern intermediary routing and validation. + nameHeader = "Mcp-Name" // nameHeader mirrors the tool, resource, or prompt identifier for selected modern methods. + contentTypeJSON = "application/json" // contentTypeJSON is the JSON response content type used for one-shot request responses. + contentTypeSSE = "text/event-stream" // contentTypeSSE is the SSE content type clients must advertise for Streamable HTTP. + base64ValuePrefix = "=?base64?" // base64ValuePrefix starts the exact modern MCP sentinel for unsafe HTTP header values. + base64ValueSuffix = "?=" // base64ValueSuffix ends the exact modern MCP sentinel for unsafe HTTP header values. +) + +// Handler serves the standard MCP Streamable HTTP endpoint while delegating protocol methods to jsonrpc.Handler. +type Handler struct { + rpc *jsonrpc.Handler + allowedOrigins []string +} + +// wireMessage captures just enough JSON-RPC envelope metadata to classify Streamable HTTP inputs before dispatch. +type wireMessage struct { + JSONRPC string `json:"jsonrpc"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` + ID interface{} `json:"id"` + Result json.RawMessage `json:"result"` + Error json.RawMessage `json:"error"` + IDPresent bool `json:"-"` // IDPresent distinguishes an omitted notification id from an explicitly invalid null id. +} + +// UnmarshalJSON decodes one Streamable HTTP envelope while retaining whether its top-level id member was present on the wire. +func (m *wireMessage) UnmarshalJSON(data []byte) error { + type wireMessageAlias wireMessage // Disable recursive UnmarshalJSON calls while preserving every wire field tag. + var decoded wireMessageAlias // Hold ordinarily decoded request, notification, or response fields. + decoder := json.NewDecoder(bytes.NewReader(data)) // Decode the exact wire envelope while controlling generic number representation. + decoder.UseNumber() // Preserve arbitrary-size JSON-RPC numeric ids for validation, dispatch, and exact response echoing. + if err := decoder.Decode(&decoded); err != nil { // Decode the complete lightweight JSON-RPC envelope first. + return err // Preserve malformed JSON diagnostics for the transport's parse-error response. + } + var fields map[string]json.RawMessage // Decode top-level members separately so JSON null remains distinguishable from omission. + if err := json.Unmarshal(data, &fields); err != nil { // Require an object-shaped envelope before transport classification. + return err // Preserve the object decoding failure for the transport's parse-error response. + } + *m = wireMessage(decoded) // Copy all decoded wire fields into the target message. + _, m.IDPresent = fields["id"] // Record exact id-member presence for downstream request classification. + return nil // Confirm that values and wire-presence metadata were decoded successfully. +} + +// NewHandler constructs one Streamable HTTP handler over an existing JSON-RPC handler and a comma-separated browser origin allowlist. +func NewHandler(rpcHandler *jsonrpc.Handler, rawAllowedOrigins string) *Handler { + return &Handler{ + rpc: rpcHandler, // Reuse the caller-provided JSON-RPC handler so /mcp and /jsonrpc share dispatch and cancellation state. + allowedOrigins: parseAllowedOrigins(rawAllowedOrigins), // Normalize configured origins once so per-request checks are exact and cheap. + } +} + +// ServeHTTP routes Streamable HTTP requests by method after applying the transport-level Origin defense. +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if !h.originAllowed(r) { // Enforce browser Origin checks before reading request bodies to reduce DNS rebinding exposure. + http.Error(w, "forbidden origin", http.StatusForbidden) // Return a plain HTTP 403 because this failure happens before JSON-RPC message acceptance. + return // Stop request processing after rejecting the origin. + } + + switch r.Method { // Route the single MCP endpoint by HTTP method as required by Streamable HTTP. + case http.MethodPost: + h.handlePost(w, r) // Process one client-to-server JSON-RPC message sent as a POST body. + case http.MethodGet: + h.handleGet(w) // Reject GET because MCP 2026-07-28 removed standalone Streamable HTTP listening streams. + default: + w.Header().Set("Allow", "POST") // Advertise only POST because the modern transport removed GET. + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) // Reject methods outside the Streamable HTTP transport surface. + } +} + +// handleGet rejects standalone HTTP streams because MCP 2026-07-28 permits client traffic only through POST on this endpoint. +func (h *Handler) handleGet(w http.ResponseWriter) { + w.Header().Set("Allow", "POST") // Tell modern and legacy clients that request-scoped POST is the only supported operation. + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) // Return the mandatory method rejection without opening a legacy GET stream. +} + +// handlePost accepts one JSON-RPC message, selects modern or legacy semantics from that message, and enforces the corresponding Streamable HTTP contract. +func (h *Handler) handlePost(w http.ResponseWriter, r *http.Request) { + if !acceptsContentType(r.Header.Get("Accept"), contentTypeJSON) || !acceptsContentType(r.Header.Get("Accept"), contentTypeSSE) { // Require both response formats listed by the Streamable HTTP POST contract. + http.Error(w, "missing MCP Streamable HTTP accept headers", http.StatusNotAcceptable) // Return 406 so clients can fix the Accept header before retrying. + return // Stop request processing because content negotiation failed. + } + if !hasJSONContentType(r.Header.Get("Content-Type")) { // Require the request body media type mandated by both modern and legacy Streamable HTTP revisions. + h.writeError(w, http.StatusUnsupportedMediaType, nil, -32600, "Invalid Request", "Content-Type must be application/json", "") // Return a JSON-RPC diagnostic alongside HTTP 415 for an unsupported request representation. + return // Stop before decoding a body whose representation was not declared as JSON. + } + + if r.ContentLength > httpinput.MaxRequestBodyBytes { // Reject a declared oversized body before allocating a decoder or reading any payload bytes. + h.writeError(w, http.StatusRequestEntityTooLarge, nil, -32600, "Invalid Request", "request body too large", "") // Return HTTP 413 with a sanitized JSON-RPC diagnostic. + return // Stop request processing after the declared-size rejection. + } + r.Body = http.MaxBytesReader(w, r.Body, httpinput.MaxRequestBodyBytes) // Enforce the transport ceiling for unknown-length or streaming bodies. + var msg wireMessage // Allocate the lightweight envelope used to classify the incoming JSON-RPC message. + if err := httpinput.DecodeSingleJSON(r.Body, &msg); err != nil { // Decode exactly one bounded JSON-RPC message and reject concatenated documents. + if httpinput.IsBodyTooLarge(err) { // Map the typed request-size sentinel before ordinary JSON parse failures. + h.writeError(w, http.StatusRequestEntityTooLarge, nil, -32600, "Invalid Request", "request body too large", "") // Return HTTP 413 with a sanitized JSON-RPC diagnostic. + return // Stop request processing after the request-size rejection. + } + h.writeError(w, http.StatusBadRequest, nil, -32700, "Parse error", err.Error(), "") // Return a JSON-RPC parse error with HTTP 400 for malformed or trailing JSON. + return // Stop request processing after the parse failure. + } + if msg.JSONRPC != "2.0" { // Reject messages that do not use JSON-RPC 2.0 before dispatching protocol methods. + h.writeError(w, http.StatusBadRequest, msg.ID, -32600, "Invalid Request", "jsonrpc must be 2.0", "") // Return an invalid-request envelope so clients see the precise protocol error. + return // Stop request processing after the invalid JSON-RPC version. + } + + metadata, err := mcp.ParseRequestMetadata(msg.Params) // Inspect request-local protocol fields before selecting one of the dual-era transport contracts. + if err != nil { // Reject malformed params._meta before validating or trusting mirrored HTTP headers. + h.writeHandlerError(w, http.StatusBadRequest, msg.ID, err, mcp.CurrentProtocolVersion) // Return the parser's required invalid-params error as a modern HTTP 400 response. + return // Stop after rejecting malformed request metadata. + } + headerVersion := strings.TrimSpace(r.Header.Get(protocolVersionHeader)) // Normalize optional whitespace before comparing the transport protocol version. + modern := metadata.ProtocolFieldsPresent || msg.Method == "server/discover" || headerVersion == mcp.CurrentProtocolVersion // Select stateless semantics from modern namespaced fields, discovery, or the current header without misclassifying legacy progress metadata. + responseVersion := headerVersion // Echo a valid negotiated legacy revision by default. + if modern { // Identify modern responses using the revision this server actually implements. + responseVersion = mcp.CurrentProtocolVersion // Avoid echoing an unsupported requested revision as though the server implemented it. + } + if msg.Method == "initialize" && responseVersion == "" { // Preserve a protocol response header for legacy handshake clients that have not selected a version yet. + responseVersion = mcp.LegacyProtocolVersion // Use the historical fallback until the initialize result supplies the final negotiated version. + } + + if isJSONRPCResponse(msg) { // Classify client response envelopes before request-header validation because they have no method to mirror. + if modern { // Reject client responses because the modern Streamable HTTP binding permits only client requests and notifications. + h.writeError(w, http.StatusBadRequest, msg.ID, -32600, "Invalid Request", "clients must not send JSON-RPC responses over modern Streamable HTTP", responseVersion) // Return an explicit modern transport violation. + return // Stop without dispatching the methodless response envelope. + } + w.WriteHeader(http.StatusAccepted) // Preserve legacy acceptance for clients using the initialization-based Streamable HTTP contract. + return // Stop request processing because legacy client responses do not produce server responses. + } + req := &jsonrpc.Request{JSONRPC: msg.JSONRPC, Method: msg.Method, Params: msg.Params, ID: msg.ID, IDPresent: msg.IDPresent} // Convert values and id presence into the shared JSON-RPC request type used by existing dispatch. + if modern && jsonrpc.IsNotification(req) { // Reject modern notifications before header validation because current Streamable HTTP defines no notification request headers. + h.writeError(w, http.StatusBadRequest, nil, -32600, "Invalid Request", "modern Streamable HTTP does not accept client notifications", responseVersion) // Return the allowed no-id error body with an explicit transport diagnostic. + return // Stop before header validation or dispatch so HTTP cancellation cannot diverge from response-stream closure semantics. + } + if modern { // Enforce mirrored headers only for the 2026-07-28 per-request metadata era. + if err := validateModernHeaders(r, msg, metadata); err != nil { // Compare every required standard header against the decoded JSON-RPC body. + h.writeHandlerError(w, http.StatusBadRequest, msg.ID, err, responseVersion) // Return HTTP 400 and the protocol-reserved HeaderMismatch error. + return // Stop before dispatch so intermediaries and the application cannot act on different request identities. + } + if err := mcp.ValidateModernRequestMetadata(metadata); err != nil { // Require body-local version and capabilities even when the current HTTP header selected modern semantics. + h.writeHandlerError(w, http.StatusBadRequest, msg.ID, err, responseVersion) // Return malformed metadata or retryable UnsupportedProtocolVersion errors as HTTP 400. + return // Stop before shared dispatch so header-only requests cannot fall through to legacy methods. + } + } else if msg.Method != "initialize" && !validLegacyProtocolHeader(headerVersion) { // Require one supported negotiated version after the legacy initialize handshake. + h.writeError(w, http.StatusBadRequest, msg.ID, -32600, "Invalid Request", "unsupported MCP protocol version", responseVersion) // Preserve the existing legacy negotiation diagnostic. + return // Stop request processing after the legacy version-header rejection. + } + + if jsonrpc.IsNotification(req) { // Apply notification semantics before request response handling. + h.handleNotification(w, r, req, responseVersion) // Process the notification and return the Streamable HTTP accepted response shape. + return // Stop request processing because notifications never produce JSON-RPC response bodies. + } + if !jsonrpc.IsRequest(req) { // Reject methodless non-response messages because they are not valid JSON-RPC requests or notifications. + h.writeError(w, http.StatusBadRequest, msg.ID, -32600, "Invalid Request", "method or response payload is required", responseVersion) // Return a JSON-RPC invalid-request envelope for malformed envelopes. + return // Stop request processing after the invalid envelope. + } + + h.handleRequest(w, r, req, modern, responseVersion) // Dispatch the request and apply era-specific HTTP status and response-version semantics. +} + +// handleNotification dispatches one JSON-RPC notification and returns an empty 202 response when its side effects are accepted. +func (h *Handler) handleNotification(w http.ResponseWriter, r *http.Request, req *jsonrpc.Request, protocolVersion string) { + if _, err := h.rpc.ProcessRequest(r.Context(), req); err != nil { // Dispatch the notification so initialized/cancelled side effects are applied. + h.writeHandlerError(w, http.StatusBadRequest, nil, err, protocolVersion) // Return a no-id JSON-RPC error when the notification cannot be accepted. + return // Stop request processing after reporting the notification acceptance failure. + } + + w.Header().Set(protocolVersionHeader, protocolVersion) // Identify the accepted protocol revision without emitting a JSON-RPC notification response body. + w.WriteHeader(http.StatusAccepted) // Return 202 with no body for accepted notifications per Streamable HTTP semantics. +} + +// handleRequest dispatches one JSON-RPC request and maps modern protocol errors to their required HTTP status while preserving legacy HTTP 200 envelopes. +func (h *Handler) handleRequest(w http.ResponseWriter, r *http.Request, req *jsonrpc.Request, modern bool, protocolVersion string) { + ctx := r.Context() // Start from the HTTP request context so disconnects and shutdown still cancel request work. + requestCtx, cancel := context.WithCancel(ctx) // Create one cancellable child context for notifications/cancelled. + cleanup := h.rpc.RegisterInFlightRequest(req.ID, cancel) // Register the request id before dispatch so concurrent cancellation notifications can find it. + defer cleanup() // Remove the in-flight request when dispatch completes. + defer cancel() // Release child context resources after dispatch. + + result, err := h.rpc.ProcessRequest(requestCtx, req) // Dispatch the request through the shared JSON-RPC handler. + if err != nil { // Convert handler errors into JSON-RPC error responses. + h.writeHandlerError(w, handlerErrorStatus(err, modern), req.ID, err, protocolVersion) // Apply current MCP transport statuses without changing legacy JSON-RPC-over-HTTP behavior. + return // Stop request processing after writing the JSON-RPC error response. + } + + protocolVersion = negotiatedResponseVersion(result, protocolVersion) // Read the selected revision from a successful legacy initialize result when present. + h.writeResponse(w, http.StatusOK, jsonrpc.Response{JSONRPC: "2.0", Result: result, ID: req.ID}, protocolVersion) // Write the successful JSON-RPC response envelope with the actual modern or negotiated legacy version. +} + +// writeHandlerError preserves typed MCP errors, maps repository errors, and writes one JSON-RPC envelope with the selected protocol response version. +func (h *Handler) writeHandlerError(w http.ResponseWriter, status int, id interface{}, err error, protocolVersion string) { + if mcpErr, ok := err.(*mcp.MCPError); ok { // Preserve MCP protocol errors without remapping their JSON-RPC code or data. + h.writeResponse(w, status, jsonrpc.Response{JSONRPC: "2.0", Error: &internalerrors.JSONRPCError{Code: mcpErr.Code, Message: mcpErr.Message, Data: mcpErr.Data}, ID: id}, protocolVersion) // Write the MCP error envelope with the caller-selected HTTP status and revision. + return // Stop after writing the typed MCP error response. + } + + h.writeResponse(w, status, jsonrpc.Response{JSONRPC: "2.0", Error: internalerrors.MapToJSONRPC(err), ID: id}, protocolVersion) // Map repository errors into JSON-RPC error envelopes consistently with the compatibility transport. +} + +// writeError writes one direct JSON-RPC error envelope with explicit transport status, code, diagnostic data, and protocol response version. +func (h *Handler) writeError(w http.ResponseWriter, status int, id interface{}, code int, message string, data interface{}, protocolVersion string) { + h.writeResponse(w, status, jsonrpc.Response{JSONRPC: "2.0", Error: &internalerrors.JSONRPCError{Code: code, Message: message, Data: data}, ID: id}, protocolVersion) // Write the direct protocol error response with era-appropriate headers. +} + +// writeResponse serializes one JSON-RPC response as application/json and includes a protocol header only when the request era is known. +func (h *Handler) writeResponse(w http.ResponseWriter, status int, response jsonrpc.Response, protocolVersion string) { + w.Header().Set("Content-Type", contentTypeJSON) // Mark the response as a one-shot JSON response rather than an SSE stream. + if protocolVersion != "" { // Avoid inventing an era for parse errors received before any version could be identified. + w.Header().Set(protocolVersionHeader, protocolVersion) // Echo the implemented or negotiated revision for validly classified MCP exchanges. + } + w.WriteHeader(status) // Write the transport status before encoding the JSON-RPC envelope. + _ = json.NewEncoder(w).Encode(response) // Encode the response body while ignoring late write failures because net/http has already accepted the response. +} + +// validLegacyProtocolHeader reports whether one already-normalized header names a supported initialization-based MCP revision. +func validLegacyProtocolHeader(protocolVersion string) bool { + return protocolVersion == mcp.LatestLegacyProtocolVersion || protocolVersion == mcp.LegacyProtocolVersion // Accept both the latest legacy revision and the repository's previous target. +} + +// validateModernHeaders compares every required standard MCP 2026-07-28 HTTP header with its authoritative JSON-RPC body field. +func validateModernHeaders(r *http.Request, msg wireMessage, metadata mcp.RequestMetadata) error { + protocolVersion := strings.TrimSpace(r.Header.Get(protocolVersionHeader)) // Read the mirrored protocol version while tolerating transport-level optional whitespace. + if protocolVersion == "" { // Reject omission before any intermediary can infer a protocol era from incomplete headers. + return newHeaderMismatchError(protocolVersionHeader + " header is required") // Use the specification-reserved error for every missing standard header. + } + if metadata.ProtocolVersion != "" && protocolVersion != metadata.ProtocolVersion { // Compare the transport version with the request-local metadata version when the body field exists. + return newHeaderMismatchError(protocolVersionHeader + " header does not match params._meta protocol version") // Prevent routing and application layers from selecting different protocol revisions. + } + + requestMethod := r.Header.Get(methodHeader) // Read the exact case-sensitive method value mirrored for intermediaries. + if requestMethod == "" { // Reject a missing method header on every modern request. + return newHeaderMismatchError(methodHeader + " header is required") // Name the absent standard header for direct client remediation. + } + if requestMethod != msg.Method { // Require byte-for-byte method agreement because MCP method names are case-sensitive. + return newHeaderMismatchError(methodHeader + " header value does not match JSON-RPC method") // Reject ambiguous routing identities before dispatch. + } + + targetName, required, err := requestTargetName(msg.Method, msg.Params) // Extract params.name or params.uri only for methods that require Mcp-Name. + if err != nil { // Convert missing or malformed body targets into the same header-validation error family. + return err // Preserve the precise HeaderMismatch diagnostic created by the target extractor. + } + if !required { // Complete validation immediately for methods whose identity is fully represented by Mcp-Method. + return nil // Confirm that all standard headers applicable to this request match its body. + } + rawHeaderName := r.Header.Get(nameHeader) // Read the potentially sentinel-encoded target identity from the standard header. + if rawHeaderName == "" { // Reject omission for tools/call, resources/read, and prompts/get. + return newHeaderMismatchError(nameHeader + " header is required for " + msg.Method) // Identify both the missing header and method-specific requirement. + } + decodedHeaderName, err := decodeMCPHeaderValue(rawHeaderName) // Decode the exact Base64 sentinel form before comparing non-ASCII or whitespace-sensitive values. + if err != nil { // Reject malformed encodings and unsafe plain header bytes. + return newHeaderMismatchError(nameHeader + " header is malformed") // Avoid reflecting attacker-controlled header bytes while identifying the failing field. + } + if decodedHeaderName != targetName { // Compare the decoded header identity with the authoritative body value exactly. + return newHeaderMismatchError(nameHeader + " header value does not match request params") // Prevent intermediaries and tool/resource dispatch from using different names. + } + return nil // Confirm that all modern standard HTTP headers are present, safe, and body-consistent. +} + +// requestTargetName returns the body identifier mirrored by Mcp-Name and reports whether the current method requires that standard header. +func requestTargetName(method string, params json.RawMessage) (string, bool, error) { + parameterName := "" // Start without a mirrored parameter for methods that require only Mcp-Method. + switch method { // Select the exact body field defined by the modern standard-header table. + case "tools/call", "prompts/get": + parameterName = "name" // Mirror the tool or prompt name for intermediary routing and policy checks. + case "resources/read": + parameterName = "uri" // Mirror the resource URI under the shared Mcp-Name HTTP header. + default: + return "", false, nil // Report that this method has no standard target-name header requirement. + } + + var paramsObject map[string]json.RawMessage // Decode only the selected target field from the JSON-RPC params object. + if err := json.Unmarshal(params, ¶msObject); err != nil || paramsObject == nil { // Require method parameters to be an object before extracting a mirrored identity. + return "", true, newHeaderMismatchError("request params must contain " + parameterName + " for " + method) // Reject a body that cannot supply the required comparison source. + } + rawTarget, exists := paramsObject[parameterName] // Read the authoritative body target selected for this method. + if !exists { // Reject omission because the transport cannot validate a required Mcp-Name header without its body source. + return "", true, newHeaderMismatchError("request params must contain " + parameterName + " for " + method) // Name the missing target parameter and method. + } + var target string // Decode the mirrored identity as the string type required by all three standard methods. + if err := json.Unmarshal(rawTarget, &target); err != nil || target == "" { // Reject null, non-string, and empty target identities. + return "", true, newHeaderMismatchError("request params " + parameterName + " must be a non-empty string") // Return a stable body/header validation diagnostic. + } + return target, true, nil // Return the exact authoritative value for decoded Mcp-Name comparison. +} + +// decodeMCPHeaderValue validates a plain safe ASCII value or decodes the exact =?base64?...?= sentinel into UTF-8 text. +func decodeMCPHeaderValue(value string) (string, error) { + hasPrefix := strings.HasPrefix(value, base64ValuePrefix) // Detect the exact case-sensitive opening sentinel defined by MCP. + hasSuffix := strings.HasSuffix(value, base64ValueSuffix) // Detect the exact case-sensitive closing sentinel defined by MCP. + if hasPrefix && hasSuffix { // Decode only the complete sentinel pattern because a single marker remains unambiguous plain ASCII. + encodedValue := strings.TrimSuffix(strings.TrimPrefix(value, base64ValuePrefix), base64ValueSuffix) // Remove only the exact outer sentinel markers. + decodedValue, err := base64.StdEncoding.DecodeString(encodedValue) // Decode standard padded Base64 bytes from the sentinel payload. + if err != nil || !utf8.Valid(decodedValue) { // Require both valid Base64 syntax and valid UTF-8 request text. + return "", newHeaderMismatchError("invalid Base64 or UTF-8 header value") // Reject malformed encoded identities before comparison. + } + return string(decodedValue), nil // Return the original Unicode or whitespace-sensitive body value represented by the header. + } + + if strings.TrimSpace(value) != value { // Require values with leading or trailing whitespace to use sentinel encoding. + return "", newHeaderMismatchError("unsafe plain header whitespace") // Reject ambiguous whitespace that HTTP implementations may normalize differently. + } + for index := 0; index < len(value); index++ { // Inspect every byte because compliant plain values are restricted to ASCII HTTP field content. + currentByte := value[index] // Read one byte without decoding runes because any non-ASCII UTF-8 byte is forbidden in plain form. + if currentByte == '\t' { // Permit internal horizontal tab as allowed by the modern MCP value-encoding rules. + continue // Skip the ordinary visible-ASCII range check for this one permitted control byte. + } + if currentByte < 0x20 || currentByte > 0x7e { // Reject controls, DEL, and every non-ASCII byte in unencoded header values. + return "", newHeaderMismatchError("unsafe plain header characters") // Require sentinel encoding for values outside the safe HTTP field range. + } + } + return value, nil // Return a header-safe plain ASCII value unchanged for exact body comparison. +} + +// newHeaderMismatchError creates the protocol-reserved modern error used for missing, malformed, or body-inconsistent HTTP headers. +func newHeaderMismatchError(detail string) *mcp.MCPError { + return &mcp.MCPError{Code: mcp.ErrorCodeHeaderMismatch, Message: "Header mismatch: " + detail} // Return the canonical error family without duplicating attacker-controlled data fields. +} + +// handlerErrorStatus maps modern method, metadata, capability, and version errors to required HTTP statuses while retaining legacy HTTP 200 behavior. +func handlerErrorStatus(err error, modern bool) int { + if !modern { // Preserve initialization-based Streamable HTTP behavior for existing clients. + return http.StatusOK // Carry legacy method errors inside a normal JSON-RPC HTTP response envelope. + } + mcpErr, ok := err.(*mcp.MCPError) // Inspect only typed protocol errors because repository business errors retain ordinary JSON-RPC HTTP handling. + if !ok { // Avoid assigning protocol statuses to unrelated application failures. + return http.StatusOK // Return the business error in a valid modern JSON-RPC response envelope. + } + switch mcpErr.Code { // Apply the explicit transport status requirements defined by MCP 2026-07-28. + case -32601: + return http.StatusNotFound // Distinguish an unimplemented modern RPC from a missing legacy endpoint. + case -32600, -32602, mcp.ErrorCodeHeaderMismatch, -32021, mcp.ErrorCodeUnsupportedVersion: + return http.StatusBadRequest // Reject malformed requests, missing capabilities, header mismatches, and unsupported revisions as HTTP 400. + default: + return http.StatusOK // Preserve JSON-RPC envelope semantics for execution and application errors without mandated HTTP mappings. + } +} + +// negotiatedResponseVersion reads a supported legacy initialize version from a successful result and otherwise preserves the supplied fallback revision. +func negotiatedResponseVersion(result interface{}, fallback string) string { + resultObject, ok := result.(map[string]interface{}) // Initialize returns a map before any JSON serialization transforms its values. + if !ok { // Leave ordinary modern and legacy method responses on the request-selected revision. + return fallback // Return the transport's previously classified protocol version unchanged. + } + protocolVersion, ok := resultObject["protocolVersion"].(string) // Read the selected revision emitted only by the legacy initialize handler. + if !ok || !validLegacyProtocolHeader(protocolVersion) { // Never echo arbitrary result data as a negotiated protocol revision. + return fallback // Preserve the trusted request-era fallback when initialize metadata is absent or invalid. + } + return protocolVersion // Echo the exact mutually supported legacy revision selected by initialization. +} + +// isJSONRPCResponse reports whether the envelope is a client response message rather than a request or notification. +func isJSONRPCResponse(msg wireMessage) bool { + return msg.Method == "" && (msg.Result != nil || msg.Error != nil) // Classify methodless envelopes with result or error as JSON-RPC responses. +} + +// acceptsContentType reports whether an HTTP Accept header explicitly allows one required content type. +func acceptsContentType(header string, required string) bool { + for _, part := range strings.Split(header, ",") { // Walk each comma-separated Accept value because clients can list multiple media ranges. + mediaType, parameters, err := mime.ParseMediaType(strings.TrimSpace(part)) // Parse media parameters so an explicit q=0 is not mistaken for client support. + if err != nil || !strings.EqualFold(mediaType, required) { // Ignore malformed entries and unrelated media types while scanning the list. + continue // Continue because a later Accept entry may validly advertise the required response representation. + } + if rawQuality, present := parameters["q"]; present { // Evaluate the optional HTTP quality weight when the client supplies one. + quality, err := strconv.ParseFloat(rawQuality, 64) // Parse the quality value as the HTTP decimal range represented by Go floating point. + if err != nil || quality <= 0 || quality > 1 { // Reject malformed, explicitly unacceptable, and out-of-range quality values. + continue // Keep searching in case another entry advertises the same required type with a positive valid weight. + } + } + return true // Report support once the required type has no quality restriction or a positive valid quality. + } + return false // Report that the required media type was not explicitly advertised. +} + +// hasJSONContentType reports whether a Content-Type header declares application/json with only syntactically valid optional parameters. +func hasJSONContentType(header string) bool { + mediaType, _, err := mime.ParseMediaType(header) // Parse media-type parameters rather than relying on unsafe prefix matching. + if err != nil { // Reject absent and malformed Content-Type values before body decoding. + return false // Report that the request does not provide a trustworthy JSON representation declaration. + } + return strings.EqualFold(mediaType, contentTypeJSON) // Accept application/json case-insensitively as required for HTTP media types. +} + +// parseAllowedOrigins normalizes a comma-separated origin allowlist into canonical scheme://host values. +func parseAllowedOrigins(rawOrigins string) []string { + allowedOrigins := make([]string, 0) // Start with an empty allowlist so same-origin fallback remains active when no config is supplied. + for _, rawOrigin := range strings.Split(rawOrigins, ",") { // Walk every comma-delimited origin entry from config. + trimmedOrigin := strings.TrimSpace(rawOrigin) // Remove surrounding whitespace commonly present in YAML or environment lists. + if trimmedOrigin == "" { // Ignore empty entries so accidental extra commas do not create invalid origins. + continue // Skip blank entries because they cannot match a browser Origin header. + } + parsedOrigin, err := url.Parse(trimmedOrigin) // Parse the configured origin before normalizing its scheme and host. + if err != nil { // Ignore malformed entries defensively because startup validation owns operator-facing errors. + continue // Skip malformed origins rather than panicking during request handling. + } + if parsedOrigin.Scheme == "" || parsedOrigin.Host == "" { // Reject partial origins because browser Origin always includes scheme and host. + continue // Skip incomplete origins because they cannot be compared safely. + } + allowedOrigins = append(allowedOrigins, strings.ToLower(parsedOrigin.Scheme+"://"+parsedOrigin.Host)) // Store canonical lowercase origin values for exact matching. + } + return allowedOrigins // Return the normalized allowlist used by originAllowed. +} + +// originAllowed enforces explicit allowlist or same-origin fallback for browser-originated MCP HTTP requests. +func (h *Handler) originAllowed(r *http.Request) bool { + originHeader := strings.TrimSpace(r.Header.Get("Origin")) // Read and trim the Origin header once before validation. + if originHeader == "" { // Permit non-browser clients because CLI MCP clients commonly omit Origin entirely. + return true // Accept requests without Origin because DNS rebinding protection applies to browser-originated traffic. + } + + parsedOrigin, err := url.Parse(originHeader) // Parse the browser-supplied Origin header into scheme and host. + if err != nil { // Reject malformed Origin values because they cannot be safely compared. + return false // Deny malformed browser origins. + } + if parsedOrigin.Scheme == "" || parsedOrigin.Host == "" { // Reject partial Origin headers because they cannot establish a concrete authority. + return false // Deny incomplete browser origins. + } + + normalizedOrigin := strings.ToLower(parsedOrigin.Scheme + "://" + parsedOrigin.Host) // Normalize the incoming Origin to the same representation as configured allowlist entries. + if len(h.allowedOrigins) > 0 { // Prefer explicit allowlist checks when configured by the operator. + for _, allowedOrigin := range h.allowedOrigins { // Walk the normalized allowlist because it is expected to stay very small. + if allowedOrigin == normalizedOrigin { // Match exact origin strings so scheme and host both matter. + return true // Accept explicitly allowed browser origins. + } + } + return false // Deny browser origins that are absent from the explicit allowlist. + } + + return strings.EqualFold(strings.TrimSpace(r.Host), parsedOrigin.Host) // Fall back to strict same-host validation when no explicit allowlist is configured. +} diff --git a/internal/gateway/mcphttp/handler_test.go b/internal/gateway/mcphttp/handler_test.go new file mode 100644 index 0000000..a5f881c --- /dev/null +++ b/internal/gateway/mcphttp/handler_test.go @@ -0,0 +1,384 @@ +// handler_test.go verifies the MCP Streamable HTTP transport semantics implemented at the HTTP package boundary. +package mcphttp + +import ( + "encoding/base64" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "mcp_for_appium/internal/gateway/jsonrpc" + "mcp_for_appium/internal/gateway/mcp" +) + +// newTestHandler constructs one Streamable HTTP handler with no orchestrator dependency for protocol-only tests. +func newTestHandler() *Handler { + return NewHandler(jsonrpc.NewHandler(nil, nil), "") // Reuse the production JSON-RPC handler because these tests exercise transport behavior over pure protocol methods. +} + +// newStreamablePOST builds one POST request with the Accept header required by MCP Streamable HTTP. +func newStreamablePOST(body string) *http.Request { + request := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body)) // Build an in-memory POST request targeting the standard MCP endpoint path. + request.Header.Set("Accept", "application/json, text/event-stream") // Advertise both response content types required by Streamable HTTP POST. + request.Header.Set("Content-Type", contentTypeJSON) // Declare the JSON request representation required by Streamable HTTP POST. + return request // Return the prepared request so tests can add protocol-version headers when needed. +} + +// newModernPOST builds one current-protocol request with mirrored standard headers and an optional method target name. +func newModernPOST(body string, method string, targetName string, protocolVersion string) *http.Request { + request := newStreamablePOST(body) // Start from the common JSON and response-content negotiation headers. + request.Header.Set(protocolVersionHeader, protocolVersion) // Mirror the request-local modern protocol revision at the HTTP layer. + request.Header.Set(methodHeader, method) // Mirror the exact case-sensitive JSON-RPC method for server validation. + if targetName != "" { // Add Mcp-Name only for methods whose params provide a target identity. + request.Header.Set(nameHeader, targetName) // Mirror the tool, resource, or prompt identity for header/body comparison. + } + return request // Return the fully prepared modern request for transport-level assertions. +} + +// TestPostRejectsOversizedBody verifies that direct Streamable HTTP mounts enforce the shared request-size ceiling with HTTP 413. +func TestPostRejectsOversizedBody(t *testing.T) { + handler := newTestHandler() // Construct the production transport without application dependencies. + request := newStreamablePOST(strings.Repeat("x", (1<<20)+1)) // Build a body one byte larger than the shared one-mebibyte ceiling. + recorder := httptest.NewRecorder() // Capture the transport status and JSON-RPC error body. + handler.ServeHTTP(recorder, request) // Execute the oversized request through the direct handler mount. + if recorder.Code != http.StatusRequestEntityTooLarge { // Require the standard transport status instead of a generic parse error. + t.Fatalf("expected status %d, got %d", http.StatusRequestEntityTooLarge, recorder.Code) // Surface the incorrect status and preserve the size-contract regression signal. + } +} + +// TestPostRejectsTrailingJSONDocument verifies that one Streamable HTTP POST cannot contain multiple concatenated JSON-RPC messages. +func TestPostRejectsTrailingJSONDocument(t *testing.T) { + handler := newTestHandler() // Construct the production transport without application dependencies. + request := newStreamablePOST(`{"jsonrpc":"2.0","method":"ping","id":1}{"jsonrpc":"2.0","method":"ping","id":2}`) // Build two valid envelopes concatenated into one HTTP body. + recorder := httptest.NewRecorder() // Capture the parse-error transport response. + handler.ServeHTTP(recorder, request) // Execute the concatenated body through strict single-document decoding. + if recorder.Code != http.StatusBadRequest { // Require transport rejection before either request can dispatch. + t.Fatalf("expected status %d, got %d", http.StatusBadRequest, recorder.Code) // Surface accidental acceptance or misclassification. + } +} + +// TestAcceptsContentTypeHonorsQuality verifies that explicitly unacceptable media types do not satisfy Streamable HTTP response negotiation. +func TestAcceptsContentTypeHonorsQuality(t *testing.T) { + if acceptsContentType("application/json;q=0, text/event-stream", contentTypeJSON) { // Check that an explicit zero JSON quality does not count as supported. + t.Fatal("expected application/json with q=0 to be rejected") // Surface accidental response negotiation that could return a forbidden representation. + } + if !acceptsContentType("application/json;q=0.5, text/event-stream", contentTypeJSON) { // Check that a positive valid quality still advertises JSON support. + t.Fatal("expected application/json with positive quality to be accepted") // Surface overly strict parsing that would reject a compliant client. + } +} + +// TestPostInitializeReturnsJSONAndProtocolVersion verifies that initialize can negotiate before the version header exists. +func TestPostInitializeReturnsJSONAndProtocolVersion(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only Streamable HTTP handler. + request := newStreamablePOST(`{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}},"id":1}`) // Build an initialize request without MCP-Protocol-Version because negotiation has not completed yet. + recorder := httptest.NewRecorder() // Capture the response so status, headers, and body can be asserted. + + handler.ServeHTTP(recorder, request) // Execute the initialize request through the production Streamable HTTP handler. + + if recorder.Code != http.StatusOK { // Fail when request-style initialize no longer returns a JSON response. + t.Fatalf("expected HTTP 200, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the response body so transport regressions are easy to diagnose. + } + if recorder.Header().Get(protocolVersionHeader) != mcp.LegacyProtocolVersion { // Fail when the response no longer echoes the fallback legacy protocol version. + t.Fatalf("expected protocol header %s, got %q", mcp.LegacyProtocolVersion, recorder.Header().Get(protocolVersionHeader)) // Surface the actual header for negotiation debugging. + } + if !strings.Contains(recorder.Body.String(), `"protocolVersion":"2025-06-18"`) { // Fail when an unknown legacy initialize request does not receive the historical fallback version. + t.Fatalf("expected initialize body to contain target protocol version, got %s", recorder.Body.String()) // Surface the actual body so protocol-version regressions are obvious. + } +} + +// TestPostPingRequiresProtocolVersionHeader verifies that post-initialize requests must include MCP-Protocol-Version. +func TestPostPingRequiresProtocolVersionHeader(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only Streamable HTTP handler. + request := newStreamablePOST(`{"jsonrpc":"2.0","method":"ping","id":2}`) // Build one post-initialize request without the required protocol-version header. + recorder := httptest.NewRecorder() // Capture the response so status and body can be asserted. + + handler.ServeHTTP(recorder, request) // Execute the invalid request through the production Streamable HTTP handler. + + if recorder.Code != http.StatusBadRequest { // Fail when the transport accepts a post-initialize request without protocol version. + t.Fatalf("expected HTTP 400, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the response body so header-validation regressions are easy to diagnose. + } + if !strings.Contains(recorder.Body.String(), "unsupported MCP protocol version") { // Fail when the diagnostic no longer explains the protocol-version rejection. + t.Fatalf("expected protocol-version diagnostic, got %s", recorder.Body.String()) // Surface the body so validation regressions are easy to diagnose. + } +} + +// TestPostPingReturnsJSONWhenProtocolVersionMatches verifies that request-style POSTs return one JSON-RPC response body. +func TestPostPingReturnsJSONWhenProtocolVersionMatches(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only Streamable HTTP handler. + request := newStreamablePOST(`{"jsonrpc":"2.0","method":"ping","id":"p"}`) // Build one valid ping request so request response semantics can be asserted. + request.Header.Set(protocolVersionHeader, mcp.LegacyProtocolVersion) // Attach the negotiated legacy MCP protocol version required after initialize. + recorder := httptest.NewRecorder() // Capture the response so status, headers, and body can be asserted. + + handler.ServeHTTP(recorder, request) // Execute the valid ping request through the production Streamable HTTP handler. + + if recorder.Code != http.StatusOK { // Fail when request-style POST no longer returns HTTP 200 with a JSON-RPC envelope. + t.Fatalf("expected HTTP 200, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the response body so transport regressions are easy to diagnose. + } + if recorder.Header().Get("Content-Type") != contentTypeJSON { // Fail when the request response is no longer served as application/json. + t.Fatalf("expected content type %s, got %q", contentTypeJSON, recorder.Header().Get("Content-Type")) // Surface the actual header so content negotiation regressions are obvious. + } + if !strings.Contains(recorder.Body.String(), `"id":"p"`) || !strings.Contains(recorder.Body.String(), `"result":{}`) { // Fail when ping no longer returns the expected JSON-RPC result envelope. + t.Fatalf("expected ping JSON-RPC response, got %s", recorder.Body.String()) // Surface the actual body so request-response regressions are obvious. + } +} + +// TestPostPingEchoesLargeNumericIDExactly verifies that Streamable HTTP preserves arbitrary-size JSON-RPC integer identifiers through its wire envelope. +func TestPostPingEchoesLargeNumericIDExactly(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only Streamable HTTP handler for the legacy ping path. + request := newStreamablePOST(`{"jsonrpc":"2.0","method":"ping","id":9007199254740993}`) // Use an integer above IEEE-754's exact range to detect lossy generic decoding. + request.Header.Set(protocolVersionHeader, mcp.LegacyProtocolVersion) // Attach the negotiated legacy revision required by the ping transport contract. + recorder := httptest.NewRecorder() // Capture the exact JSON response body. + handler.ServeHTTP(recorder, request) // Execute through the Streamable HTTP wire-message custom unmarshaler and shared JSON-RPC handler. + if recorder.Code != http.StatusOK { // Require normal request-response success for the valid large identifier. + t.Fatalf("expected HTTP 200, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface transport output on precision regression. + } + if !strings.Contains(recorder.Body.String(), `"id":9007199254740993`) { // Require the original integer text rather than a float64-rounded value. + t.Fatalf("expected exact large numeric id in response, got %s", recorder.Body.String()) // Surface the full response for diagnosis. + } +} + +// TestPostNotificationReturnsAcceptedNoBody verifies that accepted notifications return HTTP 202 with no JSON-RPC body. +func TestPostNotificationReturnsAcceptedNoBody(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only Streamable HTTP handler. + request := newStreamablePOST(`{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}`) // Build one initialized notification with no id. + request.Header.Set(protocolVersionHeader, mcp.LegacyProtocolVersion) // Attach the negotiated legacy MCP protocol version required after initialize. + recorder := httptest.NewRecorder() // Capture the response so status and body can be asserted. + + handler.ServeHTTP(recorder, request) // Execute the notification through the production Streamable HTTP handler. + + if recorder.Code != http.StatusAccepted { // Fail when accepted notifications no longer return the Streamable HTTP 202 status. + t.Fatalf("expected HTTP 202, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the response body so notification regressions are easy to diagnose. + } + if recorder.Body.Len() != 0 { // Fail when notifications emit a JSON-RPC response body. + t.Fatalf("expected empty notification body, got %q", recorder.Body.String()) // Surface the unexpected body so notification semantics are obvious. + } +} + +// TestPostResponseReturnsAcceptedNoBody verifies that client JSON-RPC responses are accepted without dispatch. +func TestPostResponseReturnsAcceptedNoBody(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only Streamable HTTP handler. + request := newStreamablePOST(`{"jsonrpc":"2.0","result":{"ok":true},"id":3}`) // Build one JSON-RPC response envelope from a client. + request.Header.Set(protocolVersionHeader, mcp.LegacyProtocolVersion) // Attach the negotiated legacy MCP protocol version required after initialize. + recorder := httptest.NewRecorder() // Capture the response so status and body can be asserted. + + handler.ServeHTTP(recorder, request) // Execute the response envelope through the production Streamable HTTP handler. + + if recorder.Code != http.StatusAccepted { // Fail when accepted JSON-RPC responses no longer return Streamable HTTP 202. + t.Fatalf("expected HTTP 202, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the response body so response-acceptance regressions are easy to diagnose. + } + if recorder.Body.Len() != 0 { // Fail when client responses emit any server response body. + t.Fatalf("expected empty response body, got %q", recorder.Body.String()) // Surface the unexpected body so response semantics are obvious. + } +} + +// TestGetReturnsMethodNotAllowedWhenSSEUnavailable verifies the allowed no-SSE GET behavior for the MCP endpoint. +func TestGetReturnsMethodNotAllowedWhenSSEUnavailable(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only Streamable HTTP handler. + request := httptest.NewRequest(http.MethodGet, "/mcp", nil) // Build one GET request targeting the MCP endpoint. + request.Header.Set("Accept", contentTypeSSE) // Advertise SSE support so the handler reaches the no-stream decision. + request.Header.Set(protocolVersionHeader, mcp.LegacyProtocolVersion) // Attach one legacy version to prove GET rejection no longer depends on negotiation state. + recorder := httptest.NewRecorder() // Capture the response so status can be asserted. + + handler.ServeHTTP(recorder, request) // Execute the GET request through the production Streamable HTTP handler. + + if recorder.Code != http.StatusMethodNotAllowed { // Fail when the no-SSE GET path no longer returns the spec-allowed 405 status. + t.Fatalf("expected HTTP 405, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the response body so GET behavior regressions are easy to diagnose. + } +} + +// TestPostRejectsMismatchedOrigin verifies that browser-originated requests must be same-origin when no explicit allowlist exists. +func TestPostRejectsMismatchedOrigin(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only Streamable HTTP handler with same-origin fallback. + request := newStreamablePOST(`{"jsonrpc":"2.0","method":"ping","id":1}`) // Build one otherwise-valid request so origin rejection is isolated. + request.Header.Set(protocolVersionHeader, mcp.LegacyProtocolVersion) // Attach the negotiated legacy MCP protocol version required after initialize. + request.Header.Set("Origin", "https://evil.example") // Simulate a browser request from a different host than the MCP endpoint. + recorder := httptest.NewRecorder() // Capture the response so status can be asserted. + + handler.ServeHTTP(recorder, request) // Execute the request through the production Streamable HTTP handler. + + if recorder.Code != http.StatusForbidden { // Fail when mismatched browser origins are no longer rejected. + t.Fatalf("expected HTTP 403, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the body so origin-policy regressions are easy to diagnose. + } +} + +// TestModernDiscoverReturnsCurrentProtocolMetadata verifies mandatory stateless discovery and modern result decoration over Streamable HTTP. +func TestModernDiscoverReturnsCurrentProtocolMetadata(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because server/discover does not require an orchestrator. + body := `{"jsonrpc":"2.0","method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"test","version":"1.0.0"}}},"id":"discover"}` // Build a complete stateless discovery request using the current protocol metadata fields. + request := newModernPOST(body, "server/discover", "", mcp.CurrentProtocolVersion) // Mirror the modern version and discovery method in required HTTP headers. + recorder := httptest.NewRecorder() // Capture the discovery response status, version header, and JSON result. + + handler.ServeHTTP(recorder, request) // Execute discovery through the production modern HTTP path. + + if recorder.Code != http.StatusOK { // Fail when mandatory discovery does not produce one successful JSON-RPC response. + t.Fatalf("expected HTTP 200, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the response body so discovery failures are actionable. + } + if recorder.Header().Get(protocolVersionHeader) != mcp.CurrentProtocolVersion { // Require the response to identify the implemented modern protocol revision. + t.Fatalf("expected current protocol header, got %q", recorder.Header().Get(protocolVersionHeader)) // Surface the actual version header for negotiation debugging. + } + for _, expected := range []string{`"resultType":"complete"`, `"supportedVersions":["2026-07-28"`, `"io.modelcontextprotocol/serverInfo"`, `"ttlMs":3600000`, `"cacheScope":"public"`} { // Assert each mandatory or advertised discovery field independently of JSON map ordering. + if !strings.Contains(recorder.Body.String(), expected) { // Fail when any modern discovery or base-result field is absent. + t.Fatalf("expected discovery body to contain %s, got %s", expected, recorder.Body.String()) // Name the missing fragment and preserve the full response for diagnosis. + } + } +} + +// TestModernRequestRequiresPerRequestMetadata verifies that a current-version HTTP header cannot substitute for stateless body metadata. +func TestModernRequestRequiresPerRequestMetadata(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler for metadata validation. + request := newModernPOST(`{"jsonrpc":"2.0","method":"tools/list","params":{},"id":1}`, "tools/list", "", mcp.CurrentProtocolVersion) // Build a header-complete request that deliberately omits params._meta. + recorder := httptest.NewRecorder() // Capture the required modern malformed-request response. + + handler.ServeHTTP(recorder, request) // Execute the request through modern header and metadata validation. + + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":-32602`) { // Require HTTP 400 and the protocol-mandated invalid-params code. + t.Fatalf("expected missing metadata HTTP 400/-32602, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface both transport and JSON-RPC outputs on regression. + } +} + +// TestModernRequestRejectsMethodHeaderMismatch verifies the protocol-reserved HeaderMismatch response before dispatch. +func TestModernRequestRejectsMethodHeaderMismatch(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because rejection occurs before method execution. + body := `{"jsonrpc":"2.0","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}},"id":2}` // Build one otherwise-valid tools/list request. + request := newModernPOST(body, "tools/call", "", mcp.CurrentProtocolVersion) // Deliberately mirror a different method in the required HTTP header. + recorder := httptest.NewRecorder() // Capture the header-validation error envelope. + + handler.ServeHTTP(recorder, request) // Execute the mismatch through the production validation path. + + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":-32020`) { // Require the exact modern HeaderMismatch status and code. + t.Fatalf("expected method mismatch HTTP 400/-32020, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the unexpected response for transport debugging. + } +} + +// TestModernRequestReturnsSupportedVersionsForUnknownRevision verifies retryable protocol negotiation without an initialize handshake. +func TestModernRequestReturnsSupportedVersionsForUnknownRevision(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because version rejection occurs before discovery execution. + body := `{"jsonrpc":"2.0","method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"1900-01-01","io.modelcontextprotocol/clientCapabilities":{}}},"id":3}` // Build a structurally valid discovery request for an unavailable revision. + request := newModernPOST(body, "server/discover", "", "1900-01-01") // Keep HTTP and body versions consistent so the version error is not masked by HeaderMismatch. + recorder := httptest.NewRecorder() // Capture the retry metadata returned with the modern error. + + handler.ServeHTTP(recorder, request) // Execute unsupported-version selection through the production transport. + + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":-32022`) { // Require the protocol-reserved unsupported-version error. + t.Fatalf("expected unsupported version HTTP 400/-32022, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface transport and JSON-RPC outputs on regression. + } + if !strings.Contains(recorder.Body.String(), `"supported":["2026-07-28","2025-11-25","2025-06-18"]`) || !strings.Contains(recorder.Body.String(), `"requested":"1900-01-01"`) { // Require enough data for deterministic client retry or legacy fallback. + t.Fatalf("expected supported/requested version data, got %s", recorder.Body.String()) // Surface the incomplete negotiation payload. + } +} + +// TestModernRemovedPingReturnsHTTPNotFound verifies that a legacy lifecycle method is not exposed under current stateless semantics. +func TestModernRemovedPingReturnsHTTPNotFound(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because ping never reaches an orchestrator. + body := `{"jsonrpc":"2.0","method":"ping","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}},"id":4}` // Build a current-protocol request for the removed ping method. + request := newModernPOST(body, "ping", "", mcp.CurrentProtocolVersion) // Supply every modern header so only method availability is under test. + recorder := httptest.NewRecorder() // Capture the modern unknown-method status and envelope. + + handler.ServeHTTP(recorder, request) // Execute the removed method through modern dispatch gating. + + if recorder.Code != http.StatusNotFound || !strings.Contains(recorder.Body.String(), `"code":-32601`) { // Require the current transport's explicit 404 plus JSON-RPC method-not-found code. + t.Fatalf("expected modern ping HTTP 404/-32601, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the unexpected response for era-selection debugging. + } +} + +// TestModernRequestRejectsNameHeaderMismatch verifies target identity consistency for tools/call before any tool execution. +func TestModernRequestRejectsNameHeaderMismatch(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because the mismatch prevents healthCheck execution. + body := `{"jsonrpc":"2.0","method":"tools/call","params":{"name":"healthCheck","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}},"id":5}` // Build one valid target-bearing modern request. + request := newModernPOST(body, "tools/call", "startSession", mcp.CurrentProtocolVersion) // Deliberately mirror a different tool identity in Mcp-Name. + recorder := httptest.NewRecorder() // Capture the pre-dispatch HeaderMismatch response. + + handler.ServeHTTP(recorder, request) // Execute the request through standard target-header validation. + + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":-32020`) { // Require an exact HeaderMismatch result for target disagreement. + t.Fatalf("expected name mismatch HTTP 400/-32020, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the unexpected result for routing-safety debugging. + } +} + +// TestModernNameHeaderAcceptsBase64Sentinel verifies that an explicitly encoded request target is decoded safely before normal method dispatch. +func TestModernNameHeaderAcceptsBase64Sentinel(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because prompts/get is intentionally unimplemented after header validation. + body := `{"jsonrpc":"2.0","method":"prompts/get","params":{"name":"weather-test","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}},"id":6}` // Build a modern target-bearing request that will reach method gating. + encodedName := base64ValuePrefix + base64.StdEncoding.EncodeToString([]byte("weather-test")) + base64ValueSuffix // Encode even a safe ASCII sentinel payload to verify exact Base64 decoding support. + request := newModernPOST(body, "prompts/get", encodedName, mcp.CurrentProtocolVersion) // Supply the sentinel-encoded target under Mcp-Name. + recorder := httptest.NewRecorder() // Capture the post-validation method-not-found response. + + handler.ServeHTTP(recorder, request) // Execute the encoded header through decoding, comparison, and modern dispatch. + + if recorder.Code != http.StatusNotFound || !strings.Contains(recorder.Body.String(), `"code":-32601`) { // Prove header validation succeeded by observing the later unimplemented-method response. + t.Fatalf("expected decoded name to reach HTTP 404/-32601, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface a HeaderMismatch if decoding regresses. + } +} + +// TestDecodeMCPHeaderValueAcceptsPartialSentinelText verifies that safe ASCII matching only one sentinel marker remains an ordinary plain header value. +func TestDecodeMCPHeaderValueAcceptsPartialSentinelText(t *testing.T) { + plainValue := "=?base64?literal-name" // Build one safe ASCII name with the sentinel prefix but no closing marker. + decodedValue, err := decodeMCPHeaderValue(plainValue) // Decode the value through the production header safety helper. + if err != nil { // Fail when one unambiguous partial marker is incorrectly treated as malformed Base64. + t.Fatalf("expected partial sentinel text to remain plain, got %v", err) // Surface the unexpected header-validation failure. + } + if decodedValue != plainValue { // Require exact byte preservation for plain ASCII request target comparison. + t.Fatalf("expected decoded value %q, got %q", plainValue, decodedValue) // Surface unwanted mutation of the valid target name. + } +} + +// TestModernToolsListReturnsCacheAndSchemaMetadata verifies the current tool catalog's result, cache, and JSON Schema dialect fields end to end. +func TestModernToolsListReturnsCacheAndSchemaMetadata(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because tools/list reads only the embedded registry. + body := `{"jsonrpc":"2.0","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}},"id":7}` // Build one complete modern tool discovery request. + request := newModernPOST(body, "tools/list", "", mcp.CurrentProtocolVersion) // Supply the two standard headers required for a non-targeted modern method. + recorder := httptest.NewRecorder() // Capture the fully decorated tool catalog response. + + handler.ServeHTTP(recorder, request) // Execute tool discovery through modern HTTP and shared JSON-RPC layers. + + if recorder.Code != http.StatusOK { // Require successful current-protocol tool discovery. + t.Fatalf("expected modern tools/list HTTP 200, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the full response on failure. + } + for _, expected := range []string{`"resultType":"complete"`, `"ttlMs":300000`, `"cacheScope":"public"`, `"$schema":"https://json-schema.org/draft/2020-12/schema"`} { // Assert all alignment fields independently of catalog length and map ordering. + if !strings.Contains(recorder.Body.String(), expected) { // Fail when result decoration, caching, or dialect advertisement regresses. + t.Fatalf("expected tools/list body to contain %s, got %s", expected, recorder.Body.String()) // Name the missing current-protocol field. + } + } +} + +// TestModernClientResponseIsRejected verifies that the current Streamable HTTP binding no longer accepts client JSON-RPC response envelopes. +func TestModernClientResponseIsRejected(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because the transport rejects the envelope before dispatch. + request := newModernPOST(`{"jsonrpc":"2.0","result":{"ok":true},"id":8}`, "unused", "", mcp.CurrentProtocolVersion) // Build a methodless modern response envelope with a current-version header. + recorder := httptest.NewRecorder() // Capture the modern invalid-request response. + + handler.ServeHTTP(recorder, request) // Execute the forbidden envelope through transport classification. + + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":-32600`) { // Require explicit rejection instead of the legacy empty 202 behavior. + t.Fatalf("expected modern client response HTTP 400/-32600, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the unexpected response for era behavior debugging. + } +} + +// TestModernClientNotificationIsRejected verifies that current Streamable HTTP uses request-stream closure rather than client cancellation notifications. +func TestModernClientNotificationIsRejected(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because the transport rejects the notification before cancellation dispatch. + body := `{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"active-request","_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}` // Build a complete current-protocol cancellation notification without a JSON-RPC id. + request := newStreamablePOST(body) // Omit modern request headers because current Streamable HTTP defines no header contract for unsupported client notifications. + recorder := httptest.NewRecorder() // Capture the transport-level invalid-request response. + + handler.ServeHTTP(recorder, request) // Execute the unsupported notification through modern Streamable HTTP classification. + + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":-32600`) { // Require explicit rejection instead of dispatching stdio-only cancellation behavior. + t.Fatalf("expected modern notification HTTP 400/-32600, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the unexpected status or JSON-RPC code. + } +} + +// TestModernRequestRejectsExplicitNullID verifies that an id member set to JSON null is not treated as a fire-and-forget notification. +func TestModernRequestRejectsExplicitNullID(t *testing.T) { + handler := newTestHandler() // Construct one protocol-only handler because request classification fails before tools/list dispatch. + body := `{"jsonrpc":"2.0","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}},"id":null}` // Build a header-complete modern request whose explicit null id violates MCP request rules. + request := newModernPOST(body, "tools/list", "", mcp.CurrentProtocolVersion) // Supply valid mirrored headers so only id classification is under test. + recorder := httptest.NewRecorder() // Capture the invalid-request status and JSON-RPC error body. + + handler.ServeHTTP(recorder, request) // Execute the malformed request through production wire decoding and classification. + + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":-32600`) { // Require a JSON-RPC Invalid Request response rather than notification-style HTTP 202. + t.Fatalf("expected explicit null id HTTP 400/-32600, got %d with body %s", recorder.Code, recorder.Body.String()) // Surface the unexpected transport behavior. + } +} diff --git a/internal/gateway/middleware/auth.go b/internal/gateway/middleware/auth.go index 39f884a..8c1e6f2 100644 --- a/internal/gateway/middleware/auth.go +++ b/internal/gateway/middleware/auth.go @@ -2,14 +2,18 @@ package middleware import ( - "bytes" "context" - "io" + "log/slog" "net/http" "strings" + "mcp_for_appium/internal/audit" "mcp_for_appium/internal/auth" "mcp_for_appium/internal/errors" + "mcp_for_appium/internal/gateway/httpinput" + "mcp_for_appium/internal/telemetry" + + "github.com/google/uuid" ) // patValidator defines the PAT validation contract consumed by the HTTP auth middleware. @@ -35,6 +39,8 @@ type AuthMiddleware struct { patValidator patValidator oidcValidator oidcValidator hmacValidator hmacValidator + auditRecorder audit.Recorder + logger *slog.Logger } // NewAuthMiddleware constructs the gateway auth middleware when at least one validator has been configured. @@ -43,7 +49,15 @@ func NewAuthMiddleware(hmac *auth.HMACValidator, oidc *auth.OIDCValidator, pat * return nil // Signal to the caller that no auth wrapper is needed because there is no active credential source. } - return &AuthMiddleware{hmacValidator: hmac, oidcValidator: oidc, patValidator: pat} // Store the configured validators once so every request can authenticate against the same startup-built set. + return &AuthMiddleware{hmacValidator: hmac, oidcValidator: oidc, patValidator: pat, logger: telemetry.Logger()} // Store the configured validators and logger once so every request shares the same authentication and audit diagnostics. +} + +// SetAuditRecorder installs the append-only recorder used for authentication success and failure events. +func (m *AuthMiddleware) SetAuditRecorder(recorder audit.Recorder) { + if m == nil { // Ignore optional wiring when authentication itself is disabled and no middleware was constructed. + return // Keep startup wiring concise without dereferencing a nil middleware. + } + m.auditRecorder = recorder // Store the shared recorder so every protected request emits one best-effort authentication audit event. } // Handle wraps an HTTP handler with gateway request authentication. @@ -53,17 +67,117 @@ func (m *AuthMiddleware) Handle(next http.Handler) http.Handler { } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Build one auth-enforcing wrapper around the protected handler. - subject, err := m.authenticate(r) // Resolve the caller identity before the protected handler is allowed to run. - if err != nil { // Stop request processing when none of the configured auth schemes accept the request. - http.Error(w, err.Error(), errors.MapToHTTP(err)) // Return a transport-appropriate auth status so clients can distinguish missing credentials from permission failures. - return // Stop before the protected handler runs because the request has not been authenticated successfully. + requestID := strings.TrimSpace(r.Header.Get("X-Request-ID")) // Reuse a caller or upstream request identifier when supplied for end-to-end correlation. + if requestID == "" { // Generate a trustworthy local correlation identifier when the request omitted one. + requestID = uuid.NewString() // Assign one random request identifier without deriving it from credentials or body content. + } + w.Header().Set("X-Request-ID", requestID) // Return the effective request identifier so callers can correlate responses, logs, and audit records. + subject, err := m.authenticate(r) // Resolve the caller identity before the protected handler is allowed to run. + if err != nil { // Stop request processing when none of the configured auth schemes accept the request. + m.recordAuthentication(r, requestID, nil, err) // Record the rejected attempt without storing bearer tokens, signatures, or raw backend errors. + status := errors.MapToHTTP(err) // Map typed authentication failures without exposing their wrapped backend causes. + message := "authentication failed" // Return one stable public diagnostic for ordinary credential failures. + if httpinput.IsBodyTooLarge(err) { // Preserve the request-size contract when HMAC body hashing encounters the byte ceiling. + status = http.StatusRequestEntityTooLarge // Return HTTP 413 so clients can distinguish size rejection from invalid credentials. + message = "request body too large" // Explain the actionable transport constraint without reflecting request content. + } + http.Error(w, message, status) // Write only the sanitized public diagnostic and mapped transport status. + return // Stop before the protected handler runs because the request has not been authenticated successfully. } + m.recordAuthentication(r, requestID, subject, nil) // Record successful authentication before application dispatch under the resolved principal. - ctx := auth.WithSubject(r.Context(), subject) // Attach the authenticated subject to the request context so downstream handlers can read tenant and principal metadata. - next.ServeHTTP(w, r.WithContext(ctx)) // Forward the authenticated request to the protected handler with the injected subject context. + auditContext := audit.WithRequestContext(r.Context(), audit.RequestContext{RequestID: requestID, SourceIP: audit.RequestSourceIP(r)}) // Attach sanitized request correlation for downstream audit producers. + ctx := auth.WithSubject(auditContext, subject) // Attach the authenticated subject to the correlated request context so downstream handlers can read tenant and principal metadata. + next.ServeHTTP(w, r.WithContext(ctx)) // Forward the authenticated request to the protected handler with the injected subject context. }) } +// recordAuthentication appends one sanitized authentication outcome without changing request success when the audit sink is unavailable. +func (m *AuthMiddleware) recordAuthentication(r *http.Request, requestID string, subject *auth.Subject, authErr error) { + if m == nil || m.auditRecorder == nil { // Skip optional audit work when startup did not configure a recorder. + return // Preserve authentication behavior in protocol-only tests and deployments without PostgreSQL wiring. + } + event := audit.Event{ // Build the complete sanitized authentication audit record before determining the outcome. + ActorID: "anonymous", // Attribute rejected pre-authentication attempts without inventing a principal. + ActorType: "anonymous", // Classify the pre-authentication actor explicitly for security queries. + AuthScheme: requestAuthScheme(r), // Record only the classified credential scheme, never the credential value. + CredentialID: requestCredentialID(r), // Record a safe key or PAT identifier when it can be extracted without a secret. + Action: "auth.authenticate", // Use one stable action for both successful and rejected protected requests. + ResourceType: "http_route", // Classify the protected route as the resource under authentication. + ResourceID: r.URL.Path, // Record the requested path without query parameters that may carry subscription tokens. + Result: "failure", // Default to failure until a validated subject proves success below. + Reason: auditErrorReason(authErr), // Record a stable internal code or generic marker without wrapped error text. + SourceIP: audit.RequestSourceIP(r), // Record the directly observed peer address for investigation. + RequestID: strings.TrimSpace(requestID), // Correlate this audit row with response and telemetry identifiers. + } + if subject != nil && authErr == nil { // Populate authoritative principal fields only after one validator succeeds. + event.ActorID = strings.TrimSpace(subject.ID) // Record the authenticated principal identifier. + event.ActorType = "subject" // Classify authenticated callers uniformly while AuthScheme preserves credential type. + event.AuthScheme = strings.TrimSpace(subject.Type) // Prefer the validator-produced scheme over request-shape inference. + event.CredentialID = strings.TrimSpace(subject.CredentialID) // Record the safe token or key identifier supplied by the validator. + event.TenantID = strings.TrimSpace(subject.TenantID) // Preserve the authenticated tenant scope for audit filtering. + event.Result = "success" // Mark the request as authenticated successfully. + event.Reason = "" // Keep successful authentication records free of failure reason text. + } + if err := m.auditRecorder.Record(r.Context(), event); err != nil { // Append the audit event without allowing recorder availability to bypass or reject authentication. + logger := m.logger // Reuse the middleware logger when constructor wiring supplied one. + if logger == nil { // Fall back to the current global logger for zero-value middleware instances used in tests. + logger = telemetry.Logger() // Preserve observability for audit persistence failures without panicking. + } + logger.WarnContext(r.Context(), "failed to record authentication audit event", "request_id", requestID, "result", event.Result, "error", err) // Log the recorder failure without credential or raw request data. + } +} + +// requestAuthScheme classifies one request credential shape without validating or persisting the credential value. +func requestAuthScheme(r *http.Request) string { + if r == nil { // Return unknown when no request metadata exists. + return "unknown" // Avoid dereferencing nil in failure-path audit handling. + } + if hasAnyHMACHeaders(r) { // Classify every complete or partial HMAC attempt consistently with authentication routing. + return "hmac" // Record only the scheme name without any signature material. + } + authorization := strings.TrimSpace(r.Header.Get("Authorization")) // Read the bearer transport only for shape classification. + rawToken, err := parseBearerToken(authorization) // Reuse strict bearer parsing while keeping errors private. + if err != nil { // Classify missing or malformed Authorization headers generically. + return "unknown" // Avoid reflecting malformed header values into audit metadata. + } + if looksLikePAT(rawToken) { // Match the stable repository PAT prefix. + return "pat" // Record the PAT scheme without persisting its secret. + } + if looksLikeJWT(rawToken) { // Match the compact three-segment JWT shape. + return "oidc" // Record the OIDC scheme without parsing or persisting the raw JWT. + } + return "bearer" // Classify unsupported bearer formats without exposing their contents. +} + +// requestCredentialID extracts only a safe HMAC key ID or PAT token ID for audit correlation. +func requestCredentialID(r *http.Request) string { + if r == nil { // Return no credential identifier when request metadata is unavailable. + return "" // Avoid dereferencing nil in failure-path audit handling. + } + if hasAnyHMACHeaders(r) { // Use the dedicated non-secret key identifier from HMAC attempts. + return strings.TrimSpace(r.Header.Get("X-MCP-Key-Id")) // Never record the HMAC signature, nonce, or shared secret. + } + rawToken, err := parseBearerToken(strings.TrimSpace(r.Header.Get("Authorization"))) // Parse the bearer envelope without validating its secret. + if err != nil || !looksLikePAT(rawToken) { // Return no identifier for malformed bearer values and opaque JWTs. + return "" // Avoid decoding or persisting any part of unsupported credentials. + } + tokenBody := strings.TrimPrefix(strings.TrimSpace(rawToken), "mcp_v1_") // Remove the fixed PAT prefix before locating the ID/secret separator. + separatorIndex := strings.Index(tokenBody, "_") // Locate the first separator after the safe token identifier. + if separatorIndex <= 0 { // Reject malformed PAT bodies without a complete identifier. + return "" // Avoid persisting an ambiguous or secret-bearing fragment. + } + return strings.TrimSpace(tokenBody[:separatorIndex]) // Return only the token ID segment before the secret. +} + +// auditErrorReason returns one stable repository error code or a generic failure marker without exposing wrapped backend details. +func auditErrorReason(err error) string { + if code, ok := errors.CodeOf(err); ok { // Prefer the repository's machine-readable error classification when available. + return string(code) // Store only the stable code in the append-only audit record. + } + return "unclassified_failure" // Classify untyped failures without copying their error text. +} + // authenticate resolves one request by classifying the presented credentials and delegating to the single matching validator. func (m *AuthMiddleware) authenticate(r *http.Request) (*auth.Subject, error) { if m == nil { // Defend against accidental direct calls on a nil middleware even though Handle already guards this case. @@ -106,8 +220,8 @@ func (m *AuthMiddleware) authenticate(r *http.Request) (*auth.Subject, error) { // authenticateHMAC validates one HMAC-signed HTTP request while restoring the request body for downstream handlers. func (m *AuthMiddleware) authenticateHMAC(r *http.Request) (*auth.Subject, error) { - body, err := cloneRequestBody(r) // Read and restore the request body so HMAC validation can hash it without consuming it for downstream handlers. - if err != nil { // Stop immediately when the request body cannot be read because signature validation would become unreliable. + body, err := httpinput.ReadAndRestoreBody(r, httpinput.MaxRequestBodyBytes) // Read and restore a bounded request body so HMAC validation cannot consume unbounded memory. + if err != nil { // Stop immediately when the request body cannot be read because signature validation would become unreliable. return nil, errors.Wrap(errors.CodeUnauthenticated, "failed to read request body for HMAC validation", err) // Surface the body-read failure as an authentication error because the request cannot be verified safely. } @@ -160,18 +274,3 @@ func looksLikeJWT(rawToken string) bool { return true // Report the three-segment non-empty token as JWT-shaped so the request routes into OIDC validation only. } - -// cloneRequestBody reads the current request body and replaces it with a fresh reader over the same bytes. -func cloneRequestBody(r *http.Request) ([]byte, error) { - if r.Body == nil { // Treat nil bodies as empty so GET and body-less requests can still participate in HMAC verification deterministically. - return nil, nil // Return an empty byte slice equivalent without mutating the request because there is no body reader to restore. - } - - body, err := io.ReadAll(r.Body) // Read the original request body bytes so the HMAC validator can hash the exact payload sent by the client. - if err != nil { // Stop when the body cannot be read because the signed payload would be ambiguous and unsafe to verify. - return nil, err // Preserve the low-level body read failure for the caller so it can be wrapped appropriately. - } - r.Body = io.NopCloser(bytes.NewReader(body)) // Restore the request body so downstream handlers can parse the same bytes after HMAC verification succeeds. - - return body, nil // Return the cloned request body bytes to the caller for signature validation. -} diff --git a/internal/gateway/middleware/auth_test.go b/internal/gateway/middleware/auth_test.go index 4caec9e..1c97b82 100644 --- a/internal/gateway/middleware/auth_test.go +++ b/internal/gateway/middleware/auth_test.go @@ -3,9 +3,13 @@ package middleware import ( "context" + "encoding/json" + "net/http" "net/http/httptest" + "strings" "testing" + "mcp_for_appium/internal/audit" "mcp_for_appium/internal/auth" "mcp_for_appium/internal/errors" ) @@ -97,3 +101,78 @@ func TestAuthMiddlewareRoutesJWTToOIDC(t *testing.T) { t.Fatalf("expected OIDC subject oidc-subject, got %#v", subject) // Surface the unexpected returned subject so routing drift is easy to diagnose. } } + +// TestAuthMiddlewareRecordsSanitizedSuccess verifies that successful protected requests emit attributable audit metadata without bearer secrets. +func TestAuthMiddlewareRecordsSanitizedSuccess(t *testing.T) { + const rawToken = "mcp_v1_token-safe_super-secret-value" // Build one PAT whose safe identifier and secret can be distinguished in audit assertions. + var recordedEvents []audit.Event // Collect middleware audit records through an in-memory recorder. + recorder := audit.RecorderFunc(func(ctx context.Context, event audit.Event) error { // Adapt one deterministic callback into the production recorder contract. + recordedEvents = append(recordedEvents, event) // Preserve the exact event emitted before downstream request dispatch. + return nil // Keep audit persistence successful so authentication behavior remains the focus. + }) + patValidator := &fakePATValidator{subject: &auth.Subject{ID: "subject-audit", Type: "pat", TenantID: "tenant-audit", CredentialID: "token-safe"}} // Return one fully attributable authenticated subject. + middleware := &AuthMiddleware{patValidator: patValidator, auditRecorder: recorder} // Construct the middleware with strict PAT routing and the in-memory audit sink. + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Verify authenticated and correlated context reaches the protected handler. + if subject, ok := auth.SubjectFrom(r.Context()); !ok || subject.ID != "subject-audit" { // Require the validator-produced subject downstream. + t.Fatalf("expected authenticated subject in downstream context, got %#v", subject) // Surface context propagation regression. + } + if requestContext, ok := audit.RequestContextFrom(r.Context()); !ok || requestContext.RequestID != "request-audit-success" { // Require audit correlation metadata downstream. + t.Fatalf("expected request audit context downstream, got %#v", requestContext) // Surface missing request correlation. + } + w.WriteHeader(http.StatusNoContent) // Mark successful protected-handler execution without a response body. + }) + request := httptest.NewRequest(http.MethodGet, "/jsonrpc?ignored=secret", nil) // Build one protected request whose query must not appear as the audited resource id. + request.Header.Set("Authorization", "Bearer "+rawToken) // Present the PAT through the standard bearer transport. + request.Header.Set("X-Request-ID", "request-audit-success") // Supply one deterministic correlation id for assertions. + request.RemoteAddr = "192.0.2.10:4321" // Supply one deterministic directly observed peer address. + response := httptest.NewRecorder() // Capture the protected response and effective request id. + middleware.Handle(next).ServeHTTP(response, request) // Execute authentication, audit recording, and downstream context propagation. + if response.Code != http.StatusNoContent { // Require successful authentication to reach the protected handler. + t.Fatalf("expected HTTP 204, got %d with body %s", response.Code, response.Body.String()) // Surface unexpected auth rejection. + } + if len(recordedEvents) != 1 { // Require exactly one authentication outcome per protected request. + t.Fatalf("expected one authentication audit event, got %d", len(recordedEvents)) // Surface missing or duplicated audit writes. + } + event := recordedEvents[0] // Read the sole success event for field-level assertions. + if event.Result != "success" || event.ActorID != "subject-audit" || event.CredentialID != "token-safe" || event.ResourceID != "/jsonrpc" { // Require principal, safe credential id, and query-free route attribution. + t.Fatalf("unexpected authentication success audit event: %#v", event) // Surface malformed attribution without hiding fields. + } + serializedEvent, err := json.Marshal(event) // Serialize the complete event so every string field can be checked for secret leakage. + if err != nil { // Fail when the audit event cannot be serialized for persistence. + t.Fatalf("failed to serialize authentication audit event: %v", err) // Surface incompatible metadata immediately. + } + if strings.Contains(string(serializedEvent), "super-secret-value") || strings.Contains(string(serializedEvent), rawToken) { // Reject full or suffix credential disclosure anywhere in the event. + t.Fatalf("authentication audit event leaked PAT secret: %s", serializedEvent) // Surface the unsafe event payload for diagnosis. + } +} + +// TestAuthMiddlewareRecordsSanitizedFailure verifies that rejected credentials emit only a stable code and generic public response. +func TestAuthMiddlewareRecordsSanitizedFailure(t *testing.T) { + const backendSecret = "postgres-password=do-not-expose" // Embed a sentinel secret in the validator error to detect unsafe propagation. + var recordedEvent audit.Event // Capture the sole rejected authentication event. + recorder := audit.RecorderFunc(func(ctx context.Context, event audit.Event) error { // Adapt one deterministic callback into the recorder contract. + recordedEvent = event // Preserve the exact failure event emitted by middleware. + return nil // Keep audit persistence successful so sanitization remains the focus. + }) + patValidator := &fakePATValidator{err: errors.New(errors.CodeUnauthenticated, backendSecret)} // Return one typed failure whose raw message must stay private. + middleware := &AuthMiddleware{patValidator: patValidator, auditRecorder: recorder} // Construct the protected middleware with the failing validator and audit sink. + request := httptest.NewRequest(http.MethodGet, "/mcp", nil) // Build one protected request for rejected PAT authentication. + request.Header.Set("Authorization", "Bearer mcp_v1_token-failure_secret-material") // Present a PAT with a safe token identifier and private secret. + response := httptest.NewRecorder() // Capture the sanitized public authentication rejection. + middleware.Handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Install a handler that must never run after authentication failure. + t.Fatal("expected rejected authentication not to reach protected handler") // Fail immediately if middleware bypasses the validator error. + })).ServeHTTP(response, request) + if response.Code != http.StatusUnauthorized || strings.Contains(response.Body.String(), backendSecret) { // Require stable status and no backend diagnostic disclosure. + t.Fatalf("expected sanitized HTTP 401, got %d with body %s", response.Code, response.Body.String()) // Surface status or leakage regression. + } + if recordedEvent.Result != "failure" || recordedEvent.Reason != string(errors.CodeUnauthenticated) || recordedEvent.CredentialID != "token-failure" { // Require stable failure classification and safe PAT id extraction. + t.Fatalf("unexpected authentication failure audit event: %#v", recordedEvent) // Surface malformed failure attribution. + } + serializedEvent, err := json.Marshal(recordedEvent) // Serialize every audit field for sentinel leakage detection. + if err != nil { // Fail when the event cannot be serialized for persistence. + t.Fatalf("failed to serialize authentication failure audit event: %v", err) // Surface incompatible event metadata. + } + if strings.Contains(string(serializedEvent), backendSecret) || strings.Contains(string(serializedEvent), "secret-material") { // Reject validator diagnostics and PAT secrets anywhere in the audit row. + t.Fatalf("authentication failure audit event leaked secret data: %s", serializedEvent) // Surface the unsafe payload directly. + } +} diff --git a/internal/gateway/rest/router.go b/internal/gateway/rest/router.go index 5750d9c..428f9f5 100644 --- a/internal/gateway/rest/router.go +++ b/internal/gateway/rest/router.go @@ -79,7 +79,7 @@ func (rt *Router) handleTraceSubscriptionToken(w http.ResponseWriter, r *http.Re issuedToken, err := rt.subscriptionTokenStore.Issue(r.Context(), subject, traceID) // Issue the short-lived opaque token bound to the caller and requested trace ID. if err != nil { // Stop immediately when token issuance fails because no WebSocket subscription can be established without it. - writeAPIError(w, errors.MapToHTTP(err), "failed to issue subscription token", err) // Surface token-store failures with internal codes and raw cause details. + writeAPIError(w, errors.MapToHTTP(err), "failed to issue subscription token", err) // Surface token-store failures with a stable internal code and no backend cause text. return // Stop after the issuance failure because no valid response payload exists. } @@ -101,9 +101,7 @@ func writeJSON(w http.ResponseWriter, status int, v interface{}) { // writeAPIError writes one structured helper-endpoint error payload that preserves the internal error code when available. func writeAPIError(w http.ResponseWriter, status int, message string, err error) { internalCode := "" // Initialize the internal code field so untyped errors still produce a stable response shape. - rawError := "" // Initialize the raw-error field so downstream-native details can be preserved when an error is available. if err != nil { // Fill the structured error fields only when a downstream error has actually been supplied. - rawError = err.Error() // Preserve the exact wrapped or native error text for diagnostics. if code, ok := errors.CodeOf(err); ok { // Prefer the typed internal error code whenever the downstream error uses the repository-standard error wrapper. internalCode = string(code) // Copy the stable machine-readable internal code into the helper error envelope. } @@ -113,7 +111,6 @@ func writeAPIError(w http.ResponseWriter, status int, message string, err error) "error": map[string]interface{}{ // Nest the details under the conventional error key so clients can parse failures uniformly. "message": message, // Return the human-readable summary describing why the helper request failed. "internalCode": internalCode, // Return the stable machine-readable internal code when one was available downstream. - "rawError": rawError, // Return the original downstream or native error text for diagnostics. }, }) } diff --git a/internal/gateway/stdio/transport.go b/internal/gateway/stdio/transport.go index 0b29969..bf4da8e 100644 --- a/internal/gateway/stdio/transport.go +++ b/internal/gateway/stdio/transport.go @@ -45,7 +45,7 @@ func NewTransportWithIO(orch *orchestrator.Service, capSvc *capabilities.Service } } -// Run starts the stdio transport loop +// Run reads newline-delimited JSON-RPC messages, dispatches requests asynchronously, handles notifications synchronously, and writes responses to stdout until EOF or context cancellation. func (t *Transport) Run(ctx context.Context) error { // Log to stderr only (stdout is reserved for JSON-RPC responses) log.SetOutput(t.stderr) @@ -56,6 +56,7 @@ func (t *Transport) Run(ctx context.Context) error { buf := make([]byte, 0, 64*1024) scanner.Buffer(buf, 1024*1024) // 1MB max message size + var requestWG sync.WaitGroup // Track asynchronous request handlers so EOF can wait for already accepted work to finish before returning. for { select { case <-ctx.Done(): @@ -69,6 +70,7 @@ func (t *Transport) Run(ctx context.Context) error { } // EOF reached log.Println("EOF on stdin, shutting down") + requestWG.Wait() // Wait for accepted asynchronous requests to finish so EOF does not drop responses that were already in progress. return nil } @@ -78,7 +80,8 @@ func (t *Transport) Run(ctx context.Context) error { } // Process the JSON-RPC request - if err := t.handleRequest(ctx, line); err != nil { + lineCopy := append([]byte(nil), line...) // Copy the scanner buffer because request handling may continue asynchronously after the next Scan call. + if err := t.dispatchMessage(ctx, lineCopy, &requestWG); err != nil { // Dispatch the decoded line while keeping the read loop available for later notifications. log.Printf("Error handling request: %v", err) // Continue processing next request even if this one failed } @@ -86,23 +89,76 @@ func (t *Transport) Run(ctx context.Context) error { } } -// handleRequest processes a single JSON-RPC request +// dispatchMessage routes notifications synchronously and request messages asynchronously so cancellation notifications can be read while requests run. +func (t *Transport) dispatchMessage(ctx context.Context, reqData []byte, requestWG *sync.WaitGroup) error { + var req jsonrpc.Request + if err := json.Unmarshal(reqData, &req); err != nil { // Decode the line before deciding whether it can run asynchronously. + return t.writeError(nil, -32700, "Parse error", err.Error()) // Emit parse errors synchronously because malformed messages have no request id to track. + } + + if !jsonrpc.IsRequest(&req) { // Handle notifications and invalid methodless messages synchronously because they either suppress responses or fail quickly. + return t.handleDecodedRequest(ctx, &req) // Reuse the normal decoded-message path so notification logging and suppression remain identical. + } + + requestCtx, cleanup := t.prepareRequestContext(ctx, &req) // Register the request before starting the goroutine so later cancellation notifications can find it deterministically. + requestWG.Add(1) // Track the request goroutine so EOF can wait for this accepted request to finish. + go func() { // Process the request asynchronously so stdio can continue reading cancellation notifications. + defer requestWG.Done() // Mark this asynchronous request complete once response writing and cleanup finish. + defer cleanup() // Remove the request from the in-flight registry and release the context when processing ends. + if err := t.handleDecodedRequest(requestCtx, &req); err != nil { // Process the request on a goroutine so stdio can keep reading notifications. + log.Printf("Error handling request: %v", err) // Keep asynchronous request errors visible because dispatchMessage cannot return them after spawning. + } + }() + return nil // Report successful dispatch because the request goroutine now owns processing and response emission. +} + +// handleRequest processes one incoming JSON-RPC message and suppresses any response when the message is a notification. func (t *Transport) handleRequest(ctx context.Context, reqData []byte) error { var req jsonrpc.Request - if err := json.Unmarshal(reqData, &req); err != nil { - return t.writeError(nil, -32700, "Parse error", err.Error()) + if err := json.Unmarshal(reqData, &req); err != nil { // Decode the incoming line into one JSON-RPC message before dispatching it through the transport. + return t.writeError(nil, -32700, "Parse error", err.Error()) // Emit the standard parse-error response when the line is not valid JSON. + } + + requestCtx, cleanup := t.prepareRequestContext(ctx, &req) // Register request ids for cancellation while leaving notifications attached to the original context. + defer cleanup() // Remove the request from the in-flight registry and release context resources after synchronous processing. + return t.handleDecodedRequest(requestCtx, &req) // Process the decoded message through the shared transport path used by synchronous tests and asynchronous Run dispatch. +} + +// prepareRequestContext returns a cancellable request context and cleanup hook for request messages, or the original context for notifications. +func (t *Transport) prepareRequestContext(ctx context.Context, req *jsonrpc.Request) (context.Context, func()) { + if !jsonrpc.IsRequest(req) { // Skip in-flight registration for notifications because they have no id and must not be cancellable by request id. + return ctx, func() {} // Return a no-op cleanup so callers can always defer cleanup safely. } + requestCtx, cancel := context.WithCancel(ctx) // Create the cancellable child context that notifications/cancelled will trigger. + cleanup := t.handler.RegisterInFlightRequest(req.ID, cancel) // Register the request id and cancel hook before business dispatch begins. + return requestCtx, func() { // Return a cleanup closure that unregisters the request and releases the child context. + cleanup() // Remove the request id from the shared cancellation registry once processing finishes. + cancel() // Release context resources and make cleanup idempotent even when no cancellation notification arrived. + } // Return the cancellable context and cleanup closure to the caller. +} + +// handleDecodedRequest processes one decoded JSON-RPC message and emits a response only for request-style messages. +func (t *Transport) handleDecodedRequest(ctx context.Context, req *jsonrpc.Request) error { + isNotification := jsonrpc.IsNotification(req) // Classify the decoded message once so request-vs-notification response handling stays consistent below. + // Log the request to stderr log.Printf("Received request: method=%s id=%v", req.Method, req.ID) - if progressToken, ok := extractProgressToken(&req); ok { // Detect one optional MCP progress token so long-running tools can emit notifications/progress over stdio. + if progressToken, ok := extractProgressToken(req); ok { // Detect one optional MCP progress token so long-running tools can emit notifications/progress over stdio. ctx = mcp.WithProgressToken(ctx, progressToken) // Attach the client-supplied progress token so downstream tool handlers can correlate notifications correctly. ctx = mcp.WithProgressReporter(ctx, t.writeProgressNotification) // Attach the transport-backed progress reporter so downstream tool handlers can emit progress safely. } // Call the handler - result, err := t.processRequest(ctx, &req) + result, err := t.processRequest(ctx, req) // Dispatch the decoded message through the shared JSON-RPC handler. + + if isNotification { // Suppress all notification responses because JSON-RPC notifications are fire-and-forget messages. + if err != nil { // Log notification failures locally because the transport intentionally will not emit a JSON-RPC error envelope. + log.Printf("Ignoring notification error: method=%s error=%v", req.Method, err) // Preserve observability for malformed or unsupported notifications without polluting stdout. + } + return nil // Report transport success because the notification was consumed without any response write. + } if err != nil { // Check if it's an MCP error or other error @@ -113,7 +169,7 @@ func (t *Transport) handleRequest(ctx context.Context, reqData []byte) error { return t.writeResult(req.ID, result) } -// processRequest routes the request to the appropriate handler method +// processRequest routes one decoded JSON-RPC request or notification to the shared handler after validating the protocol version. func (t *Transport) processRequest(ctx context.Context, req *jsonrpc.Request) (interface{}, error) { if req.JSONRPC != "2.0" { return nil, fmt.Errorf("invalid jsonrpc version") @@ -246,6 +302,6 @@ func (t *Transport) writeJSONLocked(v interface{}) error { return err } - log.Printf("Sent response: %s", string(data)) + log.Printf("Sent JSON-RPC response (%d bytes)", len(data)) // Record transport completion without copying tool results, tokens, or backend details into logs. return nil } diff --git a/internal/gateway/stdio/transport_test.go b/internal/gateway/stdio/transport_test.go index 5a6fe78..f707fa1 100644 --- a/internal/gateway/stdio/transport_test.go +++ b/internal/gateway/stdio/transport_test.go @@ -32,3 +32,38 @@ func TestProcessRequestRejectsInvalidVersion(t *testing.T) { t.Fatal("expected invalid jsonrpc version to fail") // Surface the missing failure because the transport must reject non-2.0 requests deterministically. } } + +// TestHandleRequestSuppressesInitializedNotificationResponse verifies that stdio consumes initialized notifications without writing any JSON-RPC response line. +func TestHandleRequestSuppressesInitializedNotificationResponse(t *testing.T) { + var stdout bytes.Buffer // Capture the transport stdout stream in memory so notification suppression can be asserted directly. + transport := &Transport{handler: jsonrpc.NewHandler(nil, nil), stdout: &stdout, stderr: &bytes.Buffer{}} // Construct one transport with in-memory sinks because this test exercises only stdio notification handling. + + if err := transport.handleRequest(context.Background(), []byte(`{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}`)); err != nil { // Process one initialized notification through the production stdio handler. + t.Fatalf("expected initialized notification to be handled successfully, got error: %v", err) // Surface unexpected transport failures because notifications should be consumed quietly. + } + if stdout.Len() != 0 { // Fail when the stdio transport still writes one JSON-RPC response for notifications. + t.Fatalf("expected no stdout output for notification, got %q", stdout.String()) // Surface the unexpected stdout payload so notification regressions are obvious. + } +} + +// TestHandleRequestCancelledNotificationSuppressesResponseAndCancelsInflightRequest verifies stdio cancellation notification behavior. +func TestHandleRequestCancelledNotificationSuppressesResponseAndCancelsInflightRequest(t *testing.T) { + var stdout bytes.Buffer // Capture the transport stdout stream in memory so cancellation notifications can be asserted as silent. + handler := jsonrpc.NewHandler(nil, nil) // Construct one shared handler so the test can register an in-flight request and then cancel it through stdio. + transport := &Transport{handler: handler, stdout: &stdout, stderr: &bytes.Buffer{}} // Construct one transport with in-memory sinks because this test exercises only stdio cancellation handling. + requestCtx, cancel := context.WithCancel(context.Background()) // Create one cancellable context that stands in for an active request owned by the transport. + cleanup := handler.RegisterInFlightRequest("stdio-cancel", cancel) // Register the active request id exactly as stdio request dispatch does before handler execution. + defer cleanup() // Ensure the registry entry is removed if the test fails before cancellation. + + if err := transport.handleRequest(context.Background(), []byte(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"stdio-cancel","reason":"client cancelled"}}`)); err != nil { // Process one cancellation notification through the production stdio handler. + t.Fatalf("expected cancellation notification to be handled successfully, got error: %v", err) // Surface unexpected transport failures because cancellation notifications should be consumed quietly. + } + select { // Check the registered request context synchronously because cancellation is invoked before handleRequest returns. + case <-requestCtx.Done(): // Observe context cancellation to prove the stdio notification reached the shared in-flight registry. + default: + t.Fatal("expected stdio cancellation notification to cancel registered request") // Surface the missing cancellation because MCP clients rely on notifications/cancelled for long calls. + } + if stdout.Len() != 0 { // Fail when the stdio transport writes any JSON-RPC response for a cancellation notification. + t.Fatalf("expected no stdout output for cancellation notification, got %q", stdout.String()) // Surface the unexpected stdout payload so notification regressions are obvious. + } +} diff --git a/internal/gateway/websocket/handler.go b/internal/gateway/websocket/handler.go index b6324db..d376415 100644 --- a/internal/gateway/websocket/handler.go +++ b/internal/gateway/websocket/handler.go @@ -1,44 +1,71 @@ +// handler.go authorizes, audits, upgrades, and serves trace-scoped WebSocket event subscriptions. package websocket import ( + "log/slog" "net/http" "strings" + "mcp_for_appium/internal/audit" "mcp_for_appium/internal/errors" + "mcp_for_appium/internal/telemetry" + "github.com/google/uuid" "github.com/gorilla/websocket" ) type Handler struct { - hub *Hub - tokenStore *SubscriptionTokenStore - upgrader websocket.Upgrader + hub *Hub + tokenStore *SubscriptionTokenStore + upgrader websocket.Upgrader + auditRecorder audit.Recorder + logger *slog.Logger } // NewHandler constructs one WebSocket handler that enforces origin checks plus short-lived subscription-token validation. func NewHandler(hub *Hub, tokenStore *SubscriptionTokenStore, allowedOrigins []string) *Handler { - return &Handler{ + handler := &Handler{ hub: hub, tokenStore: tokenStore, + logger: telemetry.Logger(), upgrader: websocket.Upgrader{ CheckOrigin: newOriginChecker(allowedOrigins), // Enforce same-origin or explicit allowlist checks during the WebSocket handshake instead of accepting every browser origin. }, } + if tokenStore != nil { // Share the token store's recorder so issuance and connection lifecycle events land in the same sink. + handler.auditRecorder = tokenStore.auditRecorder // Reuse optional audit wiring without expanding the public constructor signature. + } + return handler // Return the fully configured WebSocket handler. } // ServeHTTP upgrades one authorized HTTP request into a trace-scoped WebSocket subscription. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - claims, err := h.resolveSubscription(r) // Resolve and validate the short-lived subscription token before any WebSocket upgrade occurs. - if err != nil { // Stop immediately when the request is missing or presents an invalid subscription token. - http.Error(w, err.Error(), errors.MapToHTTP(err)) // Return the mapped auth error so callers can distinguish missing tokens from expired or invalid ones. - return // Stop before the WebSocket handshake begins because the subscription is not authorized. + requestID := strings.TrimSpace(r.Header.Get("X-Request-ID")) // Reuse upstream request correlation when the handshake came through another trusted middleware. + if requestID == "" { // Generate a local correlation identifier for the public WebSocket route. + requestID = uuid.NewString() // Assign one random request identifier without deriving it from the token or query string. + } + w.Header().Set("X-Request-ID", requestID) // Return the effective correlation id on rejected HTTP handshakes and successful upgrade responses. + claims, err := h.resolveSubscription(r) // Resolve and validate the short-lived subscription token before any WebSocket upgrade occurs. + if err != nil { // Stop immediately when the request is missing or presents an invalid subscription token. + h.recordWebSocketAudit(r, requestID, claims, "denied", websocketAuditReason(err)) // Record denied and expired attempts without storing the opaque query token. + message := "websocket authorization failed" // Return one stable public diagnostic for unknown and malformed subscription credentials. + if errors.IsCode(err, errors.CodeTokenExpired) { // Preserve an actionable public distinction for short-lived credential refresh. + message = "subscription token expired" // Tell the browser to request a fresh token without exposing stored claims. + } + http.Error(w, message, errors.MapToHTTP(err)) // Return the mapped auth status with sanitized text. + return // Stop before the WebSocket handshake begins because the subscription is not authorized. } conn, err := h.upgrader.Upgrade(w, r, nil) // Perform the WebSocket upgrade only after the subscription token and origin policy have both been validated. if err != nil { + h.recordWebSocketAudit(r, requestID, claims, "denied", "websocket_upgrade_failed") // Record origin, protocol, and handshake rejection without copying the upgrader error text. return } - defer conn.Close() + h.recordWebSocketAudit(r, requestID, claims, "success", "") // Record successful connection establishment under the authoritative token claims. + defer func() { // Record connection closure and release the network resource together. + h.recordWebSocketAudit(r, requestID, claims, "closed", "") // Append the normal connection lifecycle terminal event without message payloads. + _ = conn.Close() // Close the WebSocket connection after lifecycle recording returns. + }() client := h.hub.Subscribe(r.Context(), claims.TraceID, conn.RemoteAddr().String()) // Bind the new client subscription to the trace authorized by the opaque subscription token. defer h.hub.Unsubscribe(client) @@ -77,7 +104,7 @@ func (h *Handler) resolveSubscription(r *http.Request) (*SubscriptionTokenClaims subscriptionToken := strings.TrimSpace(r.URL.Query().Get("subscriptionToken")) // Read the opaque subscription token from the agreed browser query parameter transport. claims, err := h.tokenStore.Lookup(r.Context(), subscriptionToken) // Resolve the subscription token against the authoritative Redis-backed token store. if err != nil { // Stop immediately when the token is missing, expired, or unknown. - return nil, err // Preserve the token lookup error so the HTTP layer can map it to the correct auth status. + return claims, err // Preserve safe stored claims for expired-token audit attribution while returning nil for unknown tokens. } requestTraceID := strings.TrimSpace(r.URL.Query().Get("traceId")) // Read the optional traceId query parameter so callers can still include it for debugging or compatibility checks. if requestTraceID != "" && requestTraceID != claims.TraceID { // Reject mismatched trace IDs because the query string must never override the authorized trace binding stored in the token. @@ -86,3 +113,51 @@ func (h *Handler) resolveSubscription(r *http.Request) (*SubscriptionTokenClaims return claims, nil // Return the authoritative trace binding carried by the subscription token so the handler can open the correct trace stream. } + +// recordWebSocketAudit appends one sanitized WebSocket connection lifecycle event without storing opaque tokens or message payloads. +func (h *Handler) recordWebSocketAudit(r *http.Request, requestID string, claims *SubscriptionTokenClaims, result string, reason string) { + if h == nil || h.auditRecorder == nil { // Skip optional audit work when gateway startup did not configure a recorder. + return // Preserve WebSocket behavior in isolated tests and deployments without PostgreSQL audit persistence. + } + event := audit.Event{ // Build a pre-authentication-safe event before optionally attaching authoritative claims. + ActorID: "anonymous", // Attribute unknown-token attempts without inventing a principal. + ActorType: "anonymous", // Classify denied callers explicitly for security review. + AuthScheme: "subscription_token", // Record the short-lived WebSocket credential scheme without its value. + Action: "ws.connect", // Use one stable action for connection success, denial, expiry, and closure. + ResourceType: "trace", // Classify trace event delivery as the authorized resource. + ResourceID: strings.TrimSpace(r.URL.Query().Get("traceId")), // Preserve only the optional trace identifier, never the subscriptionToken query value. + Result: strings.TrimSpace(result), // Record success, denied, or closed lifecycle outcome. + Reason: strings.TrimSpace(reason), // Record a stable error code or sanitized upgrade reason. + SourceIP: audit.RequestSourceIP(r), // Record the directly observed handshake peer. + RequestID: strings.TrimSpace(requestID), // Correlate the WebSocket lifecycle with HTTP response telemetry. + } + if claims != nil { // Attribute successful and expired known-token attempts using authoritative stored metadata. + event.ActorID = strings.TrimSpace(claims.SubjectID) // Record the principal originally authorized to receive trace events. + event.ActorType = "subject" // Classify the known token owner as an authenticated subject. + event.CredentialID = strings.TrimSpace(claims.JTI) // Record only the independent JTI, not the opaque token value. + event.TenantID = strings.TrimSpace(claims.TenantID) // Preserve tenant scope for audit filtering. + event.ResourceID = strings.TrimSpace(claims.TraceID) // Use the authoritative token trace binding instead of caller query data. + event.Metadata = map[string]interface{}{ // Preserve safe connection authorization metadata. + "scope": strings.TrimSpace(claims.Scope), // Record the granted trace-events scope. + "expiresAt": claims.ExpiresAt.UTC(), // Record the credential expiry used during authorization. + } + if result == "success" || result == "closed" { // Attach a trace foreign key only for a connection whose trace was accepted and therefore known to exist. + event.TraceID = strings.TrimSpace(claims.TraceID) // Enable indexed trace audit lookup for successful connection lifecycle records. + } + } + if err := h.auditRecorder.Record(r.Context(), event); err != nil { // Append best-effort without changing handshake authorization or live connection behavior. + logger := h.logger // Reuse the production logger initialized by NewHandler. + if logger == nil { // Fall back for zero-value handlers used by direct unit tests. + logger = telemetry.Logger() // Preserve audit sink failure observability without panicking. + } + logger.WarnContext(r.Context(), "failed to record websocket audit event", "request_id", requestID, "result", result, "error", err) // Log no opaque token or message data. + } +} + +// websocketAuditReason returns one stable repository error code or a generic authorization marker without wrapped error text. +func websocketAuditReason(err error) string { + if code, ok := errors.CodeOf(err); ok { // Prefer the repository's machine-readable authentication or expiry code. + return string(code) // Store only the stable code in the append-only audit event. + } + return "websocket_authorization_failed" // Classify untyped handshake failures without copying their text. +} diff --git a/internal/gateway/websocket/subscription_token.go b/internal/gateway/websocket/subscription_token.go index b1db143..7711972 100644 --- a/internal/gateway/websocket/subscription_token.go +++ b/internal/gateway/websocket/subscription_token.go @@ -6,12 +6,18 @@ import ( "crypto/rand" "encoding/hex" "encoding/json" + stdErrors "errors" + "log/slog" "strings" "time" + "mcp_for_appium/internal/audit" "mcp_for_appium/internal/auth" "mcp_for_appium/internal/errors" "mcp_for_appium/internal/storage/redis" + "mcp_for_appium/internal/telemetry" + + goredis "github.com/redis/go-redis/v9" ) const defaultSubscriptionTokenTTL = 60 * time.Second // defaultSubscriptionTokenTTL bounds browser subscription-token lifetime when the caller does not configure a custom TTL. @@ -36,8 +42,10 @@ type IssuedSubscriptionToken struct { // SubscriptionTokenStore issues and resolves short-lived opaque WebSocket subscription tokens backed by Redis. type SubscriptionTokenStore struct { - cache *redis.Cache - ttl time.Duration + cache *redis.Cache + ttl time.Duration + auditRecorder audit.Recorder + logger *slog.Logger } // NewSubscriptionTokenStore constructs one Redis-backed subscription-token store. @@ -46,7 +54,15 @@ func NewSubscriptionTokenStore(cache *redis.Cache, ttl time.Duration) *Subscript ttl = defaultSubscriptionTokenTTL // Preserve the repository default browser subscription-token lifetime for callers that do not configure a custom value. } - return &SubscriptionTokenStore{cache: cache, ttl: ttl} // Store the cache dependency and TTL once so every issue or lookup operation follows the same runtime contract. + return &SubscriptionTokenStore{cache: cache, ttl: ttl, logger: telemetry.Logger()} // Store cache, TTL, and logger once so token operations and audit failures share one runtime contract. +} + +// SetAuditRecorder installs the append-only recorder used for subscription-token lifecycle and WebSocket authorization events. +func (s *SubscriptionTokenStore) SetAuditRecorder(recorder audit.Recorder) { + if s == nil { // Ignore optional wiring when no token store was constructed. + return // Avoid dereferencing nil during gateway startup or protocol-only tests. + } + s.auditRecorder = recorder // Share the gateway's PostgreSQL audit sink with token issuance and handshake handling. } // Issue creates one short-lived opaque token bound to the supplied authenticated subject and trace identifier. @@ -82,12 +98,49 @@ func (s *SubscriptionTokenStore) Issue(ctx context.Context, subject *auth.Subjec return nil, errors.Wrap(errors.CodeInternal, "failed to serialize websocket subscription token", err) // Surface JSON serialization failures as internal server errors. } if err := s.cache.Set(ctx, subscriptionTokenKey(token), string(serializedClaims), s.ttl); err != nil { // Persist the opaque token claims with the configured TTL so every gateway instance that shares Redis can validate the token during the handshake. + s.recordTokenAudit(ctx, subject, claims, "failure", string(errors.CodeStoreWrite)) // Record the failed creation without persisting the opaque token or wrapped Redis diagnostic. return nil, errors.Wrap(errors.CodeStoreWrite, "failed to store websocket subscription token", err) // Surface Redis persistence failures as storage write errors because the authoritative token store is unavailable. } + s.recordTokenAudit(ctx, subject, claims, "success", "") // Record successful token creation using only the safe JTI, trace binding, scope, and expiry. return &IssuedSubscriptionToken{Token: token, TraceID: normalizedTraceID, ExpiresAt: expiresAt, Scope: claims.Scope}, nil // Return the opaque token payload so the caller can establish the WebSocket subscription before it expires. } +// recordTokenAudit appends one sanitized subscription-token creation event without changing issuance when audit persistence is unavailable. +func (s *SubscriptionTokenStore) recordTokenAudit(ctx context.Context, subject *auth.Subject, claims SubscriptionTokenClaims, result string, reason string) { + if s == nil || s.auditRecorder == nil { // Skip optional audit work when the gateway has no recorder wiring. + return // Preserve token behavior in isolated tests and deployments without PostgreSQL audit persistence. + } + requestContext, _ := audit.RequestContextFrom(ctx) // Reuse source IP and request ID attached by authentication middleware when available. + event := audit.Event{ // Build one sanitized append-only token lifecycle record. + ActorID: strings.TrimSpace(subject.ID), // Attribute token creation to the authenticated subject. + ActorType: "subject", // Classify the actor as an authenticated gateway principal. + AuthScheme: strings.TrimSpace(subject.Type), // Preserve PAT, OIDC, or HMAC authentication provenance. + CredentialID: strings.TrimSpace(subject.CredentialID), // Record only the safe parent credential identifier. + TenantID: strings.TrimSpace(subject.TenantID), // Preserve tenant scope for audit filtering. + TraceID: strings.TrimSpace(claims.TraceID), // Link the record to the authorized trace foreign key. + Action: "ws.subscription_token.issue", // Use the stable WebSocket token creation action. + ResourceType: "trace", // Identify the trace as the resource receiving subscription authority. + ResourceID: strings.TrimSpace(claims.TraceID), // Preserve the exact authorized trace identifier. + Result: strings.TrimSpace(result), // Record success or failure without backend details. + Reason: strings.TrimSpace(reason), // Record a stable error code only on failure. + SourceIP: strings.TrimSpace(requestContext.SourceIP), // Correlate the creation with the directly observed gateway peer. + RequestID: strings.TrimSpace(requestContext.RequestID), // Correlate the creation with the authenticated HTTP request. + Metadata: map[string]interface{}{ // Preserve safe token metadata without storing the opaque credential itself. + "jti": strings.TrimSpace(claims.JTI), // Record the independent token identifier for investigations and revocation analysis. + "scope": strings.TrimSpace(claims.Scope), // Record the granted WebSocket subscription scope. + "expiresAt": claims.ExpiresAt.UTC(), // Record the short-lived credential expiry. + }, + } + if err := s.auditRecorder.Record(ctx, event); err != nil { // Append best-effort without turning an audit sink outage into token behavior changes. + logger := s.logger // Reuse the store logger initialized by the production constructor. + if logger == nil { // Fall back for zero-value test stores that inject only a recorder. + logger = telemetry.Logger() // Preserve audit failure observability without panicking. + } + logger.WarnContext(ctx, "failed to record websocket token audit event", "trace_id", claims.TraceID, "result", result, "error", err) // Log no opaque token or request secret. + } +} + // Lookup resolves one opaque subscription token to its authoritative claims and rejects expired or malformed entries. func (s *SubscriptionTokenStore) Lookup(ctx context.Context, rawToken string) (*SubscriptionTokenClaims, error) { if s == nil || s.cache == nil { // Reject calls on an unconfigured store because handshake validation requires a shared authoritative backing store. @@ -101,15 +154,18 @@ func (s *SubscriptionTokenStore) Lookup(ctx context.Context, rawToken string) (* serializedClaims, err := s.cache.Get(ctx, subscriptionTokenKey(normalizedToken)) // Resolve the opaque token against the authoritative Redis-backed token store. if err != nil { // Stop immediately when the token cannot be found or the token store is unavailable. - return nil, errors.Wrap(errors.CodeUnauthenticated, "subscription token not found", err) // Surface unknown tokens as authentication failures without revealing whether a trace exists. + if stdErrors.Is(err, goredis.Nil) { // Distinguish an unknown credential from an unavailable authoritative token store. + return nil, errors.New(errors.CodeUnauthenticated, "subscription token not found") // Reject unknown tokens without reflecting Redis sentinel text. + } + return nil, errors.Wrap(errors.CodeStoreRead, "failed to read websocket subscription token", err) // Preserve infrastructure failures for HTTP 5xx mapping and operator diagnosis. } var claims SubscriptionTokenClaims // Allocate the destination claims struct once so the stored JSON can be decoded deterministically. if err := json.Unmarshal([]byte(serializedClaims), &claims); err != nil { // Reject malformed stored claims because the token store entry is unreadable or corrupted. - return nil, errors.Wrap(errors.CodeUnauthenticated, "subscription token is invalid", err) // Surface malformed token-store entries as authentication failures. + return nil, errors.Wrap(errors.CodeStoreRead, "stored websocket subscription token is invalid", err) // Classify corrupted authoritative state as a server storage failure rather than a caller authentication mistake. } if time.Now().UTC().After(claims.ExpiresAt.UTC()) { // Reject expired subscription tokens even if Redis has not yet evicted the record. - return nil, errors.New(errors.CodeTokenExpired, "subscription token expired") // Surface token expiry distinctly so callers can request a fresh token. + return &claims, errors.New(errors.CodeTokenExpired, "subscription token expired") // Return safe stored claims for audit attribution while still rejecting the expired credential. } return &claims, nil // Return the authoritative claims so the handshake can bind the WebSocket connection to the authorized trace subscription. diff --git a/internal/gateway/websocket/subscription_token_test.go b/internal/gateway/websocket/subscription_token_test.go index 591b16e..e3279a9 100644 --- a/internal/gateway/websocket/subscription_token_test.go +++ b/internal/gateway/websocket/subscription_token_test.go @@ -3,10 +3,13 @@ package websocket import ( "context" + "encoding/json" "net/http/httptest" + "strings" "testing" "time" + "mcp_for_appium/internal/audit" "mcp_for_appium/internal/auth" "mcp_for_appium/internal/config" "mcp_for_appium/internal/errors" @@ -49,6 +52,53 @@ func TestSubscriptionTokenStoreIssueAndLookup(t *testing.T) { } } +// TestSubscriptionTokenStoreAuditOmitsOpaqueToken verifies that issuance audit records use JTI and never persist the browser credential itself. +func TestSubscriptionTokenStoreAuditOmitsOpaqueToken(t *testing.T) { + store, cleanup := newSubscriptionTokenStoreForTest(t) // Construct one disposable Redis-backed token store for audited issuance. + defer cleanup() // Release Redis resources after the audit assertions complete. + var recordedEvents []audit.Event // Collect append-only token events through an in-memory recorder. + store.SetAuditRecorder(audit.RecorderFunc(func(ctx context.Context, event audit.Event) error { // Install one deterministic recorder under the production token store API. + recordedEvents = append(recordedEvents, event) // Preserve the exact token lifecycle event emitted after Redis persistence. + return nil // Keep audit persistence successful so issuance behavior remains unchanged. + })) + requestContext := audit.WithRequestContext(context.Background(), audit.RequestContext{RequestID: "request-ws-token", SourceIP: "192.0.2.20"}) // Attach the safe gateway correlation metadata used by runtime issuance. + subject := &auth.Subject{ID: "subject-token-audit", TenantID: "tenant-token-audit", Type: "pat", CredentialID: "pat-safe-id"} // Build one fully attributable authenticated issuer. + issuedToken, err := store.Issue(requestContext, subject, "trace-token-audit") // Issue one real opaque token through Redis and audit recording. + if err != nil { // Fail when audited issuance unexpectedly rejects the valid request. + t.Fatalf("expected audited subscription token issuance to succeed, got error: %v", err) // Surface setup or audit integration failures. + } + if len(recordedEvents) != 1 { // Require exactly one token issuance event. + t.Fatalf("expected one subscription token audit event, got %d", len(recordedEvents)) // Surface missing or duplicated token audit writes. + } + event := recordedEvents[0] // Read the sole issuance event for safe identifier assertions. + if event.Result != "success" || event.CredentialID != "pat-safe-id" || event.TraceID != "trace-token-audit" || event.RequestID != "request-ws-token" { // Require complete issuer, trace, and request attribution. + t.Fatalf("unexpected subscription token audit event: %#v", event) // Surface malformed lifecycle metadata. + } + if strings.TrimSpace(event.Metadata["jti"].(string)) == "" { // Require one independent token identifier for audit correlation. + t.Fatal("expected subscription token audit event to include a non-empty JTI") // Surface missing safe token identity. + } + serializedEvent, err := json.Marshal(event) // Serialize every event field for opaque-token leakage detection. + if err != nil { // Fail when the event cannot be represented by the PostgreSQL recorder. + t.Fatalf("failed to serialize subscription token audit event: %v", err) // Surface incompatible metadata. + } + if strings.Contains(string(serializedEvent), issuedToken.Token) { // Reject the actual browser credential anywhere in the audit event. + t.Fatalf("subscription token audit event leaked opaque token: %s", serializedEvent) // Surface unsafe token persistence immediately. + } +} + +// TestSubscriptionTokenStoreLookupClassifiesRedisFailure verifies that token-store outages remain server errors instead of invalid-credential responses. +func TestSubscriptionTokenStoreLookupClassifiesRedisFailure(t *testing.T) { + store, cleanup := newSubscriptionTokenStoreForTest(t) // Construct one real cache wrapper before forcing its client closed. + defer cleanup() // Release the already closed client and in-memory Redis listener idempotently after the assertion. + if err := store.cache.Close(); err != nil { // Close the production Redis client so Lookup encounters an infrastructure failure. + t.Fatalf("failed to close websocket token cache: %v", err) // Surface fixture failure because the classification scenario was not created. + } + _, err := store.Lookup(context.Background(), "unknown-opaque-token") // Resolve one token while the authoritative store is unavailable. + if !errors.IsCode(err, errors.CodeStoreRead) { // Require infrastructure classification rather than unauthenticated. + t.Fatalf("expected closed token store lookup to return %q, got %v", errors.CodeStoreRead, err) // Surface fail-open or misclassified outage behavior. + } +} + // TestHandlerResolveSubscriptionRejectsMissingToken verifies that the WebSocket handler rejects missing subscription tokens before any upgrade attempt. func TestHandlerResolveSubscriptionRejectsMissingToken(t *testing.T) { store, cleanup := newSubscriptionTokenStoreForTest(t) // Construct one disposable Redis-backed token store for the handler validation test. diff --git a/internal/orchestrator/devicefarm_runtime.go b/internal/orchestrator/devicefarm_runtime.go index c17ab68..ca23491 100644 --- a/internal/orchestrator/devicefarm_runtime.go +++ b/internal/orchestrator/devicefarm_runtime.go @@ -3,6 +3,7 @@ package orchestrator import ( "context" + stdErrors "errors" "strings" "time" @@ -11,6 +12,8 @@ import ( "mcp_for_appium/internal/errors" "mcp_for_appium/internal/storage/postgres" "mcp_for_appium/internal/worker/appium" + + goredis "github.com/redis/go-redis/v9" ) // deviceFarmRuntimeClient captures the Device Farm operations that the orchestrator actually needs across run_api and remote-access flows. @@ -199,30 +202,54 @@ func (s *Service) cleanupFailedStartSession(ctx context.Context, target *startSe } } -// releaseSessionAutomation releases the Appium session, removes all persisted session-specific mappings, and stops any backing Device Farm remote-access reservation. -func (s *Service) releaseSessionAutomation(ctx context.Context, sessionID string) { - client, err := s.restoreAppiumClient(ctx, sessionID) // Restore one Appium client from persisted mappings when the in-memory cache no longer holds the session-specific endpoint and session id. - if err == nil { // Stop the live Appium session only when the restore succeeded and therefore identified one concrete automation session. - _ = client.DeleteSession(ctx) // Best-effort close the Appium session so local and remote backends both release the underlying automation state promptly. +// releaseSessionAutomation closes one Appium session, stops its Device Farm reservation, and deletes persisted handles only after external cleanup succeeds. +func (s *Service) releaseSessionAutomation(ctx context.Context, sessionID string, client *appium.Client) error { + if client == nil { // Restore the Appium handle only when no live in-memory client survived until cleanup. + restoredClient, restoreErr := s.restoreAppiumClient(ctx, sessionID) // Rebuild the handle from Redis so cleanup remains restart-safe. + if restoreErr != nil && !errors.IsCode(restoreErr, errors.CodeSessionNotFound) { // Treat missing mappings as an already-cleaned retry while preserving real cache failures. + return restoreErr // Keep the session ending and its remaining handles intact on Redis read failures. + } + client = restoredClient // Use the restored client when available, or nil when a previous cleanup already removed the mapping. + } + if client != nil { // Close the live Appium session before deleting the only persisted reattachment handle. + cleanupContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) // Bound Appium cleanup while allowing it to finish after caller cancellation. + deleteErr := client.DeleteSession(cleanupContext) // Ask Appium to release the concrete automation session exactly once per retry attempt. + cancel() // Release the Appium cleanup timer immediately after the request returns. + if deleteErr != nil && !errors.IsCode(deleteErr, errors.CodeSessionDead) && !errors.IsCode(deleteErr, errors.CodeSessionNotFound) { // Treat an already-dead backend session as successful idempotent cleanup. + return errors.WrapPreservingCode("failed to delete appium session", deleteErr) // Keep all Redis handles available for a later retry when Appium cleanup is ambiguous or failed. + } } - if s.deviceFarm != nil { // Attempt Device Farm cleanup only when the orchestrator actually has one initialized Device Farm client. - if remoteAccessSessionARN, err := s.cache.Get(ctx, deviceFarmRemoteKeyPrefix+sessionID); err == nil && strings.TrimSpace(remoteAccessSessionARN) != "" { // Look up one persisted remote-access reservation ARN for this platform session before removing cache keys. - stopCtx, cancel := context.WithTimeout(ctx, 30*time.Second) // Bound remote-access cleanup time so EndSession cannot hang forever on the AWS stop call. - _ = s.deviceFarm.StopRemoteAccessSession(stopCtx, strings.TrimSpace(remoteAccessSessionARN)) // Best-effort stop the remote-access reservation so the AWS device slot is released even after the Appium session closes. - cancel() // Release the cleanup timeout resources immediately after the Device Farm stop attempt returns. + if s.cache == nil { // Refuse to report cleanup success when persisted handles cannot be inspected or deleted. + return errors.New(errors.CodeStoreRead, "session automation cache is unavailable") // Leave the session ending so cleanup can retry after Redis recovery. + } + remoteAccessSessionARN, remoteLookupErr := s.cache.Get(ctx, deviceFarmRemoteKeyPrefix+sessionID) // Read the Device Farm handle before deleting any persisted session mapping. + if remoteLookupErr != nil && !stdErrors.Is(remoteLookupErr, goredis.Nil) { // Ignore a missing handle because local sessions and completed retries legitimately have none. + return errors.Wrap(errors.CodeStoreRead, "failed to load device farm cleanup handle", remoteLookupErr) // Preserve retryability when Redis cannot determine whether a reservation exists. + } + if strings.TrimSpace(remoteAccessSessionARN) != "" { // Stop the persisted AWS reservation before deleting its only durable handle. + if s.deviceFarm == nil { // Refuse to discard the reservation handle when no runtime client can release it. + return errors.New(errors.CodeConfigMissing, "device farm client is unavailable for session cleanup") // Keep the session ending until the dependency recovers. + } + stopContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) // Bound AWS cleanup while allowing it to finish after caller cancellation. + stopErr := s.deviceFarm.StopRemoteAccessSession(stopContext, strings.TrimSpace(remoteAccessSessionARN)) // Release the exact persisted Device Farm reservation. + cancel() // Release the Device Farm cleanup timer immediately after the request returns. + if stopErr != nil { // Keep the ARN and all other mappings when AWS does not confirm cleanup. + return errors.WrapPreservingCode("failed to stop device farm remote access session", stopErr) // Preserve the provider failure for a later retry. } } - if err := s.cache.Del(ctx, appiumSessionKeyPrefix+sessionID); err != nil { // Delete the persisted platform-to-Appium session id mapping after best-effort Appium cleanup has run. - s.logger.WarnContext(ctx, "failed to delete appium session mapping", "session_id", sessionID, "error", err) // Surface cleanup failures without masking the otherwise successful EndSession flow. + var deletionErrors []error // Collect Redis deletion failures after external resources are confirmed closed so partial key deletion remains retryable. + if err := s.cache.Del(ctx, appiumSessionKeyPrefix+sessionID); err != nil { // Delete the Appium session id only after Appium and AWS cleanup succeed. + deletionErrors = append(deletionErrors, errors.Wrap(errors.CodeStoreWrite, "failed to delete appium session mapping", err)) // Preserve the failed key deletion for caller retry. } - if err := s.cache.Del(ctx, appiumSessionURLKeyPrefix+sessionID); err != nil { // Delete the persisted per-session Appium endpoint mapping after the automation session has been released. - s.logger.WarnContext(ctx, "failed to delete appium session url mapping", "session_id", sessionID, "error", err) // Surface cleanup failures without masking the otherwise successful EndSession flow. + if err := s.cache.Del(ctx, appiumSessionURLKeyPrefix+sessionID); err != nil { // Delete the endpoint mapping after no future reattachment is required. + deletionErrors = append(deletionErrors, errors.Wrap(errors.CodeStoreWrite, "failed to delete appium session url mapping", err)) // Preserve the failed key deletion for caller retry. } - if err := s.cache.Del(ctx, deviceFarmRemoteKeyPrefix+sessionID); err != nil { // Delete the persisted Device Farm remote-access reservation mapping after the AWS slot stop attempt has been made. - s.logger.WarnContext(ctx, "failed to delete device farm remote access mapping", "session_id", sessionID, "error", err) // Surface cleanup failures without masking the otherwise successful EndSession flow. + if err := s.cache.Del(ctx, deviceFarmRemoteKeyPrefix+sessionID); err != nil { // Delete the AWS handle only after the provider confirmed reservation cleanup. + deletionErrors = append(deletionErrors, errors.Wrap(errors.CodeStoreWrite, "failed to delete device farm remote access mapping", err)) // Preserve the failed key deletion for caller retry. } + return stdErrors.Join(deletionErrors...) // Return nil when every handle was deleted or a joined retryable storage error otherwise. } // cachedSessionAppiumURL returns the persisted per-session Appium endpoint, falling back to the configured local default when no session-specific mapping exists. diff --git a/internal/orchestrator/dispatcher.go b/internal/orchestrator/dispatcher.go index 89e2588..f852cbc 100644 --- a/internal/orchestrator/dispatcher.go +++ b/internal/orchestrator/dispatcher.go @@ -11,33 +11,40 @@ import ( "sync" "time" + "mcp_for_appium/internal/audit" "mcp_for_appium/internal/config" "mcp_for_appium/internal/errors" "mcp_for_appium/internal/rpc" "mcp_for_appium/internal/storage/redis" "mcp_for_appium/internal/telemetry" + + "github.com/google/uuid" ) const ( - numShards = 8 - consumerGroup = "orchestrator-group" - consumerName = "orchestrator-consumer" - batchSize = 10 - blockTime = 5 * time.Second - claimMinIdleTime = 30 * time.Second - maxRetries = 3 - retryBackoffBase = 200 * time.Millisecond - retryBackoffJitter = 1000 * time.Millisecond - streamTrimMaxLen = 10000 - streamTrimApprox = true - cancelledTracePrefix = "cancelled:trace:" - cancelledTraceTTL = time.Hour - retryKeyPrefix = "retries:trace:" - retryKeyTTL = 10 * time.Minute - inflightTracePrefix = "inflight:trace:" - inflightTraceTTL = 2 * time.Hour - inflightMonitorTick = 5 * time.Second - executionLeaseGrace = 15 * time.Second + numShards = 8 + consumerGroup = "orchestrator-group" + consumerName = "orchestrator-consumer" + batchSize = 10 + blockTime = 5 * time.Second + claimMinIdleTime = 30 * time.Second + maxRetries = 3 + retryBackoffBase = 200 * time.Millisecond + retryBackoffJitter = 1000 * time.Millisecond + streamTrimMaxLen = 10000 + streamTrimApprox = true + cancelledTracePrefix = "cancelled:trace:" + cancelledTraceTTL = time.Hour + retryKeyPrefix = "retries:trace:" + retryKeyTTL = 10 * time.Minute + inflightTracePrefix = "inflight:trace:" + inflightTraceTTL = 2 * time.Hour + dispatchLockPrefix = "dispatch:trace:" + dispatchLockTTL = 45 * time.Second + dispatchUnlockTimeout = 2 * time.Second + inflightMonitorTick = 5 * time.Second + executionLeaseGrace = 15 * time.Second + workerRPCTimeout = 10 * time.Second ) type Dispatcher struct { @@ -52,6 +59,12 @@ type Dispatcher struct { planTimeout time.Duration heartbeatInterval time.Duration rpcSecurity config.RPCSecurityConfig + auditRecorder audit.Recorder +} + +// SetAuditRecorder installs the optional append-only sink used for distributed lease and timeout audit events. +func (d *Dispatcher) SetAuditRecorder(recorder audit.Recorder) { + d.auditRecorder = recorder // Store the process-wired recorder before dispatch loops begin serving queue messages. } // TraceFinalizer records dispatcher-owned terminal outcomes for queued traces before the queue message is ACKed. @@ -269,25 +282,29 @@ func (d *Dispatcher) dispatchMessage(ctx context.Context, stream string, msg red // dispatchToWorker assigns a worker and sends the plan via gRPC. func (d *Dispatcher) dispatchToWorker(ctx context.Context, traceID, projectID, sessionID, planStr string) error { - w := d.registry.AssignWorker(ctx, projectID, map[string]string{}) - if w == nil { - d.logger.WarnContext(ctx, "no available worker", - "trace_id", traceID, - "project_id", projectID) - // Return a transient scheduling error so upstream retry logic keeps - // the message pending for later auto-claim re-dispatch. - return errors.New(errors.CodeSchedNoWorker, "no available worker") - } - - client, err := d.getWorkerClient(w.Address) - if err != nil { - return errors.Wrap(errors.CodeSchedNoWorker, "failed to connect to worker", err) - } - owner, ok := d.finalizer.(distributedAttemptOwner) // Detect whether the wired finalizer can reserve and promote distributed attempts around worker acceptance. if !ok { // Reject distributed dispatch when no attempt owner is wired because stale-result protection would be impossible. return errors.New(errors.CodeInternal, "distributed attempt owner is not configured") // Surface the missing attempt owner as an internal wiring failure. } + dispatchLockKey := dispatchLockPrefix + traceID // Namespace the per-trace lock separately from the longer-lived execution lease. + dispatchLockToken := uuid.NewString() // Generate one unguessable ownership value so an expired lock holder cannot delete a successor's lock. + locked, err := d.cache.SetNX(ctx, dispatchLockKey, dispatchLockToken, dispatchLockTTL) // Acquire distributed serialization before incrementing the trace attempt or selecting a worker. + if err != nil { // Fail closed when Redis cannot establish unique dispatch ownership. + return errors.Wrap(errors.CodeStoreWrite, "failed to acquire distributed dispatch lock", err) // Keep the queue message retryable without sending any worker RPC. + } + if !locked { // Treat a concurrent dispatcher for the same trace as transient scheduling pressure. + return errors.New(errors.CodeSchedNoWorker, "trace dispatch is already in progress") // Preserve the duplicate queue delivery for a later benign retry. + } + defer func() { // Release only this exact lock token after every dispatch outcome. + releaseCtx, releaseCancel := context.WithTimeout(context.Background(), dispatchUnlockTimeout) // Detach lock cleanup from a cancelled request while keeping Redis I/O bounded. + defer releaseCancel() // Release the detached cleanup timer after the ownership-guarded delete returns. + released, releaseErr := d.cache.CompareAndDelete(releaseCtx, dispatchLockKey, dispatchLockToken) // Prevent an expired owner from deleting a newer dispatch lock. + if releaseErr != nil { // Log infrastructure failure while allowing the short lock TTL to recover automatically. + d.logger.WarnContext(ctx, "failed to release distributed dispatch lock", "trace_id", traceID, "error", releaseErr) // Surface cleanup failure without changing the completed dispatch outcome. + } else if !released { // Record when the lock already expired or changed ownership before cleanup. + d.logger.InfoContext(ctx, "distributed dispatch lock no longer owned at release", "trace_id", traceID) // Keep ownership drift observable for timing diagnosis. + } + }() attempt, err := owner.ReserveDispatchedTraceAttempt(ctx, traceID) // Reserve the next distributed attempt before the worker RPC so the worker can receive a stable ownership token. if err != nil { // Surface attempt-reservation failures before any worker RPC is sent. return err // Preserve the wrapped storage error so retry logic can decide whether to requeue or fail. @@ -296,13 +313,30 @@ func (d *Dispatcher) dispatchToWorker(ctx context.Context, traceID, projectID, s d.logger.InfoContext(ctx, "skipping distributed dispatch because trace is no longer pending", "trace_id", traceID, "project_id", projectID) // Record the benign race so operators can correlate skipped dispatches with concurrent cancels or terminal transitions. return nil // Report success so the queue message can be ACKed after another lifecycle transition already won. } + reservationID := distributedReservationID(traceID, attempt) // Derive one exact capacity token from the durably reserved trace attempt. + w := d.registry.AssignWorker(ctx, projectID, map[string]string{}, reservationID) // Atomically select a worker and reserve one local slot for this exact attempt. + if w == nil { // Return a transient scheduling result while preserving the monotonic attempt number for a later retry. + d.logger.WarnContext(ctx, "no available worker", "trace_id", traceID, "project_id", projectID, "attempt", attempt) // Surface fleet capacity exhaustion for operator diagnosis. + return errors.New(errors.CodeSchedNoWorker, "no available worker") // Leave the queue message pending so auto-claim can retry after capacity returns. + } + releaseReservation := true // Roll back this exact local slot on every path that does not produce a durable running attempt. + defer func() { // Centralize capacity rollback so new error returns cannot accidentally leak a worker slot. + if releaseReservation { // Keep the reservation only after durable running-state promotion succeeds. + d.registry.ReleaseWorkerReservation(reservationID) // Release this exact trace attempt idempotently after dispatch failure or a fast terminal callback. + } + }() + + client, err := d.getWorkerClient(w.Address) // Reuse or dial the selected worker's internal gRPC client after capacity is reserved. + if err != nil { // Treat worker dial failures as transient fleet availability problems. + return errors.Wrap(errors.CodeSchedNoWorker, "failed to connect to worker", err) // Preserve the dial cause for server logs while allowing queue retry. + } workerSessionID, err := d.resolveWorkerSessionID(ctx, sessionID) // Resolve the worker-facing Appium session identifier before dispatch so the worker can attach to the real Appium session instead of the platform session id. if err != nil { // Surface session-resolution failures before any worker RPC is sent because distributed execution cannot proceed safely without the Appium session id. return err // Preserve the wrapped cache lookup failure so upstream retry and terminalization logic can react consistently. } - dispatchedAt := time.Now() // Capture one dispatch timestamp before the worker RPC so any immediate callback already has a persisted lease baseline to renew against. - d.persistInflightAssignment(ctx, traceID, inflightTraceAssignment{ // Persist the provisional distributed assignment before the worker RPC so fast step callbacks cannot race ahead of lease creation. + dispatchedAt := time.Now().UTC() // Capture one dispatch timestamp before lease persistence and the worker RPC. + assignment := inflightTraceAssignment{ // Build the provisional ownership lease before any remote execution can begin. Address: w.Address, // Record the worker address so later cancel RPCs can reach the same worker instance. WorkerID: w.ID, // Record the worker identifier so callback renewals and timeout logs can pinpoint the same assignment. Attempt: attempt, // Record the reserved execution attempt so callback ownership checks can reject stale results deterministically. @@ -310,50 +344,75 @@ func (d *Dispatcher) dispatchToWorker(ctx context.Context, traceID, projectID, s LastRenewedAtUnix: dispatchedAt.UnixMilli(), // Seed the lease-renewal timestamp immediately so the first worker callback can refresh the same lease instead of racing a missing key. LeaseExpiresAtUnix: d.inflightLeaseDeadlineUnix(dispatchedAt), // Capture the ownership-lease expiry derived from the worker heartbeat cadence and grace window. DeadlineAtUnix: d.inflightDeadlineUnix(dispatchedAt), // Capture the absolute timeout deadline derived from the configured plan timeout for later watchdog sweeps. - }) // Persist the accepted-attempt lease metadata early so immediate worker callbacks see a valid ownership record. - - resp, err := client.ExecutePlan(ctx, &rpc.ExecutePlanRequest{ - TraceID: traceID, - SessionID: workerSessionID, - Attempt: attempt, - Plan: json.RawMessage(planStr), + } // Complete the ownership metadata that every fast callback must validate against. + rawAssignment, err := d.persistInflightAssignment(ctx, traceID, assignment) // Require durable Redis ownership before allowing the worker to accept execution. + if err != nil { // Stop before the worker RPC whenever ownership creation fails or conflicts. + d.recordAudit(ctx, "execution.lease_create", traceID, "failure", "store_write", assignment) // Audit the fail-closed lease outcome without recording backend error text. + return err // Leave the queued trace pending for retry because no worker RPC was sent. + } + + rpcCtx, rpcCancel := context.WithTimeout(ctx, workerRPCTimeout) // Bound worker acceptance so a stalled peer cannot pin queue dispatch indefinitely. + resp, err := client.ExecutePlan(rpcCtx, &rpc.ExecutePlanRequest{ // Ask the worker to admit this exact leased execution attempt. + TraceID: traceID, // Identify the persisted trace whose callback state the worker will own. + SessionID: workerSessionID, // Attach execution to the resolved live Appium session. + Attempt: attempt, // Carry the monotonic ownership token used by every callback guard. + Plan: json.RawMessage(planStr), // Forward the already accepted plan JSON without reparsing it in the dispatcher. }) - if err != nil { - d.cleanupInflightTrace(ctx, traceID) // Remove the provisional lease immediately because the worker RPC never accepted the attempt successfully. - return errors.Wrap(errors.CodeInternal, "worker ExecutePlan RPC failed", err) + rpcCancel() // Release the per-acceptance timer immediately after the worker RPC returns. + if err != nil { // Roll back the provisional lease when the worker never acknowledged admission. + d.cleanupInflightTraceIfOwned(ctx, traceID, rawAssignment) // Remove only the unchanged provisional lease because a fast renewal can prove remote acceptance. + return errors.Wrap(errors.CodeSchedNoWorker, "worker ExecutePlan RPC failed", err) // Keep transport and timeout failures retryable through the scheduler path. + } + if resp == nil { // Reject malformed gRPC success responses that omit the admission result entirely. + d.cleanupInflightTraceIfOwned(ctx, traceID, rawAssignment) // Remove only the unchanged provisional lease because no valid acceptance decision exists. + return errors.New(errors.CodeSchedNoWorker, "worker returned an empty ExecutePlan response") // Retry on another dispatch instead of assuming remote execution began. + } + if resp.Status == "busy" { // Treat authoritative worker-side capacity rejection as transient scheduling pressure. + d.cleanupInflightTraceIfOwned(ctx, traceID, rawAssignment) // Remove the exact unused ownership lease before the queue message is retried. + return errors.New(errors.CodeSchedNoWorker, "worker is at capacity") // Preserve the queue message for later scheduling without marking the plan invalid. } - if resp.Status != "accepted" { - d.cleanupInflightTrace(ctx, traceID) // Remove the provisional lease immediately because the worker rejected the reserved attempt. - return errors.New(errors.CodePlanInvalid, "worker rejected plan: "+resp.Message) + if resp.Status != "accepted" { // Treat all explicit non-capacity rejections as terminal request validation failures. + d.cleanupInflightTraceIfOwned(ctx, traceID, rawAssignment) // Remove the exact provisional lease because the worker rejected the reserved attempt. + return errors.New(errors.CodePlanInvalid, "worker rejected plan") // Avoid propagating arbitrary worker response text into external terminal events. } attemptRecorded, err := owner.MarkDispatchedTraceRunning(ctx, traceID, attempt) // Promote the reserved trace attempt to running only after the worker has acknowledged acceptance. if err != nil { // Best-effort cancel the accepted worker trace when durable running-state promotion fails after acceptance. - cancelResponse, cancelErr := client.CancelPlan(ctx, &rpc.CancelPlanRequest{TraceID: traceID}) // Try to stop the accepted worker trace because retrying after a lost running-state promotion would risk duplicate execution. - if cancelErr != nil { // Log cancellation failures because the worker may continue executing a trace the orchestrator could not mark as running. - d.logger.WarnContext(ctx, "failed to cancel accepted trace after running-state persistence error", "trace_id", traceID, "worker_id", w.ID, "attempt", attempt, "error", cancelErr) // Surface the failed cleanup attempt for operator diagnosis. - } else { - d.logger.InfoContext(ctx, "cancelled accepted trace after running-state persistence error", "trace_id", traceID, "worker_id", w.ID, "attempt", attempt, "cancel_status", cancelResponse.Status) // Record the best-effort cleanup outcome for operator visibility. - } - d.cleanupInflightTrace(ctx, traceID) // Remove the provisional lease because the accepted worker attempt could not be promoted to the durable running state. - return err // Preserve the wrapped storage error so upstream handling can surface the failed acceptance bookkeeping. + d.cancelAcceptedWorker(ctx, client, traceID, w.ID, attempt, "running-state persistence error") // Stop remote work before this failed acceptance bookkeeping can be retried as a duplicate execution. + d.cleanupInflightTraceIfOwned(ctx, traceID, rawAssignment) // Remove the lease only if no fast callback renewed or released it during promotion failure. + return err // Preserve the wrapped storage error so upstream handling can surface the failed acceptance bookkeeping. } if !attemptRecorded { // Cancel stale worker acceptance when another lifecycle transition already moved the reserved trace out of pending before running-state promotion committed. - cancelResponse, cancelErr := client.CancelPlan(ctx, &rpc.CancelPlanRequest{TraceID: traceID}) // Best-effort cancel the stale worker acceptance so the worker stops a trace the orchestrator no longer owns. - if cancelErr != nil { // Log cancellation failures because the worker may continue executing a trace the orchestrator has already terminalized. - d.logger.WarnContext(ctx, "failed to cancel stale distributed acceptance", "trace_id", traceID, "worker_id", w.ID, "error", cancelErr) // Surface the failed stale-acceptance cancel without retrying dispatch. - } else { - d.logger.InfoContext(ctx, "cancelled stale distributed acceptance", "trace_id", traceID, "worker_id", w.ID, "cancel_status", cancelResponse.Status) // Record the best-effort worker-side cancel result for operator visibility. - } - d.cleanupInflightTrace(ctx, traceID) // Remove the provisional lease because another lifecycle transition already won before the accepted attempt could become running. - return nil // Treat the stale acceptance as a successful no-op because the trace has already moved to another lifecycle state elsewhere. + d.cancelAcceptedWorker(ctx, client, traceID, w.ID, attempt, "stale distributed acceptance") // Stop any run that did not already finish through a fast pending-state callback. + d.cleanupInflightTraceIfOwned(ctx, traceID, rawAssignment) // Remove only the unchanged lease because a fast callback may already have released it. + return nil // Treat the stale acceptance as a successful no-op because the trace has already moved to another lifecycle state elsewhere. } + releaseReservation = false // Keep capacity charged to this exact attempt until completion, cancellation, timeout, or orphan cleanup releases it. - d.logger.InfoContext(ctx, "dispatched to worker", - "trace_id", traceID, - "worker_id", w.ID, - "attempt", attempt) - return nil + d.logger.InfoContext(ctx, "dispatched to worker", "trace_id", traceID, "worker_id", w.ID, "attempt", attempt) // Record the accepted and durably promoted distributed assignment. + d.recordAudit(ctx, "execution.dispatched", traceID, "success", "", assignment) // Append safe routing, attempt, and deadline metadata for execution audit. + return nil // Allow the queue message to be acknowledged after durable running-state promotion. +} + +// cancelAcceptedWorker best-effort cancels one remotely accepted plan through a bounded RPC during dispatcher rollback. +func (d *Dispatcher) cancelAcceptedWorker(ctx context.Context, client *rpc.WorkerClient, traceID string, workerID string, attempt int64, reason string) { + cancelCtx, cancel := context.WithTimeout(ctx, workerRPCTimeout) // Bound cleanup so an unreachable worker cannot stall queue ownership indefinitely. + response, err := client.CancelPlan(cancelCtx, &rpc.CancelPlanRequest{TraceID: traceID}) // Ask the selected worker to stop the remotely accepted trace. + cancel() // Release the rollback RPC timer immediately after the call returns. + if err != nil { // Keep cancellation best-effort because the original persistence or lifecycle result remains authoritative. + d.logger.WarnContext(ctx, "failed to cancel accepted distributed trace", "trace_id", traceID, "worker_id", workerID, "attempt", attempt, "reason", reason, "error", err) // Surface cleanup failure for operator diagnosis. + return // Leave watchdog and worker lease loss as the fallback remote stop mechanisms. + } + status := "" // Normalize nil responses into an empty status for safe structured logging. + if response != nil { // Read the worker response only when the gRPC client returned one. + status = response.Status // Preserve the stable cancellation outcome without logging arbitrary response messages. + } + d.logger.InfoContext(ctx, "cancelled accepted distributed trace", "trace_id", traceID, "worker_id", workerID, "attempt", attempt, "reason", reason, "cancel_status", status) // Record the best-effort rollback result. +} + +// distributedReservationID derives the exact local capacity token shared by dispatch, callback, cancellation, and watchdog cleanup paths. +func distributedReservationID(traceID string, attempt int64) string { + return fmt.Sprintf("%s:%d", traceID, attempt) // Combine the immutable trace id and monotonic attempt without relying on worker load counters alone. } // resolveWorkerSessionID maps one platform session identifier to the underlying Appium session identifier required by distributed workers. @@ -430,21 +489,37 @@ func (d *Dispatcher) inflightLeaseDuration() time.Duration { return (interval * 3) + executionLeaseGrace // Give each worker three missed heartbeats plus one grace window before ownership is considered orphaned. } -// persistInflightAssignment stores one accepted distributed worker assignment and logs any failure without triggering a dangerous queue retry. -func (d *Dispatcher) persistInflightAssignment(ctx context.Context, traceID string, assignment inflightTraceAssignment) { +// persistInflightAssignment stores one distributed worker ownership lease and fails closed when Redis cannot durably accept it. +func (d *Dispatcher) persistInflightAssignment(ctx context.Context, traceID string, assignment inflightTraceAssignment) (string, error) { payload, err := json.Marshal(assignment) // Encode the accepted worker assignment into one Redis-storable JSON payload for cancel and timeout lookups. - if err != nil { // Surface impossible-but-real serialization failures without changing control flow after the worker already accepted the plan. - d.logger.ErrorContext(ctx, "failed to marshal inflight trace assignment", // Emit the failure loudly because timeout and cancellation bookkeeping will be incomplete for this accepted trace. - "trace_id", traceID, - "worker_id", assignment.WorkerID, - "error", err) - return // Preserve the accepted dispatch outcome because retrying after worker acceptance could duplicate execution. + if err != nil { // Reject malformed metadata before any worker RPC can begin remote execution. + return "", errors.Wrap(errors.CodeInternal, "failed to marshal inflight trace assignment", err) // Preserve the serialization cause under a stable internal code. } - if err := d.cache.Set(ctx, inflightTracePrefix+traceID, string(payload), inflightTraceTTL); err != nil { // Persist the worker assignment with a bounded TTL so stale distributed traces do not remain forever after watchdog failure. - d.logger.WarnContext(ctx, "failed to persist inflight trace assignment", // Surface the Redis failure because later cancel and timeout sweeps may not be able to find the accepted trace. - "trace_id", traceID, - "worker_id", assignment.WorkerID, - "error", err) + created, err := d.cache.SetNX(ctx, inflightTracePrefix+traceID, string(payload), inflightTraceTTL) // Create ownership only when no earlier accepted or provisional lease already exists for this trace. + if err != nil { // Fail closed when Redis cannot persist the initial distributed ownership lease. + return "", errors.Wrap(errors.CodeStoreWrite, "failed to persist inflight trace assignment", err) // Fail closed because unleased remote execution cannot be cancelled or ownership-validated safely. + } + if !created { // Reject dispatch when another ownership lease already protects this trace. + return "", errors.New(errors.CodeStateConflict, "inflight trace assignment already exists") // Keep the queue message retryable without overwriting the existing owner. + } + return string(payload), nil // Return the exact stored value so rollback can atomically delete only this owner. +} + +// recordAudit appends one best-effort sanitized distributed execution event without changing queue or lease control flow. +func (d *Dispatcher) recordAudit(ctx context.Context, action string, traceID string, result string, reason string, assignment inflightTraceAssignment) { + if d.auditRecorder == nil { // Skip audit work when process wiring did not install an append-only sink. + return // Preserve dispatcher behavior in protocol-only tests and minimal deployments. + } + metadata := map[string]interface{}{ // Build a safe metadata set that excludes plan JSON, Appium identifiers, credentials, and backend errors. + "workerId": assignment.WorkerID, // Identify the assigned worker for fleet and incident correlation. + "attempt": assignment.Attempt, // Preserve the monotonic distributed ownership token. + "dispatchedAtUnix": assignment.DispatchedAtUnix, // Preserve when the current assignment began. + "leaseExpiresAtUnix": assignment.LeaseExpiresAtUnix, // Preserve the ownership deadline used by orphan detection. + "deadlineAtUnix": assignment.DeadlineAtUnix, // Preserve the absolute plan timeout deadline when configured. + } + event := audit.Event{TraceID: traceID, ActorID: assignment.WorkerID, ActorType: "worker", Action: action, ResourceType: "trace", ResourceID: traceID, Result: result, Reason: reason, Metadata: metadata, CreatedAt: time.Now().UTC()} // Normalize the distributed operation into the repository audit contract. + if err := d.auditRecorder.Record(ctx, event); err != nil { // Keep audit persistence best-effort after the authoritative scheduling state has already been decided. + d.logger.WarnContext(ctx, "failed to record distributed execution audit event", "action", action, "trace_id", traceID, "worker_id", assignment.WorkerID, "error", err) // Surface sink failure without logging plan or credential data. } } @@ -482,9 +557,11 @@ func (d *Dispatcher) checkInflightTimeouts(ctx context.Context) { if finalizerErr := d.finalizeQueuedTrace(ctx, traceID, "failed", "orphaned", "trace failed because distributed execution ownership lease expired", leaseErr, 0); finalizerErr != nil { // Persist the orphaned terminal outcome before dropping lease metadata. continue // Leave the assignment key in place so the next sweep can retry orphan terminalization after transient storage failures. } - d.cleanupInflightTrace(ctx, traceID) // Remove the expired ownership lease once the orphaned terminal outcome has been durably recorded. - d.cleanupRetryState(ctx, traceID) // Drop any stale retry counter so later traces with the same identifier never inherit orphaned dispatch state. - d.logger.WarnContext(ctx, "distributed trace orphaned", // Emit the orphan closure so operators can correlate it with the worker assignment that stopped renewing its lease. + d.cleanupInflightTraceIfOwned(ctx, traceID, rawAssignment) // Remove only the exact expired ownership lease read by this watchdog sweep. + d.registry.ReleaseWorkerReservation(distributedReservationID(traceID, assignment.Attempt)) // Release the exact local capacity token after durable orphan terminalization. + d.cleanupRetryState(ctx, traceID) // Drop any stale retry counter so later traces with the same identifier never inherit orphaned dispatch state. + d.recordAudit(ctx, "execution.orphaned", traceID, "failure", "lease_expired", assignment) // Append a sanitized ownership-loss audit event for investigation. + d.logger.WarnContext(ctx, "distributed trace orphaned", // Emit the orphan closure so operators can correlate it with the worker assignment that stopped renewing its lease. "trace_id", traceID, "worker_id", assignment.WorkerID, "address", assignment.Address, @@ -499,9 +576,11 @@ func (d *Dispatcher) checkInflightTimeouts(ctx context.Context) { if finalizerErr := d.finalizeQueuedTrace(ctx, traceID, "failed", "timeout", "trace failed because distributed execution exceeded plan timeout", timeoutErr, 0); finalizerErr != nil { // Persist the timeout terminal outcome before dropping watchdog metadata. continue // Leave the assignment key in place so the next sweep can retry terminalization after transient storage failures. } - d.cleanupInflightTrace(ctx, traceID) // Remove the accepted-assignment bookkeeping once the trace has reached a durable terminal timeout state. - d.cleanupRetryState(ctx, traceID) // Drop any stale retry counter so later traces with the same identifier never inherit this timed-out dispatch state. - d.logger.WarnContext(ctx, "distributed trace timed out", // Emit the timeout closure so operators can correlate the terminal event with the stalled worker assignment. + d.cleanupInflightTraceIfOwned(ctx, traceID, rawAssignment) // Remove only the exact timed-out ownership lease read by this watchdog sweep. + d.registry.ReleaseWorkerReservation(distributedReservationID(traceID, assignment.Attempt)) // Release the exact local capacity token after durable timeout terminalization. + d.cleanupRetryState(ctx, traceID) // Drop any stale retry counter so later traces with the same identifier never inherit this timed-out dispatch state. + d.recordAudit(ctx, "execution.timed_out", traceID, "failure", "plan_timeout", assignment) // Append a sanitized distributed timeout audit event. + d.logger.WarnContext(ctx, "distributed trace timed out", // Emit the timeout closure so operators can correlate the terminal event with the stalled worker assignment. "trace_id", traceID, "worker_id", assignment.WorkerID, "address", assignment.Address, @@ -529,31 +608,34 @@ func parseInflightTraceAssignment(raw string) (inflightTraceAssignment, error) { return assignment, nil // Return the normalized assignment metadata for timeout or cancellation handling. } -// cleanupInflightTrace removes one accepted distributed assignment after cancellation, completion, or timeout terminalization. -func (d *Dispatcher) cleanupInflightTrace(ctx context.Context, traceID string) { - if err := d.cache.Del(ctx, inflightTracePrefix+traceID); err != nil { // Delete the Redis assignment key so future cancel or timeout sweeps do not see a stale in-flight trace. - d.logger.WarnContext(ctx, "failed to delete inflight trace assignment", // Surface cleanup failures without changing control flow because the trace already reached a stable outcome. - "trace_id", traceID, - "error", err) +// cleanupInflightTraceIfOwned removes one provisional assignment only when its exact original Redis value still owns the trace. +func (d *Dispatcher) cleanupInflightTraceIfOwned(ctx context.Context, traceID string, rawAssignment string) { + removed, err := d.cache.CompareAndDelete(ctx, inflightTracePrefix+traceID, rawAssignment) // Prevent rollback after a lost RPC response from deleting a lease already renewed by the worker. + if err != nil { // Log Redis failures while allowing lease expiry and watchdog cleanup to recover later. + d.logger.WarnContext(ctx, "failed to delete owned inflight trace assignment", "trace_id", traceID, "error", err) // Surface ownership-cleanup failure without changing the dispatch error classification. + return // Leave the lease intact because safe ownership deletion could not be established. + } + if !removed { // Record benign ownership loss when a callback already renewed or released the provisional value. + d.logger.InfoContext(ctx, "inflight trace assignment changed before rollback", "trace_id", traceID) // Keep fast callback and response-loss races observable. } } // loadInflightTraceAssignment loads one persisted distributed execution lease for callback validation, renewal, or cancellation routing. -func (d *Dispatcher) loadInflightTraceAssignment(ctx context.Context, traceID string) (inflightTraceAssignment, bool, error) { +func (d *Dispatcher) loadInflightTraceAssignment(ctx context.Context, traceID string) (inflightTraceAssignment, string, bool, error) { rawAssignment, err := d.cache.Get(ctx, inflightTracePrefix+traceID) // Load the persisted distributed assignment so callback ownership can be validated against Redis lease state. if err != nil { // Treat missing keys as a clean "not found" signal while surfacing real cache failures to the caller. if err.Error() == "redis: nil" { // Translate the Redis nil sentinel into a stable absent-assignment result for higher-layer stale-result handling. - return inflightTraceAssignment{}, false, nil // Report that no active distributed lease exists for the requested trace. + return inflightTraceAssignment{}, "", false, nil // Report that no active distributed lease exists for the requested trace. } - return inflightTraceAssignment{}, false, errors.Wrap(errors.CodeStoreRead, "failed to load inflight trace assignment", err) // Surface Redis read failures through the standard storage-read contract. + return inflightTraceAssignment{}, "", false, errors.Wrap(errors.CodeStoreRead, "failed to load inflight trace assignment", err) // Surface Redis read failures through the standard storage-read contract. } assignment, parseErr := parseInflightTraceAssignment(rawAssignment) // Decode the stored distributed assignment payload into the normalized in-memory lease model. if parseErr != nil { // Surface malformed Redis payloads because distributed ownership cannot be validated safely without them. - return inflightTraceAssignment{}, false, parseErr // Preserve the wrapped decode failure so callers can log or surface the broken lease state. + return inflightTraceAssignment{}, "", false, parseErr // Preserve the wrapped decode failure so callers can log or surface the broken lease state. } - return assignment, true, nil // Return the decoded distributed lease metadata for callback validation or renewal. + return assignment, rawAssignment, true, nil // Return decoded metadata plus the exact Redis value required by atomic ownership updates. } // assignmentMatches returns true when one persisted distributed lease still belongs to the supplied worker and execution attempt. @@ -563,8 +645,8 @@ func assignmentMatches(assignment inflightTraceAssignment, workerID string, atte // RenewExecutionLease refreshes one distributed execution lease when the supplied worker and attempt still own the trace. func (d *Dispatcher) RenewExecutionLease(ctx context.Context, traceID string, workerID string, attempt int64) (bool, error) { - assignment, found, err := d.loadInflightTraceAssignment(ctx, traceID) // Load the current distributed lease metadata before validating ownership or refreshing expiry. - if err != nil { // Surface Redis or payload failures because lease renewal cannot proceed safely without current assignment state. + assignment, rawAssignment, found, err := d.loadInflightTraceAssignment(ctx, traceID) // Load current metadata and its exact Redis value before validating ownership or refreshing expiry. + if err != nil { // Surface Redis or payload failures because lease renewal cannot proceed safely without current assignment state. return false, err // Preserve the wrapped storage error for the caller. } if !found || !assignmentMatches(assignment, workerID, attempt) { // Reject renewal when the trace no longer has an active lease for this worker attempt. @@ -577,24 +659,42 @@ func (d *Dispatcher) RenewExecutionLease(ctx context.Context, traceID string, wo } assignment.LastRenewedAtUnix = now.UnixMilli() // Record the successful renewal time so operators can see recent distributed ownership activity. - assignment.LeaseExpiresAtUnix = d.inflightLeaseDeadlineUnix(now) // Extend the ownership expiry from the current renewal moment using the configured heartbeat-derived lease duration. - d.persistInflightAssignment(ctx, traceID, assignment) // Persist the refreshed lease metadata so watchdog and callback validation observe the new expiry. + assignment.LeaseExpiresAtUnix = d.inflightLeaseDeadlineUnix(now) // Extend ownership expiry from the current renewal moment. + nextPayload, err := json.Marshal(assignment) // Encode the refreshed lease before the atomic ownership comparison. + if err != nil { // Surface unexpected assignment serialization failures without touching the current lease. + return false, errors.Wrap(errors.CodeInternal, "failed to marshal renewed inflight trace assignment", err) // Preserve the encoding cause under a stable internal code. + } + replaced, err := d.cache.CompareAndSet(ctx, inflightTracePrefix+traceID, rawAssignment, string(nextPayload), inflightTraceTTL) // Refresh only when the exact lease read above still owns the key. + if err != nil { // Require durable renewal so workers never receive a false ownership confirmation during Redis failure. + d.recordAudit(ctx, "execution.lease_renew", traceID, "failure", "store_write", assignment) // Append a stable fail-closed lease-renewal audit record. + return false, errors.Wrap(errors.CodeStoreWrite, "failed to renew inflight trace assignment", err) // Surface Redis script failure for transport handling. + } + if !replaced { // Reject a renewal that lost ownership after its initial read. + return false, nil // Tell the worker to stop because a newer lease or cleanup won the race. + } return true, nil // Report that the distributed lease still belongs to this worker attempt and was refreshed successfully. } // ReleaseExecutionLease removes one distributed execution lease only when the supplied worker and attempt still own the trace. func (d *Dispatcher) ReleaseExecutionLease(ctx context.Context, traceID string, workerID string, attempt int64) (bool, error) { - assignment, found, err := d.loadInflightTraceAssignment(ctx, traceID) // Load the current distributed lease metadata before deciding whether cleanup should proceed. - if err != nil { // Surface Redis or payload failures because lease cleanup cannot be validated safely without the current assignment state. + assignment, rawAssignment, found, err := d.loadInflightTraceAssignment(ctx, traceID) // Load current metadata and its exact Redis value before deciding whether cleanup should proceed. + if err != nil { // Surface Redis or payload failures because lease cleanup cannot be validated safely without the current assignment state. return false, err // Preserve the wrapped storage error for the caller. } if !found || !assignmentMatches(assignment, workerID, attempt) { // Reject cleanup when the trace no longer has an active lease for this worker attempt. return false, nil // Report a stale or already-cleaned lease without treating it as an infrastructure failure. } - d.cleanupInflightTrace(ctx, traceID) // Remove the persisted distributed lease once the owning worker attempt has reported a terminal result successfully. - return true, nil // Report that the distributed lease belonged to this worker attempt and has now been removed. + released, err := d.cache.CompareAndDelete(ctx, inflightTracePrefix+traceID, rawAssignment) // Delete only the exact lease validated for this worker attempt. + if err != nil { // Require successful Redis deletion before declaring the ownership lease released. + return false, errors.Wrap(errors.CodeStoreWrite, "failed to release inflight trace assignment", err) // Preserve retryable cleanup state when Redis rejects deletion. + } + if !released { // Treat a value change after the initial read as lost ownership rather than deleting a successor. + return false, nil // Report stale cleanup so the caller leaves the newer lease untouched. + } + d.registry.ReleaseWorkerReservation(distributedReservationID(traceID, attempt)) // Release the exact local capacity token only after durable lease cleanup succeeds. + return true, nil // Report that the distributed lease and matching local reservation were removed successfully. } // handleDispatchError decides whether to ACK (terminal or retries exhausted) or @@ -736,21 +836,39 @@ func (d *Dispatcher) CancelDispatchedPlan(ctx context.Context, traceID string) ( return false, errors.Wrap(errors.CodeSchedNoWorker, "failed to connect to assigned worker", err) } - resp, err := client.CancelPlan(ctx, &rpc.CancelPlanRequest{TraceID: traceID}) - if err != nil { - return false, errors.Wrap(errors.CodeInternal, "worker CancelPlan RPC failed", err) + rpcCtx, rpcCancel := context.WithTimeout(ctx, workerRPCTimeout) // Bound cancellation so an unreachable worker cannot stall the caller indefinitely. + resp, err := client.CancelPlan(rpcCtx, &rpc.CancelPlanRequest{TraceID: traceID}) // Forward cancellation to the worker that owns the persisted assignment. + rpcCancel() // Release the per-cancellation timer immediately after the worker RPC returns. + if err != nil { // Surface transport and deadline failures without deleting ownership metadata prematurely. + return false, errors.Wrap(errors.CodeSchedNoWorker, "worker CancelPlan RPC failed", err) // Keep the lease available for retry or watchdog cleanup. + } + if resp == nil { // Reject malformed successful RPC responses that omit a cancellation status. + return false, errors.New(errors.CodeInternal, "worker returned an empty CancelPlan response") // Preserve lease state because cancellation outcome is unknown. } - switch resp.Status { + switch resp.Status { // Normalize the worker's stable cancellation result into lease and capacity cleanup. case "cancelled": - d.cleanupInflightTrace(ctx, traceID) // Remove the in-flight assignment because the worker has acknowledged cancellation for this trace. - return true, nil + cleanupErr := d.cleanupCancelledAssignment(ctx, traceID, rawAssignment, assignment.Attempt) // Remove only the cancelled owner's lease and exact local reservation. + return true, cleanupErr // Report that a live worker execution was cancelled while preserving any Redis cleanup failure. case "not_found": - d.cleanupInflightTrace(ctx, traceID) // Remove the stale assignment because the worker no longer knows about this supposedly in-flight trace. - return false, nil + cleanupErr := d.cleanupCancelledAssignment(ctx, traceID, rawAssignment, assignment.Attempt) // Remove only the stale owner's lease and exact local reservation. + return false, cleanupErr // Report no live remote cancellation while preserving any Redis cleanup failure. default: - return false, errors.New(errors.CodeInternal, "worker returned unexpected cancel status: "+resp.Status) + return false, errors.New(errors.CodeInternal, "worker returned unexpected cancel status") // Avoid propagating arbitrary worker-controlled status text into higher-layer errors. + } +} + +// cleanupCancelledAssignment atomically removes the lease value routed to the cancelled worker and releases its exact local capacity token. +func (d *Dispatcher) cleanupCancelledAssignment(ctx context.Context, traceID string, rawAssignment string, attempt int64) error { + removed, err := d.cache.CompareAndDelete(ctx, inflightTracePrefix+traceID, rawAssignment) // Prevent a stale cancellation response from deleting a newer trace owner. + d.registry.ReleaseWorkerReservation(distributedReservationID(traceID, attempt)) // Release the cancelled attempt's exact local token regardless of later lease replacement. + if err != nil { // Surface Redis cleanup failures after local capacity has been reconciled. + return errors.Wrap(errors.CodeStoreWrite, "failed to remove cancelled inflight trace assignment", err) // Preserve retryable stale Redis state for operator handling. + } + if !removed { // Record benign ownership change without deleting the successor lease. + d.logger.InfoContext(ctx, "cancelled inflight assignment no longer owned at cleanup", "trace_id", traceID, "attempt", attempt) // Keep cross-attempt cancellation races observable. } + return nil // Confirm that cleanup either removed this exact lease or safely left a successor untouched. } // finalizeQueuedTrace records one dispatcher-owned terminal outcome before the queue message is ACKed. diff --git a/internal/orchestrator/distributed_callback_test.go b/internal/orchestrator/distributed_callback_test.go index 1060c2a..a75d9a6 100644 --- a/internal/orchestrator/distributed_callback_test.go +++ b/internal/orchestrator/distributed_callback_test.go @@ -4,12 +4,57 @@ package orchestrator import ( "context" "encoding/json" + "net" "testing" "time" "mcp_for_appium/internal/rpc" + + "google.golang.org/grpc" ) +// immediateCompletionWorkerService reports terminal completion before returning ExecutePlan acceptance to reproduce the distributed acknowledgement race deterministically. +type immediateCompletionWorkerService struct { + service *Service + workerID string +} + +// ExecutePlan completes the leased attempt synchronously before acknowledging worker admission. +func (s immediateCompletionWorkerService) ExecutePlan(ctx context.Context, req *rpc.ExecutePlanRequest) (*rpc.ExecutePlanResponse, error) { + accepted, err := s.service.CompleteDistributedPlan(ctx, &rpc.CompletePlanRequest{TraceID: req.TraceID, WorkerID: s.workerID, Attempt: req.Attempt, FinalStatus: "completed", TerminalReason: "completed", Message: "completed before acceptance response"}) // Send the terminal callback while the trace row is still pending but its attempt and Redis lease already exist. + if err != nil { // Surface callback infrastructure failures through the fake worker RPC so the test fails at dispatch. + return nil, err // Preserve the callback error for direct diagnosis by the dispatcher test. + } + if !accepted { // Reject dispatch when the pending-state callback was incorrectly classified as stale. + return &rpc.ExecutePlanResponse{Status: "rejected", Message: "completion callback was stale"}, nil // Make the lost race visible as a deterministic worker rejection. + } + return &rpc.ExecutePlanResponse{Status: "accepted"}, nil // Acknowledge only after the terminal callback has durably completed. +} + +// CancelPlan reports that no active run remains because this fake worker completes before its ExecutePlan response returns. +func (s immediateCompletionWorkerService) CancelPlan(ctx context.Context, req *rpc.CancelPlanRequest) (*rpc.CancelPlanResponse, error) { + return &rpc.CancelPlanResponse{Status: "not_found"}, nil // Preserve idempotent dispatcher rollback after the fast callback already finished the trace. +} + +// startImmediateCompletionWorkerServer starts one loopback gRPC worker that deterministically completes before acknowledging ExecutePlan. +func startImmediateCompletionWorkerServer(t *testing.T, service *Service, workerID string) (string, func()) { + t.Helper() // Attribute listener and server setup failures to the calling race test. + listener, err := net.Listen("tcp4", "127.0.0.1:0") // Reserve one IPv4 loopback endpoint for the production worker client path. + if err != nil { // Skip only when the environment cannot provide loopback networking. + t.Skipf("skipping immediate completion callback test because loopback listen failed: %v", err) // Surface the environment limitation explicitly. + } + server := grpc.NewServer() // Construct one plain in-process gRPC server for the fake worker implementation. + rpc.RegisterWorkerServiceServer(server, immediateCompletionWorkerService{service: service, workerID: workerID}) // Register the race-producing worker under the production RPC contract. + go func() { // Serve worker RPCs concurrently while dispatcher execution remains synchronous in the test goroutine. + _ = server.Serve(listener) // Ignore the expected shutdown error after the test stops the server. + }() + stop := func() { // Return one deterministic cleanup closure for the test. + server.GracefulStop() // Drain and stop the fake worker gRPC server. + _ = listener.Close() // Release the loopback listener even when the server already closed it. + } + return listener.Addr().String(), stop // Return the routable endpoint and its matching cleanup closure. +} + // TestDistributedCallbacksFinalizeAcceptedTrace verifies that one accepted distributed worker attempt can append step events and finalize the trace successfully. func TestDistributedCallbacksFinalizeAcceptedTrace(t *testing.T) { harness := newTraceTerminalHarness(t) // Start one isolated orchestrator harness so this test can exercise real DAO, Redis, and distributed callback handling. @@ -97,6 +142,42 @@ func TestDistributedCallbacksFinalizeAcceptedTrace(t *testing.T) { } } +// TestDistributedCompletionBeforeAcceptanceResponse verifies that a worker terminal callback can atomically win while the reserved trace is still pending. +func TestDistributedCompletionBeforeAcceptanceResponse(t *testing.T) { + harness := newTraceTerminalHarness(t) // Start isolated PostgreSQL and Redis dependencies for the real distributed state machine. + defer harness.service.Stop() // Stop dispatcher, registry, and background resources after the race scenario completes. + sessionID, traceID := harness.seedPendingTrace(t) // Seed the pending trace and Appium session mapping required before distributed dispatch. + const workerID = "worker-immediate-completion" // Use one stable worker identity across registry, lease, and callback validation. + workerAddress, stopWorker := startImmediateCompletionWorkerServer(t, harness.service, workerID) // Start the worker that invokes completion before returning acceptance. + defer stopWorker() // Stop the loopback gRPC worker after all state assertions complete. + if err := harness.service.registry.Register(context.Background(), &WorkerNode{ID: workerID, Address: workerAddress, Capacity: 1, Tags: map[string]string{}}); err != nil { // Make the race-producing worker eligible for scheduler reservation. + t.Fatalf("failed to register immediate completion worker: %v", err) // Surface fixture failure because dispatch cannot reproduce the race without registration. + } + harness.service.dispatcher.executor = nil // Force the production distributed gRPC dispatch path instead of monolith execution. + plan := string(json.RawMessage(`[{"type":"wait","params":{"ms":1}}]`)) // Build one valid minimal plan whose contents are irrelevant to the fake worker callback. + if err := harness.service.dispatcher.dispatchToWorker(context.Background(), traceID, "test-project", sessionID, plan); err != nil { // Dispatch through lease creation, capacity reservation, worker callback, and delayed acceptance promotion. + t.Fatalf("expected immediate completion dispatch to succeed, got error: %v", err) // Surface any acknowledgement-boundary regression directly. + } + + trace, events := harness.loadTraceAndEvents(t, traceID) // Read the durable lifecycle and replay state after dispatch returns. + if trace.Status != "completed" { // Require the fast callback to win instead of leaving the trace pending or running forever. + t.Fatalf("expected trace status completed after pre-acceptance callback, got %s", trace.Status) // Surface the lost terminal transition. + } + if trace.CurrentAttempt != 1 { // Preserve the exact reserved ownership token across the pending-state finalization. + t.Fatalf("expected current attempt 1 after pre-acceptance callback, got %d", trace.CurrentAttempt) // Surface attempt drift that would weaken stale-result protection. + } + if len(events) != 1 || events[0].Status != "completed" { // Require exactly one terminal replay event from the fast callback. + t.Fatalf("expected one completed terminal event, got %#v", events) // Surface missing or duplicate callback persistence. + } + if _, err := harness.cache.Get(context.Background(), inflightTracePrefix+traceID); err == nil { // Confirm successful terminalization removed the provisional ownership lease. + t.Fatal("expected pre-acceptance completion to remove the inflight lease") // Surface stale Redis ownership that could accept late callbacks incorrectly. + } + workerSnapshot := harness.service.registry.GetWorker(workerID) // Read an isolated post-dispatch worker capacity snapshot. + if workerSnapshot == nil || workerSnapshot.ActiveLoad != 0 { // Require exact reservation cleanup even though dispatcher rollback runs after callback cleanup. + t.Fatalf("expected worker active load 0 after immediate completion, got %#v", workerSnapshot) // Surface leaked or double-adjusted capacity state. + } +} + // TestDistributedCallbacksRejectStaleAttempt verifies that late callbacks from an older attempt cannot append events or overwrite the current trace state. func TestDistributedCallbacksRejectStaleAttempt(t *testing.T) { harness := newTraceTerminalHarness(t) // Start one isolated orchestrator harness so this test can exercise real DAO, Redis, and distributed callback handling. diff --git a/internal/orchestrator/distributed_callbacks.go b/internal/orchestrator/distributed_callbacks.go index 3b79838..89b1c2a 100644 --- a/internal/orchestrator/distributed_callbacks.go +++ b/internal/orchestrator/distributed_callbacks.go @@ -32,7 +32,7 @@ func (s *Service) RenewDistributedExecutionLease(ctx context.Context, traceID st return renewed, nil // Report whether the distributed lease still belongs to the supplied worker attempt. } -// ReportDistributedPlanEvent appends one worker-emitted step event when the supplied worker attempt still owns the running trace. +// ReportDistributedPlanEvent appends one worker-emitted step event when the supplied worker attempt owns the reserved pending or running trace. func (s *Service) ReportDistributedPlanEvent(ctx context.Context, req *rpc.ReportPlanEventRequest) (bool, error) { if req == nil { // Reject nil callback payloads because no trace, worker, or event data can be validated safely from them. return false, errors.New(errors.CodePlanInvalid, "report plan event request is required") // Surface invalid callback payloads before any lease or DAO work begins. @@ -100,18 +100,18 @@ func (s *Service) CompleteDistributedPlan(ctx context.Context, req *rpc.Complete return false, err // Preserve the wrapped DAO or serialization failure for higher-layer transport mapping and worker logging. } - released, releaseErr := s.dispatcher.ReleaseExecutionLease(ctx, req.TraceID, req.WorkerID, req.Attempt) // Remove the Redis-backed ownership lease once this worker attempt has either finalized or been confirmed stale. - if releaseErr != nil { // Log lease-release failures without discarding the already-persisted terminal outcome. - s.logger.WarnContext(ctx, "failed to release distributed execution lease", "trace_id", req.TraceID, "worker_id", req.WorkerID, "attempt", req.Attempt, "error", releaseErr) // Surface the Redis cleanup failure for operator visibility. - } - if !released { // Log lease-release misses so operators can see when another path already cleaned up the ownership record first. - s.logger.InfoContext(ctx, "distributed execution lease already released", "trace_id", req.TraceID, "worker_id", req.WorkerID, "attempt", req.Attempt) // Record the benign double-cleanup so races stay observable. - } if !finalized { // Treat late results rejected by the DAO attempt guard as a benign stale callback after lease validation already succeeded. s.logger.InfoContext(ctx, "ignored distributed completion after DAO ownership check", "trace_id", req.TraceID, "worker_id", req.WorkerID, "attempt", req.Attempt, "final_status", req.FinalStatus) // Log the stale drop so operators can correlate it with terminalization races. return false, nil // Report the stale callback without surfacing it as an infrastructure failure. } + released, releaseErr := s.dispatcher.ReleaseExecutionLease(ctx, req.TraceID, req.WorkerID, req.Attempt) // Remove Redis ownership and exact local capacity only after the database terminal transition commits. + if releaseErr != nil { // Log lease-release failures without discarding the already-persisted terminal outcome. + s.logger.WarnContext(ctx, "failed to release distributed execution lease", "trace_id", req.TraceID, "worker_id", req.WorkerID, "attempt", req.Attempt, "error", releaseErr) // Surface the Redis cleanup failure for operator visibility. + } else if !released { // Log lease-release misses only when cleanup completed without an infrastructure error. + s.logger.InfoContext(ctx, "distributed execution lease already released", "trace_id", req.TraceID, "worker_id", req.WorkerID, "attempt", req.Attempt) // Record the benign double-cleanup so races stay observable. + } + return true, nil // Report that the worker terminal callback finalized the current distributed attempt successfully. } @@ -127,10 +127,11 @@ func (s *Service) finalizeDistributedAttempt(ctx context.Context, traceID string "terminalStatus": nextStatus, // Duplicate the terminal lifecycle state inside the payload for clients that rely on payload inspection alone. "terminalReason": terminalReason, // Persist the structured terminal reason so replay consumers can distinguish timeout, orphaned, cancelled, and normal completion outcomes. } - if cause != nil { // Attach the underlying error details only when the terminal transition was triggered by a failure path. - payloadMap["error"] = cause.Error() // Preserve the original error string so operators can diagnose distributed terminal failures from event replay alone. - if code, ok := errors.CodeOf(cause); ok { // Attach the structured error code when the failure path used the repository-standard error type. + if cause != nil { // Attach only a stable machine-readable classification when the terminal transition was triggered by failure. + if code, ok := errors.CodeOf(cause); ok { // Resolve the repository code without exposing worker or backend error text in replay payloads. payloadMap["errorCode"] = string(code) // Preserve the stable machine-readable error code for downstream diagnostics and metrics correlation. + } else { + payloadMap["errorCode"] = string(errors.CodeInternal) // Classify untyped failures generically while keeping raw diagnostic text server-side only. } } @@ -139,8 +140,8 @@ func (s *Service) finalizeDistributedAttempt(ctx context.Context, traceID string return false, errors.Wrap(errors.CodeInternal, "failed to marshal distributed terminal trace event", err) // Surface payload serialization failures as internal orchestrator errors. } - terminalReasonCopy := terminalReason // Copy the terminal reason into one addressable local variable for PostgreSQL parameter binding. - finalized, err := s.dao.TransitionTraceAttemptWithEvent(ctx, traceID, attempt, []string{"running"}, nextStatus, &terminalReasonCopy, &postgres.PlanEvent{ // Commit the terminal status change, reason, and final event only when this attempt still owns the running trace. + terminalReasonCopy := terminalReason // Copy the terminal reason into one addressable local variable for PostgreSQL parameter binding. + finalized, err := s.dao.TransitionTraceAttemptWithEvent(ctx, traceID, attempt, []string{"pending", "running"}, nextStatus, &terminalReasonCopy, &postgres.PlanEvent{ // Commit terminal state when this attempt wins either side of the worker-acceptance boundary. TraceID: traceID, // Target the same trace row that is transitioning into its terminal state. StepIndex: -1, // Use a sentinel step index so clients can distinguish trace-level terminal events from step-level execution events. Status: nextStatus, // Mirror the terminal trace state in the event status for simple client-side filtering. diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.go index c8f64cf..46bc43c 100644 --- a/internal/orchestrator/health.go +++ b/internal/orchestrator/health.go @@ -47,10 +47,11 @@ func (s *Service) HealthCheck(ctx context.Context) map[string]interface{} { err := s.dao.Ping(probeCtx) // Probe PostgreSQL connectivity using the live DAO pool so the result matches runtime behavior. cancel() // Release the probe timeout resources immediately after the database check finishes. if err != nil { // Treat a failed PostgreSQL ping as a hard-down condition for the orchestrator. - checks["database"] = "error" // Report the database probe failure directly in the compact check map. - issues = appendIssueOnce(issues, "postgres") // Add the stable database issue key once for alerting and dashboards. - details["database"] = map[string]interface{}{"error": err.Error()} // Preserve the exact database failure string for operator diagnosis. - criticalFailure = true // Mark the health snapshot down because core persistence is unavailable. + checks["database"] = "error" // Report the database probe failure directly in the compact check map. + issues = appendIssueOnce(issues, "postgres") // Add the stable database issue key once for alerting and dashboards. + details["database"] = map[string]interface{}{"status": "unavailable"} // Return only a stable public classification instead of PostgreSQL connection details. + s.logger.WarnContext(ctx, "database health probe failed", "error", err) // Retain the exact probe diagnostic in protected server logs for operators. + criticalFailure = true // Mark the health snapshot down because core persistence is unavailable. } else { checks["database"] = "ok" // Report a healthy database probe in the compact check map. } @@ -65,10 +66,11 @@ func (s *Service) HealthCheck(ctx context.Context) map[string]interface{} { err := s.cache.Ping(probeCtx) // Probe Redis using the live cache wrapper so the result matches runtime queue behavior. cancel() // Release the probe timeout resources immediately after the Redis check finishes. if err != nil { // Treat a failed Redis ping as a hard-down condition for the orchestrator. - checks["redis"] = "error" // Report the Redis probe failure directly in the compact check map. - issues = appendIssueOnce(issues, "redis") // Add the stable Redis issue key once for alerting and dashboards. - details["redis"] = map[string]interface{}{"error": err.Error()} // Preserve the exact Redis failure string for operator diagnosis. - criticalFailure = true // Mark the health snapshot down because core queue and coordination state are unavailable. + checks["redis"] = "error" // Report the Redis probe failure directly in the compact check map. + issues = appendIssueOnce(issues, "redis") // Add the stable Redis issue key once for alerting and dashboards. + details["redis"] = map[string]interface{}{"status": "unavailable"} // Return only a stable public classification instead of Redis endpoint details. + s.logger.WarnContext(ctx, "redis health probe failed", "error", err) // Retain the exact probe diagnostic in protected server logs for operators. + criticalFailure = true // Mark the health snapshot down because core queue and coordination state are unavailable. } else { checks["redis"] = "ok" // Report a healthy Redis probe in the compact check map. } @@ -82,10 +84,11 @@ func (s *Service) HealthCheck(ctx context.Context) map[string]interface{} { err := s.s3.ValidateBucket(probeCtx) // Probe the configured artifact bucket using the live S3 client so the result matches runtime uploads. cancel() // Release the probe timeout resources immediately after the S3 check finishes. if err != nil { // Treat artifact-store failure as degraded because trace execution can still proceed while uploads fail. - checks["s3"] = "error" // Report the artifact-store probe failure directly in the compact check map. - issues = appendIssueOnce(issues, "s3") // Add the stable artifact-store issue key once for alerting and dashboards. - details["s3"] = map[string]interface{}{"configured": true, "error": err.Error()} // Preserve the exact S3 failure string for operator diagnosis. - degradedFailure = true // Mark the health snapshot degraded because artifact persistence is impaired but not fully fatal. + checks["s3"] = "error" // Report the artifact-store probe failure directly in the compact check map. + issues = appendIssueOnce(issues, "s3") // Add the stable artifact-store issue key once for alerting and dashboards. + details["s3"] = map[string]interface{}{"configured": true, "status": "unavailable"} // Return safe object-store state without provider response or bucket details. + s.logger.WarnContext(ctx, "s3 health probe failed", "error", err) // Retain the exact provider diagnostic in protected server logs for operators. + degradedFailure = true // Mark the health snapshot degraded because artifact persistence is impaired but not fully fatal. } else { checks["s3"] = "ok" // Report a healthy artifact-store probe in the compact check map. details["s3"] = map[string]interface{}{"configured": true} // Return explicit metadata so operators can see that object storage is wired and healthy. @@ -102,13 +105,14 @@ func (s *Service) HealthCheck(ctx context.Context) map[string]interface{} { err := startup.CheckAppiumReachability(probeCtx, s.appiumURL) // Probe the configured Appium status endpoint using the same startup-time reachability check. cancel() // Release the probe timeout resources immediately after the Appium check finishes. if err != nil { // Treat an unreachable Appium dependency as a hard-down condition in monolith mode. - checks["appium"] = "error" // Report the Appium probe failure directly in the compact check map. - issues = appendIssueOnce(issues, "appium") // Add the stable Appium issue key once for alerting and dashboards. - details["appium"] = map[string]interface{}{"url": s.appiumURL, "error": err.Error()} // Preserve the failing Appium URL and error string for operator diagnosis. - criticalFailure = true // Mark the health snapshot down because direct execution is unavailable. + checks["appium"] = "error" // Report the Appium probe failure directly in the compact check map. + issues = appendIssueOnce(issues, "appium") // Add the stable Appium issue key once for alerting and dashboards. + details["appium"] = map[string]interface{}{"configured": true, "status": "unavailable"} // Return safe dependency state without exposing URL credentials or backend diagnostics. + s.logger.WarnContext(ctx, "appium health probe failed", "error", err) // Retain the exact reachability diagnostic in protected server logs for operators. + criticalFailure = true // Mark the health snapshot down because direct execution is unavailable. } else { - checks["appium"] = "ok" // Report a healthy Appium probe in the compact check map. - details["appium"] = map[string]interface{}{"url": s.appiumURL} // Return the probed Appium URL for operator confirmation. + checks["appium"] = "ok" // Report a healthy Appium probe in the compact check map. + details["appium"] = map[string]interface{}{"configured": true, "status": "available"} // Confirm readiness without exposing the configured endpoint. } } checks["workers"] = "skipped" // Skip worker-fleet checks in monolith mode because this service does not depend on remote workers for execution. @@ -146,10 +150,11 @@ func (s *Service) HealthCheck(ctx context.Context) map[string]interface{} { summary, err := s.dispatcher.HealthSummary(probeCtx) // Inspect retained queue depth, pending claims, and in-flight distributed traces through the live dispatcher. cancel() // Release the probe timeout resources immediately after queue inspection finishes. if err != nil { // Treat queue-inspection failure as degraded because Redis reachability is already reported separately above. - checks["queue"] = "error" // Report the queue inspection failure directly in the compact check map. - issues = appendIssueOnce(issues, "queue") // Add the stable queue issue key once for alerting and dashboards. - details["queue"] = map[string]interface{}{"error": err.Error()} // Preserve the exact queue inspection error string for operator diagnosis. - degradedFailure = true // Mark the health snapshot degraded because execution backlog visibility is impaired. + checks["queue"] = "error" // Report the queue inspection failure directly in the compact check map. + issues = appendIssueOnce(issues, "queue") // Add the stable queue issue key once for alerting and dashboards. + details["queue"] = map[string]interface{}{"status": "unavailable"} // Return only a stable public classification instead of Redis stream diagnostics. + s.logger.WarnContext(ctx, "queue health inspection failed", "error", err) // Retain the exact queue diagnostic in protected server logs for operators. + degradedFailure = true // Mark the health snapshot degraded because execution backlog visibility is impaired. } else { checks["queue"] = "ok" // Report successful queue inspection in the compact check map. details["queue"] = map[string]interface{}{ // Return the raw queue counters so operators can inspect backlog and in-flight activity directly. diff --git a/internal/orchestrator/health_check_test.go b/internal/orchestrator/health_check_test.go index 30d8219..116b05e 100644 --- a/internal/orchestrator/health_check_test.go +++ b/internal/orchestrator/health_check_test.go @@ -36,6 +36,14 @@ func TestHealthCheckReportsMonolithAppiumFailure(t *testing.T) { if checks["s3"] != "skipped" { // Fail the test when the harness without an S3 client does not report the artifact store probe as skipped. t.Fatalf("expected s3 health skipped, got %#v", checks["s3"]) // Surface the unexpected S3 status because the harness intentionally omits object storage wiring. } + details := payload["details"].(map[string]interface{}) // Read public dependency details so the test can enforce diagnostic sanitization. + appiumDetails := details["appium"].(map[string]interface{}) // Read the failed Appium probe's safe public metadata. + if _, exists := appiumDetails["error"]; exists { // Reject raw reachability diagnostics in externally visible health responses. + t.Fatalf("expected appium health details to omit raw error text, got %#v", appiumDetails["error"]) // Surface sensitive diagnostic regression explicitly. + } + if _, exists := appiumDetails["url"]; exists { // Reject configured endpoint disclosure because URLs can contain internal hosts or credentials. + t.Fatalf("expected appium health details to omit configured URL, got %#v", appiumDetails["url"]) // Surface endpoint disclosure regression explicitly. + } } // TestHealthCheckReportsDistributedWorkerAndQueueSummary verifies that distributed health reports worker-capacity degradation and live queue counters. @@ -50,8 +58,9 @@ func TestHealthCheckReportsDistributedWorkerAndQueueSummary(t *testing.T) { if err := harness.service.registry.Register(context.Background(), &WorkerNode{ID: "degraded-worker", Address: "127.0.0.1:19091", Capacity: 1, Tags: map[string]string{}}); err != nil { // Register one second worker that the test will mark degraded to simulate partial fleet impairment. t.Fatalf("failed to register degraded worker: %v", err) // Surface worker-registration failures because the degraded-fleet scenario depends on two workers being present. } - degradedWorker := harness.service.registry.GetWorker("degraded-worker") // Load the second worker back out of the registry so the test can mutate its in-memory status directly. - degradedWorker.Status = "degraded" // Mark the worker degraded so the distributed health snapshot should report partial capacity impairment. + updateWorkerForTest(t, harness.service.registry, "degraded-worker", func(worker *WorkerNode) { // Seed partial fleet impairment under the registry's production synchronization boundary. + worker.Status = "degraded" // Mark the selected worker degraded so distributed health reports reduced fleet quality. + }) if _, err := harness.cache.XAdd(context.Background(), harness.service.dispatcher.streamName(0), map[string]interface{}{"trace_id": "queued-trace"}, streamTrimMaxLen); err != nil { // Add one retained queue message so the health endpoint has non-zero stream depth to report. t.Fatalf("failed to seed queue stream entry: %v", err) // Surface queue-seeding failures because the queue summary assertion depends on one retained message. @@ -60,9 +69,11 @@ func TestHealthCheckReportsDistributedWorkerAndQueueSummary(t *testing.T) { if err != nil { // Skip the test only when even explicit loopback listeners are unavailable in the current environment. t.Skipf("skipping distributed health queue summary test because loopback listen failed: %v", err) // Surface the environment limitation without misclassifying the production logic as passing. } - listenerAddress := listener.Addr().String() // Capture the kernel-assigned loopback address before the temporary listener is closed. - listener.Close() // Release the temporary loopback listener immediately so the address can be used only as inert metadata in the in-flight assignment record. - harness.service.dispatcher.persistInflightAssignment(context.Background(), "inflight-trace", inflightTraceAssignment{Address: listenerAddress, WorkerID: "healthy-worker", DispatchedAtUnix: time.Now().UnixMilli(), DeadlineAtUnix: time.Now().Add(time.Minute).UnixMilli()}) // Seed one active distributed assignment so the health endpoint can report current in-flight trace count. + listenerAddress := listener.Addr().String() // Capture the kernel-assigned loopback address before the temporary listener is closed. + listener.Close() // Release the temporary loopback listener immediately so the address can be used only as inert metadata in the in-flight assignment record. + if _, err := harness.service.dispatcher.persistInflightAssignment(context.Background(), "inflight-trace", inflightTraceAssignment{Address: listenerAddress, WorkerID: "healthy-worker", DispatchedAtUnix: time.Now().UnixMilli(), DeadlineAtUnix: time.Now().Add(time.Minute).UnixMilli()}); err != nil { // Seed one active distributed assignment so the health endpoint can report current in-flight trace count. + t.Fatalf("failed to persist inflight trace assignment: %v", err) // Surface Redis fixture failures because health cannot report an assignment that was never stored. + } payload := harness.service.HealthCheck(context.Background()) // Evaluate the production health snapshot against the seeded distributed-capacity and queue state. if payload["status"] != "degraded" { // Fail the test when partial worker degradation does not surface as an overall degraded health state. diff --git a/internal/orchestrator/persistence.go b/internal/orchestrator/persistence.go index 4b80f8c..01f23f1 100644 --- a/internal/orchestrator/persistence.go +++ b/internal/orchestrator/persistence.go @@ -10,9 +10,11 @@ import ( "mcp_for_appium/internal/storage/postgres" ) -// markSessionEnded serializes concurrent end-session requests with a row lock and reports whether this call changed the stored session state. -func (s *Service) markSessionEnded(ctx context.Context, sessionID string, endedAt time.Time) (bool, error) { - changed := false // Track whether this call performed the state transition so callers can keep end-session idempotent. +const detachedFinalizationTimeout = 5 * time.Second // detachedFinalizationTimeout bounds durable terminal writes after request or execution cancellation. + +// prepareSessionEnd locks one session row, moves active state into ending, and reports whether external cleanup still needs to run. +func (s *Service) prepareSessionEnd(ctx context.Context, sessionID string, updatedAt time.Time) (bool, error) { + cleanupRequired := false // Track whether the caller should run or retry external automation cleanup after the transaction commits. err := s.dao.WithTx(ctx, func(tx *postgres.TxDAO) error { // Run the lock-and-update sequence in one transaction so the row lock stays valid for the write. session, err := tx.GetSessionForUpdate(ctx, sessionID) // Lock the session row before inspecting its current lifecycle state. if err != nil { // Stop immediately when the target session does not exist or cannot be locked. @@ -22,20 +24,48 @@ func (s *Service) markSessionEnded(ctx context.Context, sessionID string, endedA if session.Status == "ended" { // Treat repeated end calls as a no-op once the session is already terminal. return nil // Return success so higher layers can keep the API idempotent. } + if session.Status == "ending" { // Allow a later EndSession call to retry cleanup after an earlier external cleanup failure. + cleanupRequired = true // Tell the caller to retry the still-incomplete external cleanup phase. + return nil // Leave the existing ending row unchanged while committing the read transaction safely. + } - updated, err := tx.EndSessionIfActive(ctx, sessionID, endedAt) // Persist the terminal session state while the row lock is still held. - if err != nil { // Surface storage write failures from the transactional update helper. + updated, err := tx.MarkSessionEnding(ctx, sessionID, updatedAt) // Persist cleanup-in-progress while the row lock is still held. + if err != nil { // Surface storage write failures from the transactional update helper. return err // Preserve the wrapped write error so callers can map it consistently. } - - changed = updated // Remember whether this transaction performed the transition. - return nil // Finish the callback so DAO.WithTx can commit the locked write. + cleanupRequired = updated // Require cleanup only when this transaction successfully prepared the ending state. + return nil // Finish the callback so DAO.WithTx can commit the locked write. }) if err != nil { // Return any lookup, locking, or write failure to the caller. return false, err // Keep the original repository error chain intact. } - return changed, nil // Tell the caller whether this request actually ended the session row. + return cleanupRequired, nil // Tell the caller whether external cleanup must run before terminal finalization. +} + +// completeSessionEnd locks one prepared session row and commits ended only after the caller reports successful external cleanup. +func (s *Service) completeSessionEnd(ctx context.Context, sessionID string, endedAt time.Time) error { + err := s.dao.WithTx(ctx, func(tx *postgres.TxDAO) error { // Serialize finalization with any concurrent lifecycle writer on the same session row. + session, err := tx.GetSessionForUpdate(ctx, sessionID) // Lock and reload the authoritative lifecycle state before terminalizing it. + if err != nil { // Stop when the row cannot be loaded or locked. + return err // Preserve the repository lookup failure for transport mapping. + } + if session.Status == "ended" { // Keep finalization idempotent when an earlier call committed the terminal state. + return nil // Report success without changing the original ended timestamp. + } + if session.Status != "ending" { // Reject terminalization that skipped the explicit cleanup-in-progress phase. + return errors.New(errors.CodeStateConflict, "session is not ending") // Preserve state-machine integrity under unexpected lifecycle mutations. + } + updated, err := tx.EndSessionIfEnding(ctx, sessionID, endedAt) // Commit ended only while the row still carries the prepared ending state. + if err != nil { // Surface write failures so callers can retry finalization. + return err // Preserve the stable storage write classification from the TxDAO helper. + } + if !updated { // Detect a lost lifecycle race even though the row was locked defensively. + return errors.New(errors.CodeStateConflict, "session end transition lost") // Refuse to report success without a durable terminal row. + } + return nil // Let DAO.WithTx commit the terminal lifecycle update. + }) + return err // Return nil after commit or preserve the exact lookup, conflict, or write failure. } // transitionTraceStatus performs an optimistic compare-and-swap on the trace lifecycle state. @@ -62,10 +92,11 @@ func (s *Service) finalizeTrace(ctx context.Context, traceID string, currentStat if terminalReason != "" { // Persist the structured terminal reason whenever the caller supplies one so trace readers can distinguish timeout, orphaned, cancelled, and normal completion outcomes. payloadMap["terminalReason"] = terminalReason // Duplicate the terminal reason inside the event payload for replay consumers that inspect only event data. } - if cause != nil { // Attach the underlying error details only when the terminal transition was triggered by a failure path. - payloadMap["error"] = cause.Error() // Preserve the original error string so operators can diagnose terminal failures from event replay alone. - if code, ok := errors.CodeOf(cause); ok { // Attach the structured error code when the failure path used the repository error type. + if cause != nil { // Attach only a stable machine-readable classification when the terminal transition was triggered by a failure path. + if code, ok := errors.CodeOf(cause); ok { // Resolve the repository code without exposing backend or worker error text in replay payloads. payloadMap["errorCode"] = string(code) // Preserve the stable machine-readable error code for downstream diagnostics and metrics correlation. + } else { + payloadMap["errorCode"] = string(errors.CodeInternal) // Classify untyped failures generically while retaining full diagnostics only in server logs. } } if retryCount > 0 { // Record retry exhaustion counts only for terminal dispatch failures that actually consumed retries. @@ -97,6 +128,14 @@ func (s *Service) finalizeTrace(ctx context.Context, traceID string, currentStat return changed, nil // Report whether this caller actually won the terminal transition and appended the final event. } +// finalizeTraceDetached persists one terminal trace transition with a bounded context that survives cancellation of the initiating request or execution timeout. +func (s *Service) finalizeTraceDetached(parent context.Context, traceID string, currentStatuses []string, nextStatus string, terminalReason string, message string, cause error, retryCount int64) (bool, error) { + detachedContext := context.WithoutCancel(parent) // Preserve context values while removing the cancellation that triggered this terminalization path. + finalizationContext, cancel := context.WithTimeout(detachedContext, detachedFinalizationTimeout) // Bound the detached database write so cleanup cannot hang indefinitely. + defer cancel() // Release the finalization timer promptly after the transaction finishes. + return s.finalizeTrace(finalizationContext, traceID, currentStatuses, nextStatus, terminalReason, message, cause, retryCount) // Commit the terminal row and event atomically under the bounded detached context. +} + // FinalizeQueuedTrace records a dispatcher-owned terminal outcome for a queued trace without overwriting a terminal state that has already been committed elsewhere. func (s *Service) FinalizeQueuedTrace(ctx context.Context, traceID string, nextStatus string, terminalReason string, message string, cause error, retryCount int64) error { _, err := s.finalizeTrace(ctx, traceID, []string{"pending", "running"}, nextStatus, terminalReason, message, cause, retryCount) // Allow dispatcher-originated terminalization to win only while the trace is still active. diff --git a/internal/orchestrator/service.go b/internal/orchestrator/service.go index 571bac6..42a8a28 100644 --- a/internal/orchestrator/service.go +++ b/internal/orchestrator/service.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + stdErrors "errors" "log/slog" "strings" "sync" @@ -57,6 +58,7 @@ type Service struct { appiumMu sync.Mutex appiumMap map[string]*appium.Client appiumLastUsed map[string]time.Time + sessionEndMu sync.Mutex planMu sync.Mutex planCancel map[string]context.CancelFunc snapshotMu sync.Mutex @@ -75,6 +77,8 @@ func NewService(cfg config.OrchestratorConfig, rpcCfg config.RPCSecurityConfig, mode := normalizeExecutionMode(cfg.ExecutionMode) cfg.ExecutionMode = mode registry := NewWorkerRegistry(cache) + auditRecorder := postgres.NewAuditRecorder(dao) // Reuse the authoritative append-only PostgreSQL sink for worker and lease lifecycle events. + registry.SetAuditRecorder(auditRecorder) // Wire worker registration, recovery, degradation, offline, and removal audit events before service startup. publisher := NewEventsPublisher(dao, cache) svc := &Service{ @@ -113,6 +117,7 @@ func NewService(cfg config.OrchestratorConfig, rpcCfg config.RPCSecurityConfig, } dispatcher := NewDispatcher(cache, registry, executor, cfg.PlanTimeout, workerCfg.HeartbeatInterval, rpcCfg) // Pass the configured plan timeout, worker heartbeat cadence, and RPC security into dispatcher so distributed leases and worker calls follow the selected runtime model. dispatcher.finalizer = svc // Wire the service's durable terminalization helper into dispatcher-owned terminal paths before the service starts processing queue messages. + dispatcher.SetAuditRecorder(auditRecorder) // Wire fail-closed lease, dispatch, orphan, and timeout audit events before queue processing begins. svc.dispatcher = dispatcher return svc @@ -253,9 +258,9 @@ func (s *Service) ExecutePlanWithTrace(ctx context.Context, sessionID string, tr s.logger.ErrorContext(ctx, "orchestrator ExecutePlan failed", "session_id", sessionID, "trace_id", traceID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Log session lookup failure. return "", err } - if sess.Status == "ended" { - s.logger.ErrorContext(ctx, "orchestrator ExecutePlan failed", "session_id", sessionID, "trace_id", traceID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", "session ended") // Log invalid session state before returning. - return "", errors.New(errors.CodeSessionDead, "session ended") + if sess.Status != "created" && sess.Status != "active" { // Reject ending and ended sessions before creating a trace or queue message. + s.logger.ErrorContext(ctx, "orchestrator ExecutePlan failed", "session_id", sessionID, "trace_id", traceID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", "session is not active") // Log invalid session state before returning. + return "", errors.New(errors.CodeSessionDead, "session is not active") // Preserve the stable dead-session classification for every unusable lifecycle state. } // 2. Create Trace @@ -272,15 +277,19 @@ func (s *Service) ExecutePlanWithTrace(ctx context.Context, sessionID string, tr CreatedAt: time.Now(), UpdatedAt: time.Now(), } - if err := s.dao.CreateTrace(ctx, trace); err != nil { + if err := s.dao.CreateOrRearmQueuedTrace(ctx, trace); err != nil { // Insert the new trace or safely rearm only a matching trace whose previous queue enqueue failed. s.logger.ErrorContext(ctx, "orchestrator ExecutePlan failed", "session_id", sessionID, "trace_id", traceID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Log trace creation failures. - return "", errors.Wrap(errors.CodeInternal, "failed to create trace", err) + return "", errors.WrapPreservingCode("failed to prepare trace", err) // Preserve state-conflict and storage classifications from the atomic trace preparation helper. } // 3. Enqueue Plan if err := s.dispatcher.EnqueuePlan(ctx, sess.ProjectID, sessionID, traceID, plan); err != nil { s.logger.ErrorContext(ctx, "orchestrator ExecutePlan failed", "session_id", sessionID, "trace_id", traceID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Log enqueue failures for queue-level troubleshooting. - return "", errors.Wrap(errors.CodeInternal, "failed to enqueue plan", err) + _, finalizationErr := s.finalizeTraceDetached(ctx, traceID, []string{"pending"}, "failed", "queue_enqueue_failed", "trace failed before queue acceptance", err, 0) // Close the prepared trace even when the request context was cancelled by the enqueue failure. + if finalizationErr != nil { // Surface both failures when PostgreSQL cannot record the queue rejection durably. + return "", errors.Wrap(errors.CodeStoreWrite, "failed to enqueue plan and finalize trace", stdErrors.Join(err, finalizationErr)) // Preserve both root causes for server logs under a stable storage-write code. + } + return "", errors.Wrap(errors.CodeInternal, "failed to enqueue plan", err) // Return the enqueue failure after the trace has reached a retryable terminal state. } s.logger.InfoContext(ctx, "orchestrator ExecutePlan done", "session_id", sessionID, "trace_id", traceID, "duration_ms", time.Since(startedAt).Milliseconds()) // Log successful method completion. @@ -310,7 +319,7 @@ func (s *Service) GetSession(ctx context.Context, sessionID string) (*postgres.S return s.authorizeSessionAccess(ctx, sessionID) // Reuse the shared session-authorization helper so every authenticated session read enforces persisted ownership. } -// EndSession marks the persisted session as ended exactly once, then releases the cached Appium session and Redis mapping. +// EndSession moves one session through ending, retries external cleanup safely, and commits ended only after every cleanup handle is released. func (s *Service) EndSession(ctx context.Context, sessionID string) error { ctx, span := otel.Tracer("orchestrator").Start(ctx, "EndSession") defer span.End() @@ -320,23 +329,36 @@ func (s *Service) EndSession(ctx context.Context, sessionID string) error { s.logger.ErrorContext(ctx, "orchestrator EndSession failed", "session_id", sessionID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Log authorization failures before returning. return err // Preserve the authorization failure so transports keep the correct status mapping. } + s.sessionEndMu.Lock() // Serialize cleanup attempts so concurrent EndSession calls cannot delete the same Appium or Device Farm resource twice. + defer s.sessionEndMu.Unlock() // Release the lifecycle lock after cleanup and durable finalization complete or fail. - ended, err := s.markSessionEnded(ctx, sessionID, time.Now()) // Persist the terminal session state first so concurrent callers observe idempotent completion from the database record. - if err != nil { // Stop before touching the in-memory Appium session map when the persisted session transition fails. + cleanupRequired, err := s.prepareSessionEnd(ctx, sessionID, time.Now()) // Persist cleanup-in-progress before any external resource operation begins. + if err != nil { // Stop before touching the in-memory Appium session map when the persisted session transition fails. s.logger.ErrorContext(ctx, "orchestrator EndSession failed", "session_id", sessionID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Log lookup failures before returning. return err } - if !ended { // Treat repeated end-session requests as successful no-ops once another caller has already completed the transition. + if !cleanupRequired { // Treat repeated end-session requests as successful no-ops only after the persisted row is already ended. s.logger.InfoContext(ctx, "orchestrator EndSession done", "session_id", sessionID, "duration_ms", time.Since(startedAt).Milliseconds(), "already_ended", true) // Log idempotent completion path. return nil } - s.appiumMu.Lock() - delete(s.appiumMap, sessionID) - delete(s.appiumLastUsed, sessionID) - s.appiumMu.Unlock() - - s.releaseSessionAutomation(ctx, sessionID) // Release the Appium session, cached endpoint mappings, and any Device Farm remote-access reservation backing this platform session. + s.appiumMu.Lock() // Read the cached client under the same mutex used by interactive operations and cleanup eviction. + app := s.appiumMap[sessionID] // Preserve the live client so cleanup does not depend exclusively on Redis restoration. + s.appiumMu.Unlock() // Release the cache mutex before performing network cleanup. + if err := s.releaseSessionAutomation(ctx, sessionID, app); err != nil { // Release Appium, Device Farm, and persisted handles while retaining them on any external failure. + s.logger.ErrorContext(ctx, "orchestrator EndSession cleanup failed", "session_id", sessionID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Record the retryable cleanup failure while the row remains ending. + return err // Preserve the cleanup error so the caller knows to retry the ending session. + } + finalizationContext, finalizationCancel := context.WithTimeout(context.WithoutCancel(ctx), detachedFinalizationTimeout) // Give the terminal database write a bounded chance to succeed after request cancellation. + defer finalizationCancel() // Release the detached finalization timer when the method returns. + if err := s.completeSessionEnd(finalizationContext, sessionID, time.Now()); err != nil { // Commit ended only after every external cleanup operation succeeded. + s.logger.ErrorContext(ctx, "orchestrator EndSession finalization failed", "session_id", sessionID, "duration_ms", time.Since(startedAt).Milliseconds(), "error", err) // Record the retryable database finalization failure. + return err // Leave the row in ending so a later call can retry idempotent cleanup and finalization. + } + s.appiumMu.Lock() // Evict the now-closed client only after durable terminal finalization succeeds. + delete(s.appiumMap, sessionID) // Remove the closed Appium client from the in-memory session map. + delete(s.appiumLastUsed, sessionID) // Remove its idle-cleanup timestamp alongside the client. + s.appiumMu.Unlock() // Release the cache mutex after terminal eviction completes. s.logger.InfoContext(ctx, "orchestrator EndSession done", "session_id", sessionID, "duration_ms", time.Since(startedAt).Milliseconds()) // Log successful session termination. return nil @@ -446,9 +468,13 @@ func (s *Service) TakeScreenshot(ctx context.Context, sessionID string, traceID if traceID == "" { return nil, errors.New(errors.CodePlanInvalid, "traceId is required for takeScreenshot") } - if _, err := s.authorizeTraceAccess(ctx, traceID); err != nil { // Validate persisted trace ownership before storing new screenshot artifacts under the supplied trace identifier. + trace, err := s.authorizeTraceAccess(ctx, traceID) // Validate persisted trace ownership and load its authoritative session binding before storing artifacts. + if err != nil { // Stop before touching Appium when the trace is missing or not owned by the caller. return nil, err // Preserve the trace-not-found or permission-denied error so transports keep stable status mapping. } + if trace.SessionID != sessionID { // Reject cross-session artifact attachment even when the caller owns both resources. + return nil, errors.New(errors.CodePlanInvalid, "trace does not belong to session") // Prevent screenshots from one automation session being stored under another trace. + } app, err := s.getAppiumClient(ctx, sessionID) if err != nil { @@ -485,9 +511,13 @@ func (s *Service) TakeScreenshot(ctx context.Context, sessionID string, traceID // getAppiumClient executes this operation. func (s *Service) getAppiumClient(ctx context.Context, sessionID string) (*appium.Client, error) { - if _, err := s.authorizeSessionAccess(ctx, sessionID); err != nil { // Validate persisted session ownership before exposing the cached or restored Appium session to authenticated callers. + session, err := s.authorizeSessionAccess(ctx, sessionID) // Validate persisted session ownership and load the authoritative lifecycle state before exposing automation handles. + if err != nil { // Reject missing or unauthorized sessions before inspecting in-memory state. return nil, err // Preserve the session-not-found or permission-denied error so transports keep stable status mapping. } + if session.Status != "created" && session.Status != "active" { // Reject ending and ended sessions before any cached or restored Appium command can run. + return nil, errors.New(errors.CodeSessionDead, "session is not active") // Preserve the stable dead-session classification throughout interactive and plan operations. + } s.appiumMu.Lock() app := s.appiumMap[sessionID] @@ -576,31 +606,49 @@ func (s *Service) ExecuteDispatchedPlan(ctx context.Context, traceID string, ses return err // Preserve the wrapped storage error from the optimistic transition helper. } if !transitioned { // Reject execution when the trace is no longer in the expected pending state. - return errors.New(errors.CodeStateConflict, "trace is not pending") // Return a stable state-conflict error instead of overwriting another terminal state. + trace, lookupErr := s.dao.GetTrace(ctx, traceID) // Inspect the durable state so duplicate queue deliveries can be acknowledged without re-executing the plan. + if lookupErr != nil { // Preserve storage and not-found failures because the dispatcher cannot classify the duplicate safely without the trace row. + return lookupErr // Return the authoritative lookup failure so queue retry policy remains consistent. + } + switch trace.Status { // Treat an already accepted or terminal trace as a benign duplicate delivery. + case "running", "completed", "failed", "cancelled": + s.logger.InfoContext(ctx, "duplicate queued plan ignored", "trace_id", traceID, "status", trace.Status) // Record duplicate suppression without replaying device actions. + return nil // Let the dispatcher ACK the duplicate message because another delivery already owns or completed the trace. + default: + return errors.New(errors.CodeStateConflict, "trace is not pending") // Preserve a stable conflict for unknown lifecycle states that require operator attention. + } } steps, err := worker.ParsePlan(plan) if err != nil { - _, _ = s.finalizeTrace(runCtx, traceID, []string{"running"}, "failed", "parse_error", "trace failed before execution started", err, 0) // Persist the failed terminal state and matching final event before returning the plan-parse error. - return err + _, finalizationErr := s.finalizeTraceDetached(ctx, traceID, []string{"running"}, "failed", "parse_error", "trace failed before execution started", err, 0) // Persist the failed terminal state even if the execution context already expired. + return stdErrors.Join(err, finalizationErr) // Return both parsing and persistence failures while preserving the original plan error when finalization succeeds. } - app, err := s.getAppiumClient(ctx, sessionID) + app, err := s.getAppiumClient(runCtx, sessionID) // Bind session restoration and validation to the plan execution timeout. if err != nil { - _, _ = s.finalizeTrace(runCtx, traceID, []string{"running"}, "failed", "session_unavailable", "trace failed before acquiring the session client", err, 0) // Persist the failed terminal state and final event without overwriting a concurrent cancellation result. - return err + _, finalizationErr := s.finalizeTraceDetached(ctx, traceID, []string{"running"}, "failed", "session_unavailable", "trace failed before acquiring the session client", err, 0) // Persist the failed terminal state without relying on the possibly expired execution context. + return stdErrors.Join(err, finalizationErr) // Return both session and persistence failures when needed. } - seq := int64(0) + seq := int64(0) // Allocate step-event sequence numbers monotonically within this newly accepted trace execution. + var publishErr error // Capture the first durable event failure because executor callbacks cannot return errors directly. exec := worker.NewExecutor(app, s.cfg.StepTimeout, s.cfg.AutoWaitMax, func(ev worker.StepEvent) { - seq++ - payload, _ := json.Marshal(map[string]interface{}{ + if publishErr != nil { // Stop attempting later event writes after the first durable persistence failure. + return // Preserve the first failure as the root cause that will terminalize the trace. + } + seq++ // Reserve the next ordered event sequence before serializing this executor callback. + payload, marshalErr := json.Marshal(map[string]interface{}{ // Serialize the complete step event payload before attempting persistence. "message": ev.Message, "metrics": ev.Metrics, "artifactRefs": ev.ArtifactRefs, "phase": ev.Phase, }) - _ = s.publisher.Publish(runCtx, &postgres.PlanEvent{ + if marshalErr != nil { // Stop when one event payload cannot be represented as JSON. + publishErr = errors.Wrap(errors.CodeInternal, "failed to marshal plan event", marshalErr) // Preserve the serialization cause for terminal diagnostics. + return // Skip persistence because no valid event payload exists. + } + publishErr = s.publisher.Publish(runCtx, &postgres.PlanEvent{ // Persist every step event and retain the first failure for execution outcome handling. TraceID: traceID, Seq: seq, StepIndex: ev.StepIndex, @@ -612,29 +660,32 @@ func (s *Service) ExecuteDispatchedPlan(ctx context.Context, traceID string, ses start := time.Now() err = exec.Execute(runCtx, steps) + if publishErr != nil { // Treat a missing durable step event as a trace execution failure even when device actions completed. + err = stdErrors.Join(err, publishErr) // Preserve any executor failure together with the first event persistence failure. + } elapsed := time.Since(start).Seconds() if err != nil { if code, ok := errors.CodeOf(err); ok { telemetry.ErrorCodeTotal.WithLabelValues(string(code), "orchestrator").Inc() } if errors.IsCode(err, errors.CodeSessionDead) || errors.IsCode(err, errors.CodeSessionBroken) { - _, _ = s.finalizeTrace(runCtx, traceID, []string{"running"}, "failed", "session_broken", "trace failed because the session became unusable", err, 0) // Persist the failed terminal state and final event without clobbering a concurrent cancellation or other terminal transition. + _, finalizationErr := s.finalizeTraceDetached(ctx, traceID, []string{"running"}, "failed", "session_broken", "trace failed because the session became unusable", err, 0) // Persist the failed terminal state without relying on the failed execution context. telemetry.ExecuteLatency.WithLabelValues("", "", "failed").Observe(elapsed) - return err + return stdErrors.Join(err, finalizationErr) // Preserve execution and terminal persistence failures for dispatcher retry decisions. } if runCtx.Err() == context.Canceled || runCtx.Err() == context.DeadlineExceeded { - _, _ = s.finalizeTrace(runCtx, traceID, []string{"running"}, "cancelled", "cancelled", "trace cancelled during execution", err, 0) // Persist cancellation as the winning terminal state together with one final trace event. + _, finalizationErr := s.finalizeTraceDetached(ctx, traceID, []string{"running"}, "cancelled", "cancelled", "trace cancelled during execution", err, 0) // Persist cancellation after the execution context has already been cancelled. telemetry.ExecuteLatency.WithLabelValues("", "", "failed").Observe(elapsed) - return err + return stdErrors.Join(err, finalizationErr) // Preserve execution and terminal persistence failures for dispatcher retry decisions. } telemetry.ExecuteLatency.WithLabelValues("", "", "failed").Observe(elapsed) - _, _ = s.finalizeTrace(runCtx, traceID, []string{"running"}, "failed", "execution_failed", "trace failed during execution", err, 0) // Persist the failed terminal state and final event without clobbering a concurrent terminal state update. - return err + _, finalizationErr := s.finalizeTraceDetached(ctx, traceID, []string{"running"}, "failed", "execution_failed", "trace failed during execution", err, 0) // Persist the failed terminal state independently from the request context. + return stdErrors.Join(err, finalizationErr) // Preserve execution and terminal persistence failures for dispatcher retry decisions. } telemetry.ExecuteLatency.WithLabelValues("", "", "passed").Observe(elapsed) - _, err = s.finalizeTrace(runCtx, traceID, []string{"running"}, "completed", "completed", "trace completed", nil, 0) // Persist the completed terminal state together with one final trace event when this executor still owns the running state. - return err // Return any storage-layer failure while treating a lost race to another terminal state as a successful no-op. + _, err = s.finalizeTraceDetached(ctx, traceID, []string{"running"}, "completed", "completed", "trace completed", nil, 0) // Persist completion with a fresh bounded context so a just-expired request cannot strand the trace in running. + return err // Return any storage-layer failure while treating a lost race to another terminal state as a successful no-op. } // Interactive element operations diff --git a/internal/orchestrator/trace_terminal_test.go b/internal/orchestrator/trace_terminal_test.go index 9eb1767..fec9e72 100644 --- a/internal/orchestrator/trace_terminal_test.go +++ b/internal/orchestrator/trace_terminal_test.go @@ -5,6 +5,8 @@ import ( "context" "encoding/json" "net" + "net/http" + "net/http/httptest" "os" "path/filepath" "runtime" @@ -37,6 +39,7 @@ type traceTerminalHarness struct { dao *postgres.DAO cache *redisstore.Cache service *Service + redisServer *miniredis.Miniredis stopPostgres func() stopRedis func() } @@ -96,7 +99,7 @@ func newTraceTerminalHarness(t *testing.T) *traceTerminalHarness { AppiumURL: "http://127.0.0.1:4723", // Provide a syntactically valid Appium URL even though these tests avoid real Appium calls. }, config.AWSConfig{}, config.DeviceFarmConfig{Mode: "disabled"}, dao, cache, nil) // Disable Device Farm and S3 because the terminalization tests do not touch those integrations. - return &traceTerminalHarness{dao: dao, cache: cache, service: service, stopPostgres: stopPostgres, stopRedis: stopRedis} // Return the fully wired harness so individual tests can seed traces and assert final states. + return &traceTerminalHarness{dao: dao, cache: cache, service: service, redisServer: redisServer, stopPostgres: stopPostgres, stopRedis: stopRedis} // Return the fully wired harness so individual tests can seed traces, control Redis availability, and assert final states. } // reserveLoopbackPort reserves one IPv4 loopback TCP port and returns it so embedded PostgreSQL can bind deterministically during tests. @@ -265,6 +268,9 @@ func TestExecuteDispatchedPlanFinalizesParseFailure(t *testing.T) { if payload["errorCode"] != "E.PLAN.INVALID" { // Fail the test when the final event payload does not preserve the structured plan-validation error code. t.Fatalf("expected terminal payload error code E.PLAN.INVALID, got %#v", payload["errorCode"]) // Surface the unexpected error code because operators rely on it for diagnosis. } + if _, exists := payload["error"]; exists { // Reject raw parser or backend diagnostics in replayable terminal payloads. + t.Fatalf("expected terminal payload to omit raw error text, got %#v", payload["error"]) // Surface any regression that could disclose sensitive server details to trace readers. + } } // TestHandleDispatchErrorFinalizesAfterRetriesExhausted verifies that retry exhaustion closes a queued trace with one failed terminal state and one final replayable event before ACK. @@ -327,3 +333,118 @@ func TestGetTraceRejectsDifferentSubject(t *testing.T) { t.Fatalf("expected permission denied, got %v", err) // Surface the unexpected error because transport mapping depends on the stable authorization code. } } + +// TestExecutePlanQueueFailureCanRearmSameTrace verifies that Redis enqueue failure terminalizes the trace and permits one safe retry with the same owned trace id. +func TestExecutePlanQueueFailureCanRearmSameTrace(t *testing.T) { + harness := newTraceTerminalHarness(t) // Start isolated PostgreSQL and Redis dependencies for the queue-failure lifecycle test. + ctx := context.Background() // Use one non-cancelled context so the only scheduling failure comes from Redis availability. + now := time.Now().UTC() // Capture one stable creation timestamp for the session and trace retry payload. + sessionID := uuid.NewString() // Generate one unique active session that the failed plan submission can target. + traceID := uuid.NewString() // Generate the caller-supplied trace id that will be reused after failure. + if err := harness.dao.CreateSession(ctx, &postgres.Session{ID: sessionID, ProjectID: "queue-project", Status: "created", Capabilities: []byte(`{}`), CreatedAt: now, UpdatedAt: now}); err != nil { // Seed the active session before scheduling. + t.Fatalf("failed to seed queue-failure session: %v", err) // Surface the setup failure because no trace can reference a missing session. + } + harness.redisServer.Close() // Make XADD fail after the trace row is prepared while leaving PostgreSQL available for detached terminalization. + if _, err := harness.service.ExecutePlanWithTrace(ctx, sessionID, traceID, json.RawMessage(`[{"type":"wait","params":{"ms":1}}]`)); err == nil { // Submit one valid plan through the production trace-first enqueue path. + t.Fatal("expected queue enqueue failure") // Require the unavailable Redis dependency to reach the caller. + } + failedTrace, err := harness.dao.GetTrace(ctx, traceID) // Load the trace directly because Redis is intentionally unavailable. + if err != nil { // Stop when the trace row was not retained for retry. + t.Fatalf("failed to load queue-failed trace: %v", err) // Surface missing durable failure state. + } + if failedTrace.Status != "failed" || failedTrace.TerminalReason == nil || *failedTrace.TerminalReason != "queue_enqueue_failed" { // Require the retry-gating terminal classification. + t.Fatalf("expected failed queue trace, got status=%s reason=%v", failedTrace.Status, failedTrace.TerminalReason) // Surface orphaned or misclassified trace state. + } + if err := harness.dao.CreateOrRearmQueuedTrace(ctx, &postgres.Trace{ID: traceID, SessionID: sessionID, ProjectID: "queue-project", Status: "pending", CreatedAt: now, UpdatedAt: time.Now().UTC()}); err != nil { // Retry the exact owned trace through the atomic DAO contract. + t.Fatalf("expected queue-failed trace to rearm, got %v", err) // Surface unsafe idempotency conflicts after a confirmed enqueue failure. + } + rearmedTrace, err := harness.dao.GetTrace(ctx, traceID) // Reload the trace after the retry preparation transaction. + if err != nil { // Stop when the rearmed trace cannot be read. + t.Fatalf("failed to load rearmed trace: %v", err) // Surface storage regressions in the retry path. + } + if rearmedTrace.Status != "pending" || rearmedTrace.TerminalReason != nil { // Require a clean pending lifecycle with no stale failure reason. + t.Fatalf("expected clean pending trace, got status=%s reason=%v", rearmedTrace.Status, rearmedTrace.TerminalReason) // Surface stale terminal state after rearm. + } + events, err := harness.dao.ListEvents(ctx, traceID, 0, 100) // Verify the old queue-failure terminal event was removed atomically with rearm. + if err != nil { // Stop when event history cannot be read. + t.Fatalf("failed to load rearmed trace events: %v", err) // Surface storage regressions in event cleanup. + } + if len(events) != 0 { // Reject stale terminal events because a retried trace must begin a fresh monotonic execution history. + t.Fatalf("expected no stale events after rearm, got %d", len(events)) // Surface sequence-conflict risk directly. + } +} + +// TestEndSessionRetriesFailedAutomationCleanup verifies that ended is committed only after a later Appium cleanup retry succeeds. +func TestEndSessionRetriesFailedAutomationCleanup(t *testing.T) { + harness := newTraceTerminalHarness(t) // Start isolated persistence dependencies for the two-phase session lifecycle test. + deleteAttempts := 0 // Count Appium DELETE requests across the failed and successful EndSession calls. + appiumServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Simulate one ambiguous cleanup failure followed by success. + if r.Method != http.MethodDelete { // Reject unexpected Appium commands because this test exercises cleanup only. + w.WriteHeader(http.StatusMethodNotAllowed) // Return a deterministic failure for any accidental non-delete request. + return // Stop before mutating the delete attempt count. + } + deleteAttempts++ // Record the concrete cleanup request sent by each EndSession attempt. + if deleteAttempts == 1 { // Fail the first cleanup so the session must remain retryable in ending. + w.WriteHeader(http.StatusInternalServerError) // Return an ambiguous server failure that DELETE must not retry automatically. + _ = json.NewEncoder(w).Encode(map[string]interface{}{"value": map[string]interface{}{"error": "internal error", "message": "cleanup unavailable"}}) // Return a valid Appium error envelope. + return // Stop before writing the later success response. + } + w.WriteHeader(http.StatusOK) // Confirm cleanup on the second explicit EndSession call. + _ = json.NewEncoder(w).Encode(map[string]interface{}{"value": nil}) // Return a valid Appium delete-session success envelope. + })) + defer appiumServer.Close() // Release the loopback Appium server after lifecycle assertions complete. + + ctx := context.Background() // Use one stable context for both explicit cleanup attempts. + now := time.Now().UTC() // Capture one stable session creation timestamp. + sessionID := uuid.NewString() // Generate one unique platform session id for this lifecycle test. + if err := harness.dao.CreateSession(ctx, &postgres.Session{ID: sessionID, ProjectID: "cleanup-project", Status: "created", Capabilities: []byte(`{}`), CreatedAt: now, UpdatedAt: now}); err != nil { // Seed one active platform session. + t.Fatalf("failed to seed cleanup session: %v", err) // Surface setup failure before Redis handle creation. + } + if err := harness.cache.Set(ctx, appiumSessionKeyPrefix+sessionID, "appium-cleanup-session", appiumSessionKeyTTL); err != nil { // Persist the Appium session id used by restart-safe cleanup. + t.Fatalf("failed to seed appium session mapping: %v", err) // Surface missing cleanup handle setup. + } + if err := harness.cache.Set(ctx, appiumSessionURLKeyPrefix+sessionID, appiumServer.URL, appiumSessionKeyTTL); err != nil { // Persist the exact fake endpoint used by restored cleanup clients. + t.Fatalf("failed to seed appium url mapping: %v", err) // Surface missing endpoint handle setup. + } + if err := harness.service.EndSession(ctx, sessionID); err == nil { // Run the first cleanup attempt against the failing Appium response. + t.Fatal("expected first EndSession cleanup to fail") // Require external cleanup failure to reach the caller. + } + endingSession, err := harness.dao.GetSession(ctx, sessionID) // Reload lifecycle state after the failed cleanup attempt. + if err != nil { // Stop when the session cannot be inspected. + t.Fatalf("failed to load ending session: %v", err) // Surface storage regressions in the two-phase flow. + } + if endingSession.Status != "ending" { // Require cleanup-in-progress rather than premature terminal state. + t.Fatalf("expected session status ending, got %s", endingSession.Status) // Surface resource-leaking terminalization directly. + } + if _, err := harness.cache.Get(ctx, appiumSessionKeyPrefix+sessionID); err != nil { // Require the Appium handle to remain available for retry. + t.Fatalf("expected cleanup handle to remain after failure: %v", err) // Surface unsafe handle deletion after ambiguous cleanup. + } + if err := harness.service.EndSession(ctx, sessionID); err != nil { // Retry cleanup explicitly after the fake dependency recovers. + t.Fatalf("expected second EndSession to succeed, got %v", err) // Surface failures in retrying the ending state. + } + endedSession, err := harness.dao.GetSession(ctx, sessionID) // Reload the durable terminal state after successful cleanup. + if err != nil { // Stop when the ended session cannot be inspected. + t.Fatalf("failed to load ended session: %v", err) // Surface storage regressions after cleanup success. + } + if endedSession.Status != "ended" || !endedSession.EndedAt.Valid { // Require the final state and terminal timestamp only after cleanup confirmation. + t.Fatalf("expected ended session with timestamp, got status=%s endedAt=%v", endedSession.Status, endedSession.EndedAt) // Surface incomplete terminalization. + } + if deleteAttempts != 2 { // Require one request per explicit EndSession call and no hidden DELETE retries. + t.Fatalf("expected two explicit delete attempts, got %d", deleteAttempts) // Surface unsafe transport retries or missing cleanup retry. + } +} + +// TestTakeScreenshotRejectsTraceFromDifferentSession verifies that artifact capture cannot attach one session's screenshot to another session's trace. +func TestTakeScreenshotRejectsTraceFromDifferentSession(t *testing.T) { + harness := newTraceTerminalHarness(t) // Start isolated persistence dependencies for the ownership-binding check. + _, traceID := harness.seedPendingTrace(t) // Seed one trace bound to the first active session. + ctx := context.Background() // Use the legacy unauthenticated context so both empty-owner sessions remain accessible. + now := time.Now().UTC() // Capture one stable timestamp for the second active session. + otherSessionID := uuid.NewString() // Generate a distinct session that must not write artifacts under the first trace. + if err := harness.dao.CreateSession(ctx, &postgres.Session{ID: otherSessionID, ProjectID: "test-project", Status: "created", Capabilities: []byte(`{}`), CreatedAt: now, UpdatedAt: now}); err != nil { // Seed the second active session. + t.Fatalf("failed to seed second screenshot session: %v", err) // Surface setup failure before the binding assertion. + } + if _, err := harness.service.TakeScreenshot(ctx, otherSessionID, traceID, false); !errors.IsCode(err, errors.CodePlanInvalid) { // Attempt cross-session capture and require rejection before Appium or S3 access. + t.Fatalf("expected cross-session screenshot rejection, got %v", err) // Surface missing trace-to-session consistency enforcement. + } +} diff --git a/internal/orchestrator/worker_registry.go b/internal/orchestrator/worker_registry.go index 51f8455..9a289ac 100644 --- a/internal/orchestrator/worker_registry.go +++ b/internal/orchestrator/worker_registry.go @@ -1,17 +1,23 @@ +// worker_registry.go maintains race-free worker health, capacity reservations, Redis persistence, and lifecycle auditing. package orchestrator import ( "context" "encoding/json" + stdErrors "errors" "fmt" "log/slog" "sort" + "strings" "sync" "time" + "mcp_for_appium/internal/audit" "mcp_for_appium/internal/errors" "mcp_for_appium/internal/storage/redis" "mcp_for_appium/internal/telemetry" + + goredis "github.com/redis/go-redis/v9" ) const ( @@ -26,314 +32,462 @@ const ( recoveryWindow = 60 * time.Second ) +// WorkerRegistry stores authoritative in-process worker snapshots and serializes every mutation that affects scheduling. type WorkerRegistry struct { - cache *redis.Cache - logger *slog.Logger - workers sync.Map // workerID -> *WorkerNode (in-memory cache) - stopCh chan struct{} + cache *redis.Cache + logger *slog.Logger + mu sync.RWMutex + workers map[string]*WorkerNode + reservations map[string]string + stopCh chan struct{} + stopOnce sync.Once + auditRecorder audit.Recorder } +// WorkerNode describes one worker's routing metadata, capacity, load, and heartbeat-derived lifecycle state. type WorkerNode struct { ID string `json:"id"` Address string `json:"address"` Tags map[string]string `json:"tags"` Capacity int `json:"capacity"` ActiveLoad int `json:"active_load"` - Status string `json:"status"` // healthy|degraded|offline + Status string `json:"status"` LastSeen time.Time `json:"last_seen"` MissedBeats int `json:"missed_beats"` RecoveryStarted time.Time `json:"recovery_started,omitempty"` } -// NewWorkerRegistry executes this operation. +// NewWorkerRegistry creates an empty worker registry backed by the supplied Redis cache. func NewWorkerRegistry(cache *redis.Cache) *WorkerRegistry { - return &WorkerRegistry{ - cache: cache, - logger: telemetry.Logger(), - stopCh: make(chan struct{}), - } + return &WorkerRegistry{ // Return a fully initialized registry whose map and stop channel are safe for immediate concurrent use. + cache: cache, // Persist worker metadata and heartbeat liveness through the shared Redis cache. + logger: telemetry.Logger(), // Reuse the process-wide structured logger for lifecycle and failure diagnostics. + workers: make(map[string]*WorkerNode), // Keep mutable worker records private behind the registry mutex. + reservations: make(map[string]string), // Track exact trace-attempt reservations so cleanup remains idempotent. + stopCh: make(chan struct{}), // Allow the monitor loop to stop independently from its parent context. + } // Complete registry construction with no externally shared mutable worker pointers. } -// Register registers a worker node -func (r *WorkerRegistry) Register(ctx context.Context, worker *WorkerNode) error { - worker.Status = "healthy" - worker.LastSeen = time.Now() - worker.MissedBeats = 0 +// SetAuditRecorder installs the optional append-only sink used for worker lifecycle audit events. +func (r *WorkerRegistry) SetAuditRecorder(recorder audit.Recorder) { + r.mu.Lock() // Serialize recorder replacement with concurrent lifecycle-event snapshots. + r.auditRecorder = recorder // Store the caller-provided sink without exposing mutable registry state. + r.mu.Unlock() // Release the registry lock after the recorder pointer is visible atomically. +} - data, err := json.Marshal(worker) - if err != nil { - return errors.Wrap(errors.CodeInternal, "failed to marshal worker", err) +// Register validates, persists, and publishes one healthy worker snapshot without retaining the caller's mutable pointer. +func (r *WorkerRegistry) Register(ctx context.Context, worker *WorkerNode) error { + if worker == nil { // Reject nil registration payloads before reading worker metadata. + return errors.New(errors.CodePlanInvalid, "worker is required") // Return a stable validation error for malformed internal RPC input. } - - // Store in Redis Hash - if err := r.cache.HSet(ctx, workerHashKey, map[string]interface{}{ - worker.ID: string(data), - }); err != nil { - return errors.Wrap(errors.CodeStoreWrite, "failed to register worker", err) + if strings.TrimSpace(worker.ID) == "" { // Require a stable worker identifier for registry and heartbeat keys. + return errors.New(errors.CodePlanInvalid, "worker id is required") // Prevent anonymous workers from colliding in Redis. } - - // Set heartbeat key with TTL - hbKey := fmt.Sprintf(workerHeartbeatKey, worker.ID) - if err := r.cache.Set(ctx, hbKey, "1", heartbeatTTL); err != nil { - return errors.Wrap(errors.CodeStoreWrite, "failed to set heartbeat", err) + if strings.TrimSpace(worker.Address) == "" { // Require a routable address before making the worker schedulable. + return errors.New(errors.CodePlanInvalid, "worker address is required") // Prevent assignments that cannot produce a worker RPC client. + } + if worker.Capacity <= 0 { // Reject workers that can never accept one execution slot. + return errors.New(errors.CodePlanInvalid, "worker capacity must be greater than zero") // Preserve a clear internal validation contract. } - // Cache in memory - r.workers.Store(worker.ID, worker) + now := time.Now().UTC() // Capture one registration timestamp for both liveness and persisted metadata. + normalized := cloneWorkerNode(worker) // Deep-copy tags so caller mutations cannot race with registry readers. + normalized.ID = strings.TrimSpace(normalized.ID) // Normalize the identifier used in all Redis and in-memory keys. + normalized.Address = strings.TrimSpace(normalized.Address) // Normalize the routable address before it is handed to the dispatcher. + normalized.ActiveLoad = 0 // Treat registration as a fresh process with no accepted local plans yet. + normalized.Status = "healthy" // Make a successfully persisted worker immediately eligible for scheduling. + normalized.LastSeen = now // Seed liveness from the successful registration timestamp. + normalized.MissedBeats = 0 // Clear stale heartbeat history supplied by any caller. + normalized.RecoveryStarted = time.Time{} // Clear stale recovery state supplied by any caller. + data, err := json.Marshal(normalized) // Encode the isolated snapshot before acquiring the mutation lock. + if err != nil { // Stop when worker metadata cannot be serialized safely. + return errors.Wrap(errors.CodeInternal, "failed to marshal worker", err) // Preserve the serialization cause under the repository error contract. + } - r.logger.InfoContext(ctx, "worker registered", - "worker_id", worker.ID, - "address", worker.Address, - "capacity", worker.Capacity) + r.mu.Lock() // Serialize Redis registration and in-memory publication with heartbeat, monitor, and re-registration mutations. + if err := r.cache.HSet(ctx, workerHashKey, map[string]interface{}{normalized.ID: string(data)}); err != nil { // Persist routing metadata before making the worker visible to local scheduling. + r.mu.Unlock() // Release the mutation lock before returning the storage failure. + r.recordAudit(ctx, "worker.register", normalized.ID, "failure", "store_write", map[string]interface{}{"address": normalized.Address}) // Record the safe failure classification without persisting backend error text. + return errors.Wrap(errors.CodeStoreWrite, "failed to register worker", err) // Surface the Redis hash failure as a storage write error. + } + hbKey := fmt.Sprintf(workerHeartbeatKey, normalized.ID) // Build the worker-specific liveness key from the normalized identifier. + if err := r.cache.Set(ctx, hbKey, "1", heartbeatTTL); err != nil { // Require the heartbeat key before publishing this worker as healthy. + _ = r.cache.HDel(ctx, workerHashKey, normalized.ID) // Best-effort remove the incomplete hash record so a later sync cannot resurrect it as healthy. + r.mu.Unlock() // Release the mutation lock before returning the heartbeat persistence failure. + r.recordAudit(ctx, "worker.register", normalized.ID, "failure", "heartbeat_store_write", map[string]interface{}{"address": normalized.Address}) // Audit the stable failure class without recording Redis details. + return errors.Wrap(errors.CodeStoreWrite, "failed to set heartbeat", err) // Surface the heartbeat write failure through the stable storage contract. + } + r.workers[normalized.ID] = normalized // Publish only the registry-owned deep copy after both Redis writes succeed. + for reservationID, reservedWorkerID := range r.reservations { // Remove abandoned reservations when this worker id registers as a fresh process. + if reservedWorkerID == normalized.ID { // Match only capacity tokens routed to the restarted worker. + delete(r.reservations, reservationID) // Prevent pre-restart assignments from consuming new-process capacity. + } + } + r.mu.Unlock() // Allow schedulers and heartbeat handlers to observe the complete worker atomically. - return nil + r.logger.InfoContext(ctx, "worker registered", "worker_id", normalized.ID, "address", normalized.Address, "capacity", normalized.Capacity) // Log safe routing and capacity metadata for operator visibility. + r.recordAudit(ctx, "worker.register", normalized.ID, "success", "", map[string]interface{}{"address": normalized.Address, "capacity": normalized.Capacity}) // Append a successful worker-registration audit record. + return nil // Confirm that Redis and in-memory registry state now contain the healthy worker. } -// Heartbeat updates worker heartbeat +// Heartbeat refreshes worker liveness and atomically reconciles reported active load plus recovery state. func (r *WorkerRegistry) Heartbeat(ctx context.Context, workerID string, activeLoad int) error { - // Update heartbeat key - hbKey := fmt.Sprintf(workerHeartbeatKey, workerID) - if err := r.cache.Set(ctx, hbKey, "1", heartbeatTTL); err != nil { - return errors.Wrap(errors.CodeStoreWrite, "failed to update heartbeat", err) - } - - // Update worker in registry - val, ok := r.workers.Load(workerID) - if !ok { - // Worker not in cache, reload from Redis - return r.syncWorkerFromRedis(ctx, workerID) - } - - worker := val.(*WorkerNode) - now := time.Now() // Capture one heartbeat timestamp so state updates, recovery checks, and persistence all share the same wall-clock baseline. - worker.LastSeen = now // Record the latest successful heartbeat time before any recovery-state transitions are evaluated. - worker.ActiveLoad = activeLoad // Persist the latest active-load snapshot reported by the worker heartbeat. - worker.MissedBeats = 0 // Reset the missed-heartbeat counter because a fresh heartbeat has arrived successfully. - if worker.Status == "offline" { // Re-enter offline workers through degraded first so they pass one stabilization window before receiving new work. - worker.Status = "degraded" // Keep the recovering worker out of the healthy scheduling pool until it proves stability. - worker.RecoveryStarted = now // Start the recovery stabilization window from the current successful heartbeat. - r.logger.InfoContext(ctx, "worker entered recovery window", "worker_id", workerID) // Log the recovery-window entry so operators can see that the worker is back but not yet fully healthy. - } else if worker.Status == "degraded" && !worker.RecoveryStarted.IsZero() { // Promote recovering workers back to healthy only after the stabilization window has elapsed. - if now.Sub(worker.RecoveryStarted) >= recoveryWindow { // Check whether the worker has remained reachable throughout the full recovery stabilization window. - worker.Status = "healthy" // Return the worker to the healthy scheduling pool after the stabilization window succeeds. - worker.RecoveryStarted = time.Time{} // Clear the recovery window marker because the worker is now fully healthy again. - r.logger.InfoContext(ctx, "worker recovered", "worker_id", workerID) // Log the recovery completion so operators can see the worker is assignable again. + workerID = strings.TrimSpace(workerID) // Normalize the identifier before any Redis or in-memory lookup. + if workerID == "" { // Reject heartbeat calls that cannot identify a registry entry. + return errors.New(errors.CodePlanInvalid, "worker id is required") // Return a stable validation error to the internal RPC boundary. + } + if activeLoad < 0 { // Reject impossible negative load reports before they affect scheduling ratios. + return errors.New(errors.CodePlanInvalid, "worker active load cannot be negative") // Preserve non-negative capacity invariants inside the registry. + } + + r.mu.Lock() // Serialize the full heartbeat reconciliation with scheduler reservations and monitor transitions. + worker, ok := r.workers[workerID] // Resolve the private mutable record while holding the registry lock. + if !ok { // Reload workers missing from this process before applying the heartbeat. + r.mu.Unlock() // Avoid recursively acquiring the registry lock during Redis synchronization. + if err := r.syncWorkerFromRedis(ctx, workerID); err != nil { // Restore the registered worker snapshot from the shared Redis hash. + return err // Preserve not-found or storage failures from synchronization. + } + r.mu.Lock() // Reacquire the mutation lock after the worker snapshot has been synchronized. + worker = r.workers[workerID] // Resolve the synchronized registry-owned record under the lock. + if worker == nil { // Reject a worker removed concurrently after Redis synchronization completed. + r.mu.Unlock() // Release the mutation lock before returning the lost-registration result. + return errors.New(errors.CodeWorkerNotFound, "worker not found in registry") // Prevent a nil snapshot from entering heartbeat reconciliation. } - } else if worker.Status == "degraded" { // Preserve the existing degraded->healthy fast path for workers that never went fully offline. - worker.Status = "healthy" // Return mildly degraded workers to healthy once a fresh heartbeat arrives and no recovery window is active. - r.logger.InfoContext(ctx, "worker recovered", "worker_id", workerID) // Log the recovery so operators can correlate the worker's return to the healthy pool. } - // Update Redis - data, _ := json.Marshal(worker) - if err := r.cache.HSet(ctx, workerHashKey, map[string]interface{}{ - workerID: string(data), - }); err != nil { - return err + hbKey := fmt.Sprintf(workerHeartbeatKey, workerID) // Build the liveness key while the worker mutation remains serialized. + if err := r.cache.Set(ctx, hbKey, "1", heartbeatTTL); err != nil { // Refresh the heartbeat before changing the worker's schedulable state. + r.mu.Unlock() // Release the mutation lock before returning the storage failure. + return errors.Wrap(errors.CodeStoreWrite, "failed to update heartbeat", err) // Keep liveness failures under the storage write contract. } - return nil -} + now := time.Now().UTC() // Capture one timestamp for liveness and recovery calculations. + next := cloneWorkerNode(worker) // Mutate a private candidate so failed persistence leaves the prior snapshot intact. + next.LastSeen = now // Record when this successful heartbeat reached the orchestrator. + reservedLoad := r.reservedLoadLocked(workerID) // Count pre-RPC and accepted trace reservations while the mutation lock is held. + if activeLoad < reservedLoad { // Preserve locally promised capacity that the worker heartbeat cannot observe yet. + next.ActiveLoad = reservedLoad // Keep all exact reservations represented until their owning cleanup path releases them. + } else { + next.ActiveLoad = activeLoad // Reconcile to the authoritative worker count when it covers every known reservation. + } + next.MissedBeats = 0 // Clear all missed-heartbeat history after successful liveness persistence. + action := "" // Track an optional lifecycle transition for logs and audit after persistence succeeds. + if next.Status == "offline" { // Route offline workers through a stabilization period before new assignment. + next.Status = "degraded" // Keep the worker outside the healthy scheduling pool during recovery. + next.RecoveryStarted = now // Start the recovery window at this first successful heartbeat. + action = "worker.recovering" // Classify the lifecycle transition for audit and logs. + } else if next.Status == "degraded" && !next.RecoveryStarted.IsZero() && now.Sub(next.RecoveryStarted) >= recoveryWindow { // Promote only after the full recovery window has elapsed. + next.Status = "healthy" // Restore scheduling eligibility after sustained liveness. + next.RecoveryStarted = time.Time{} // Clear the completed recovery marker for future outages. + action = "worker.recovered" // Classify the successful recovery transition. + } else if next.Status == "degraded" && next.RecoveryStarted.IsZero() { // Preserve the fast recovery path for workers that never reached offline. + next.Status = "healthy" // Restore scheduling after a transient degraded heartbeat period. + action = "worker.recovered" // Classify the transient recovery transition. + } -// AssignWorker assigns a worker based on project and tags -func (r *WorkerRegistry) AssignWorker(ctx context.Context, projectID string, requiredTags map[string]string) *WorkerNode { - var candidates []*WorkerNode + data, err := json.Marshal(next) // Encode the complete candidate before replacing the in-memory snapshot. + if err != nil { // Stop when the worker candidate cannot be serialized. + r.mu.Unlock() // Release the mutation lock before returning the internal serialization failure. + return errors.Wrap(errors.CodeInternal, "failed to marshal worker heartbeat", err) // Preserve the encoding cause under a stable internal code. + } + if err := r.cache.HSet(ctx, workerHashKey, map[string]interface{}{workerID: string(data)}); err != nil { // Persist the reconciled worker snapshot before local publication. + r.mu.Unlock() // Release the mutation lock while preserving the previous local snapshot. + return errors.Wrap(errors.CodeStoreWrite, "failed to persist worker heartbeat", err) // Surface Redis hash failures consistently. + } + r.workers[workerID] = next // Publish the fully persisted heartbeat snapshot atomically to schedulers. + r.mu.Unlock() // Release the mutation lock before logging or audit I/O. - // Collect healthy workers matching tags - r.workers.Range(func(key, value interface{}) bool { - worker := value.(*WorkerNode) - if worker.Status != "healthy" { - return true - } + if action != "" { // Emit lifecycle diagnostics only when the heartbeat changed health state. + r.logger.InfoContext(ctx, "worker heartbeat changed lifecycle state", "worker_id", workerID, "status", next.Status) // Log the resulting state without exposing request credentials or payloads. + r.recordAudit(ctx, action, workerID, "success", "", map[string]interface{}{"status": next.Status}) // Append the matching worker recovery audit record. + } + return nil // Confirm that both heartbeat liveness and worker metadata were persisted successfully. +} - // Check if worker has capacity - if worker.ActiveLoad >= worker.Capacity { - return true +// AssignWorker selects the least-loaded matching healthy worker and atomically binds one exact reservation id to a local execution slot. +func (r *WorkerRegistry) AssignWorker(ctx context.Context, projectID string, requiredTags map[string]string, reservationID string) *WorkerNode { + r.mu.Lock() // Serialize candidate comparison and slot reservation so concurrent dispatches cannot oversubscribe local registry capacity. + if workerID, ok := r.reservations[reservationID]; ok { // Reuse a prior routing decision when the same trace attempt is scheduled more than once. + worker, exists := r.workers[workerID] // Resolve the worker that owns this exact reservation. + if exists { // Return the prior assignment while its worker remains registered. + reserved := cloneWorkerNode(worker) // Isolate the existing worker state before releasing the registry lock. + r.mu.Unlock() // Release scheduling serialization without incrementing load a second time. + return reserved // Preserve idempotent assignment for duplicate delivery of one trace attempt. } - - // Check tags match - if !r.tagsMatch(worker.Tags, requiredTags) { - return true + delete(r.reservations, reservationID) // Drop a token whose worker disappeared so scheduling can select a live candidate. + } + var selected *WorkerNode // Track the best private worker record found in this locked scheduling snapshot. + for _, worker := range r.workers { // Inspect every registered worker while no heartbeat or monitor mutation can race. + if worker.Status != "healthy" || worker.Capacity <= 0 || worker.ActiveLoad >= worker.Capacity { // Skip unhealthy, malformed, or fully reserved workers. + continue // Continue searching for an assignable candidate. + } + if !tagsMatch(worker.Tags, requiredTags) { // Enforce every caller-required scheduling tag. + continue // Skip workers whose declared tags do not satisfy the request. + } + if selected == nil || workerLessLoaded(worker, selected) { // Prefer lower utilization and then stable worker id order. + selected = worker // Retain the best registry-owned candidate while still under the lock. } - - candidates = append(candidates, worker) - return true - }) - - if len(candidates) == 0 { - r.logger.WarnContext(ctx, "no available workers", "project_id", projectID) - return nil } + if selected == nil { // Report cleanly when this registry snapshot contains no available capacity. + r.mu.Unlock() // Release the scheduling lock before writing logs. + r.logger.WarnContext(ctx, "no available workers", "project_id", projectID) // Surface capacity exhaustion without treating it as an infrastructure failure. + return nil // Let dispatcher retry the queued message through the transient no-worker path. + } + selected.ActiveLoad++ // Reserve one slot before any competing dispatcher can select the same capacity. + r.reservations[reservationID] = selected.ID // Bind this trace attempt to the selected worker for idempotent cleanup. + reserved := cloneWorkerNode(selected) // Return an isolated snapshot that cannot mutate registry state outside the lock. + r.mu.Unlock() // Release scheduling serialization after the slot reservation is visible. - // Sort by load (least loaded first) - sort.Slice(candidates, func(i, j int) bool { - loadI := float64(candidates[i].ActiveLoad) / float64(candidates[i].Capacity) - loadJ := float64(candidates[j].ActiveLoad) / float64(candidates[j].Capacity) - return loadI < loadJ - }) - - selected := candidates[0] - r.logger.InfoContext(ctx, "worker assigned", - "worker_id", selected.ID, - "project_id", projectID, - "load", selected.ActiveLoad, - "capacity", selected.Capacity) + r.logger.InfoContext(ctx, "worker assigned", "worker_id", reserved.ID, "project_id", projectID, "load", reserved.ActiveLoad, "capacity", reserved.Capacity) // Log post-reservation utilization for capacity diagnostics. + return reserved // Return the immutable scheduling snapshot for RPC routing and later rollback by worker id. +} - return selected +// ReleaseWorkerReservation releases one exact trace-attempt slot after rejection, failure, completion, cancellation, or timeout. +func (r *WorkerRegistry) ReleaseWorkerReservation(reservationID string) { + r.mu.Lock() // Serialize reservation rollback with heartbeat reconciliation and new assignments. + workerID, reserved := r.reservations[reservationID] // Resolve the exact capacity token targeted by this cleanup call. + if reserved { // Ignore duplicate cleanup after another path already consumed the same token. + delete(r.reservations, reservationID) // Remove ownership before adjusting the aggregate worker load. + if worker, ok := r.workers[workerID]; ok && worker.ActiveLoad > 0 { // Decrement only an existing positive count so rollback cannot underflow. + worker.ActiveLoad-- // Return exactly one scheduling slot to the local availability snapshot. + } + } + r.mu.Unlock() // Release the registry lock after the idempotent capacity correction. } -// ListAvailable returns all available workers -func (r *WorkerRegistry) ListAvailable(ctx context.Context) ([]*WorkerNode, error) { - var workers []*WorkerNode - r.workers.Range(func(key, value interface{}) bool { - worker := value.(*WorkerNode) - if worker.Status == "healthy" { - workers = append(workers, worker) +// ListAvailable returns deep-copy snapshots of healthy workers that currently retain at least one unreserved slot. +func (r *WorkerRegistry) ListAvailable(_ context.Context) ([]*WorkerNode, error) { + r.mu.RLock() // Freeze the registry snapshot while worker records are copied. + workers := make([]*WorkerNode, 0, len(r.workers)) // Preallocate enough room for the maximum possible healthy snapshot. + for _, worker := range r.workers { // Inspect every private worker record under the read lock. + if worker.Status == "healthy" && worker.Capacity > worker.ActiveLoad { // Include only workers that can accept another local reservation. + workers = append(workers, cloneWorkerNode(worker)) // Deep-copy the worker so callers cannot mutate registry state. } - return true + } + r.mu.RUnlock() // Release the read lock after every returned snapshot is isolated. + sort.Slice(workers, func(i, j int) bool { // Return deterministic order for health output and tests. + return workers[i].ID < workers[j].ID // Sort snapshots by stable worker identifier. }) - return workers, nil + return workers, nil // Return the isolated available-worker snapshot without exposing registry pointers. } -// HealthSummary returns the current in-memory worker health counts used by the orchestrator health endpoint. +// HealthSummary returns race-free counts for every worker lifecycle state in the current registry snapshot. func (r *WorkerRegistry) HealthSummary() workerRegistryHealthSummary { - summary := workerRegistryHealthSummary{} // Allocate the mutable summary that will accumulate worker counts across the registry snapshot. - r.workers.Range(func(key, value interface{}) bool { - worker := value.(*WorkerNode) // Read one cached worker entry so this snapshot can classify its current health state. - summary.Total++ // Count every cached worker regardless of health state so callers can see total fleet size. - switch worker.Status { // Bucket the worker by its current health state so health output can report healthy, degraded, and offline capacity separately. + r.mu.RLock() // Freeze worker lifecycle state for the duration of summary aggregation. + defer r.mu.RUnlock() // Release the read lock after every worker has been classified. + summary := workerRegistryHealthSummary{} // Allocate the mutable aggregate returned to the health endpoint. + for _, worker := range r.workers { // Classify every registry-owned worker record under the read lock. + summary.Total++ // Count every known worker regardless of lifecycle state. + switch worker.Status { // Bucket the worker by its current heartbeat-derived state. case "healthy": - summary.Healthy++ // Count workers that are currently considered healthy and assignable. + summary.Healthy++ // Count workers currently eligible for scheduling. case "degraded": - summary.Degraded++ // Count workers that are still known but have missed enough heartbeats to lose full trust. + summary.Degraded++ // Count workers temporarily excluded after missed heartbeats or recovery. case "offline": - summary.Offline++ // Count workers that have missed enough heartbeats to be treated as offline. + summary.Offline++ // Count workers known to be unreachable but not yet removed. default: - summary.Unknown++ // Count any unexpected state explicitly so health output reveals registry-state drift instead of hiding it. + summary.Unknown++ // Expose malformed lifecycle values rather than silently treating them as healthy. } - return true // Continue iterating until every cached worker has been included in the summary snapshot. - }) - - return summary // Return the completed registry snapshot for health-check reporting. + } + return summary // Return the complete race-free fleet snapshot. } -// StartMonitor starts monitoring worker heartbeats +// StartMonitor starts the heartbeat monitor loop in a background goroutine. func (r *WorkerRegistry) StartMonitor(ctx context.Context) { - go r.monitorLoop(ctx) - r.logger.Info("worker registry monitor started") + go r.monitorLoop(ctx) // Run periodic liveness checks without blocking orchestrator startup. + r.logger.Info("worker registry monitor started") // Record that heartbeat monitoring is active. } -// Stop stops the monitor +// Stop idempotently signals the heartbeat monitor to exit. func (r *WorkerRegistry) Stop() { - close(r.stopCh) - r.logger.Info("worker registry stopped") + r.stopOnce.Do(func() { // Close the stop channel exactly once across repeated service shutdown paths. + close(r.stopCh) // Wake the monitor select loop and prevent future heartbeat sweeps. + }) + r.logger.Info("worker registry stopped") // Record the idempotent monitor shutdown request. } -// monitorLoop periodically checks worker heartbeats +// monitorLoop periodically checks worker heartbeat keys until the parent context or registry stop signal fires. func (r *WorkerRegistry) monitorLoop(ctx context.Context) { - ticker := time.NewTicker(monitorInterval) - defer ticker.Stop() - - for { + ticker := time.NewTicker(monitorInterval) // Create the fixed-cadence heartbeat sweep ticker. + defer ticker.Stop() // Release ticker resources when monitoring exits. + for { // Continue monitoring until one explicit shutdown signal arrives. select { case <-ctx.Done(): - return + return // Stop when the orchestrator parent context is cancelled. case <-r.stopCh: - return + return // Stop when Service.Stop closes the registry channel. case <-ticker.C: - r.checkHeartbeats(ctx) + r.checkHeartbeats(ctx) // Evaluate all known workers against their Redis heartbeat keys. } } } -// checkHeartbeats checks all workers for missed heartbeats +// checkHeartbeats degrades, offlines, or removes workers with expired heartbeat keys without treating Redis outages as fleet failure. func (r *WorkerRegistry) checkHeartbeats(ctx context.Context) { - now := time.Now() - - r.workers.Range(func(key, value interface{}) bool { - workerID := key.(string) - worker := value.(*WorkerNode) - - // Check if heartbeat key exists - hbKey := fmt.Sprintf(workerHeartbeatKey, workerID) - _, err := r.cache.Get(ctx, hbKey) - - if err != nil { - // Heartbeat missed - worker.MissedBeats++ - - if worker.MissedBeats >= degradeAfterMisses && worker.Status == "healthy" { - worker.Status = "degraded" - r.logger.WarnContext(ctx, "worker degraded", - "worker_id", workerID, - "missed_beats", worker.MissedBeats) - } + r.mu.RLock() // Freeze map membership while collecting worker identifiers for this sweep. + workerIDs := make([]string, 0, len(r.workers)) // Preallocate one identifier snapshot for every known worker. + for workerID := range r.workers { // Collect stable identifiers without exposing worker pointers. + workerIDs = append(workerIDs, workerID) // Add this worker to the independent sweep list. + } + r.mu.RUnlock() // Allow heartbeat and registration mutations while Redis keys are queried. + sort.Strings(workerIDs) // Use deterministic sweep order for reproducible logs and tests. + + now := time.Now().UTC() // Capture one comparison timestamp for all removal decisions in this sweep. + for _, workerID := range workerIDs { // Check every worker that existed when the sweep began. + hbKey := fmt.Sprintf(workerHeartbeatKey, workerID) // Build the worker-specific Redis liveness key. + if _, err := r.cache.Get(ctx, hbKey); err == nil { // Leave workers unchanged while their heartbeat key remains present. + continue // Advance to the next worker without incrementing missed-heartbeat state. + } else if !stdErrors.Is(err, goredis.Nil) { // Treat Redis infrastructure failures as unknown liveness rather than mass worker death. + r.logger.WarnContext(ctx, "failed to read worker heartbeat", "worker_id", workerID, "error", err) // Surface the cache outage for operators while preserving fleet state. + continue // Retry on the next sweep instead of degrading a worker without evidence its key expired. + } - if worker.MissedBeats >= heartbeatMissMax { - worker.Status = "offline" - worker.RecoveryStarted = time.Time{} - r.logger.ErrorContext(ctx, "worker offline", - "worker_id", workerID, - "missed_beats", worker.MissedBeats) + r.mu.Lock() // Serialize this missed-heartbeat transition with concurrent heartbeats and scheduler reservations. + worker, ok := r.workers[workerID] // Re-resolve the worker because it may have been removed after the identifier snapshot. + if !ok { // Skip identifiers removed concurrently before this state transition. + r.mu.Unlock() // Release the mutation lock before advancing the sweep. + continue // Avoid recreating or auditing a worker that no longer exists. + } + next := cloneWorkerNode(worker) // Mutate an isolated candidate so failed persistence does not expose a partial state. + next.MissedBeats++ // Record this confirmed heartbeat-key expiration. + action := "" // Track at most one lifecycle transition generated by this missed beat. + if next.MissedBeats >= heartbeatMissMax && next.Status != "offline" { // Move any sufficiently stale worker to the offline state. + next.Status = "offline" // Exclude the worker from all scheduling immediately. + next.RecoveryStarted = time.Time{} // Require a new stabilization window after it returns. + action = "worker.offline" // Classify the lifecycle transition for logs and audit. + } else if next.MissedBeats >= degradeAfterMisses && next.Status == "healthy" { // Degrade healthy workers before the full offline threshold. + next.Status = "degraded" // Remove the worker from scheduling while retaining it for recovery. + action = "worker.degraded" // Classify the intermediate liveness transition. + } + remove := next.Status == "offline" && now.Sub(next.LastSeen) > removeAfterSeconds*time.Second // Remove workers that remain offline beyond the retention window. + if remove { // Delete old offline workers from Redis and memory under the same mutation lock. + if err := r.cache.HDel(ctx, workerHashKey, workerID); err != nil { // Require Redis hash removal before dropping the local record. + r.mu.Unlock() // Release the mutation lock before logging the failed removal. + r.logger.ErrorContext(ctx, "failed to remove worker from redis", "worker_id", workerID, "error", err) // Surface the storage failure so the next sweep can retry. + continue // Keep the local offline record until durable registry removal succeeds. } - - // Remove if offline too long - if worker.Status == "offline" && now.Sub(worker.LastSeen) > removeAfterSeconds*time.Second { - r.removeWorker(ctx, workerID) + delete(r.workers, workerID) // Remove the same worker from local scheduling and health snapshots. + for reservationID, reservedWorkerID := range r.reservations { // Remove capacity tokens owned by the deleted worker. + if reservedWorkerID == workerID { // Match only reservations routed to this removed registry record. + delete(r.reservations, reservationID) // Prevent deleted-worker reservations from leaking indefinitely. + } } + r.mu.Unlock() // Release the mutation lock after durable and local removal agree. + r.logger.InfoContext(ctx, "worker removed", "worker_id", workerID) // Record the completed lifecycle cleanup. + r.recordAudit(ctx, "worker.removed", workerID, "success", "heartbeat_timeout", nil) // Append the worker removal audit event with a stable reason. + continue // Advance because this worker no longer has metadata to persist. } - return true - }) + data, err := json.Marshal(next) // Encode the full degraded or offline candidate before publication. + if err != nil { // Preserve the prior local snapshot when encoding unexpectedly fails. + r.mu.Unlock() // Release the mutation lock before logging the internal failure. + r.logger.ErrorContext(ctx, "failed to marshal worker heartbeat state", "worker_id", workerID, "error", err) // Surface the serialization failure for diagnosis. + continue // Retry the missed-heartbeat transition on the next monitor sweep. + } + if err := r.cache.HSet(ctx, workerHashKey, map[string]interface{}{workerID: string(data)}); err != nil { // Persist monitor-derived state before local publication. + r.mu.Unlock() // Release the mutation lock while preserving the prior local snapshot. + r.logger.ErrorContext(ctx, "failed to persist worker heartbeat state", "worker_id", workerID, "error", err) // Surface the Redis write failure for diagnosis. + continue // Retry the transition on the next monitor sweep. + } + r.workers[workerID] = next // Publish the persisted liveness state atomically to schedulers and health readers. + r.mu.Unlock() // Release the mutation lock before logs and audit writes. + if action != "" { // Emit lifecycle records only when this missed beat crossed a state threshold. + r.logger.WarnContext(ctx, "worker heartbeat changed lifecycle state", "worker_id", workerID, "status", next.Status, "missed_beats", next.MissedBeats) // Log the safe state transition details. + r.recordAudit(ctx, action, workerID, "success", "heartbeat_timeout", map[string]interface{}{"missedBeats": next.MissedBeats, "status": next.Status}) // Append the matching lifecycle audit event. + } + } } -// removeWorker removes a worker from registry -func (r *WorkerRegistry) removeWorker(ctx context.Context, workerID string) { - r.workers.Delete(workerID) - if err := r.cache.HDel(ctx, workerHashKey, workerID); err != nil { - r.logger.ErrorContext(ctx, "failed to remove worker from redis", - "worker_id", workerID, - "error", err) +// syncWorkerFromRedis reloads one worker snapshot into local memory when a heartbeat reaches a fresh orchestrator process. +func (r *WorkerRegistry) syncWorkerFromRedis(ctx context.Context, workerID string) error { + data, err := r.cache.HGetAll(ctx, workerHashKey) // Load the shared worker registry because the cache wrapper does not expose single-field lookup. + if err != nil { // Surface Redis read failures instead of treating the worker as absent. + return errors.Wrap(errors.CodeStoreRead, "failed to load worker registry", err) // Preserve the infrastructure failure under the stable storage read code. } - r.logger.InfoContext(ctx, "worker removed", "worker_id", workerID) + workerData, ok := data[workerID] // Resolve the requested worker's serialized snapshot from the shared hash. + if !ok { // Reject heartbeats from workers that were never durably registered. + return errors.New(errors.CodeWorkerNotFound, "worker not found in registry") // Keep the internal RPC response deterministic for unknown workers. + } + var worker WorkerNode // Allocate an isolated destination for the persisted worker JSON. + if err := json.Unmarshal([]byte(workerData), &worker); err != nil { // Decode the persisted routing, capacity, and liveness metadata. + return errors.Wrap(errors.CodeInternal, "failed to unmarshal worker", err) // Preserve malformed shared state as an internal data error. + } + if worker.Capacity <= 0 { // Reject corrupted snapshots that could divide by zero during scheduling. + return errors.New(errors.CodeInternal, "persisted worker capacity must be greater than zero") // Keep malformed registry data outside the scheduling pool. + } + r.mu.Lock() // Serialize publication with registrations, monitor transitions, and scheduler reservations. + r.workers[workerID] = cloneWorkerNode(&worker) // Store a registry-owned deep copy of the decoded snapshot. + r.mu.Unlock() // Release the mutation lock after the worker becomes visible atomically. + return nil // Confirm that the local registry now contains the persisted worker. } -// syncWorkerFromRedis reloads worker from Redis -func (r *WorkerRegistry) syncWorkerFromRedis(ctx context.Context, workerID string) error { - data, err := r.cache.HGetAll(ctx, workerHashKey) - if err != nil { - return err +// GetWorker returns a deep-copy snapshot for one worker id, or nil when no worker is registered. +func (r *WorkerRegistry) GetWorker(workerID string) *WorkerNode { + r.mu.RLock() // Protect map lookup and worker-field copying from concurrent mutations. + worker, ok := r.workers[workerID] // Resolve the private worker record under the read lock. + if !ok { // Return a clean absence result when no matching worker exists. + r.mu.RUnlock() // Release the read lock before returning nil. + return nil // Avoid exposing a fabricated or partially initialized worker. } + snapshot := cloneWorkerNode(worker) // Deep-copy tags and scalar state before releasing the lock. + r.mu.RUnlock() // Allow registry mutations after the snapshot is fully isolated. + return snapshot // Return a caller-owned worker snapshot that cannot race with registry state. +} - workerData, ok := data[workerID] - if !ok { - return errors.New(errors.CodeWorkerNotFound, "worker not found in registry") +// recordAudit appends one best-effort worker lifecycle event without allowing audit sink failure to change scheduling state. +func (r *WorkerRegistry) recordAudit(ctx context.Context, action string, workerID string, result string, reason string, metadata map[string]interface{}) { + r.mu.RLock() // Read the optional recorder pointer consistently with SetAuditRecorder. + recorder := r.auditRecorder // Copy the interface while holding the read lock so later replacement cannot race. + r.mu.RUnlock() // Release the registry lock before invoking external audit storage. + if recorder == nil { // Skip audit work when process wiring did not install a sink. + return // Preserve registry operation behavior in tests and minimal deployments. + } + event := audit.Event{Action: action, ResourceType: "worker", ResourceID: workerID, Result: result, Reason: reason, ActorType: "system", Metadata: metadata, CreatedAt: time.Now().UTC()} // Build a sanitized lifecycle record with no worker request payload or credential data. + if err := recorder.Record(ctx, event); err != nil { // Keep audit persistence best-effort so an unavailable audit table cannot deadlock fleet recovery. + r.logger.WarnContext(ctx, "failed to record worker audit event", "action", action, "worker_id", workerID, "error", err) // Surface sink failures to operators without logging secrets. } +} - var worker WorkerNode - if err := json.Unmarshal([]byte(workerData), &worker); err != nil { - return errors.Wrap(errors.CodeInternal, "failed to unmarshal worker", err) +// reservedLoadLocked counts exact trace-attempt reservations for one worker while the caller holds the registry mutex. +func (r *WorkerRegistry) reservedLoadLocked(workerID string) int { + reservedLoad := 0 // Start from zero locally promised slots for the requested worker. + for _, reservedWorkerID := range r.reservations { // Inspect every exact reservation under the caller-held mutation lock. + if reservedWorkerID == workerID { // Count only reservations routed to the requested worker. + reservedLoad++ // Preserve one unit of worker capacity for this trace attempt. + } } + return reservedLoad // Return the number of still-owned exact reservations. +} - r.workers.Store(workerID, &worker) - return nil +// cloneWorkerNode deep-copies one worker record so mutable tag maps never cross registry lock boundaries. +func cloneWorkerNode(worker *WorkerNode) *WorkerNode { + if worker == nil { // Preserve nil semantics for defensive internal call sites. + return nil // Avoid dereferencing absent worker records. + } + clone := *worker // Copy every scalar and time field into caller-owned storage. + clone.Tags = make(map[string]string, len(worker.Tags)) // Allocate an independent tag map for race-free use. + for key, value := range worker.Tags { // Copy each immutable scheduling tag pair explicitly. + clone.Tags[key] = value // Preserve the exact tag key and value without sharing map storage. + } + return &clone // Return the fully isolated worker snapshot. } -// tagsMatch checks if worker tags match required tags -func (r *WorkerRegistry) tagsMatch(workerTags, requiredTags map[string]string) bool { - for k, v := range requiredTags { - if workerTags[k] != v { - return false +// tagsMatch reports whether one worker tag set contains every required key and exact value. +func tagsMatch(workerTags map[string]string, requiredTags map[string]string) bool { + for key, value := range requiredTags { // Check each caller-required tag independently. + if workerTags[key] != value { // Reject missing keys and mismatched values through the same map lookup. + return false // Stop at the first unsatisfied scheduling constraint. } } - return true + return true // Confirm that every required tag is present with the requested value. } -// GetWorker returns a worker by ID -func (r *WorkerRegistry) GetWorker(workerID string) *WorkerNode { - val, ok := r.workers.Load(workerID) - if !ok { - return nil +// workerLessLoaded orders workers by utilization ratio and then by stable id for deterministic reservations. +func workerLessLoaded(candidate *WorkerNode, current *WorkerNode) bool { + candidateLoad := int64(candidate.ActiveLoad) * int64(current.Capacity) // Cross-multiply candidate utilization to avoid floating-point ordering drift. + currentLoad := int64(current.ActiveLoad) * int64(candidate.Capacity) // Cross-multiply current utilization using the same positive capacities. + if candidateLoad != currentLoad { // Prefer the worker with the strictly lower utilization ratio. + return candidateLoad < currentLoad // Compare exact integer products without division by zero. } - return val.(*WorkerNode) + return candidate.ID < current.ID // Break equal-load ties deterministically by worker identifier. } diff --git a/internal/orchestrator/worker_registry_recovery_test.go b/internal/orchestrator/worker_registry_recovery_test.go index 682beb8..d19b487 100644 --- a/internal/orchestrator/worker_registry_recovery_test.go +++ b/internal/orchestrator/worker_registry_recovery_test.go @@ -30,31 +30,49 @@ func TestWorkerHeartbeatRecoveryWindow(t *testing.T) { t.Fatalf("failed to register worker: %v", err) // Surface registration failures because the recovery-path test cannot proceed without a persisted worker. } - liveWorker := registry.GetWorker(worker.ID) // Load the in-memory worker record so the test can manipulate its state directly before heartbeat recovery assertions. + liveWorker := registry.GetWorker(worker.ID) // Load an isolated worker snapshot so the test first verifies successful registration visibility. if liveWorker == nil { // Fail the test when the worker is not present in the in-memory registry after successful registration. t.Fatal("expected registered worker to be present in registry") // Surface the missing registry entry because the recovery-path test cannot proceed without it. } - liveWorker.Status = "offline" // Force the worker into the offline state so the next heartbeat must enter the recovery window instead of becoming healthy immediately. - liveWorker.RecoveryStarted = time.Time{} // Clear any previous recovery timestamp so the test controls the entire recovery-window transition explicitly. + updateWorkerForTest(t, registry, worker.ID, func(current *WorkerNode) { // Mutate registry-owned lifecycle state under its production mutex to seed the offline recovery scenario safely. + current.Status = "offline" // Force the worker offline so the next heartbeat must enter the recovery window first. + current.RecoveryStarted = time.Time{} // Clear prior recovery state so this test controls the stabilization window. + }) if err := registry.Heartbeat(context.Background(), worker.ID, 0); err != nil { // Deliver one fresh heartbeat so the offline worker enters the degraded recovery window. t.Fatalf("expected offline worker heartbeat to succeed, got error: %v", err) // Surface heartbeat failures because the recovery transition cannot be asserted without one. } - if liveWorker.Status != "degraded" { // Fail the test when offline workers do not re-enter through degraded first. + liveWorker = registry.GetWorker(worker.ID) // Read a fresh isolated snapshot because registry queries no longer expose mutable internal pointers. + if liveWorker.Status != "degraded" { // Fail the test when offline workers do not re-enter through degraded first. t.Fatalf("expected worker status degraded after first recovery heartbeat, got %s", liveWorker.Status) // Surface the unexpected recovery state because workers must stabilize before becoming healthy again. } if liveWorker.RecoveryStarted.IsZero() { // Fail the test when the recovery-window timestamp was not recorded during the first recovery heartbeat. t.Fatal("expected recovery window to start on first heartbeat after offline") // Surface the missing timestamp because later stabilization checks depend on it. } - liveWorker.RecoveryStarted = time.Now().Add(-recoveryWindow) // Pretend the worker has already stayed reachable throughout the full stabilization window. + updateWorkerForTest(t, registry, worker.ID, func(current *WorkerNode) { // Advance the registry-owned recovery marker under the same mutex used by production heartbeats. + current.RecoveryStarted = time.Now().Add(-recoveryWindow) // Pretend the worker has remained reachable for the entire stabilization interval. + }) if err := registry.Heartbeat(context.Background(), worker.ID, 0); err != nil { // Deliver one more heartbeat so the registry can promote the recovered worker back to healthy. t.Fatalf("expected recovering worker heartbeat to succeed, got error: %v", err) // Surface heartbeat failures because the healthy promotion cannot be asserted without one. } - if liveWorker.Status != "healthy" { // Fail the test when the worker does not become healthy again after the stabilization window has elapsed. + liveWorker = registry.GetWorker(worker.ID) // Read the post-heartbeat snapshot so assertions observe the newly published healthy state. + if liveWorker.Status != "healthy" { // Fail the test when the worker does not become healthy again after the stabilization window has elapsed. t.Fatalf("expected worker status healthy after recovery window elapsed, got %s", liveWorker.Status) // Surface the unexpected recovery state because healthy scheduling depends on this promotion. } if !liveWorker.RecoveryStarted.IsZero() { // Fail the test when the recovery-window marker is not cleared after the worker becomes healthy again. t.Fatalf("expected recovery timestamp to be cleared after healthy promotion, got %v", liveWorker.RecoveryStarted) // Surface the lingering recovery marker because later recovery cycles must start fresh. } } + +// updateWorkerForTest mutates one registry-owned worker under the production mutex so lifecycle tests never depend on escaped internal pointers. +func updateWorkerForTest(t *testing.T, registry *WorkerRegistry, workerID string, update func(*WorkerNode)) { + t.Helper() // Attribute failures to the scenario call site instead of this synchronization helper. + registry.mu.Lock() // Serialize test-only state injection with the same lock used by production registry mutations. + defer registry.mu.Unlock() // Always release the registry lock even when a test assertion aborts inside this helper. + worker, ok := registry.workers[workerID] // Resolve the private registry record while mutation is exclusively locked. + if !ok { // Fail immediately when the requested worker was not registered successfully. + t.Fatalf("worker %s not found in registry", workerID) // Surface the missing fixture because the requested state mutation cannot be applied. + } + update(worker) // Apply the narrowly scoped test mutation without exposing the private worker pointer outside the lock. +} diff --git a/internal/storage/postgres/audit_recorder.go b/internal/storage/postgres/audit_recorder.go new file mode 100644 index 0000000..75c49a5 --- /dev/null +++ b/internal/storage/postgres/audit_recorder.go @@ -0,0 +1,84 @@ +// audit_recorder.go adapts repository-wide structured audit events into append-only PostgreSQL audit_log rows. +package postgres + +import ( + "context" + "encoding/json" + "strings" + "time" + + "mcp_for_appium/internal/audit" + "mcp_for_appium/internal/errors" + + "github.com/google/uuid" +) + +// AuditRecorder persists structured security audit events through the PostgreSQL DAO. +type AuditRecorder struct { + dao *DAO +} + +// NewAuditRecorder constructs one PostgreSQL audit recorder, or nil when no DAO is available. +func NewAuditRecorder(dao *DAO) audit.Recorder { + if dao == nil { // Skip recorder construction when persistence is not wired, such as protocol-only unit tests. + return nil // Signal to callers that audit recording is unavailable rather than creating a panic-prone adapter. + } + return &AuditRecorder{dao: dao} // Reuse the process-wide DAO pool for append-only audit writes. +} + +// Record serializes one structured audit event and appends it to the existing audit_logs table. +func (r *AuditRecorder) Record(ctx context.Context, event audit.Event) error { + if r == nil || r.dao == nil { // Reject direct use of an unconfigured recorder defensively. + return errors.New(errors.CodeStoreWrite, "audit recorder is not configured") // Preserve a stable storage classification for wiring defects. + } + createdAt := event.CreatedAt.UTC() // Normalize caller-supplied audit timestamps for consistent ordering. + if createdAt.IsZero() { // Fill timestamps for callers that omit an explicit operation time. + createdAt = time.Now().UTC() // Stamp the record at persistence time while retaining UTC semantics. + } + projectID := strings.TrimSpace(event.ProjectID) // Prefer the concrete project scope when the audited resource belongs to one. + if projectID == "" { // Fall back to tenant scope for authentication and gateway-only events. + projectID = strings.TrimSpace(event.TenantID) // Keep tenant security events queryable through the existing project_id index. + } + if projectID == "" { // Assign a stable system scope for pre-authentication and worker lifecycle events. + projectID = "system" // Satisfy the existing non-null audit schema without inventing a user or tenant identity. + } + actorID := strings.TrimSpace(event.ActorID) // Preserve the authenticated principal when one is known. + if actorID == "" { // Classify pre-authentication failures without a fake credential identity. + actorID = "anonymous" // Keep the non-null actor column explicit and searchable for rejected traffic. + } + resourceType := strings.TrimSpace(event.ResourceType) // Preserve the audited resource category when supplied. + if resourceType == "" { // Fall back to a stable generic category for process events. + resourceType = "system" // Satisfy the non-null schema while keeping the record semantically explicit. + } + resourceID := strings.TrimSpace(event.ResourceID) // Preserve the concrete resource identifier when supplied. + if resourceID == "" { // Fall back to the action identifier when no separate resource exists. + resourceID = strings.TrimSpace(event.Action) // Keep resource-oriented audit queries deterministic for action-only events. + } + payload, err := json.Marshal(map[string]interface{}{ // Serialize the requirement-level audit fields not represented by dedicated legacy columns. + "actorId": actorID, // Duplicate the actor identifier inside the self-contained JSON payload. + "actorType": strings.TrimSpace(event.ActorType), // Record whether the actor is a user, service, worker, or anonymous requester. + "authScheme": strings.TrimSpace(event.AuthScheme), // Record PAT, OIDC, HMAC, subscription token, or internal RPC authentication. + "credentialId": strings.TrimSpace(event.CredentialID), // Record a safe key or token identifier without storing any credential secret. + "tenantId": strings.TrimSpace(event.TenantID), // Record the authenticated tenant scope when available. + "result": strings.TrimSpace(event.Result), // Record success, failure, denied, expired, or another stable outcome. + "reason": strings.TrimSpace(event.Reason), // Record only a stable error code or sanitized lifecycle reason. + "sourceIp": strings.TrimSpace(event.SourceIP), // Record the directly observed network peer for security investigation. + "requestId": strings.TrimSpace(event.RequestID), // Correlate the audit event with gateway or RPC request telemetry. + "metadata": event.Metadata, // Preserve operation-specific non-secret context such as capacity, attempt, or expiry. + }) + if err != nil { // Stop before persistence when operation metadata cannot be represented as JSON. + return errors.Wrap(errors.CodeInternal, "failed to serialize audit event", err) // Preserve the serialization cause for server logs. + } + return r.dao.InsertAuditLog(ctx, &AuditLog{ // Append the normalized event through the existing persistence helper. + ID: uuid.NewString(), // Assign one globally unique audit record identifier. + ProjectID: projectID, // Store project, tenant, or system scope in the indexed legacy column. + SessionID: strings.TrimSpace(event.SessionID), // Preserve an optional valid session foreign-key reference. + TraceID: strings.TrimSpace(event.TraceID), // Preserve an optional valid trace foreign-key reference. + Actor: actorID, // Store the normalized actor in the indexed legacy field. + Action: strings.TrimSpace(event.Action), // Store the stable audited action name. + ResourceType: resourceType, // Store the normalized resource category. + ResourceID: resourceID, // Store the normalized resource identifier. + Payload: payload, // Store the complete structured security context as JSON bytes. + CreatedAt: createdAt, // Store the normalized operation timestamp. + }) +} diff --git a/internal/storage/postgres/auth_store.go b/internal/storage/postgres/auth_store.go index b4f8345..0b42dc9 100644 --- a/internal/storage/postgres/auth_store.go +++ b/internal/storage/postgres/auth_store.go @@ -4,8 +4,11 @@ package postgres import ( "context" "database/sql" + stdErrors "errors" "mcp_for_appium/internal/errors" + + "github.com/jackc/pgx/v5" ) // PATToken stores one PostgreSQL-backed PAT credential record resolved by token ID. @@ -39,8 +42,11 @@ func (d *DAO) GetPATToken(ctx context.Context, tokenID string) (*PATToken, error FROM pat_tokens WHERE token_id = $1 `, tokenID).Scan(&record.TokenID, &record.TenantID, &record.SubjectID, &record.DisplayName, &record.SecretHash, &record.Status, &record.ScopesJSON, &record.ExpiresAt) // Read the authoritative PAT row by token ID because PAT bearer validation starts from the parsed token identifier. - if err != nil { // Convert missing-row and database failures into the repository-standard storage read contract. - return nil, errors.Wrap(errors.CodeUnauthenticated, "pat token not found", err) // Preserve the raw lookup failure while returning a stable authentication-oriented code to the caller. + if stdErrors.Is(err, pgx.ErrNoRows) { // Map only an authoritative empty result to the credential-not-found contract. + return nil, errors.Wrap(errors.CodeUnauthenticated, "pat token not found", err) // Preserve no-row context without exposing it externally. + } + if err != nil { // Keep database availability and decoding failures distinct from an unknown token id. + return nil, errors.Wrap(errors.CodeStoreRead, "failed to read pat token", err) // Allow the gateway to return a server failure instead of misleading 401. } return record, nil // Return the authoritative PAT record so the caller can validate status, expiry, and secret hash. @@ -54,8 +60,11 @@ func (d *DAO) GetHMACKey(ctx context.Context, keyID string) (*HMACKey, error) { FROM hmac_keys WHERE key_id = $1 `, keyID).Scan(&record.KeyID, &record.TenantID, &record.DisplayName, &record.SecretRef, &record.Status, &record.NotBefore, &record.NotAfter) // Read the authoritative HMAC key row by key ID because request-signature validation starts from the caller-supplied key identifier. - if err != nil { // Convert missing-row and database failures into the repository-standard storage read contract. - return nil, errors.Wrap(errors.CodeUnauthenticated, "hmac key not found", err) // Preserve the raw lookup failure while returning a stable authentication-oriented code to the caller. + if stdErrors.Is(err, pgx.ErrNoRows) { // Map only an authoritative empty result to the credential-not-found contract. + return nil, errors.Wrap(errors.CodeUnauthenticated, "hmac key not found", err) // Preserve no-row context without exposing it externally. + } + if err != nil { // Keep database availability and decoding failures distinct from an unknown key id. + return nil, errors.Wrap(errors.CodeStoreRead, "failed to read hmac key", err) // Allow the gateway to return a server failure instead of misleading 401. } return record, nil // Return the authoritative HMAC key record so the caller can validate status, validity window, and secret material. diff --git a/internal/storage/postgres/coordination.go b/internal/storage/postgres/coordination.go index 7285780..8b33bd9 100644 --- a/internal/storage/postgres/coordination.go +++ b/internal/storage/postgres/coordination.go @@ -3,6 +3,8 @@ package postgres import ( "context" + stdErrors "errors" + "strings" "time" "mcp_for_appium/internal/errors" @@ -64,8 +66,11 @@ func (d *TxDAO) GetSessionForUpdate(ctx context.Context, id string) (*Session, e WHERE id = $1 FOR UPDATE `, id).Scan(&session.ID, &session.ProjectID, &session.TenantID, &session.SubjectID, &session.Status, &session.Capabilities, &session.CreatedAt, &session.UpdatedAt, &session.EndedAt) // Lock the session row together with its ownership metadata so authorization and lifecycle mutations serialize on the same record. - if err != nil { // Convert missing-row and query failures into the repository's session-not-found contract. - return nil, errors.Wrap(errors.CodeSessionNotFound, "session not found", err) // Preserve the wrapped database error while keeping the existing caller-facing code path stable. + if stdErrors.Is(err, pgx.ErrNoRows) { // Map only an authoritative empty locked query to session-not-found. + return nil, errors.Wrap(errors.CodeSessionNotFound, "session not found", err) // Preserve the no-row cause under the stable lookup code. + } + if err != nil { // Keep lock acquisition, connection, and scan failures distinct from absence. + return nil, errors.Wrap(errors.CodeStoreRead, "failed to lock session", err) // Surface infrastructure failures through the storage-read contract. } return session, nil // Return the locked session snapshot to the transactional caller. @@ -80,8 +85,11 @@ func (d *TxDAO) GetTraceForUpdate(ctx context.Context, id string) (*Trace, error WHERE id = $1 FOR UPDATE `, id).Scan(&trace.ID, &trace.SessionID, &trace.ProjectID, &trace.TenantID, &trace.SubjectID, &trace.Status, &trace.CurrentAttempt, &trace.TerminalReason, &trace.CreatedAt, &trace.UpdatedAt) // Lock the trace row together with its ownership metadata so authorization and attempt checks observe one serialized view. - if err != nil { // Convert missing-row and query failures into the repository's trace-not-found contract. - return nil, errors.Wrap(errors.CodeTraceNotFound, "trace not found", err) // Preserve the wrapped PostgreSQL failure while keeping the caller-facing code stable. + if stdErrors.Is(err, pgx.ErrNoRows) { // Map only an authoritative empty locked query to trace-not-found. + return nil, errors.Wrap(errors.CodeTraceNotFound, "trace not found", err) // Preserve the no-row cause under the stable lookup code. + } + if err != nil { // Keep lock acquisition, connection, and scan failures distinct from absence. + return nil, errors.Wrap(errors.CodeStoreRead, "failed to lock trace", err) // Surface infrastructure failures through the storage-read contract. } return trace, nil // Return the locked trace snapshot to the transactional caller. @@ -101,6 +109,32 @@ func (d *TxDAO) EndSessionIfActive(ctx context.Context, id string, endedAt time. return tag.RowsAffected() == 1, nil // Report whether this transaction performed the state transition. } +// MarkSessionEnding moves one locked non-terminal session into the cleanup-in-progress state and reports whether this call changed the row. +func (d *TxDAO) MarkSessionEnding(ctx context.Context, id string, updatedAt time.Time) (bool, error) { + tag, err := d.tx.Exec(ctx, ` + UPDATE sessions + SET status = 'ending', updated_at = $2 + WHERE id = $1 AND status NOT IN ('ending', 'ended') + `, id, updatedAt) // Block new session operations before external Appium and Device Farm cleanup begins. + if err != nil { // Surface storage failures before callers attempt any non-transactional resource cleanup. + return false, errors.Wrap(errors.CodeStoreWrite, "failed to mark session ending", err) // Preserve the PostgreSQL cause under the stable write-error contract. + } + return tag.RowsAffected() == 1, nil // Report whether this transaction performed the transition into cleanup-in-progress. +} + +// EndSessionIfEnding marks one locked cleanup-in-progress session as ended only after external resource cleanup has succeeded. +func (d *TxDAO) EndSessionIfEnding(ctx context.Context, id string, endedAt time.Time) (bool, error) { + tag, err := d.tx.Exec(ctx, ` + UPDATE sessions + SET status = 'ended', ended_at = $2, updated_at = $2 + WHERE id = $1 AND status = 'ending' + `, id, endedAt) // Commit the terminal lifecycle state only for a session whose cleanup phase was prepared explicitly. + if err != nil { // Surface storage failures so the caller can retry finalization without repeating successful cleanup unsafely. + return false, errors.Wrap(errors.CodeStoreWrite, "failed to complete session end", err) // Preserve the PostgreSQL cause under the stable write-error contract. + } + return tag.RowsAffected() == 1, nil // Report whether this transaction committed the ending-to-ended transition. +} + // InsertPlanEvent stores a plan event inside the caller's open transaction. func (d *TxDAO) InsertPlanEvent(ctx context.Context, e *PlanEvent) error { _, err := d.tx.Exec(ctx, ` @@ -216,7 +250,7 @@ func (d *DAO) MarkTraceAttemptRunning(ctx context.Context, id string, attempt in return tag.RowsAffected() == 1, nil // Report whether the reserved attempt still owned the trace and therefore entered the running state successfully. } -// AppendPlanEventForAttempt appends one ordered step event only when the supplied attempt still owns the running trace. +// AppendPlanEventForAttempt appends one ordered step event when the supplied attempt owns a reserved pending or running trace. func (d *DAO) AppendPlanEventForAttempt(ctx context.Context, id string, expectedAttempt int64, event *PlanEvent) (bool, error) { if event == nil { // Reject nil event payloads because distributed callbacks must persist concrete step metadata. return false, errors.New(errors.CodePlanInvalid, "plan event is required") // Surface the missing event explicitly so callback handlers do not succeed silently. @@ -228,7 +262,7 @@ func (d *DAO) AppendPlanEventForAttempt(ctx context.Context, id string, expected if err != nil { // Stop immediately when the trace row cannot be loaded or locked. return err // Preserve the trace lookup failure for the caller. } - if trace.Status != "running" || trace.CurrentAttempt != expectedAttempt { // Ignore stale or late worker callbacks once the trace is no longer owned by this running attempt. + if (trace.Status != "pending" && trace.Status != "running") || trace.CurrentAttempt != expectedAttempt { // Accept immediate worker callbacks across the pending-to-running acknowledgement boundary while rejecting every stale or terminal attempt. return nil // Treat stale callbacks as successful no-ops so higher layers can respond with a clean stale acknowledgement. } @@ -370,7 +404,7 @@ func (d *DAO) InsertAuditLog(ctx context.Context, log *AuditLog) error { _, err := d.pool.Exec(ctx, ` INSERT INTO audit_logs (id, project_id, session_id, trace_id, actor, action, resource_type, resource_id, payload, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) - `, log.ID, log.ProjectID, log.SessionID, log.TraceID, log.Actor, log.Action, log.ResourceType, log.ResourceID, log.Payload, log.CreatedAt) // Persist the append-only audit record in the shared audit table. + `, log.ID, log.ProjectID, nullableAuditReference(log.SessionID), nullableAuditReference(log.TraceID), log.Actor, log.Action, log.ResourceType, log.ResourceID, log.Payload, log.CreatedAt) // Persist optional foreign keys as SQL NULL instead of invalid empty-string references. if err != nil { // Return a wrapped storage error when the audit insert fails. return errors.Wrap(errors.CodeStoreWrite, "failed to insert audit log", err) // Preserve the underlying database failure for diagnostics. } @@ -383,10 +417,19 @@ func (d *TxDAO) InsertAuditLog(ctx context.Context, log *AuditLog) error { _, err := d.tx.Exec(ctx, ` INSERT INTO audit_logs (id, project_id, session_id, trace_id, actor, action, resource_type, resource_id, payload, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) - `, log.ID, log.ProjectID, log.SessionID, log.TraceID, log.Actor, log.Action, log.ResourceType, log.ResourceID, log.Payload, log.CreatedAt) // Persist the audit record atomically with the caller's surrounding transaction. + `, log.ID, log.ProjectID, nullableAuditReference(log.SessionID), nullableAuditReference(log.TraceID), log.Actor, log.Action, log.ResourceType, log.ResourceID, log.Payload, log.CreatedAt) // Persist optional foreign keys as SQL NULL instead of invalid empty-string references. if err != nil { // Convert raw PostgreSQL failures into the repository's write-error contract. return errors.Wrap(errors.CodeStoreWrite, "failed to insert audit log", err) // Preserve the database failure while returning the standard storage write code. } return nil // Return success after the audit insert has been staged inside the current transaction. } + +// nullableAuditReference converts an optional audit foreign-key identifier into nil for SQL NULL or a normalized non-empty string. +func nullableAuditReference(value string) interface{} { + normalizedValue := strings.TrimSpace(value) // Normalize optional identifiers before deciding whether a real foreign key exists. + if normalizedValue == "" { // Store absent session and trace references as SQL NULL. + return nil // Avoid foreign-key failures against the invalid empty-string identifier. + } + return normalizedValue // Preserve the concrete normalized foreign-key identifier when supplied. +} diff --git a/internal/storage/postgres/dao.go b/internal/storage/postgres/dao.go index a4e9790..6fe1868 100644 --- a/internal/storage/postgres/dao.go +++ b/internal/storage/postgres/dao.go @@ -2,11 +2,13 @@ package postgres import ( "context" + stdErrors "errors" "time" "mcp_for_appium/internal/config" "mcp_for_appium/internal/errors" + "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) @@ -69,8 +71,11 @@ func (d *DAO) GetSession(ctx context.Context, id string) (*Session, error) { SELECT id, project_id, tenant_id, subject_id, status, capabilities, created_at, updated_at, ended_at FROM sessions WHERE id = $1 `, id).Scan(&s.ID, &s.ProjectID, &s.TenantID, &s.SubjectID, &s.Status, &s.Capabilities, &s.CreatedAt, &s.UpdatedAt, &s.EndedAt) // Load the persisted ownership metadata together with the session lifecycle fields so callers can authorize access. - if err != nil { - return nil, errors.Wrap(errors.CodeSessionNotFound, "session not found", err) + if stdErrors.Is(err, pgx.ErrNoRows) { // Map only an authoritative empty result to the public session-not-found contract. + return nil, errors.Wrap(errors.CodeSessionNotFound, "session not found", err) // Preserve the no-row cause for server logs under the stable lookup code. + } + if err != nil { // Keep connection, decoding, and PostgreSQL execution failures distinct from absence. + return nil, errors.Wrap(errors.CodeStoreRead, "failed to read session", err) // Surface infrastructure failures through the retryable storage-read contract. } return s, nil } @@ -96,6 +101,37 @@ func (d *DAO) CreateTrace(ctx context.Context, t *Trace) error { return err // Return the raw insert result so higher layers preserve the existing repository error contract. } +// CreateOrRearmQueuedTrace inserts a new pending trace or atomically rearms the same owned trace after a confirmed queue-enqueue failure. +func (d *DAO) CreateOrRearmQueuedTrace(ctx context.Context, t *Trace) error { + var preparedTraceID string // Hold the row returned only when PostgreSQL inserted or safely rearmed the requested trace. + err := d.pool.QueryRow(ctx, ` + WITH prepared AS ( + INSERT INTO traces (id, session_id, project_id, tenant_id, subject_id, status, current_attempt, terminal_reason, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, 'pending', 0, NULL, $6, $7) + ON CONFLICT (id) DO UPDATE + SET status = 'pending', current_attempt = 0, terminal_reason = NULL, updated_at = EXCLUDED.updated_at + WHERE traces.status = 'failed' + AND traces.terminal_reason = 'queue_enqueue_failed' + AND traces.session_id = EXCLUDED.session_id + AND traces.project_id = EXCLUDED.project_id + AND traces.tenant_id IS NOT DISTINCT FROM EXCLUDED.tenant_id + AND traces.subject_id IS NOT DISTINCT FROM EXCLUDED.subject_id + RETURNING id + ), cleared AS ( + DELETE FROM plan_events WHERE trace_id IN (SELECT id FROM prepared) + RETURNING trace_id + ) + SELECT id FROM prepared + `, t.ID, t.SessionID, t.ProjectID, t.TenantID, t.SubjectID, t.CreatedAt, t.UpdatedAt).Scan(&preparedTraceID) // Insert or rearm and clear the prior enqueue-failure marker inside one PostgreSQL statement. + if stdErrors.Is(err, pgx.ErrNoRows) { // Treat a conflicting active, terminal, differently owned, or differently scoped trace as an idempotency conflict. + return errors.New(errors.CodeStateConflict, "trace id is already in use") // Reject unsafe trace reuse without exposing the existing row's ownership or lifecycle. + } + if err != nil { // Wrap genuine query and write failures separately from the expected conflict path. + return errors.Wrap(errors.CodeStoreWrite, "failed to create or rearm queued trace", err) // Preserve the PostgreSQL cause for server logs under a stable storage code. + } + return nil // Confirm that the trace is pending with no stale enqueue-failure event before Redis enqueue begins. +} + // GetTrace executes this operation. func (d *DAO) GetTrace(ctx context.Context, id string) (*Trace, error) { t := &Trace{} // Allocate the destination trace model before scanning the persisted lifecycle and attempt state. @@ -103,8 +139,11 @@ func (d *DAO) GetTrace(ctx context.Context, id string) (*Trace, error) { SELECT id, session_id, project_id, tenant_id, subject_id, status, current_attempt, terminal_reason, created_at, updated_at FROM traces WHERE id = $1 `, id).Scan(&t.ID, &t.SessionID, &t.ProjectID, &t.TenantID, &t.SubjectID, &t.Status, &t.CurrentAttempt, &t.TerminalReason, &t.CreatedAt, &t.UpdatedAt) // Load the persisted trace state, ownership metadata, current attempt, and terminal reason in one query for callers. - if err != nil { // Preserve the existing trace-not-found contract when PostgreSQL cannot return the requested row. - return nil, errors.Wrap(errors.CodeTraceNotFound, "trace not found", err) // Wrap lookup failures with the stable trace-not-found code used by gateway transports. + if stdErrors.Is(err, pgx.ErrNoRows) { // Map only an authoritative empty result to the public trace-not-found contract. + return nil, errors.Wrap(errors.CodeTraceNotFound, "trace not found", err) // Preserve the no-row cause for server logs under the stable lookup code. + } + if err != nil { // Keep connection, decoding, and PostgreSQL execution failures distinct from absence. + return nil, errors.Wrap(errors.CodeStoreRead, "failed to read trace", err) // Surface infrastructure failures through the retryable storage-read contract. } return t, nil // Return the fully populated trace model once the database scan succeeds. } @@ -140,7 +179,7 @@ func (d *DAO) ListEvents(ctx context.Context, traceID string, sinceSeq int64, li LIMIT $3 `, traceID, sinceSeq, limit) if err != nil { - return nil, err + return nil, errors.Wrap(errors.CodeStoreRead, "failed to list plan events", err) // Classify query startup failures as storage reads rather than leaking raw driver errors. } defer rows.Close() @@ -148,10 +187,13 @@ func (d *DAO) ListEvents(ctx context.Context, traceID string, sinceSeq int64, li for rows.Next() { e := &PlanEvent{} if err := rows.Scan(&e.TraceID, &e.Seq, &e.StepIndex, &e.Status, &e.Payload, &e.CreatedAt); err != nil { - return nil, err + return nil, errors.Wrap(errors.CodeStoreRead, "failed to scan plan event", err) // Preserve row decoding failures through the stable storage-read contract. } events = append(events, e) } + if err := rows.Err(); err != nil { // Detect connection and protocol failures that occur after iteration begins. + return nil, errors.Wrap(errors.CodeStoreRead, "failed while iterating plan events", err) // Refuse to return a silently truncated event history. + } return events, nil } @@ -179,7 +221,7 @@ func (d *DAO) ListArtifacts(ctx context.Context, traceID string) ([]*Artifact, e ORDER BY created_at ASC `, traceID) if err != nil { - return nil, err + return nil, errors.Wrap(errors.CodeStoreRead, "failed to list artifacts", err) // Classify query startup failures as storage reads rather than leaking raw driver errors. } defer rows.Close() @@ -187,9 +229,12 @@ func (d *DAO) ListArtifacts(ctx context.Context, traceID string) ([]*Artifact, e for rows.Next() { a := &Artifact{} if err := rows.Scan(&a.ID, &a.TraceID, &a.Key, &a.Type, &a.Size, &a.CreatedAt, &a.Metadata); err != nil { - return nil, err + return nil, errors.Wrap(errors.CodeStoreRead, "failed to scan artifact", err) // Preserve row decoding failures through the stable storage-read contract. } artifacts = append(artifacts, a) } + if err := rows.Err(); err != nil { // Detect connection and protocol failures that occur after iteration begins. + return nil, errors.Wrap(errors.CodeStoreRead, "failed while iterating artifacts", err) // Refuse to return a silently truncated artifact list. + } return artifacts, nil } diff --git a/internal/storage/redis/cache.go b/internal/storage/redis/cache.go index 923041a..e8d23a9 100644 --- a/internal/storage/redis/cache.go +++ b/internal/storage/redis/cache.go @@ -247,6 +247,38 @@ func (c *Cache) SetNX(ctx context.Context, key string, value interface{}, ttl ti return c.client.SetNX(ctx, key, value, ttl).Result() } +// CompareAndSet replaces one key and refreshes its TTL only when the current string value exactly matches the expected ownership token. +func (c *Cache) CompareAndSet(ctx context.Context, key string, expectedValue string, nextValue string, ttl time.Duration) (bool, error) { + script := ` + if redis.call("GET", KEYS[1]) ~= ARGV[1] then + return 0 + end + redis.call("SET", KEYS[1], ARGV[2], "PX", ARGV[3]) + return 1 + ` // Compare and replace inside one Redis script so ownership cannot change between read and write. + result, err := c.client.Eval(ctx, script, []string{key}, expectedValue, nextValue, ttl.Milliseconds()).Int() // Execute the atomic ownership update with a refreshed millisecond TTL. + if err != nil { // Surface Redis script or connectivity failures to the lease owner. + return false, err // Preserve the raw cache error for repository-level wrapping by the caller. + } + return result == 1, nil // Report whether the expected value still owned the key and was replaced. +} + +// CompareAndDelete deletes one key only when its current string value exactly matches the expected ownership token. +func (c *Cache) CompareAndDelete(ctx context.Context, key string, expectedValue string) (bool, error) { + script := ` + if redis.call("GET", KEYS[1]) ~= ARGV[1] then + return 0 + end + redis.call("DEL", KEYS[1]) + return 1 + ` // Compare and delete inside one Redis script so stale cleanup cannot remove a newer owner's value. + result, err := c.client.Eval(ctx, script, []string{key}, expectedValue).Int() // Execute the atomic ownership-guarded deletion. + if err != nil { // Surface Redis script or connectivity failures to the cleanup caller. + return false, err // Preserve the raw cache error for repository-level wrapping by the caller. + } + return result == 1, nil // Report whether this exact ownership value was removed. +} + // Del deletes one or more keys. func (c *Cache) Del(ctx context.Context, keys ...string) error { return c.client.Del(ctx, keys...).Err() diff --git a/internal/storage/redis/cache_test.go b/internal/storage/redis/cache_test.go new file mode 100644 index 0000000..b7071eb --- /dev/null +++ b/internal/storage/redis/cache_test.go @@ -0,0 +1,62 @@ +// cache_test.go verifies atomic Redis ownership primitives used by distributed dispatch locks and execution leases. +package redis + +import ( + "context" + stdErrors "errors" + "testing" + "time" + + "mcp_for_appium/internal/config" + + "github.com/alicebob/miniredis/v2" + goredis "github.com/redis/go-redis/v9" +) + +// TestCompareAndSetAndDeletePreserveOwnership verifies that stale values cannot replace or remove a newer Redis owner. +func TestCompareAndSetAndDeletePreserveOwnership(t *testing.T) { + redisServer := miniredis.RunT(t) // Start one disposable Redis-compatible server for real Lua-script behavior. + cache, err := NewCache(config.RedisConfig{Addr: redisServer.Addr()}) // Construct the production cache wrapper against the isolated server. + if err != nil { // Stop when the cache wrapper cannot connect to the fixture. + t.Fatalf("failed to construct redis cache: %v", err) // Surface fixture setup failure explicitly. + } + defer func() { // Release both the production client and disposable server after all ownership assertions. + _ = cache.Close() // Close pooled Redis connections before stopping their endpoint. + redisServer.Close() // Release the loopback listener owned by miniredis. + }() + ctx := context.Background() // Use one synchronous context for the short ownership script calls. + if err := cache.Set(ctx, "lease:test", "owner-1", time.Minute); err != nil { // Seed the first exact lease owner. + t.Fatalf("failed to seed redis owner: %v", err) // Surface setup failure because comparison assertions require the key. + } + + replaced, err := cache.CompareAndSet(ctx, "lease:test", "stale-owner", "owner-2", time.Minute) // Attempt replacement with a stale expected value. + if err != nil { // Fail when a normal compare mismatch returns an infrastructure error. + t.Fatalf("stale compare-and-set returned error: %v", err) // Surface unexpected Lua execution failure. + } + if replaced { // Reject stale ownership replacement. + t.Fatal("expected stale compare-and-set not to replace current owner") // Surface lost lease isolation. + } + value, err := cache.Get(ctx, "lease:test") // Read the value after the rejected stale replacement. + if err != nil || value != "owner-1" { // Require the original owner to remain unchanged. + t.Fatalf("expected owner-1 after stale replacement, got %q with error %v", value, err) // Surface unexpected value mutation. + } + + replaced, err = cache.CompareAndSet(ctx, "lease:test", "owner-1", "owner-2", time.Minute) // Replace through the current exact owner. + if err != nil || !replaced { // Require the matching owner to update atomically. + t.Fatalf("expected matching compare-and-set to succeed, replaced=%v error=%v", replaced, err) // Surface script or comparison regression. + } + removed, err := cache.CompareAndDelete(ctx, "lease:test", "owner-1") // Attempt cleanup with the now-stale former owner. + if err != nil { // Fail when a normal compare mismatch returns an infrastructure error. + t.Fatalf("stale compare-and-delete returned error: %v", err) // Surface unexpected Lua execution failure. + } + if removed { // Reject stale cleanup that would delete the successor's lease. + t.Fatal("expected stale compare-and-delete not to remove current owner") // Surface unsafe ownership cleanup. + } + removed, err = cache.CompareAndDelete(ctx, "lease:test", "owner-2") // Delete through the current exact owner. + if err != nil || !removed { // Require matching ownership cleanup to succeed atomically. + t.Fatalf("expected matching compare-and-delete to succeed, removed=%v error=%v", removed, err) // Surface script or comparison regression. + } + if _, err := cache.Get(ctx, "lease:test"); !stdErrors.Is(err, goredis.Nil) { // Require the key to be absent after matching cleanup. + t.Fatalf("expected lease key to be deleted, got error %v", err) // Surface leaked ownership state. + } +} diff --git a/internal/telemetry/logging.go b/internal/telemetry/logging.go index 2c06cd8..91f953f 100644 --- a/internal/telemetry/logging.go +++ b/internal/telemetry/logging.go @@ -21,13 +21,18 @@ var logWriterMu sync.Mutex // init executes this operation. func init() { // Default to text handler for dev, can be changed to JSON - defaultLogger = slog.New(slog.NewJSONHandler(os.Stdout, nil)) // Keep stdout logging by default before config is loaded. - slog.SetDefault(defaultLogger) // Register the default logger globally. - stdLogWriter = os.Stderr // Route standard-library log package output to stderr by default. + defaultLogger = slog.New(slog.NewJSONHandler(os.Stderr, nil)) // Keep pre-configuration logs off stdout so stdio protocol frames cannot be corrupted. + slog.SetDefault(defaultLogger) // Register the default logger globally. + stdLogWriter = os.Stderr // Route standard-library log package output to stderr by default. } // InitLogger initializes the global logger with the specified level and format. func InitLogger(level string, logFilePath string) { + InitLoggerWithConsole(level, logFilePath, os.Stdout) // Preserve console logging on stdout for ordinary HTTP and worker processes. +} + +// InitLoggerWithConsole initializes structured logging with an explicit console destination so stdio processes can reserve stdout for protocol frames. +func InitLoggerWithConsole(level string, logFilePath string, console io.Writer) { var l slog.Level switch level { case "debug": @@ -40,11 +45,14 @@ func InitLogger(level string, logFilePath string) { l = slog.LevelInfo // Default to info-level output. } - writer := io.Writer(os.Stdout) // Always keep console output for local troubleshooting. - stdWriter := io.Writer(os.Stderr) // Keep standard log package bound to stderr for stdio safety. + if console == nil { // Fall back safely when a caller omits the explicit console destination. + console = os.Stderr // Keep logs observable without risking an implicit write to protocol stdout. + } + writer := console // Keep structured console output on the caller-selected safe stream. + stdWriter := io.Writer(os.Stderr) // Keep standard log package bound to stderr for stdio safety. if resolvedFileWriter, err := buildLogFileWriter(logFilePath); err == nil && resolvedFileWriter != nil { // Attempt file logging only when configured and creatable. - writer = io.MultiWriter(os.Stdout, resolvedFileWriter) // Mirror structured logs to both stdout and file. - stdWriter = io.MultiWriter(os.Stderr, resolvedFileWriter) // Mirror stdlib logs to both stderr and file. + writer = io.MultiWriter(console, resolvedFileWriter) // Mirror structured logs to the explicit console destination and file. + stdWriter = io.MultiWriter(os.Stderr, resolvedFileWriter) // Mirror stdlib logs to both stderr and file. } opts := &slog.HandlerOptions{ @@ -54,6 +62,11 @@ func InitLogger(level string, logFilePath string) { if a.Value.Kind() == slog.KindString { a.Value = slog.StringValue(util.MaskSecrets(a.Value.String())) // Redact common secret patterns before writing logs. } + if a.Value.Kind() == slog.KindAny { // Inspect error-valued attributes because slog otherwise serializes them without string masking. + if errorValue, ok := a.Value.Any().(error); ok { // Limit conversion to errors so structured non-error attributes retain their original type. + a.Value = slog.StringValue(util.MaskSecrets(errorValue.Error())) // Redact secrets embedded in wrapped downstream error messages before emission. + } + } return a // Return transformed attribute for final emission. }, } @@ -79,7 +92,7 @@ func WithContext(ctx context.Context) *slog.Logger { } return defaultLogger.With( "trace_id", sc.TraceID().String(), // Attach trace id for request-level correlation. - "span_id", sc.SpanID().String(), // Attach span id for operation-level correlation. + "span_id", sc.SpanID().String(), // Attach span id for operation-level correlation. ) // Return enriched logger with tracing metadata. } @@ -99,23 +112,23 @@ func setStdLogWriter(w io.Writer) { // buildLogFileWriter executes this operation. func buildLogFileWriter(logFilePath string) (io.Writer, error) { - trimmedPath := filepath.Clean(logFilePath) // Normalize configured path before filesystem operations. + trimmedPath := filepath.Clean(logFilePath) // Normalize configured path before filesystem operations. if trimmedPath == "." || trimmedPath == "" { // Treat empty configuration as no file logging. return nil, nil // Skip file writer creation when path is not configured. } - logWriterMu.Lock() // Serialize file handle updates. + logWriterMu.Lock() // Serialize file handle updates. defer logWriterMu.Unlock() // Ensure lock release on every return path. - if logFileHandle != nil { // Close previous file handle before reconfiguring to avoid descriptor leaks. + if logFileHandle != nil { // Close previous file handle before reconfiguring to avoid descriptor leaks. _ = logFileHandle.Close() // Best-effort close; new handle creation result determines next writer state. - logFileHandle = nil // Clear stale handle regardless of close result. + logFileHandle = nil // Clear stale handle regardless of close result. } if err := os.MkdirAll(filepath.Dir(trimmedPath), 0o755); err != nil { // Ensure parent directory exists for log file. return nil, err // Propagate directory creation errors to caller. } f, err := os.OpenFile(trimmedPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) // Open file in append mode to preserve history. - if err != nil { // Handle open failure without breaking process startup. + if err != nil { // Handle open failure without breaking process startup. return nil, err // Return error so caller can keep console-only logging. } logFileHandle = f // Retain handle for future reconfiguration close. - return f, nil // Return file writer for multi-writer composition. + return f, nil // Return file writer for multi-writer composition. } diff --git a/internal/telemetry/telemetry_test.go b/internal/telemetry/telemetry_test.go index 9d90759..a8ca35d 100644 --- a/internal/telemetry/telemetry_test.go +++ b/internal/telemetry/telemetry_test.go @@ -63,6 +63,16 @@ func TestInitLoggerMasksSecrets(t *testing.T) { } } +// TestInitLoggerWithConsoleUsesExplicitDestination verifies that stdio callers can keep every structured log record off protocol stdout. +func TestInitLoggerWithConsoleUsesExplicitDestination(t *testing.T) { + var console bytes.Buffer // Capture the explicit console stream selected by a stdio-style caller. + InitLoggerWithConsole("info", "", &console) // Configure structured logging with no file sink and the isolated console destination. + Logger().Info("stdio-safe-log", "transport", "stdio") // Emit one representative structured startup record through the global logger. + if !bytes.Contains(console.Bytes(), []byte("stdio-safe-log")) { // Require the record to reach the explicit destination instead of an implicit stdout writer. + t.Fatalf("expected structured log in explicit console, got %s", console.String()) // Surface the captured output when destination routing regresses. + } +} + // TestWithContextAttachesTraceIdentifiers verifies that loggers derived from a traced context emit trace and span identifiers. func TestWithContextAttachesTraceIdentifiers(t *testing.T) { logPath := filepath.Join(t.TempDir(), "trace.log") // Build one isolated log-file path so the production logger can write a deterministic traced record. diff --git a/internal/worker/appium/client.go b/internal/worker/appium/client.go index 5dba76e..29e434d 100644 --- a/internal/worker/appium/client.go +++ b/internal/worker/appium/client.go @@ -63,9 +63,9 @@ func NewClient(url string) *Client { func (c *Client) StartSession(ctx context.Context, caps map[string]interface{}) (string, error) { // Apply a bounded default timeout for session creation when the upstream caller omitted a deadline. if _, hasDeadline := ctx.Deadline(); !hasDeadline { // Respect explicit caller deadlines when they are already set. - var cancel context.CancelFunc // Keep cancel handle to release timer resources. - ctx, cancel = context.WithTimeout(ctx, defaultStartSessionTimeout) // Bound Appium session bootstrap duration. - defer cancel() // Ensure timer/context resources are always released. + var cancel context.CancelFunc // Keep cancel handle to release timer resources. + ctx, cancel = context.WithTimeout(ctx, defaultStartSessionTimeout) // Bound Appium session bootstrap duration. + defer cancel() // Ensure timer/context resources are always released. } payload := map[string]interface{}{ @@ -379,8 +379,8 @@ func (c *Client) HideKeyboard(ctx context.Context) error { // do executes this operation. func (c *Client) do(ctx context.Context, method, path string, body interface{}, result interface{}) error { - logger := telemetry.WithContext(ctx) // Build context-enriched logger for per-request step tracing. - startedAt := time.Now() // Capture overall call start for end-to-end duration reporting. + logger := telemetry.WithContext(ctx) // Build context-enriched logger for per-request step tracing. + startedAt := time.Now() // Capture overall call start for end-to-end duration reporting. logger.Info("appium request begin", "method", method, "path", path, "base_url", c.baseURL) // Log Appium call entry. if err := c.checkBreaker(); err != nil { @@ -422,7 +422,11 @@ func (c *Client) do(ctx context.Context, method, path string, body interface{}, if err != nil { lastErr = c.mapTransportError(err) logger.Error("appium request transport error", "method", method, "path", path, "attempt", attempt, "attempt_duration_ms", time.Since(start).Milliseconds(), "error", lastErr) // Log transport-layer failure per attempt. - if c.shouldRetry(nil, err, attempt) { + if c.shouldRetry(method, path, nil, err, attempt) { // Retry only explicitly safe Appium requests after a retryable transport failure. + if backoffErr := c.backoff(ctx, attempt); backoffErr != nil { // Stop retry scheduling when the caller context is cancelled or expires. + c.noteFailure() // Record the interrupted request as a terminal failure for circuit-breaker accounting. + return c.mapTransportError(backoffErr) // Preserve the context-driven transport failure through the standard Appium error mapping. + } logger.Info("appium request retry", "method", method, "path", path, "attempt", attempt) // Log retry scheduling to reconstruct retry behavior. continue } @@ -436,7 +440,11 @@ func (c *Client) do(ctx context.Context, method, path string, body interface{}, if readErr != nil { lastErr = errors.Wrap(errors.CodeInternal, "failed to read response body", readErr) logger.Error("appium response read failed", "method", method, "path", path, "attempt", attempt, "status_code", resp.StatusCode, "error", lastErr) // Log body-read errors for diagnostics. - if c.shouldRetry(resp, readErr, attempt) { + if c.shouldRetry(method, path, resp, readErr, attempt) { // Retry response-read failures only for explicitly safe Appium requests. + if backoffErr := c.backoff(ctx, attempt); backoffErr != nil { // Stop retry scheduling when the caller context is cancelled or expires. + c.noteFailure() // Record the interrupted request as a terminal failure for circuit-breaker accounting. + return c.mapTransportError(backoffErr) // Preserve the context-driven transport failure through the standard Appium error mapping. + } logger.Info("appium request retry", "method", method, "path", path, "attempt", attempt) // Log retry scheduling after read failures. continue } @@ -448,7 +456,11 @@ func (c *Client) do(ctx context.Context, method, path string, body interface{}, if resp.StatusCode >= 400 { lastErr = c.mapAppiumError(resp.StatusCode, b) logger.Error("appium response status error", "method", method, "path", path, "attempt", attempt, "status_code", resp.StatusCode, "error", lastErr) // Log HTTP status failures with mapped internal error. - if c.shouldRetry(resp, nil, attempt) { + if c.shouldRetry(method, path, resp, nil, attempt) { // Retry server-status failures only for explicitly safe Appium requests. + if backoffErr := c.backoff(ctx, attempt); backoffErr != nil { // Stop retry scheduling when the caller context is cancelled or expires. + c.noteFailure() // Record the interrupted request as a terminal failure for circuit-breaker accounting. + return c.mapTransportError(backoffErr) // Preserve the context-driven transport failure through the standard Appium error mapping. + } logger.Info("appium request retry", "method", method, "path", path, "attempt", attempt, "status_code", resp.StatusCode) // Log retry scheduling for retryable status errors. continue } @@ -461,7 +473,11 @@ func (c *Client) do(ctx context.Context, method, path string, body interface{}, if err := json.Unmarshal(b, result); err != nil { lastErr = errors.Wrap(errors.CodeInternal, "failed to decode response", err) logger.Error("appium response decode failed", "method", method, "path", path, "attempt", attempt, "error", lastErr) // Log JSON decode failures for payload diagnostics. - if c.shouldRetry(resp, err, attempt) { + if c.shouldRetry(method, path, resp, err, attempt) { // Retry response-decode failures only for explicitly safe Appium requests. + if backoffErr := c.backoff(ctx, attempt); backoffErr != nil { // Stop retry scheduling when the caller context is cancelled or expires. + c.noteFailure() // Record the interrupted request as a terminal failure for circuit-breaker accounting. + return c.mapTransportError(backoffErr) // Preserve the context-driven transport failure through the standard Appium error mapping. + } logger.Info("appium request retry", "method", method, "path", path, "attempt", attempt) // Log retry scheduling for decode errors. continue } @@ -540,18 +556,19 @@ func (c *Client) mapAppiumError(status int, body []byte) error { return errors.New(errors.CodeInternal, fmt.Sprintf("appium error %d: %s", status, msg)) } -// shouldRetry executes this operation. -func (c *Client) shouldRetry(resp *http.Response, err error, attempt int) bool { +// shouldRetry reports whether an explicitly idempotent or read-only Appium request may be repeated after the supplied failure. +func (c *Client) shouldRetry(method string, path string, resp *http.Response, err error, attempt int) bool { if attempt >= c.maxRetries { return false } + if !retrySafeRequest(method, path) { // Refuse automatic retries for session creation, clicks, text entry, gestures, navigation, and deletion. + return false // Prevent duplicate user-visible side effects after an ambiguous response or transport failure. + } if err != nil { if stdErrors.Is(err, syscall.ECONNRESET) || stdErrors.Is(err, syscall.EPIPE) || stdErrors.Is(err, io.EOF) { - c.backoff(attempt) return true } if nerr, ok := err.(net.Error); ok && nerr.Temporary() { - c.backoff(attempt) return true } return false @@ -560,14 +577,25 @@ func (c *Client) shouldRetry(resp *http.Response, err error, attempt int) bool { return false } if resp.StatusCode >= 500 && resp.StatusCode <= 599 { - c.backoff(attempt) return true } return false } -// backoff executes this operation. -func (c *Client) backoff(attempt int) { +// retrySafeRequest reports whether repeating one Appium command cannot duplicate a user-visible state mutation. +func retrySafeRequest(method string, path string) bool { + switch method { // Classify ordinary HTTP methods first because every Appium read endpoint uses one of these safe methods. + case http.MethodGet, http.MethodHead, http.MethodOptions: + return true // Permit automatic retries for protocol-defined idempotent reads and metadata requests. + case http.MethodPost: + return strings.HasSuffix(path, "/element") || strings.HasSuffix(path, "/elements") // Permit element lookup POSTs because repeating a lookup does not mutate the device application state. + default: + return false // Reject retries for DELETE and every unknown method to avoid ambiguous cleanup or mutation outcomes. + } +} + +// backoff waits for one bounded exponential retry delay and returns promptly when the request context is cancelled. +func (c *Client) backoff(ctx context.Context, attempt int) error { delay := c.minRetryDelay for i := 0; i < attempt; i++ { delay *= 2 @@ -576,7 +604,14 @@ func (c *Client) backoff(attempt int) { break } } - time.Sleep(delay) + timer := time.NewTimer(delay) // Allocate a stoppable timer so cancelled requests do not sleep through the retry delay. + defer timer.Stop() // Release timer resources promptly on every return path. + select { // Race the retry delay against caller cancellation or deadline expiration. + case <-ctx.Done(): + return ctx.Err() // Preserve the exact request-context error for standard Appium transport mapping. + case <-timer.C: + return nil // Permit the next safe request attempt once the bounded delay elapses. + } } // checkBreaker executes this operation. diff --git a/internal/worker/appium/client_test.go b/internal/worker/appium/client_test.go index 36c31ec..986e820 100644 --- a/internal/worker/appium/client_test.go +++ b/internal/worker/appium/client_test.go @@ -428,6 +428,27 @@ func TestRetryOn5xx(t *testing.T) { } } +// TestNonIdempotentCommandDoesNotRetry verifies that an ambiguous Appium failure cannot duplicate a device-side click action. +func TestNonIdempotentCommandDoesNotRetry(t *testing.T) { + attempts := 0 // Count received click commands so the test can prove the client sends only one mutation. + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { // Return one retryable-looking server error for every received command. + attempts++ // Record each network attempt made by the Appium client. + w.WriteHeader(http.StatusInternalServerError) // Simulate an ambiguous 500 response after the server may have processed the click. + _ = json.NewEncoder(w).Encode(map[string]interface{}{"value": map[string]interface{}{"error": "internal error", "message": "ambiguous failure"}}) // Return a valid Appium error envelope. + })) + defer server.Close() // Release the loopback test server after the retry assertion completes. + + client := NewClient(server.URL) // Construct the production client against the failing Appium endpoint. + client.sessionID = "test-session" // Attach one session directly so the click command can be issued without session setup. + client.maxRetries = 2 // Leave retries enabled to prove policy, rather than configuration, suppresses mutation retries. + if err := client.Click(context.Background(), "element-1"); err == nil { // Execute one non-idempotent click that receives the ambiguous server error. + t.Fatal("expected click failure") // Require the server failure to reach the caller after the single request. + } + if attempts != 1 { // Reject any duplicate click command regardless of the configured retry count. + t.Fatalf("expected one non-idempotent request, got %d", attempts) // Surface unsafe retry regressions directly. + } +} + // TestCircuitBreaker tests circuit breaker functionality func TestCircuitBreaker(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/worker/executor.go b/internal/worker/executor.go index 67788bc..ff6dffa 100644 --- a/internal/worker/executor.go +++ b/internal/worker/executor.go @@ -101,16 +101,24 @@ func (e *Executor) Execute(ctx context.Context, plan []PlanStep) error { return err } case "wait": - waitMs := 1000 + waitMs := int64(1000) // Use a signed 64-bit millisecond value so JSON decoding and duration validation remain explicit. if len(step.Params) > 0 { var params struct { - Ms int `json:"ms"` + Ms int64 `json:"ms"` } if err := json.Unmarshal(step.Params, ¶ms); err == nil && params.Ms > 0 { waitMs = params.Ms } } - time.Sleep(time.Duration(waitMs) * time.Millisecond) + if waitMs > int64(time.Duration(1<<63-1)/time.Millisecond) { // Reject millisecond values that would overflow time.Duration during conversion. + err := errors.New(errors.CodePlanInvalid, "wait params.ms is too large") // Return a stable validation error instead of wrapping into a negative duration. + e.emitFailure(stepCtx, i, err, start) // Emit the same terminal step event produced by other invalid step payloads. + return err // Stop this step before creating an invalid timer. + } + if err := waitForContext(stepCtx, time.Duration(waitMs)*time.Millisecond); err != nil { // Wait only until the duration, step timeout, or caller cancellation wins. + e.emitFailure(stepCtx, i, err, start) // Emit a failed step event so trace replay records the interrupted wait. + return err // Propagate cancellation or deadline expiration to stop the remaining plan. + } e.emitSuccess(i, "wait completed", start, StepMetrics{Attempt: 1}) case "sendKeys": if err := e.executeSendKeys(stepCtx, i, step, start); err != nil { @@ -175,7 +183,9 @@ func (e *Executor) executeClick(ctx context.Context, stepIndex int, step PlanSte if !e.isTransient(err) { return err } - e.backoff(attempt) + if err := e.backoff(ctx, attempt); err != nil { // Abort retry delay immediately when the step context is cancelled or expires. + return err // Preserve the context cancellation so the plan stops instead of starting another Appium attempt. + } continue } @@ -184,7 +194,9 @@ func (e *Executor) executeClick(ctx context.Context, stepIndex int, step PlanSte if !e.isTransient(err) { return err } - e.backoff(attempt) + if err := e.backoff(ctx, attempt); err != nil { // Abort retry delay immediately when the step context is cancelled or expires. + return err // Preserve the context cancellation so the plan stops instead of starting another Appium attempt. + } continue } @@ -207,7 +219,9 @@ func (e *Executor) executeClear(ctx context.Context, stepIndex int, step PlanSte if !e.isTransient(err) { return err } - e.backoff(attempt) + if err := e.backoff(ctx, attempt); err != nil { // Abort retry delay immediately when the step context is cancelled or expires. + return err // Preserve the context cancellation so the plan stops instead of starting another Appium attempt. + } continue } @@ -216,7 +230,9 @@ func (e *Executor) executeClear(ctx context.Context, stepIndex int, step PlanSte if !e.isTransient(err) { return err } - e.backoff(attempt) + if err := e.backoff(ctx, attempt); err != nil { // Abort retry delay immediately when the step context is cancelled or expires. + return err // Preserve the context cancellation so the plan stops instead of starting another Appium attempt. + } continue } @@ -246,7 +262,9 @@ func (e *Executor) executeSendKeys(ctx context.Context, stepIndex int, step Plan if !e.isTransient(err) { return err } - e.backoff(attempt) + if err := e.backoff(ctx, attempt); err != nil { // Abort retry delay immediately when the step context is cancelled or expires. + return err // Preserve the context cancellation so the plan stops instead of starting another Appium attempt. + } continue } @@ -255,7 +273,9 @@ func (e *Executor) executeSendKeys(ctx context.Context, stepIndex int, step Plan if !e.isTransient(err) { return err } - e.backoff(attempt) + if err := e.backoff(ctx, attempt); err != nil { // Abort retry delay immediately when the step context is cancelled or expires. + return err // Preserve the context cancellation so the plan stops instead of starting another Appium attempt. + } continue } @@ -328,7 +348,9 @@ func (e *Executor) executeLongPress(ctx context.Context, stepIndex int, step Pla if !e.isTransient(err) { return err } - e.backoff(attempt) + if err := e.backoff(ctx, attempt); err != nil { // Abort retry delay immediately when the step context is cancelled or expires. + return err // Preserve the context cancellation so the plan stops instead of starting another Appium attempt. + } continue } @@ -337,7 +359,9 @@ func (e *Executor) executeLongPress(ctx context.Context, stepIndex int, step Pla if !e.isTransient(err) { return err } - e.backoff(attempt) + if err := e.backoff(ctx, attempt); err != nil { // Abort retry delay immediately when the step context is cancelled or expires. + return err // Preserve the context cancellation so the plan stops instead of starting another Appium attempt. + } continue } @@ -462,16 +486,33 @@ func (e *Executor) isTransient(err error) bool { return errors.IsCode(err, errors.CodeAppTimeout) || errors.IsCode(err, errors.CodeStoreConn) || errors.IsCode(err, errors.CodeAppElemNotFound) } -// backoff executes this operation. -func (e *Executor) backoff(attempt int) { +// backoff waits for one randomized retry delay and returns immediately when the supplied step context is cancelled. +func (e *Executor) backoff(ctx context.Context, attempt int) error { if attempt <= 0 { - return + return nil // Skip invalid or pre-attempt retry delays without creating a timer. } jitterRange := int64(e.retryMaxJitter - e.retryMinJitter) if jitterRange <= 0 { - time.Sleep(e.retryMinJitter) - return + return waitForContext(ctx, e.retryMinJitter) // Apply the fixed minimum delay while remaining responsive to cancellation. } jitter := e.retryMinJitter + time.Duration(rand.Int63n(jitterRange)) - time.Sleep(jitter) + return waitForContext(ctx, jitter) // Apply the selected jitter duration while remaining responsive to cancellation. +} + +// waitForContext waits for one duration and returns the context error when cancellation or a deadline wins first. +func waitForContext(ctx context.Context, duration time.Duration) error { + if err := ctx.Err(); err != nil { // Check already-cancelled contexts before allocating a timer. + return err // Preserve the caller's exact cancellation or deadline error. + } + if duration <= 0 { // Treat zero or negative delays as an immediate successful wait. + return nil // Avoid allocating a timer when no positive delay is required. + } + timer := time.NewTimer(duration) // Allocate a stoppable timer rather than leaking time.After resources on cancellation. + defer timer.Stop() // Release the timer promptly when either select branch returns. + select { // Race the requested delay against caller cancellation and step deadlines. + case <-ctx.Done(): + return ctx.Err() // Return the exact context error so callers can classify cancellation versus deadline expiration. + case <-timer.C: + return nil // Report successful completion once the requested delay elapses. + } } diff --git a/internal/worker/executor_test.go b/internal/worker/executor_test.go index 71d8421..cfa7a2e 100644 --- a/internal/worker/executor_test.go +++ b/internal/worker/executor_test.go @@ -298,6 +298,40 @@ func TestExecuteWaitStepUsesConfiguredDuration(t *testing.T) { } } +// TestExecuteWaitStepStopsOnCallerCancellation verifies that a long wait does not outlive a cancelled plan context. +func TestExecuteWaitStepStopsOnCallerCancellation(t *testing.T) { + executor, recordedEvents := newTestExecutor(&recordingAppiumClient{}, 5*time.Second, time.Second) // Construct an executor whose step timeout is much longer than the cancellation window. + ctx, cancel := context.WithCancel(context.Background()) // Create one caller-controlled plan context for deterministic cancellation. + go func() { // Cancel shortly after execution starts so the wait branch has entered its timer select. + time.Sleep(25 * time.Millisecond) // Allow the executor to emit its running event before cancellation. + cancel() // Cancel the plan so the wait must stop without sleeping for its requested duration. + }() + startedAt := time.Now() // Capture wall-clock start time to assert prompt cancellation. + err := executor.Execute(ctx, []PlanStep{{Type: "wait", Params: json.RawMessage(`{"ms":5000}`)}}) // Execute one five-second wait under the shortly cancelled context. + if !stdErrors.Is(err, context.Canceled) { // Require the caller cancellation to propagate unchanged. + t.Fatalf("expected context cancellation, got %v", err) // Surface masking or delayed completion regressions. + } + if elapsed := time.Since(startedAt); elapsed >= time.Second { // Require termination far before the requested five-second delay. + t.Fatalf("expected cancelled wait to stop promptly, took %v", elapsed) // Surface any reintroduction of uncancellable sleep behavior. + } + if len(*recordedEvents) != 2 || (*recordedEvents)[1].Status != "failed" { // Require replayable running and failed events for the interrupted step. + t.Fatalf("expected running/failed events, got %#v", *recordedEvents) // Surface missing cancellation observability. + } +} + +// TestExecuteWaitStepStopsAtStepDeadline verifies that the configured step timeout bounds a longer requested wait duration. +func TestExecuteWaitStepStopsAtStepDeadline(t *testing.T) { + executor, _ := newTestExecutor(&recordingAppiumClient{}, 30*time.Millisecond, time.Second) // Construct an executor with a short per-step deadline. + startedAt := time.Now() // Capture wall-clock start time to assert timeout enforcement. + err := executor.Execute(context.Background(), []PlanStep{{Type: "wait", Params: json.RawMessage(`{"ms":5000}`)}}) // Execute one five-second wait under the short step timeout. + if !stdErrors.Is(err, context.DeadlineExceeded) { // Require the step deadline to propagate unchanged. + t.Fatalf("expected step deadline error, got %v", err) // Surface timeout masking regressions. + } + if elapsed := time.Since(startedAt); elapsed >= time.Second { // Require termination far before the requested five-second delay. + t.Fatalf("expected timed-out wait to stop promptly, took %v", elapsed) // Surface any reintroduction of uncancellable wait behavior. + } +} + // TestExecuteTapStepUsesConfiguredCoordinates verifies that a successful tap step forwards the configured coordinates directly to Appium. func TestExecuteTapStepUsesConfiguredCoordinates(t *testing.T) { client := &recordingAppiumClient{} // Construct one recording Appium client so the test can assert tap gesture dispatch precisely. diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go index f88b601..420c36f 100644 --- a/internal/worker/grpc_server.go +++ b/internal/worker/grpc_server.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "log/slog" + "strings" "sync" "time" @@ -13,6 +14,8 @@ import ( "mcp_for_appium/internal/worker/appium" ) +const completedPlanHistoryTTL = 2 * time.Hour + // GRPCServer implements rpc.WorkerServiceServer. // Each incoming ExecutePlan call spawns a goroutine that creates its own // Appium client and Executor so that multiple plans can run concurrently. @@ -25,13 +28,28 @@ type GRPCServer struct { renewEvery time.Duration newClient func(string) sessionAwareAppiumClient ensureReady func(context.Context) error + capacity int + slots chan struct{} - planMu sync.Mutex - planCancel map[string]context.CancelFunc + planMu sync.Mutex + activePlans map[string]activePlan + planHistory map[string]completedPlan logger *slog.Logger } +// activePlan stores the attempt and cancel function for one worker-admitted execution. +type activePlan struct { + attempt int64 + cancel context.CancelFunc +} + +// completedPlan stores a bounded deduplication tombstone for one finished trace attempt. +type completedPlan struct { + attempt int64 + completedAt time.Time +} + // distributedPlanReporter exposes the worker-to-orchestrator callback RPCs needed by distributed execution. type distributedPlanReporter interface { ReportPlanEvent(ctx context.Context, req *rpc.ReportPlanEventRequest) (*rpc.ReportPlanEventResponse, error) @@ -45,11 +63,15 @@ type sessionAwareAppiumClient interface { AttachSession(sessionID string) } -// NewGRPCServer creates a new worker gRPC service handler. -func NewGRPCServer(appiumURL string, stepTimeout, autoWaitMax time.Duration, workerID string, reporter distributedPlanReporter, renewEvery time.Duration) *GRPCServer { +// NewGRPCServer creates a worker gRPC service handler with optional authoritative execution capacity. +func NewGRPCServer(appiumURL string, stepTimeout, autoWaitMax time.Duration, workerID string, reporter distributedPlanReporter, renewEvery time.Duration, configuredCapacity ...int) *GRPCServer { if renewEvery <= 0 { // Fall back to one conservative default renewal cadence when the caller omits an explicit interval. renewEvery = 5 * time.Second // Keep lease renewals frequent enough that the orchestrator can detect lost ownership promptly. } + capacity := 4 // Preserve the historical worker default when callers do not supply explicit admission capacity. + if len(configuredCapacity) > 0 && configuredCapacity[0] > 0 { // Honor the first positive capacity supplied by process wiring or a test. + capacity = configuredCapacity[0] // Use the same capacity advertised to the orchestrator for worker-side admission. + } return &GRPCServer{ appiumURL: appiumURL, stepTimeout: stepTimeout, @@ -57,11 +79,14 @@ func NewGRPCServer(appiumURL string, stepTimeout, autoWaitMax time.Duration, wor workerID: workerID, reporter: reporter, renewEvery: renewEvery, + capacity: capacity, // Retain the authoritative admission limit so status and diagnostics use the configured worker capacity. + slots: make(chan struct{}, capacity), // Allocate one bounded semaphore slot per concurrently admitted distributed plan. newClient: func(url string) sessionAwareAppiumClient { // Build the default Appium client factory once so tests can swap it with a stub easily. return appium.NewClient(url) // Return the production Appium HTTP client used by distributed worker execution. }, - ensureReady: nil, // Leave Appium readiness unmanaged by default so callers can opt into local auto-start explicitly from process wiring. - planCancel: make(map[string]context.CancelFunc), + ensureReady: nil, // Leave Appium readiness unmanaged by default so callers can opt into local auto-start explicitly from process wiring. + activePlans: make(map[string]activePlan), // Initialize the trace-indexed cancellation registry before the worker accepts any plan. + planHistory: make(map[string]completedPlan), // Initialize bounded completion tombstones so duplicate attempts are rejected deterministically. logger: telemetry.Logger(), } } @@ -73,48 +98,85 @@ func (s *GRPCServer) SetAppiumReadyFunc(ensure func(context.Context) error) { // ActiveLoad returns the number of plans currently executing on this worker. func (s *GRPCServer) ActiveLoad() int { - s.planMu.Lock() - defer s.planMu.Unlock() - return len(s.planCancel) + s.planMu.Lock() // Serialize the active-plan map read with admission and completion updates. + defer s.planMu.Unlock() // Release the worker admission lock after calculating the heartbeat snapshot. + return len(s.activePlans) // Report exactly the runs that hold authoritative worker capacity slots. } // ExecutePlan implements rpc.WorkerServiceServer. -// The plan is executed asynchronously; this method returns "accepted" immediately. +// The plan is executed asynchronously only after synchronous validation, deduplication, capacity admission, and cancellation registration succeed. func (s *GRPCServer) ExecutePlan(_ context.Context, req *rpc.ExecutePlanRequest) (*rpc.ExecutePlanResponse, error) { - s.logger.Info("received ExecutePlan", "trace_id", req.TraceID, "session_id", req.SessionID, "attempt", req.Attempt) // Log the distributed execute request together with the reserved attempt now owning the trace. - go s.runPlan(req.TraceID, req.SessionID, req.Attempt, req.Plan) // Execute the plan asynchronously so the RPC can acknowledge acceptance immediately. - return &rpc.ExecutePlanResponse{Status: "accepted"}, nil + if req == nil { // Reject absent gRPC payloads before reading trace ownership metadata. + return &rpc.ExecutePlanResponse{Status: "rejected", Message: "request is required"}, nil // Return a stable validation result without starting execution. + } + traceID := strings.TrimSpace(req.TraceID) // Normalize the trace identifier used for admission, cancellation, and deduplication. + if traceID == "" { // Reject requests that cannot be tracked or cancelled safely. + return &rpc.ExecutePlanResponse{Status: "rejected", Message: "trace_id is required"}, nil // Keep malformed input outside worker execution. + } + if req.Attempt <= 0 { // Require the orchestrator's positive monotonic ownership token. + return &rpc.ExecutePlanResponse{Status: "rejected", Message: "attempt must be greater than zero"}, nil // Prevent unguarded callbacks and duplicate execution. + } + planRaw := append(json.RawMessage(nil), req.Plan...) // Copy plan bytes before the RPC returns so caller buffer reuse cannot race with asynchronous parsing. + now := time.Now().UTC() // Capture one admission timestamp for bounded completed-attempt deduplication. + s.planMu.Lock() // Serialize duplicate detection, capacity acquisition, and active-plan publication. + s.prunePlanHistoryLocked(now) // Remove expired tombstones before checking this trace's latest completed attempt. + if active, ok := s.activePlans[traceID]; ok { // Detect duplicate or conflicting delivery while this trace is still executing. + s.planMu.Unlock() // Release admission serialization before returning the existing ownership result. + if active.attempt == req.Attempt { // Treat an exact in-flight replay as an idempotent acknowledgement. + return &rpc.ExecutePlanResponse{Status: "accepted", Message: "attempt already active"}, nil // Prevent a second goroutine while allowing the orchestrator to recover a lost response. + } + return &rpc.ExecutePlanResponse{Status: "busy", Message: "trace already active"}, nil // Reject concurrent attempts for one trace until the current owner exits. + } + if completed, ok := s.planHistory[traceID]; ok { // Detect a response-loss replay after this worker already completed the attempt. + if completed.attempt == req.Attempt { // Acknowledge the exact completed attempt without running its Appium actions again. + s.planMu.Unlock() // Release admission serialization before returning the deduplicated result. + return &rpc.ExecutePlanResponse{Status: "accepted", Message: "attempt already completed"}, nil // Preserve at-most-once worker execution for the retained history window. + } + if completed.attempt > req.Attempt { // Reject any attempt older than the latest completion retained on this worker. + s.planMu.Unlock() // Release admission serialization before returning the stale-attempt result. + return &rpc.ExecutePlanResponse{Status: "rejected", Message: "stale attempt"}, nil // Prevent an old queue delivery from replaying Appium mutations. + } + delete(s.planHistory, traceID) // Allow a strictly newer orchestrator-owned attempt to replace the completed tombstone. + } + select { + case s.slots <- struct{}{}: + // The non-blocking send reserves one authoritative worker execution slot before acceptance is visible remotely. + default: + s.planMu.Unlock() // Release admission serialization when all configured slots are occupied. + return &rpc.ExecutePlanResponse{Status: "busy", Message: "worker is at capacity"}, nil // Let the dispatcher retry this leased attempt without oversubscribing the worker. + } + runCtx, cancel := context.WithCancel(context.Background()) // Create the worker-owned execution context before publishing acceptance. + s.activePlans[traceID] = activePlan{attempt: req.Attempt, cancel: cancel} // Register cancellation and load state synchronously before the RPC can return. + s.planMu.Unlock() // Make the admitted run visible to cancellation and heartbeat calls before starting its goroutine. + + s.logger.Info("accepted ExecutePlan", "trace_id", traceID, "session_id", req.SessionID, "attempt", req.Attempt, "active_load", s.ActiveLoad(), "capacity", s.capacity) // Log safe admission metadata for fleet diagnostics. + go s.runPlan(runCtx, traceID, req.SessionID, req.Attempt, planRaw) // Begin asynchronous execution only after every admission invariant is committed locally. + return &rpc.ExecutePlanResponse{Status: "accepted"}, nil // Acknowledge only a run that now owns a slot and cancellation entry. } // CancelPlan implements rpc.WorkerServiceServer. func (s *GRPCServer) CancelPlan(_ context.Context, req *rpc.CancelPlanRequest) (*rpc.CancelPlanResponse, error) { - s.planMu.Lock() - cancel, ok := s.planCancel[req.TraceID] - s.planMu.Unlock() - - if !ok { - return &rpc.CancelPlanResponse{Status: "not_found"}, nil + if req == nil { // Reject absent cancellation payloads without dereferencing them. + return &rpc.CancelPlanResponse{Status: "not_found"}, nil // Preserve an idempotent result for malformed cleanup calls. } - cancel() - s.logger.Info("plan cancelled", "trace_id", req.TraceID) - return &rpc.CancelPlanResponse{Status: "cancelled"}, nil + traceID := strings.TrimSpace(req.TraceID) // Normalize the lookup key used by worker admission. + s.planMu.Lock() // Serialize active-plan lookup with completion cleanup. + active, ok := s.activePlans[traceID] // Resolve the worker-owned cancellation function for this trace. + s.planMu.Unlock() // Release admission state before invoking cancellation callbacks. + if !ok { // Report cleanly when this worker no longer owns an active run for the trace. + return &rpc.CancelPlanResponse{Status: "not_found"}, nil // Let the orchestrator clean stale lease metadata idempotently. + } + active.cancel() // Signal executor and lease-renewal contexts to stop as soon as their current operation observes cancellation. + s.logger.Info("plan cancellation requested", "trace_id", traceID, "attempt", active.attempt) // Record the safe cancellation request metadata. + return &rpc.CancelPlanResponse{Status: "cancelled"}, nil // Confirm that a live worker run received the cancellation signal. } -// runPlan executes this operation. -func (s *GRPCServer) runPlan(traceID string, sessionID string, attempt int64, planRaw json.RawMessage) { - ctx, cancel := context.WithCancel(context.Background()) // Create the per-plan root context so worker-side cancel RPCs and lost-lease cancellation can stop execution cleanly. - s.planMu.Lock() - s.planCancel[traceID] = cancel // Register the per-trace cancel function so later worker cancel RPCs can stop the active run cleanly. - s.planMu.Unlock() - defer func() { - cancel() // Release the execution context so any renewal loop or nested timeouts stop promptly on every exit path. - s.planMu.Lock() - delete(s.planCancel, traceID) // Remove the trace from the in-flight plan map so ActiveLoad drops immediately after execution stops. - s.planMu.Unlock() - }() +// runPlan executes one plan that already owns an authoritative worker capacity slot and active-plan entry. +func (s *GRPCServer) runPlan(ctx context.Context, traceID string, sessionID string, attempt int64, planRaw json.RawMessage) { + defer s.finishPlan(traceID, attempt) // Release cancellation state, capacity, and deduplication bookkeeping on every terminal path. if s.reporter != nil { // Start the lease-renewal loop only when the worker has a wired orchestrator callback client. - go s.renewLeaseLoop(ctx, cancel, traceID, attempt) // Refresh the distributed ownership lease in the background until this run exits or loses ownership. + go s.renewLeaseLoop(ctx, func() { s.cancelPlanAttempt(traceID, attempt) }, traceID, attempt) // Refresh ownership and cancel only this active attempt when the orchestrator reports it stale. } if s.ensureReady != nil { // Run the optional Appium readiness hook before parsing or executing the plan so local Appium auto-start can happen on demand per plan. if err := s.ensureReady(ctx); err != nil { // Stop immediately when the configured Appium dependency is still unavailable after the readiness hook runs. @@ -158,6 +220,47 @@ func (s *GRPCServer) runPlan(traceID string, sessionID string, attempt int64, pl s.reportCompletion(traceID, attempt, "completed", "completed", "trace completed", nil) // Report the completed terminal outcome so the orchestrator can close the distributed trace cleanly. } +// finishPlan atomically removes one matching active attempt, records its bounded deduplication tombstone, and returns its capacity slot. +func (s *GRPCServer) finishPlan(traceID string, attempt int64) { + now := time.Now().UTC() // Capture one completion timestamp for deduplication retention and pruning. + s.planMu.Lock() // Serialize terminal cleanup with cancellation, heartbeat load reads, and new admissions. + active, ok := s.activePlans[traceID] // Resolve the active entry that should own this goroutine's capacity slot. + if !ok || active.attempt != attempt { // Avoid deleting or releasing capacity for a newer attempt if invariants are ever violated. + s.planMu.Unlock() // Release the admission lock without changing unrelated active state. + s.logger.Error("worker plan cleanup lost active ownership", "trace_id", traceID, "attempt", attempt) // Surface the invariant violation for operator diagnosis. + return // Preserve the newer or unknown run rather than corrupting worker load accounting. + } + active.cancel() // Stop the worker-owned context so lease renewal and nested execution timers exit promptly. + delete(s.activePlans, traceID) // Remove the completed run from cancellation and heartbeat load state. + s.planHistory[traceID] = completedPlan{attempt: attempt, completedAt: now} // Retain an exact-attempt tombstone so lost acceptance responses cannot replay Appium actions. + select { + case <-s.slots: + // The matching admission token is returned without blocking while the active-plan invariant holds. + default: + s.logger.Error("worker capacity slot missing during plan cleanup", "trace_id", traceID, "attempt", attempt) // Surface channel/map accounting drift without blocking cleanup forever. + } + s.planMu.Unlock() // Publish the freed slot and completed tombstone atomically to later admissions. +} + +// cancelPlanAttempt cancels one trace only when the supplied attempt still owns its active worker entry. +func (s *GRPCServer) cancelPlanAttempt(traceID string, attempt int64) { + s.planMu.Lock() // Serialize attempt ownership lookup with completion and newer admissions. + active, ok := s.activePlans[traceID] // Resolve the current worker-owned run for this trace. + s.planMu.Unlock() // Release admission state before invoking the cancellation function. + if ok && active.attempt == attempt { // Prevent a stale lease-renewal goroutine from cancelling a newer attempt. + active.cancel() // Signal only the matching execution context to stop. + } +} + +// prunePlanHistoryLocked removes expired completion tombstones while the caller holds the worker admission mutex. +func (s *GRPCServer) prunePlanHistoryLocked(now time.Time) { + for traceID, completed := range s.planHistory { // Inspect every bounded deduplication record under the admission lock. + if now.Sub(completed.completedAt) >= completedPlanHistoryTTL { // Expire tombstones after the distributed in-flight retention window. + delete(s.planHistory, traceID) // Bound worker memory while retaining enough history for response-loss retries. + } + } +} + // renewLeaseLoop keeps the distributed execution lease alive while the current worker attempt still owns the trace. func (s *GRPCServer) renewLeaseLoop(ctx context.Context, cancel context.CancelFunc, traceID string, attempt int64) { ticker := time.NewTicker(s.renewEvery) // Create one renewal ticker so lease refresh RPCs happen at a steady cadence while the run remains active. diff --git a/internal/worker/grpc_server_test.go b/internal/worker/grpc_server_test.go index 9a09d66..1dc6c83 100644 --- a/internal/worker/grpc_server_test.go +++ b/internal/worker/grpc_server_test.go @@ -118,7 +118,14 @@ func TestRunPlanAttachesSessionAndReportsCallbacks(t *testing.T) { return appiumClient // Return the deterministic fake Appium client so the worker run stays fully in-process. } - server.runPlan("trace-1", "appium-session-1", 7, json.RawMessage(`[{"type":"wait","params":{"ms":1}}]`)) // Execute one tiny distributed plan synchronously so the test can assert its callback side effects immediately. + response, err := server.ExecutePlan(context.Background(), &rpc.ExecutePlanRequest{TraceID: "trace-1", SessionID: "appium-session-1", Attempt: 7, Plan: json.RawMessage(`[{"type":"wait","params":{"ms":1}}]`)}) // Admit one tiny plan through the production synchronous worker admission boundary. + if err != nil { // Fail when the in-process worker RPC unexpectedly returns a transport-level error. + t.Fatalf("expected worker plan admission to succeed, got error: %v", err) // Surface admission failures because callback assertions require an accepted run. + } + if response.Status != "accepted" { // Fail when the worker rejects a valid plan despite available capacity. + t.Fatalf("expected worker plan status accepted, got %q", response.Status) // Surface the unexpected admission outcome for diagnosis. + } + waitForWorkerCompletions(t, reporter, 1) // Wait until asynchronous execution emits its terminal callback and releases worker capacity. if appiumClient.attachedSession != "appium-session-1" { // Fail the test when the worker did not attach to the orchestrator-created Appium session before execution. t.Fatalf("expected attached session appium-session-1, got %q", appiumClient.attachedSession) // Surface the unexpected attached session because distributed execution must reuse the existing session. @@ -158,7 +165,14 @@ func TestRunPlanFailsWhenAppiumReadyHookFails(t *testing.T) { return nil // Return nil only to satisfy the compiler because the fatal assertion above should abort the test first. } // Close the panic client-factory override. - server.runPlan("trace-2", "appium-session-2", 8, json.RawMessage(`[{"type":"wait","params":{"ms":1}}]`)) // Execute one tiny plan synchronously so the worker failure path can be asserted immediately. + response, err := server.ExecutePlan(context.Background(), &rpc.ExecutePlanRequest{TraceID: "trace-2", SessionID: "appium-session-2", Attempt: 8, Plan: json.RawMessage(`[{"type":"wait","params":{"ms":1}}]`)}) // Admit one tiny plan through the production worker boundary so readiness failure runs asynchronously. + if err != nil { // Fail when the in-process worker RPC unexpectedly returns a transport-level error. + t.Fatalf("expected worker plan admission to succeed, got error: %v", err) // Surface admission failures because readiness assertions require the run to start. + } + if response.Status != "accepted" { // Fail when the worker rejects a valid plan before invoking the readiness hook. + t.Fatalf("expected worker plan status accepted, got %q", response.Status) // Surface the unexpected admission outcome for diagnosis. + } + waitForWorkerCompletions(t, reporter, 1) // Wait until the asynchronous readiness failure emits its terminal callback. if ensureReadyCalls != 1 { // Fail the test when the worker did not invoke the readiness hook exactly once before deciding the trace outcome. t.Fatalf("expected readiness hook to be called once, got %d", ensureReadyCalls) // Surface the unexpected readiness-hook call count because local Appium auto-start depends on this hook firing reliably. @@ -183,3 +197,81 @@ func TestRunPlanFailsWhenAppiumReadyHookFails(t *testing.T) { t.Fatalf("expected distributed completion attempt 8, got %d", reporter.completions[0].Attempt) // Surface the unexpected attempt because stale-result protection still applies on failure paths. } } + +// TestExecutePlanEnforcesCapacityAndDeduplicatesAttempts verifies that admission rejects excess work and never starts an exact active or completed attempt twice. +func TestExecutePlanEnforcesCapacityAndDeduplicatesAttempts(t *testing.T) { + reporter := &fakeDistributedReporter{} // Record callbacks so the test can prove only one physical execution completed. + server := NewGRPCServer("http://unused-appium", time.Second, time.Second, "worker-capacity", reporter, time.Hour, 1) // Construct one worker with exactly one authoritative execution slot. + server.newClient = func(url string) sessionAwareAppiumClient { // Replace production Appium traffic with one deterministic in-process stub. + return &fakeSessionAwareAppiumClient{} // Return an isolated fake client for the single admitted wait plan. + } + request := &rpc.ExecutePlanRequest{TraceID: "trace-capacity-1", SessionID: "session-capacity-1", Attempt: 3, Plan: json.RawMessage(`[{"type":"wait","params":{"ms":100}}]`)} // Build one slow-enough valid plan so admission state remains active during duplicate and capacity checks. + firstResponse, err := server.ExecutePlan(context.Background(), request) // Admit the first trace into the worker's only slot. + if err != nil { // Fail when in-process admission unexpectedly returns a transport error. + t.Fatalf("expected first worker admission to succeed, got error: %v", err) // Surface the admission failure because the rest of the capacity scenario depends on an active run. + } + if firstResponse.Status != "accepted" { // Fail when the available worker slot does not admit the first plan. + t.Fatalf("expected first admission status accepted, got %q", firstResponse.Status) // Surface the unexpected admission result. + } + + duplicateResponse, err := server.ExecutePlan(context.Background(), request) // Replay the exact active trace attempt while its first goroutine still owns capacity. + if err != nil { // Fail when duplicate admission unexpectedly returns a transport error. + t.Fatalf("expected duplicate active admission to return cleanly, got error: %v", err) // Surface the duplicate handling failure. + } + if duplicateResponse.Status != "accepted" { // Require idempotent acknowledgement for exact response-loss replays. + t.Fatalf("expected duplicate active admission status accepted, got %q", duplicateResponse.Status) // Surface any rejection that could make the orchestrator retry dangerously. + } + + busyResponse, err := server.ExecutePlan(context.Background(), &rpc.ExecutePlanRequest{TraceID: "trace-capacity-2", SessionID: "session-capacity-2", Attempt: 1, Plan: json.RawMessage(`[{"type":"wait","params":{"ms":1}}]`)}) // Attempt a different trace while the only slot remains occupied. + if err != nil { // Fail when capacity rejection unexpectedly uses a transport error. + t.Fatalf("expected busy admission to return cleanly, got error: %v", err) // Surface the capacity handling failure. + } + if busyResponse.Status != "busy" { // Require the stable transient status understood by dispatcher retry logic. + t.Fatalf("expected second trace admission status busy, got %q", busyResponse.Status) // Surface oversubscription or incorrect terminal rejection. + } + if activeLoad := server.ActiveLoad(); activeLoad != 1 { // Prove duplicate and busy calls did not create extra active goroutines. + t.Fatalf("expected authoritative active load 1, got %d", activeLoad) // Surface worker-side load-accounting drift. + } + + waitForWorkerCompletions(t, reporter, 1) // Wait for the single physically admitted plan to finish and create its deduplication tombstone. + completedReplay, err := server.ExecutePlan(context.Background(), request) // Replay the exact attempt after completion while its bounded history remains present. + if err != nil { // Fail when completed-attempt deduplication unexpectedly returns a transport error. + t.Fatalf("expected completed replay to return cleanly, got error: %v", err) // Surface the completed replay handling failure. + } + if completedReplay.Status != "accepted" { // Acknowledge the retained completed attempt without executing it again. + t.Fatalf("expected completed replay status accepted, got %q", completedReplay.Status) // Surface a response that could provoke unsafe retries. + } + time.Sleep(20 * time.Millisecond) // Allow enough time for any accidental duplicate goroutine to emit an observable second completion. + reporter.mu.Lock() // Serialize the final completion-count assertion with callback writes. + completionCount := len(reporter.completions) // Snapshot how many physical terminal callbacks were emitted. + reporter.mu.Unlock() // Release the reporter lock before evaluating the assertion. + if completionCount != 1 { // Reject any duplicate physical execution across active and completed replays. + t.Fatalf("expected exactly one worker completion, got %d", completionCount) // Surface at-most-once admission regression explicitly. + } + if activeLoad := server.ActiveLoad(); activeLoad != 0 { // Confirm the completed tombstone does not consume execution capacity. + t.Fatalf("expected authoritative active load 0 after completion, got %d", activeLoad) // Surface a leaked worker slot. + } +} + +// waitForWorkerCompletions waits for the fake reporter to observe the requested terminal callback count without introducing an unbounded test hang. +func waitForWorkerCompletions(t *testing.T, reporter *fakeDistributedReporter, expected int) { + t.Helper() // Attribute timeout failures to the scenario that requested completion. + deadline := time.NewTimer(2 * time.Second) // Bound asynchronous worker execution to one short deterministic test window. + defer deadline.Stop() // Release the timeout timer when the expected callback arrives early. + ticker := time.NewTicker(time.Millisecond) // Poll the mutex-protected fake reporter at a low-cost cadence. + defer ticker.Stop() // Release the polling ticker on success or timeout. + for { // Continue until the expected terminal callback count appears or the deadline expires. + reporter.mu.Lock() // Serialize the completion count read with callback append operations. + completionCount := len(reporter.completions) // Snapshot the current terminal callback count. + reporter.mu.Unlock() // Release the reporter lock before blocking on timers. + if completionCount >= expected { // Return once asynchronous execution has produced every expected terminal callback. + return // Allow the caller to assert stable callback and client state. + } + select { + case <-deadline.C: + t.Fatalf("timed out waiting for %d worker completions; got %d", expected, completionCount) // Surface the missing callback count for diagnosis. + case <-ticker.C: + // Retry after one millisecond so short wait-only plans finish quickly without a busy loop. + } + } +} diff --git a/mcp_alignment_checklist.md b/mcp_alignment_checklist.md new file mode 100644 index 0000000..4d2b6ba --- /dev/null +++ b/mcp_alignment_checklist.md @@ -0,0 +1,97 @@ +# MCP 2025-06-18 对齐清单(历史基线) + +> 本清单记录已完成的 legacy alignment 批次。当前 `2026-07-28` 无状态协议支持请参阅 [MCP_2026_07_28_ALIGNMENT.md](./MCP_2026_07_28_ALIGNMENT.md)。 + +## 1. 范围结论 + +- 本期目标: + - 对齐 `stdio` 握手、通知、保活与 tool metadata 的最新规范。 + - 将当前 HTTP `/jsonrpc` 兼容入口升级为标准 `Streamable HTTP` MCP transport。 + - 保持现有业务工具、进度通知、同步等待式 `executePlan` 行为不倒退。 +- 本期不做: + - OAuth + - Elicitation + - Async Tasks(实验性) + - Tool icons + - sampling 中携带 tools / toolChoice +- 本期按“支持但不强依赖”处理: + - `structuredContent` + - `outputSchema` + +## 2. P0:必须先完成 + +### P0-1 握手与通知语义修复 +- 静默接收 `notifications/initialized`。 +- 静默接收 `notifications/cancelled`。 +- transport 层禁止对 JSON-RPC notification 写回任何 response/error。 +- `notifications/cancelled` 需要真正联动到 server 内部 cancel path,而不是仅忽略。 + +### P0-2 `ping` 支持 +- 新增 `ping` request handler。 +- 对 `ping` 返回空 result `{}`。 +- `stdio` 与 HTTP transport 行为保持一致。 + +### P0-3 协议版本升级 +- `initialize` 返回的 `protocolVersion` 升级为目标版本。 +- 对外能力声明与实际实现保持一致,不能继续保留旧版本口径。 + +### P0-4 Streamable HTTP transport +- 提供标准 `Streamable HTTP` MCP transport。 +- 区分 request 与 notification 的 HTTP 语义。 +- 支持服务器通过同一 transport 正确发送 progress / event 类消息。 +- 保留现有 `/jsonrpc` 兼容入口时,必须在文档中显式标注为 non-MCP compatibility endpoint。 + +### P0-5 `MCP-Protocol-Version` HTTP header 校验 +- 对 MCP HTTP 请求校验 `MCP-Protocol-Version`。 +- 对缺失/不兼容 header 返回明确错误。 +- 在 response 中返回 negotiated/accepted protocol version。 + +## 3. P1:应该尽快完成 + +### P1-1 Tool metadata 升级 +- 为 `Tool` 增加 `title`。 +- 为 `Tool` 增加 `annotations`。 +- 补齐工具 JSON 定义文件中的 metadata。 +- 为高风险工具标注 `destructiveHint`,为只读工具标注 `readOnlyHint`。 + +### P1-2 Tool result 升级 +- 在保持现有 `content` 不变的前提下,为适合结构化输出的工具补 `structuredContent`。 +- 为后续 `outputSchema` 引入预留设计,但本期不要求所有工具都实现。 + +### P1-3 HTTP/stdio 通用 notification model +- 统一 request / notification 的解析与分发模型。 +- 为后续 server-originated notifications 留出复用通道。 + +## 4. P2:可第二批完成 + +### P2-1 兼容入口治理 +- 评估是否保留现有 `/jsonrpc` compatibility endpoint。 +- 如果保留,增加清晰文档和测试,避免被误解为标准 MCP transport。 + +### P2-2 `structuredContent` 覆盖面扩展 +- 从高价值工具开始逐步扩展,而不是一次性覆盖全部 26 个工具。 + +### P2-3 `outputSchema` 与 richer tool contracts +- 在后续版本中为稳定工具补充 `outputSchema`。 + +## 5. 验收标准 + +- `stdio`: + - `initialize -> notifications/initialized -> tools/list -> ping` 全链路通过。 + - notification 不产生 response。 + - `notifications/cancelled` 能中止长请求或至少触发明确取消路径。 +- HTTP: + - 支持标准 `Streamable HTTP`。 + - `MCP-Protocol-Version` 缺失或不匹配时返回可诊断错误。 + - `ping` 与 `tools/call` 都能通过标准 transport 测试。 +- Tool metadata: + - `tools/list` 返回 `title` 与 `annotations`。 +- Tool result: + - 至少一组结构化工具结果带 `structuredContent`。 + +## 6. 实施顺序建议 + +1. 先改 transport 栈和 notification 语义。 +2. 再补 `ping` 与协议版本升级。 +3. 再引入 `Streamable HTTP` 与 version header 校验。 +4. 最后补 `title`、`annotations`、`structuredContent`。 diff --git a/module_mcp_alignment_design.md b/module_mcp_alignment_design.md new file mode 100644 index 0000000..320c4fc --- /dev/null +++ b/module_mcp_alignment_design.md @@ -0,0 +1,320 @@ +# MCP 2025-06-18 对齐设计说明(历史基线) + +> 本文档保留 legacy alignment 的设计记录。当前 `2026-07-28` 双时代实现说明请参阅 [MCP_2026_07_28_ALIGNMENT.md](./MCP_2026_07_28_ALIGNMENT.md)。 + +## 1. 设计目标 + +- 让 `stdio` 成为符合最新 MCP 规范的标准 transport。 +- 将当前 HTTP MCP 能力从“自定义 JSON-RPC endpoint”升级为“标准 Streamable HTTP transport”。 +- 在不破坏现有业务工具能力的前提下,升级 tool metadata 与 output schema 能力。 +- 将协议级 request / notification 行为与现有业务级 direct methods 明确解耦。 + +## 2. 当前问题摘要 + +### 2.1 Transport 层 + +- `stdio` 将所有入站消息都按 request 处理,notification 也会回包。 +- HTTP `/jsonrpc` 只支持简单 request-response,没有 Streamable HTTP 语义。 +- HTTP 层没有 `MCP-Protocol-Version` header 校验。 + +### 2.2 Handler 层 + +- `ProcessRequest` 缺少: + - `ping` + - `notifications/initialized` + - `notifications/cancelled` +- 默认 unknown method 会把合法 notification 打成协议错误。 + +### 2.3 Tool Registry 层 + +- `Tool` 缺少 `title` +- `Tool` 缺少 `annotations` +- tool JSON 文件与最新 schema 不一致 + +### 2.4 Tool Result 层 + +- `tools/call` 只返回 `content` 文本 +- 缺少 `structuredContent` + +## 3. 目标架构 + +### 3.1 分层 + +本期按以下 4 层改造: + +1. `Message Classification Layer` + - 区分 request / notification / response +2. `Protocol Dispatch Layer` + - 处理 lifecycle、ping、cancelled、tools、resources 等 MCP methods +3. `Transport Layer` + - `stdio` + - `Streamable HTTP` +4. `Tool Metadata / Result Layer` + - `title` + - `annotations` + - `structuredContent` + +## 4. 核心设计 + +### 4.1 Message Classification + +新增统一消息分类规则: + +- 带 `id` 且无 `result/error`:request +- 无 `id` 且有 `method`:notification +- 带 `result/error`:response + +当前 server 只需要完整处理 request 与 notification;response 可保留为非预期输入防御路径。 + +建议新增内部结构: + +- `IsNotification(req *Request) bool` +- `IsRequest(req *Request) bool` + +### 4.2 Notification Handling + +建议在 `jsonrpc.Handler` 中新增显式分支: + +- `notifications/initialized` + - 记录 debug/info 日志 + - 返回 `nil, nil` +- `notifications/cancelled` + - 解析 `requestId` + - 调用 in-flight request registry 的 cancel + - 返回 `nil, nil` + +transport 层必须识别 notification,并在 handler 返回后禁止写 response。 + +### 4.3 In-Flight Request Registry + +为支持 `notifications/cancelled`,需要新增 in-flight request 管理: + +- key: JSON-RPC request id +- value: `context.CancelFunc` + +建议实现: + +- 在 transport 开始处理 request 时创建子 context +- 注册 `requestId -> cancelFunc` +- request 结束后删除映射 +- `notifications/cancelled` 到来时查表并执行 cancel + +适用范围: + +- `stdio` +- `Streamable HTTP` + +### 4.4 Ping + +在 `ProcessRequest` 中新增: + +- `case "ping": result = map[string]interface{}{}` + +保持最小响应语义,不引入业务逻辑。 + +### 4.5 Streamable HTTP + +建议新增独立 transport,而不是继续在现有 `ServeHTTP` 上打补丁。 + +推荐新增目录: + +- `internal/gateway/mcphttp` + +内部职责: + +- 解析 MCP HTTP request +- 校验 `MCP-Protocol-Version` +- 区分 request / notification +- 支持 streamable response +- 复用现有 `jsonrpc.Handler` + +保留现有 `/jsonrpc` 的策略: + +- 短期保留,标记为 compatibility endpoint +- 新标准 MCP HTTP 入口使用新路径,例如 `/mcp` + +这样可以降低对现有集成的破坏性。 + +### 4.6 Protocol Version Negotiation + +建议引入一个集中版本常量: + +- `SupportedProtocolVersion = "2025-06-18"` + +协商策略: + +- `stdio` + - 在 `initialize` 中读取 client `protocolVersion` + - 若兼容则返回 server accepted version +- `HTTP` + - 除 `initialize` 外,要求请求头带 `MCP-Protocol-Version` + - 缺失或不兼容时直接拒绝 + +### 4.7 Tool Metadata Model + +建议扩展 `Tool`: + +- `Name` +- `Title` +- `Description` +- `InputSchema` +- `Annotations` +- `OutputSchema`(本期可选预留) + +建议增加结构: + +- `ToolAnnotations` + - `Title` + - `ReadOnlyHint` + - `DestructiveHint` + - `OpenWorldHint` + +虽然最新 schema 中 `title` 是顶层字段,但保留 `annotations.title` 兼容解析可以提升后续容错性。 + +### 4.8 Tool Result Model + +建议把 `tools/call` success payload 统一改为内部结果结构,再序列化输出: + +- `content` +- `structuredContent` +- `isError` + +推荐策略: + +- 默认继续返回文本 `content` +- 对适合结构化的工具额外填 `structuredContent` + +首批建议支持结构化结果的工具: + +- `healthCheck` +- `getTrace` +- `getArtifacts` +- `getSemanticSnapshot` +- `takeScreenshot` + +## 5. 模块改动建议 + +### 5.1 `internal/gateway/jsonrpc/handler.go` + +需要改: + +- 增加 `ping` +- 增加 `notifications/initialized` +- 增加 `notifications/cancelled` +- 增加 request / notification 分支辅助方法 +- 让 HTTP handler 能识别 notification 不回包 + +### 5.2 `internal/gateway/stdio/transport.go` + +需要改: + +- request 与 notification 分流 +- in-flight request registry +- 只对 request 写 response +- `notifications/cancelled` 能触发取消 + +### 5.3 新增 `internal/gateway/mcphttp` + +职责: + +- 标准 Streamable HTTP transport +- header 校验 +- response streaming + +### 5.4 `internal/gateway/mcp/tools.go` + +需要改: + +- 扩展 `Tool` 结构 +- registry 支持新字段反序列化 + +### 5.5 `internal/gateway/mcp/tools/*.json` + +需要改: + +- 为全部工具补 `title` +- 为全部工具补最小 `annotations` + +### 5.6 `internal/gateway/mcp/handler.go` + +需要改: + +- `initialize` 返回最新 protocol version +- `tools/call` 支持 `structuredContent` + +### 5.7 `cmd/gateway/main.go` + +需要改: + +- 注册新 MCP HTTP transport 路由 +- 决定旧 `/jsonrpc` compatibility route 的保留策略 + +## 6. 测试策略 + +### 6.1 单元测试 + +- handler: + - `ping` + - initialized notification + - cancelled notification +- tools: + - `title` + - `annotations` + - `structuredContent` + +### 6.2 transport 测试 + +- stdio: + - notification 不回包 + - cancelled 中止长请求 +- HTTP: + - version header 校验 + - Streamable HTTP 正常 request + - Streamable HTTP notification + +### 6.3 回归测试 + +- 现有 `tools/list` +- 现有 `tools/call` +- progress notification +- legacy direct methods + +## 7. 风险与取舍 + +### 7.1 `/jsonrpc` 是否保留 + +建议: + +- 本期保留 +- 但明确降级为 compatibility endpoint + +原因: + +- 可以避免一次性破坏现有外部集成 +- 标准 MCP 客户端逐步迁移到 `/mcp` + +### 7.2 `structuredContent` 覆盖范围 + +建议: + +- 不一次性覆盖全部 26 个工具 +- 先覆盖高价值、天然结构化的结果 + +### 7.3 取消能力边界 + +`notifications/cancelled` 本期目标应是: + +- 能取消 transport 内的 in-flight request +- 能把 cancellation 传播到当前请求 context + +不强求本期把所有业务 handler 都改造成完全可抢占中止,但至少长请求应能感知 context cancellation。 + +## 8. 交付顺序 + +1. 统一 request / notification 模型 +2. 补 `notifications/initialized`、`notifications/cancelled`、`ping` +3. 升级 `initialize` version +4. 引入 `Streamable HTTP` +5. 补 `MCP-Protocol-Version` header 校验 +6. 升级 tool metadata +7. 增量补 `structuredContent` diff --git a/requirements.mcp_alignment.md b/requirements.mcp_alignment.md new file mode 100644 index 0000000..bc3de97 --- /dev/null +++ b/requirements.mcp_alignment.md @@ -0,0 +1,150 @@ +# MCP 2025-06-18 对齐需求说明(历史基线) + +> 本文档记录已完成的 `2025-06-18` 对齐批次。当前 `2026-07-28` 实现与兼容边界以 [MCP_2026_07_28_ALIGNMENT.md](./MCP_2026_07_28_ALIGNMENT.md) 为准。 + +## 1. 背景 + +当前项目已经具备 MCP `stdio`、HTTP JSON-RPC、tool registry、progress notification 等基础能力,但仍停留在旧版握手与传输模型上。对照最新 MCP 官方规范,存在以下主要缺口: + +- 未正确处理 `notifications/initialized` +- 未支持 `ping` +- 未处理 `notifications/cancelled` +- HTTP 仍是自定义 request-response `/jsonrpc`,未升级到 `Streamable HTTP` +- 未校验 `MCP-Protocol-Version` HTTP header +- tool metadata 未包含 `title` 与 `annotations` +- tool result 未提供 `structuredContent` + +这些问题会造成: + +- 与最新 MCP 客户端互操作性下降 +- Claude Desktop 等客户端可能因为握手/保活不完整而出现异常 +- 服务端能力声明与真实实现不一致 +- 对外 HTTP 入口被误解为标准 MCP transport + +## 2. 目标 + +本期目标是实现“最新 MCP 核心互操作对齐”,具体包括: + +1. `stdio` transport 满足最新握手、notification、ping 语义。 +2. HTTP MCP 入口升级到标准 `Streamable HTTP` transport。 +3. MCP HTTP 入口校验并协商 `MCP-Protocol-Version`。 +4. `tools/list` 返回的 metadata 对齐最新 schema。 +5. `tools/call` 支持基础 `structuredContent` 返回能力。 + +## 3. 非目标 + +本期明确不包含: + +- OAuth +- Elicitation +- Async Tasks +- Tool icons +- sampling 中携带 tools / toolChoice +- 全量工具一次性补齐 `outputSchema` + +这些能力可以在后续版本中单独规划。 + +## 4. 功能需求 + +### 4.1 Lifecycle / Handshake + +- server 必须支持 `initialize`。 +- client 在 `initialize` 后发送 `notifications/initialized` 时,server 必须静默接收,不返回错误。 +- notification 不得触发 JSON-RPC response。 +- server 返回的 `protocolVersion` 必须与本期目标版本一致,或按显式协商规则返回受支持版本。 + +### 4.2 Ping + +- server 必须支持 `ping`。 +- 对 `ping` 返回空 result `{}`。 +- `stdio` 与 HTTP transport 上的 `ping` 行为必须一致。 + +### 4.3 Cancellation + +- server 必须接收 `notifications/cancelled`。 +- `notifications/cancelled` 中的 `requestId` 必须映射到当前 in-flight request。 +- 对可取消的长请求,应尽快停止关联处理逻辑。 +- 对已完成请求,允许忽略迟到的 cancellation notification,但不得报协议错误。 + +### 4.4 Streamable HTTP + +- 必须提供标准 `Streamable HTTP` MCP transport。 +- HTTP transport 必须支持 request、notification 与 server-to-client message 的规范化传输语义。 +- 现有 `/jsonrpc` request-response 兼容入口如保留,必须在文档中明确标记为 compatibility API,而非标准 MCP transport。 + +### 4.5 Protocol Version Header + +- MCP HTTP 请求必须校验 `MCP-Protocol-Version` header。 +- 缺失、非法或不兼容时,必须返回明确错误。 +- 成功响应应返回 negotiated/accepted protocol version。 + +### 4.6 Tool Metadata + +- `tools/list` 返回的每个 tool 必须支持: + - `name` + - `title` + - `description` + - `inputSchema` + - `annotations` +- `annotations` 至少支持: + - `readOnlyHint` + - `destructiveHint` + - `openWorldHint` +- 对已有 26 个工具,需要补齐最小 metadata,不允许 registry 与 JSON 文件口径不一致。 + +### 4.7 Tool Result + +- `tools/call` 必须继续支持现有 `content` 返回。 +- 支持工具可额外返回 `structuredContent`。 +- 若工具返回 `structuredContent`,其值必须可 JSON 序列化。 +- 本期不要求所有工具一次性提供结构化结果,但至少需要对高价值工具建立标准返回样例。 + +## 5. 兼容性要求 + +- 保持现有 `stdio` 客户端与现有 JSON-RPC compatibility client 不被破坏。 +- 现有 legacy direct methods 不在本次 MCP 对齐范围内移除,但不得影响 MCP 正常协商。 +- progress notification 现有行为必须保持兼容。 + +## 6. 可观测性要求 + +- 所有被忽略/接收的 MCP notifications 需要有低噪音日志,而不是 error 级噪音日志。 +- 对以下协议级行为记录结构化日志: + - initialize + - initialized + - ping + - cancelled + - protocol version negotiation + - Streamable HTTP session lifecycle + +## 7. 测试与验收 + +### 7.1 单元测试 + +- `notifications/initialized` 被静默接收且不回包。 +- `notifications/cancelled` 被静默接收并触发取消路径。 +- `ping` 返回 `{}`。 +- `tools/list` 含 `title` 与 `annotations`。 +- `tools/call` 可返回 `structuredContent`。 + +### 7.2 集成测试 + +- `stdio` 握手链路:`initialize -> notifications/initialized -> ping -> tools/list` +- HTTP MCP 链路:标准 `Streamable HTTP` request/response + progress +- HTTP header 校验失败路径 +- 长请求取消路径 + +### 7.3 文档验收 + +- README 中明确说明: + - 标准 MCP transport + - compatibility endpoint(如存在) + - protocol version + - 当前不支持的可选能力 + +## 8. 交付物 + +- MCP transport 代码变更 +- tool schema / JSON metadata 变更 +- 相关测试 +- README/集成文档更新 +- 版本升级说明