Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ The mesh server refuses wildcard bind addresses.
- `allowed_peers`: node ids or names allowed to delegate to this worker.
- `allowed_cwds`: cwd globs evaluated after home expansion and realpath normalization.
- `hop_limit`: maximum delegation hop count.
- `profile_ceilings`: optional map from a **requested** profile name to a **ceiling** profile name. When a peer requests the keyed profile, the worker silently remaps the effective profile down to the ceiling (e.g. `profile_ceilings = { system-change = "repo-dev" }` caps any `system-change` request to `repo-dev`). A ceiling may only *cap* authority, never raise it: both profiles must be configured, the ceiling's runner must be configured, and the ceiling's risk must not exceed the profile it caps. Equal-risk mappings are allowed, since capping within a risk tier still narrows capabilities. A mapping that would raise authority is rejected when the config loads, and refused again at request time. The runner that executes is the **ceiling's** runner, not the requested profile's.
- `profile_ceilings`: optional map from a **requested** profile name to a **ceiling** profile name. When a peer requests the keyed profile, the worker silently remaps the effective profile down to the ceiling (e.g. `profile_ceilings = { system-change = "repo-dev" }` caps any `system-change` request to `repo-dev`). A ceiling may only *cap* authority, never raise or redirect it: both profiles must be configured, the ceiling's runner must be configured, and the ceiling must be a narrowing of the requested profile on every axis. Its `writes`, `shell`, `network`, `git_push` and risk must not exceed the requested profile's, and every capability it grants must be one the requested profile already holds, either listed or implied by an axis the requested profile already has (`edit_repo` by `writes` of `repo_only` or above, `execute_in_repo`/`execute_repo_commands` by `shell = "allow"`, `shell_readonly` by `shell` of `allowlisted` or above, network checks by `network = true`, `git_push` by `git_push = true`, and the read-only inspection capabilities used by `query` and `query-shell` by `shell = "allow"`). So an agent profile such as `repo-dev` or `system-change` can be capped to `query`, but `readonly-agent` (shell denied) cannot. Matching risk alone is not enough: `readonly-agent` and `query-shell` are both medium risk but grant different powers, so neither can cap the other. An outbound `denied_profiles` entry also applies to the ceiling a request is remapped to. A mapping that would raise authority is rejected when the config loads, and refused again at request time. The runner that executes is the **ceiling's** runner, not the requested profile's.

`[policy.outbound]` is enforced by the origin daemon before dispatch:

Expand Down
4 changes: 2 additions & 2 deletions docs/mcp-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ Profiles set the authority ceiling for a peer. The `query` profile is the safe d
| `profile_recommend` | both | Recommend the least-powerful profile for a stated intent and explain consent, TTL, safer alternative, and first tool to use. Param: `intent` (required). |
| `profile_generate` | both | Generate a built-in template preview and TOML snippet without writing config. Params: `template`, `name`, `runner`, `capabilities`, `os` (all optional). |
| `profile_validate` | both | Validate one profile capability contract and reject unsafe contradictions (e.g. `writes=deny` with an edit capability). Params: `runner` (required), `name`, `capabilities`, `writes`, `shell`, `network`, `git_push`, `require_explicit`, `require_lease`, `enforcement_confidence`. A profile granting a high-risk capability must set both `require_explicit` and `require_lease`, whatever it is named. |
| `profile_configure` | both | Preview or add a built-in profile to the local config (e.g. `repo-dev` bound to `codex` for a peer). Params: `template`, `name`, `runner`, `peer`, `allowed_peers`, `force`, `confirmed`. Requires `confirmed=true` to write. On the gateway it hot-reloads; on setup stdio, restart or use the gateway MCP to reload a running daemon. |
| `profile_configure` | both | Preview or add a built-in profile to the local config (e.g. `repo-dev` bound to `codex` for a peer). Params: `template`, `name`, `runner`, `peer`, `allowed_peers`, `force`, `confirmed`. Requires `confirmed=true` to write. A new or changed profile or runner takes effect only after the daemon restarts (the runner registry is built at startup); the response reports `active_immediately=false`, `requires_daemon_restart=true` and `restart_required_for` when that applies. |
| `profile_describe` | gateway | Describe one configured profile, including effective capabilities and lease/explicit requirements. Param: `profile` (required). |
| `profile_current` | gateway | Show the gateway's active per-peer profile context. Empty `delegate` and `query_peer` profile requests resolve from this context, then default to `query`. No parameters. |
| `profile_use` | gateway | Set the active profile for a peer. The worker still enforces its own policy and may deny the request. Params: `peer` (required), `profile` (required), `cwd`, `ttl`, `profile_acknowledgement`. `ttl` is required for profiles with `require_lease=true`. |
Expand All @@ -106,7 +106,7 @@ Profiles set the authority ceiling for a peer. The `query` profile is the safe d
| Tool | Surface | Purpose |
|---|---|---|
| `doctor` | both | Check local cmesh setup readiness: config, Tailscale identity and reachability, runners, and gateway details. On the setup surface it checks readiness before the daemon is running. No parameters. |
| `repair_peers` | both | Diagnose and fix wrong, stale, or broken `[peers.*]` entries. Use it when a peer stops authenticating (`peer_unauthorized`) or an entry looks wrong. Checks every configured peer against its authoritative Tailscale `whois` identity and returns a per-peer diff (`ok`, `fixable`, `conflict`, `unreachable`). Param: `confirmed`. Without it, only reports. With `confirmed=true`, rewrites `fixable` entries to the whois-matchable identity, prunes stale duplicates, and reconciles allowlists while preserving trust posture. It never trusts a peer's self-reported `/v1/hello` name for the allowlist; `conflict` and `unreachable` peers are left unchanged. On the gateway the running daemon reloads the repaired policy immediately; the response reports `active_immediately` and only asks for a restart if that reload failed. |
| `repair_peers` | both | Diagnose and fix wrong, stale, or broken `[peers.*]` entries. Use it when a peer stops authenticating (`peer_unauthorized`) or an entry looks wrong. Checks every configured peer against its authoritative Tailscale `whois` identity and returns a per-peer diff (`ok`, `fixable`, `conflict`, `unreachable`). Param: `confirmed`. Without it, only reports. With `confirmed=true`, rewrites `fixable` entries to the whois-matchable identity, prunes stale duplicates, and reconciles allowlists while preserving trust posture. It never trusts a peer's self-reported `/v1/hello` name for the allowlist; `conflict` and `unreachable` peers are left unchanged. On the gateway the running daemon reloads the repaired peers and policy immediately and reports `active_immediately`. A reload applies only `[peers.*]` and `[policy]` (not `profile_ceilings`); if other sections such as profiles or runners also differ on disk, they are left inactive and named in `restart_required_for` with `requires_daemon_restart=true`. |

`repair_peers` is the one tool you may reach for long after onboarding. See [MCP onboarding tools](mcp-onboarding.md#repair_peers-both-surfaces) for the full per-status behavior.

Expand Down
2 changes: 1 addition & 1 deletion docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ A question moves the task to `awaiting_input`, which is non-terminal: the runner

Subdelegation provenance is derived from a per-task token, not from model-supplied chain fields. When a worker task starts, cmesh writes a local task context, exposes a task token to that runner as `CMESH_TASK_TOKEN`, and registers a task-scoped cmesh MCP gateway for supported agent runners. Claude Code loads a strict task MCP config file; Codex ignores ambient user MCP config for that invocation and injects the local cmesh gateway with `bearer_token_env_var = "CMESH_TASK_TOKEN"`. MCP calls from the worker therefore carry the token structurally even when the gateway requires `host_token`.

On the **local gateway**, a caller holding the gateway `host_token` is this machine's own agent and may read any task this node delegated — `peer_tasks` is precisely that mirror, and origin-restart recovery depends on those lookups. A caller holding only a **per-task token** is a worker's runner reaching back in during subdelegation, and its reads are scoped to the token's origin session: it may read status, results, transcripts, and artifacts for, and cancel, its own task and anything that task delegated onward, and nothing else. `list_tasks` is filtered to that session and withholds this node's local task history. Tasks mirrored before this scoping existed carry no session and are reachable only with the host token.
On the **local gateway**, a caller holding the gateway `host_token` is this machine's own agent and may read any task this node delegated — `peer_tasks` is precisely that mirror, and origin-restart recovery depends on those lookups. A caller holding only a **per-task token** is a worker's runner reaching back in during subdelegation, and its reads are scoped to the tasks that token delegated: each task it creates is recorded with the worker task the token was minted for as its owner, and it may read status, results, transcripts, and artifacts for, follow up, and cancel only those tasks. The origin session is not the boundary, since every host-token delegation that omits `origin_session_id` shares `gateway-default`. `list_tasks` is filtered the same way and withholds this node's local task history. Host-token delegations and tasks mirrored before ownership was recorded have no owner and are reachable only with the host token. Ownership is per task, not per follow-up chain: a follow-up runs under its own task token, so it cannot reach children its predecessor delegated; the host token still can.

Legacy provenance fields such as `origin_node_id`, `delegation_chain`, and `hop_count` are treated as compatibility hints only. On the local subdelegation path they are ignored when a task token is present, and they are never authoritative for **authorization**. A local request without a valid task token is treated as a fresh local origin and does not inherit worker provenance. On the direct mesh-RPC path these fields are also non-authoritative for authorization: the inbound peer gate, profile-level `allowed_peers`, and task ownership all key on the `whois`-authenticated peer's **unique** node identity (node id / stable id / DNS label) — never on the request-supplied `origin_node_id`, and never on a shared Tailscale tag. The fields feed only audit display and the advisory hop/cycle backstops described below.

Expand Down
128 changes: 99 additions & 29 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"time"
Expand Down Expand Up @@ -264,18 +265,10 @@ func (c *Config) ApplyDefaults(configDir string) error {
prof.Claims = append([]string(nil), prof.Capabilities...)
}
if prof.Writes == "" {
if containsString(prof.Capabilities, profiledefs.CapEditRepo) || containsString(prof.Capabilities, profiledefs.CapExecuteInRepo) {
prof.Writes = profiledefs.WritesRepoOnly
} else {
prof.Writes = profiledefs.WritesDeny
}
prof.Writes = defaultWrites(prof.Capabilities)
}
if prof.Shell == "" {
if containsString(prof.Capabilities, profiledefs.CapExecuteInRepo) || containsString(prof.Capabilities, profiledefs.CapExecuteRepoCommands) {
prof.Shell = profiledefs.ShellAllow
} else {
prof.Shell = profiledefs.ShellDeny
}
prof.Shell = defaultShell(prof.Capabilities)
}
if prof.AuditLevel == "" {
prof.AuditLevel = "normal"
Expand Down Expand Up @@ -315,6 +308,50 @@ func pickDefaultProfile(profiles map[string]ProfileConfig) string {
return first
}

// Reloadable returns a copy of c that takes from next only what a running
// daemon may apply without a restart: the [peers.*] entries and the [policy]
// table, except policy.profile_ceilings. Everything else -- profiles, runners,
// ceilings, node, tailnet, store, audit and gateway settings -- stays as c has
// it, and held lists each of those sections that differs in next.
//
// Profiles, ceilings and runners stay put because the runner registry is built
// once at startup from them. Reloading them would let policy accept a task
// under one profile definition while the runner executes it with another, and
// a peer repair would silently pick up unrelated profile edits from disk.
func (c *Config) Reloadable(next *Config) (merged *Config, held []string) {
out := *c
out.Peers = next.Peers
out.Policy = next.Policy
out.Policy.ProfileCeilings = c.Policy.ProfileCeilings
for _, section := range []struct {
name string
current, next any
}{
{"profiles", c.Profiles, next.Profiles},
{"runners", c.Runners, next.Runners},
{"policy.profile_ceilings", c.Policy.ProfileCeilings, next.Policy.ProfileCeilings},
{"node", c.Node, next.Node},
{"tailscale", c.Tailnet, next.Tailnet},
{"store", c.Store, next.Store},
{"audit", c.Audit, next.Audit},
{"gateway", c.Gateway, next.Gateway},
} {
if !reloadEqual(section.current, section.next) {
held = append(held, section.name)
}
}
return &out, held
}

// reloadEqual compares two config sections, treating nil and empty maps alike.
func reloadEqual(a, b any) bool {
va, vb := reflect.ValueOf(a), reflect.ValueOf(b)
if va.Kind() == reflect.Map && vb.Kind() == reflect.Map && va.Len() == 0 && vb.Len() == 0 {
return true
}
return reflect.DeepEqual(a, b)
}

func (c *Config) Validate() error {
if c.Node.Name == "" {
return errors.New("node.name is required")
Expand Down Expand Up @@ -427,16 +464,12 @@ func (c *Config) Validate() error {
// authority instead of capping it.
//
// A ceiling remaps a requested profile down to a weaker one at policy time. The
// remap is unconditional, so a mapping pointing at a *stronger* profile silently
// escalates every request naming the keyed profile — the opposite of what the
// field is for. Both endpoints must exist, and the ceiling's risk rank must not
// exceed the requested profile's.
//
// The comparison is rank <=, not <, so an equal-risk remap stays legal: the
// documented example (system-change -> repo-dev) is high -> high, and capping
// within a risk tier is a legitimate narrowing of capabilities. Risk comes from
// RiskForConfig rather than RiskForProfile because the latter returns "" for
// any custom profile name, which would make an unknown name compare as weakest.
// remap is unconditional, so a mapping pointing at a profile with *more* or
// *different* authority silently grants it to every request naming the keyed
// profile — the opposite of what the field is for. Both endpoints must exist,
// and the ceiling must be a narrowing of the requested profile on every axis
// (see profiledefs.CeilingExcess). Comparing only the risk rank is not enough:
// two medium-risk profiles can grant disjoint powers.
func (c *Config) validateProfileCeilings() error {
names := make([]string, 0, len(c.Policy.ProfileCeilings))
for requested := range c.Policy.ProfileCeilings {
Expand All @@ -456,23 +489,60 @@ func (c *Config) validateProfileCeilings() error {
if _, ok := c.Runners[ceilingProfile.Runner]; !ok {
return fmt.Errorf("policy.profile_ceilings[%q] ceiling profile %q references unknown runner %q", requested, ceiling, ceilingProfile.Runner)
}
if profiledefs.RiskRank(profileRisk(ceiling, ceilingProfile)) > profiledefs.RiskRank(profileRisk(requested, requestedProfile)) {
if excess := profiledefs.CeilingExcess(ceilingProfile.Authority(ceiling), requestedProfile.Authority(requested)); excess != "" {
return fmt.Errorf(
"policy.profile_ceilings[%q] raises authority: ceiling %q is risk=%s but %q is risk=%s; a ceiling must not exceed the profile it caps",
requested, ceiling, profileRisk(ceiling, ceilingProfile), requested, profileRisk(requested, requestedProfile),
"policy.profile_ceilings[%q] raises authority: ceiling %q %s of %q; a ceiling must not exceed the profile it caps",
requested, ceiling, excess, requested,
)
}
}
return nil
}

// profileRisk returns a profile's effective risk, preferring the explicit risk
// field and falling back to the capability-derived value.
func profileRisk(name string, prof ProfileConfig) string {
if prof.Risk != "" {
return prof.Risk
// Authority returns the authority this profile grants, for ceiling comparison.
// Unset writes and shell take the same defaults Load applies, so a profile
// built in-process compares the same way as one read from disk. Risk prefers
// the explicit field and falls back to the capability-derived value; it uses
// RiskForConfig rather than RiskForProfile because the latter returns "" for
// any custom profile name.
func (prof ProfileConfig) Authority(name string) profiledefs.Authority {
capabilities := profiledefs.NormalizeCapabilities(prof.Capabilities, prof.Claims)
writes := prof.Writes
if writes == "" {
writes = defaultWrites(capabilities)
}
shell := prof.Shell
if shell == "" {
shell = defaultShell(capabilities)
}
risk := prof.Risk
if risk == "" {
risk = profiledefs.RiskForConfig(name, capabilities, writes, shell, prof.Network)
}
return profiledefs.Authority{
Capabilities: capabilities,
Writes: writes,
Shell: shell,
Network: prof.Network,
GitPush: prof.GitPush,
Risk: risk,
}
}

// defaultWrites is the writes level for a profile that does not set one.
func defaultWrites(capabilities []string) string {
if containsString(capabilities, profiledefs.CapEditRepo) || containsString(capabilities, profiledefs.CapExecuteInRepo) {
return profiledefs.WritesRepoOnly
}
return profiledefs.WritesDeny
}

// defaultShell is the shell level for a profile that does not set one.
func defaultShell(capabilities []string) string {
if containsString(capabilities, profiledefs.CapExecuteInRepo) || containsString(capabilities, profiledefs.CapExecuteRepoCommands) {
return profiledefs.ShellAllow
}
return profiledefs.RiskForConfig(name, profiledefs.NormalizeCapabilities(prof.Capabilities, prof.Claims), prof.Writes, prof.Shell, prof.Network)
return profiledefs.ShellDeny
}

func containsString(values []string, needle string) bool {
Expand Down
Loading