Files
goclaw/cmd/gateway_subagent_policy_inherit_test.go
HaiDuongandmor-phongdt b39f0decb9 fix(skills): five defects in slash activation, grants, subagent tool policy, preview and import (#1534)
* fix(agent): filter skill slash commands by the agent's grants

The inline <available_skills> block was already filtered by visibility and
agent grants, but slash activation read the loader's full skill list. A
/<slug> command could therefore activate a skill the agent was never granted,
and the not-found suggestions disclosed that such skills existed.

Resolve slash commands against the agent's allow list via FilterSkills. The
list is filtered before matching, so /list-skills, /help and the near-match
suggestions are all covered by the same change.

The allow-list convention is unchanged: nil means every skill (the fallback
when the access store errors), an empty slice means none, and a populated
slice is an explicit set of slugs.

* fix(agent): split slash commands on any whitespace

The tokenizer separated the skill name from the rest of the message with
strings.Cut(after, " ") — a literal space. A user who typed the command and
pressed Enter before the rest of the message sent "/ck:git\nreview the diff",
which parsed to the target "ck:git\nreview" and matched no skill. The reply
was "skill not found" followed by near-matches that included the skill they
had just named, because the similarity fallback searched the mangled string
and still landed beside it. Multi-line messages are ordinary in Slack and
Telegram, so this was reachable in normal use.

Introduce cutFirstField, which splits on the first run of whitespace, and use
it everywhere the literal-space split appeared. The match loop had the same
assumption in strings.HasPrefix(raw, value+" "); hasFieldPrefix replaces it
and decodes the following rune properly, so a multi-byte skill name is not
truncated. That also stops a plain string prefix from matching: a command for
"frontend-design-extra" no longer resolves to "frontend-design".

* fix(tools): inherit the parent agent's tool policy in spawned subagents

buildSubagentToolsRegistry clones the parent registry, then overwrites exec,
read_file, write_file and list_files with freshly constructed tools. A fresh
tool carries none of the hardening the gateway applies to the parent's
instances at startup: exec path denials and their exemptions, the shell
deny-group toggles, the command keyword allowlist, and the read/write/list
deny prefixes covering config.json, the internal databases and delegate/.

Spawning a subagent therefore widened what an agent could reach — the parent
was blocked from the data dir, the subagent was not. Verified by disabling
the new call: the subagent's exec read config.json out of the denied data
dir, read_file did the same, and write_file overwrote it.

Copy the policy from the live parent instances rather than re-deriving it, so
there is one source of truth and a deny path reloaded later through config
pub/sub reaches subagents without a second wiring site that can drift.

Allow-prefixes are inherited alongside the denials: they are what make the
denied roots usable at all, since the skills store sits under the denied data
dir. Copying denials without them would leave a subagent unable to read the
skills it is told to use.

* fix(agent): use one inline-vs-search decision for prompt and preview

The system-prompt preview exists to show the prompt an agent actually gets,
but it decided between inline skills and search mode on its own terms: it
counted tokens with the fallback counter over the fully rendered XML — tags
and <location> paths included, at roughly runes/2 — while the prompt builder
estimated name+description at chars/4. On the same eighteen skills that read
3087 against 944, so the preview reported search mode for an agent that was
running inline.

Extract shouldInlineSkills and call it from both paths. The estimate keeps
the prompt builder's rule, mirroring BuildSummary's 200-rune description
truncation, so the decision still costs no rendering.

The preview's loader interface gains FilterSkills to feed it. Its behaviour
on an access-store error is unchanged: an empty allow list yields no skills
rather than falling back to showing every skill.

* fix(http): keep reference files when importing skills

Export archives the whole skill directory, but import recognised only
metadata.json, SKILL.md and grants.jsonl. The switch had no default, so every
other file was discarded without a log line. A skill whose SKILL.md cites
references/*.md arrived without them, the import reported success, and the
skill failed at the first read.

Collect the remaining entries and write them under the skill directory with
their structure intact. Archive entry names are attacker-controlled, so each
path goes through sanitizeRelPath: a traversal attempt collapses to a
relative path and the write stays inside the skill directory.

* test(agent): make the inline-decision table exercise both gates

The "100 skills, 200-char descriptions" case claimed to cover the token
ceiling, but 100 exceeds the count ceiling so the count check short-circuited
and the token branch never ran — deleting that branch would not have failed
the test.

Split the table so each case isolates one gate: tiny descriptions for the
count rows, a count safely under the ceiling for the token rows. Removing the
token comparison now fails the over-the-ceiling case and nothing else.

* fix(agent): gate slash commands on the managed tier only

The allow list comes from a query over the `skills` table, so filesystem-tier
skills — the workspace, .agents and ~/.agents directories of the five-tier
loader — have no row in it. Filtering every skill against the list made those
four tiers unreachable by slash while skill_search still found them
unfiltered, which turned a security fix into a functional regression.

Apply the list to managed skills only. Builtins are seeded with is_system and
returned unconditionally, so they stay reachable either way.

This closes slash activation of ungranted managed skills. It does not close
skill_search and use_skill, which still read the loader's full list; that is a
wider change and wants its own review.

* fix(http): stop imported skill files from replacing guarded ones

Two ways the auxiliary write could go wrong.

GuardSkillContent scans SKILL.md before anything reaches disk, but the switch
that routes archive entries compares the raw path. An entry named
"./SKILL.md" does not match it, so it fell through to the auxiliary set —
where sanitizeRelPath collapses it back to "SKILL.md" and the write replaced
the file that had just been scanned. Reject any auxiliary path that resolves
to a name the import handles by itself, and log the attempt.

Tar directory entries carry a trailing separator and no content. Written as
files they took the name a real directory needed, so everything beneath was
dropped — and whether that happened depended on map iteration order, making
it intermittent. Skip them; MkdirAll creates what is needed.

Also cap the number of auxiliary files per skill and log when the cap trims
an archive, so a truncated import is visible rather than silent.

---------

Co-authored-by: mor-phongdt <phong.dangtuan@mor.com.vn>
2026-09-01 02:42:47 +07:00

128 lines
4.4 KiB
Go

package cmd
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/nextlevelbuilder/goclaw/internal/tools"
)
// A subagent's file and exec tools are constructed fresh, so they start with none of the
// hardening the gateway applies to the parent's instances at startup. Before this was
// wired, spawning a subagent widened reach: the parent could not read config.json or
// exec against the data dir, the subagent could. These tests pin the inheritance.
func TestSubagentToolsInheritParentPolicy(t *testing.T) {
workspace := t.TempDir()
dataDir := t.TempDir()
// The denied files must exist. Without them a read or a `cat` fails because the file
// is missing, the assertion sees IsError and passes — for the wrong reason. Verified
// by disabling the fix: only the write_file assertion went red until these existed.
if err := os.WriteFile(filepath.Join(workspace, "config.json"), []byte("{}"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dataDir, "config.json"), []byte("{}"), 0o644); err != nil {
t.Fatal(err)
}
parent := tools.NewRegistry()
parentRead := tools.NewReadFileTool(workspace, true)
parentRead.DenyPaths("config.json", "memory.db")
parentWrite := tools.NewWriteFileTool(workspace, true)
parentWrite.DenyPaths("config.json", "delegate/")
parentList := tools.NewListFilesTool(workspace, true)
parentList.DenyPaths("config.json")
parentExec := tools.NewExecTool(workspace, true)
parentExec.DenyPaths(dataDir)
parent.Register(parentRead)
parent.Register(parentWrite)
parent.Register(parentList)
parent.Register(parentExec)
reg, execTool := buildSubagentToolsRegistry(parent, workspace, true, nil, nil)
if reg == nil || execTool == nil {
t.Fatal("buildSubagentToolsRegistry returned nil")
}
ctx := context.Background()
// exec: a command referencing the parent's denied data dir must be refused.
res := execTool.Execute(ctx, map[string]any{"command": "cat " + dataDir + "/config.json"})
if res == nil {
t.Fatal("exec returned nil result")
}
if !res.IsError {
t.Errorf("subagent exec reached the parent's denied data dir: %+v", res)
}
// read_file: the parent's denied prefixes must apply.
rf, ok := reg.Get("read_file")
if !ok {
t.Fatal("read_file missing from subagent registry")
}
res = rf.Execute(ctx, map[string]any{"path": "config.json"})
if res == nil || !res.IsError {
t.Errorf("subagent read_file reached config.json: %+v", res)
}
// write_file: same.
wf, ok := reg.Get("write_file")
if !ok {
t.Fatal("write_file missing from subagent registry")
}
res = wf.Execute(ctx, map[string]any{"path": "config.json", "content": "x"})
if res == nil || !res.IsError {
t.Errorf("subagent write_file reached config.json: %+v", res)
}
}
// Inheriting denials without the parent's exemptions would leave the subagent unable to
// read the skills it is told to use: the skills store sits under the denied data dir.
func TestSubagentExecInheritsParentPathExemptions(t *testing.T) {
workspace := t.TempDir()
dataDir := t.TempDir()
skillsStore := dataDir + "/skills-store/"
if err := os.MkdirAll(filepath.Join(skillsStore, "demo"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(skillsStore, "demo", "SKILL.md"), []byte("# demo\n"), 0o644); err != nil {
t.Fatal(err)
}
parent := tools.NewRegistry()
parentExec := tools.NewExecTool(workspace, true)
parentExec.DenyPaths(dataDir)
parentExec.AllowPathExemptions(skillsStore)
parent.Register(parentExec)
_, execTool := buildSubagentToolsRegistry(parent, workspace, true, nil, nil)
res := execTool.Execute(context.Background(), map[string]any{"command": "cat " + skillsStore + "demo/SKILL.md"})
if res == nil {
t.Fatal("exec returned nil result")
}
if res.IsError {
t.Errorf("exemption did not carry over; reading the skills store was refused: %+v", res)
}
if !strings.Contains(res.ForLLM, "# demo") {
t.Errorf("expected the skill file contents, got %q", res.ForLLM)
}
}
// A parent registry without the tools, or with nothing configured, must not panic.
func TestSubagentToolsInheritTolerantOfMissingParentTools(t *testing.T) {
workspace := t.TempDir()
reg, execTool := buildSubagentToolsRegistry(tools.NewRegistry(), workspace, true, nil, nil)
if reg == nil || execTool == nil {
t.Fatal("expected a usable registry from an empty parent")
}
if _, ok := reg.Get("read_file"); !ok {
t.Error("read_file should still be registered")
}
}