diff --git a/changelog.d/security-task-mcp-remote-url-never-hub.md b/changelog.d/security-task-mcp-remote-url-never-hub.md new file mode 100644 index 0000000000..ab63e26598 --- /dev/null +++ b/changelog.d/security-task-mcp-remote-url-never-hub.md @@ -0,0 +1 @@ +- With `task_mcp.remote_enabled` on, a hive that set neither `dashboard.public_url` nor `hub.dashboard_url` named the hub as its own task MCP: `task_assign` carried `mcp.url = /api/contribute/mcp` (`https://hive.hivecommons.dev`, the default on every hive) together with this hive's lease bearer, the relay wrote both into the contributor's `.mcp.json`, and the contributor's agent presented the bearer to the hub. A hive whose hub link is off but that still held a `hub.dashboard_url` handed that stale address out the same way. `mcp.url` is now only ever this hive's own address: `dashboard.public_url`, or `hub.dashboard_url` while `hub.enabled` is true. `hub.url` is never used. A hive with no such address sends no `mcp` block and mints no bearer, so its contributors work without the task MCP until the operator sets `dashboard.public_url`. diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index dd9a9cfaa9..0a5c153741 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -19,7 +19,7 @@ You do not need the operator or wire-protocol sections to start one relay. In th ### What your agent can see -The hub grants task context only for the task it assigned. When `task_mcp.remote_enabled` is on, `task_assign` includes a lease-scoped MCP server (`mcp.url`, `mcp.token`, `mcp.expires_at`). The relay writes it as a standard `mcpServers.hive_task` config for the launched CLI and omits the token from the debug task file. +The hub grants task context only for the task it assigned. When `task_mcp.remote_enabled` is on, `task_assign` includes a lease-scoped MCP server (`mcp.url`, `mcp.token`, `mcp.expires_at`). The relay writes it as a standard `mcpServers.hive_task` config for the launched CLI and omits the token from the debug task file. `mcp.url` is always the assigning hive's own public address: its `dashboard.public_url`, or its `hub.dashboard_url` when the hive is linked to a hosted hub. A hive with neither sends no `mcp` block, and your agent works the task without the task MCP. That MCP lease is read-only and bound to the task id, contributor session identity, repo, issue/PR number, and task-lease expiry. It can call `task_context`, `related_work`, `ci_health`, and `context_bundle` for that task's repo and related issue/PR set only. Asking for another repo or task returns a typed refusal in the tool's `data` field and is audited by the hub. Releasing, completing, failing, yanking, or expiring the task revokes the MCP token with the task lease. diff --git a/src/docs/design/task-mcp.md b/src/docs/design/task-mcp.md index 474264cf08..207d220638 100644 --- a/src/docs/design/task-mcp.md +++ b/src/docs/design/task-mcp.md @@ -39,6 +39,8 @@ Remote contributor relays can opt in with `task_mcp.remote_enabled: true`. When } ``` +`mcp.url` is always an address of the assigning hive itself, because the relay sends the lease bearer to it. It is `dashboard.public_url` when that is set, otherwise the `hub.dashboard_url` of a hive whose hub link is on (`hub.enabled: true`). `hub.url` names the hosted hub the hive reports to, not the hive itself, and has a default on every hive, so it is never used. A `hub.dashboard_url` left on a hive whose hub link is off is ignored as stale. A hive with no address left sends no `mcp` block and mints no lease bearer: the contributor works the task without the task MCP, and the hive logs `task_assign carries no mcp block` at info level for each such task. Set `dashboard.public_url` to an origin contributors can reach to hand the task MCP out. + The relay writes that block as the standard `mcpServers` JSON shape (`hive_task`) in its contributor config directory and as `.mcp.json` in the launched agent working directory. The token is not written to the debug task file. Existing dashboard/contribute authorization still works; the lease bearer is an additional remote credential and is accepted only while the server-side lease record still matches its id, hash, task, repo, contributor identity, stage, and expiry. All tools resolve scope from the lease when a lease bearer is used. A request for another task, repository, or number returns a typed refusal inside the fixed-schema `data` field instead of serving cross-task content, and the hub logs the lease id, tool, and requested repo. A staged token is valid only while the live lease remains in the same stage; once a run advances or resets, using the older stage's token returns `stage_mismatch` and records an audit entry. Unstaged lease tokens keep the previous cross-task-only behavior. Calls are rate-limited per lease; `task_mcp.lease_rate_limit_per_minute` defaults to `config.DefaultTaskMCPLeaseRateLimitPerMinute`. diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index c8eec88283..d70d7b29ec 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -298,7 +298,7 @@ Go callers keep reading `cfg.Agents`, `cfg.Governor.Gateways` and so on through | `dashboard.authorized_users` | Empty means no per-user direct-route allowlist. | Entries can be `user` or `user:role`; roles are `read`, `read-write`, `merger`, `owner`. | | `notifications.discord.allowed_users` / `notifications.slack.allowed_users` | Empty means chat commands are disabled for that surface. | Entries can be `id` or `id:role`; roles are `read`, `read-write`, `merger`, `owner`. For backwards compatibility, entry #0 without a suffix is `owner`; later bare entries are `read`. IDs match the way `dashboard.authorized_users` does — case-insensitively, with a `github:` prefix optional on either side — and the first entry for an ID wins. | | `github.mentions.*` | Disabled unless `github.mentions.enabled: true`. | Polls GitHub issue/PR comments for `@` summons. Summoners must hold `read-write` (or `min_role`) in `dashboard.authorized_users` or be listed in `summoners`; agents opt in with both `kick` and `mention` channels plus `converse: true` so #5591's dormant-channel guard still fails fast. | -| `dashboard.public_url` | Empty means OAuth redirect URIs (Linear agent install, OpenRouter funding) fall back to `hub.dashboard_url`, then the request's forwarded/`Host` origin. | Set to this dashboard's externally reachable origin (`https://hive.example.com`, no path/query) on a standalone hive whose callback is published on a different hostname or whose ingress rewrites `Host`. Must be an absolute `http(s)://` origin; a trailing slash is trimmed and anything else fails config load. See [linear-agent.md](../linear-agent.md#setup). | +| `dashboard.public_url` | Empty means OAuth redirect URIs (Linear agent install, OpenRouter funding) fall back to `hub.dashboard_url`, then the request's forwarded/`Host` origin. | Set to this dashboard's externally reachable origin (`https://hive.example.com`, no path/query) on a standalone hive whose callback is published on a different hostname or whose ingress rewrites `Host`. Must be an absolute `http(s)://` origin; a trailing slash is trimmed and anything else fails config load. See [linear-agent.md](../linear-agent.md#setup). With `task_mcp.remote_enabled` it is also the address remote contributors are given for the task MCP; a hive with neither this nor a hub-assigned `hub.dashboard_url` hands out none ([task-mcp.md](../design/task-mcp.md#phase-2-lease-scoped-remote-contributors)). | | `dashboard.experiment_lab` | Off by default. | Hides the Experiment Lab (formerly Strategy Lab) while that surface is being reworked. Set `dashboard.experiment_lab: true` to show the Experiment Lab section, sidebar nav entry, and Nous status controls. | | `dashboard.strategy_lab` | Off by default. **Deprecated** alias of `dashboard.experiment_lab`, kept for one release (#11695). | `true` still enables the Experiment Lab and logs a one-line deprecation at config load; the value is folded into `dashboard.experiment_lab` so the next config save writes the documented key. | | `dashboard.matrix` | Off by default (`enabled: false`, `repos: []`, `exclude_paths: []`). **Experimental.** | Code activity source; see [Code activity reader](../dashboard.md#code-activity-reader) for presentation, compatibility, capture and access policies. When active, pushed lines from allow-listed repos are served to authenticated read-role viewers via `GET /api/matrix/lines?since=&max=` (bounded backlog, `Cache-Control: no-store`; `404` when inactive) and `/api/events` emits a content-free `code-lines` nudge (`{"seq":N}`, ≤1/s) telling browsers to pull. `repos` is an explicit exact `owner/name` allowlist (no wildcards, URLs or bare names) and an empty list captures nothing, so `enabled: true` alone stays inactive. `exclude_paths` adds non-empty path globs to the built-in deny-list. There is no `authors` or `private_repos` key: authors are fixed and private repos are always excluded. | diff --git a/src/pkg/dashboard/task_mcp_lease.go b/src/pkg/dashboard/task_mcp_lease.go index e2a57b734e..b3979677eb 100644 --- a/src/pkg/dashboard/task_mcp_lease.go +++ b/src/pkg/dashboard/task_mcp_lease.go @@ -31,12 +31,24 @@ func (s *Server) taskMCPLeaseSecret() []byte { return []byte(s.authToken) } +// taskMCPURL is the task MCP endpoint a remote contributor is given in +// task_assign, or "" when this hive has no public address of its own. The +// relay sends the lease bearer there, so only an address of THIS hive +// qualifies: dashboard.public_url, or hub.dashboard_url while the hub is +// enabled. A disabled hub leaves a stale one behind, which is why +// resolveSpokeDashboardURL (cmd/hive) has the same condition since #10282. +// hub.url is the hub itself and has a default on every hive, so it is never +// an answer, and neither is that resolver's last resort, the local port. func (s *Server) taskMCPURL() string { if s == nil || s.deps == nil || s.deps.Config == nil { return "" } cfg := s.deps.Config - for _, raw := range []string{cfg.Dashboard.PublicURL, cfg.Hub.DashboardURL, cfg.Hub.URL} { + candidates := []string{cfg.Dashboard.PublicURL} + if cfg.Hub.Enabled { + candidates = append(candidates, cfg.Hub.DashboardURL) + } + for _, raw := range candidates { raw = strings.TrimRight(strings.TrimSpace(raw), "/") if raw == "" { continue @@ -87,9 +99,14 @@ func (h *ContributeWSHub) mintTaskMCPForAssignment(identity string, assign *WSTa if h == nil || h.server == nil || assign == nil || !h.server.taskMCPRemoteEnabled() { return nil } - endpoint := h.server.taskMCPURL() secret := h.server.taskMCPLeaseSecret() - if endpoint == "" || len(secret) == 0 { + if len(secret) == 0 { + return nil + } + endpoint := h.server.taskMCPURL() + if endpoint == "" { + h.logger.Info("[task-mcp] task_assign carries no mcp block: this hive has no public address", + "task", assign.TaskID, "repo", assign.Repo, "hint", "set dashboard.public_url to an address contributors can reach") return nil } stage := "" diff --git a/src/pkg/dashboard/task_mcp_remote_url_test.go b/src/pkg/dashboard/task_mcp_remote_url_test.go new file mode 100644 index 0000000000..1dbf4e07d0 --- /dev/null +++ b/src/pkg/dashboard/task_mcp_remote_url_test.go @@ -0,0 +1,185 @@ +package dashboard + +import ( + "encoding/json" + "testing" + "time" + + "github.com/hivecommons/hive/crux/taskmcp" + "github.com/hivecommons/hive/pkg/config" +) + +// The relay sends a task's lease bearer to whatever task_assign's mcp.url +// names, so that URL may only ever be an address of the assigning hive. +// hub.url is the hub itself and applyDefaults fills it on every hive; it used +// to be the last fallback, and a hub.dashboard_url left behind by a disabled +// hub was honoured too, so a hive with no public address of its own told its +// contributors to present its bearer to the hub. + +// remoteMCPHubURL is what applyDefaults gives hub.url on every hive. +const remoteMCPHubURL = "https://hive.hivecommons.dev" + +// remoteMCPHive is a hive with task_mcp.remote_enabled, a dashboard token to +// sign lease bearers with, and one task leased to alice. +func remoteMCPHive(t *testing.T, mutate func(*config.Config)) (*ContributeWSHub, *WSTaskAssign) { + t.Helper() + dir := t.TempDir() + t.Setenv("HIVE_CONTRIBUTORS_DIR", dir) + redirectContributeWSDisk(t, dir) + cfg := &config.Config{} + cfg.TaskMCP.RemoteEnabled = true + cfg.Dashboard.Port = 3001 + cfg.Hub.URL = remoteMCPHubURL + mutate(cfg) + s := newTestServer() + s.authToken = "secret" + s.deps = &Dependencies{Config: cfg} + h := NewContributeWSHub(s.logger, s) + t.Cleanup(h.Close) + s.contributeHub = h + assign := &WSTaskAssign{TaskID: "task-url", Kind: "issue", Repo: "owner/repo", Number: 42} + if err := h.recordLeaseForKey("alice-id", assign.TaskID, assign.Repo, assign.Number, assign.identityKey(), "trusted", 2, time.Now()); err != nil { + t.Fatalf("recordLeaseForKey: %v", err) + } + return h, assign +} + +// leaseHoldsMCPToken reports whether a lease bearer was minted for the task. +func leaseHoldsMCPToken(t *testing.T, h *ContributeWSHub, identity, taskID string) bool { + t.Helper() + h.leaseMu.Lock() + defer h.leaseMu.Unlock() + l := h.leaseForLocked(identity, taskID) + if l == nil { + t.Fatalf("no lease recorded for %s on %s", identity, taskID) + } + return l.mcpTokenID != "" || l.mcpTokenHash != "" +} + +func TestRemoteMCPBlockWithheldWithoutAPublicAddressOfThisHive(t *testing.T) { + for _, tc := range []struct { + name string + mutate func(*config.Config) + }{ + {"hub-less hive without dashboard.public_url", func(cfg *config.Config) {}}, + {"hub-less hive with a stale hub.dashboard_url", func(cfg *config.Config) { + cfg.Hub.DashboardURL = "https://old-name.hive.hivecommons.dev" + }}, + {"hub spoke the hub has not given a dashboard_url yet", func(cfg *config.Config) { + cfg.HiveID = "hive-example" + cfg.Hub.Enabled = true + }}, + } { + t.Run(tc.name, func(t *testing.T) { + h, assign := remoteMCPHive(t, tc.mutate) + if got := h.server.taskMCPURL(); got != "" { + t.Errorf("taskMCPURL = %q, want none: it is not an address of this hive", got) + } + mcp := h.mintTaskMCPForAssignment("alice-id", assign, time.Now().Add(leaseTTL), "alice") + if mcp != nil { + t.Errorf("task_assign.mcp.url = %q (bearer attached: %v), want no mcp block", mcp.URL, mcp.Token != "") + } + if leaseHoldsMCPToken(t, h, "alice-id", assign.TaskID) { + t.Error("a lease bearer was minted although there is no URL to present it to") + } + }) + } +} + +func TestRemoteMCPURLNamesThisHive(t *testing.T) { + for _, tc := range []struct { + name string + mutate func(*config.Config) + want string + }{ + {"dashboard.public_url on a hub-less hive", func(cfg *config.Config) { + cfg.Dashboard.PublicURL = "https://hive.example" + }, "https://hive.example"}, + {"dashboard.public_url beside a stale hub.dashboard_url", func(cfg *config.Config) { + cfg.Dashboard.PublicURL = "https://hive.example" + cfg.Hub.DashboardURL = "https://old-name.hive.hivecommons.dev" + }, "https://hive.example"}, + {"hub spoke with the dashboard_url its hub gave it", func(cfg *config.Config) { + cfg.HiveID = "hive-example" + cfg.Hub.Enabled = true + cfg.Hub.DashboardURL = "https://example.hive.hivecommons.dev/" + }, "https://example.hive.hivecommons.dev"}, + {"dashboard.public_url still comes first on a hub spoke", func(cfg *config.Config) { + cfg.Hub.Enabled = true + cfg.Hub.DashboardURL = "https://example.hive.hivecommons.dev" + cfg.Dashboard.PublicURL = "https://hive.example" + }, "https://hive.example"}, + {"a dashboard.public_url the operator set is used as written", func(cfg *config.Config) { + cfg.Dashboard.PublicURL = "http://localhost:3001" + }, "http://localhost:3001"}, + } { + t.Run(tc.name, func(t *testing.T) { + h, assign := remoteMCPHive(t, tc.mutate) + want := tc.want + taskmcp.EndpointPath + mcp := h.mintTaskMCPForAssignment("alice-id", assign, time.Now().Add(leaseTTL), "alice") + if mcp == nil { + t.Fatalf("no mcp block, want a bearer for %s", want) + } + if mcp.URL != want || mcp.Token == "" { + t.Fatalf("task_assign.mcp.url = %q (bearer attached: %v), want a bearer for %s", mcp.URL, mcp.Token != "", want) + } + if !leaseHoldsMCPToken(t, h, "alice-id", assign.TaskID) { + t.Error("the minted bearer was not recorded on the lease") + } + }) + } +} + +// End-to-end through selectTask: the task_assign a contributor receives. +func TestSelectTaskAssignCarriesRemoteMCPBlockOnlyForThisHive(t *testing.T) { + assignFor := func(t *testing.T, mutate func(*config.Config)) (*ContributeWSHub, *ContributorConnection, *WSMessage) { + t.Helper() + hub, s := covK2Hub(t) + oneActionableIssue(s) + s.authToken = "secret" + s.deps.Config.TaskMCP.RemoteEnabled = true + s.deps.Config.Hub.URL = remoteMCPHubURL + mutate(s.deps.Config) + conn := &ContributorConnection{ + profile: &ContributorProfile{GitHubUsername: "alice", ContributorID: "alice-id", TrustTier: "trusted"}, + cliBackend: "claude", + } + msg := hub.selectTask(conn) + if msg == nil || msg.Type != "task_assign" { + t.Fatalf("expected task_assign, got %+v", msg) + } + return hub, conn, msg + } + + t.Run("no public address", func(t *testing.T) { + hub, conn, msg := assignFor(t, func(cfg *config.Config) {}) + if msg.MCP != nil { + t.Errorf("task_assign.mcp.url = %q (bearer attached: %v), want no mcp block", msg.MCP.URL, msg.MCP.Token != "") + } + wire, err := json.Marshal(msg) + if err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(wire, &fields); err != nil { + t.Fatal(err) + } + if _, ok := fields["mcp"]; ok { + t.Error("task_assign on the wire still has an mcp key") + } + if leaseHoldsMCPToken(t, hub, identityOf(conn), msg.TaskID) { + t.Error("a lease bearer was minted although task_assign carries no mcp block") + } + }) + + t.Run("dashboard.public_url", func(t *testing.T) { + _, _, msg := assignFor(t, func(cfg *config.Config) { cfg.Dashboard.PublicURL = "https://hive.example" }) + want := "https://hive.example" + taskmcp.EndpointPath + if msg.MCP == nil { + t.Fatalf("no mcp block, want a bearer for %s", want) + } + if msg.MCP.URL != want || msg.MCP.Token == "" { + t.Fatalf("task_assign.mcp.url = %q (bearer attached: %v), want a bearer for %s", msg.MCP.URL, msg.MCP.Token != "", want) + } + }) +}