Skip to content
Open
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
50 changes: 49 additions & 1 deletion src/skillspector/nodes/analyzers/mcp_least_privilege.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,39 @@
for capability, patterns in _CAPABILITY_PATTERNS.items()
}

# Go-only capability patterns, applied only to .go files (see _detect_capabilities).
# The shared table above is language-agnostic, so a Go call such as os.Open
# must not leak into Python files, where os.open takes open flags and a
# write-only call would otherwise count as read evidence. os.Getenv stays in
# the shared table: it was already covered there before this change.
# io.ReadAll is deliberately absent: it consumes any io.Reader (a network
# response body, an in-memory buffer), so on its own it proves nothing about
# file access. A file opened with os.Open still counts through os.Open.
_GO_CAPABILITY_PATTERNS: dict[str, list[str]] = {
"file_read": [
r"os\.readfile",
r"os\.open\b",
r"os\.readdir",
r"filepath\.walk",
r"filepath\.glob",
r"ioutil\.readfile",
],
"file_write": [
r"os\.writefile",
r"os\.create\b",
r"os\.createtemp",
r"ioutil\.writefile",
],
"env": [
r"os\.lookupenv",
r"os\.expandenv",
],
}
_COMPILED_GO_CAPABILITY_PATTERNS = {
capability: tuple(re.compile(pattern, re.IGNORECASE) for pattern in patterns)
for capability, patterns in _GO_CAPABILITY_PATTERNS.items()
}

# Permission string → capability category mapping (case-insensitive word-boundary matching)
_PERM_TO_CAPABILITY: dict[str, str] = {
"bash": "shell",
Expand Down Expand Up @@ -287,8 +320,13 @@ def _detect_capabilities(
budget: _LeastPrivilegeBudget | None = None,
path: str = "SKILL.md",
) -> set[str]:
"""Return capabilities using bounded windows and cooperative checks."""
"""Return capabilities using bounded windows and cooperative checks.

Go-only patterns apply only to .go files, so a Go call never counts as
evidence in a Python or JavaScript file.
"""
found: set[str] = set()
is_go = Path(path).suffix.lower() == ".go"
step = _CAPABILITY_WINDOW_CHARS - _CAPABILITY_WINDOW_OVERLAP_CHARS
for start in range(0, max(1, len(content)), step):
if budget is not None:
Expand All @@ -303,6 +341,16 @@ def _detect_capabilities(
if pattern.search(window) is not None:
found.add(capability)
break
if is_go:
for capability, patterns in _COMPILED_GO_CAPABILITY_PATTERNS.items():
if capability in found:
continue
for pattern in patterns:
if budget is not None:
budget.check_runtime(path)
if pattern.search(window) is not None:
found.add(capability)
break
if start + _CAPABILITY_WINDOW_CHARS >= len(content):
break
return found
Expand Down
319 changes: 319 additions & 0 deletions tests/test_mcp_least_privilege.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,325 @@ def test_over_declared_detected(self):
assert lp4.file == "SKILL.md"


class TestLP4GoCapabilityPatterns:
"""Go capability calls satisfy the matching declared permission (no LP4).

LP4 previously flagged env and file_read as over-declared in Go skills
because the capability patterns only covered Python and JavaScript calls
(issue #1121). Each positive case below fails before the fix and passes
after it.
"""

@staticmethod
def _go_state(permissions: list[str], go_code: str) -> dict:
return {
"manifest": {"name": "go-skill", "permissions": permissions, "triggers": []},
"file_cache": {"main.go": go_code},
"component_metadata": [
{
"path": "main.go",
"type": "go",
"executable": True,
"lines": len(go_code.splitlines()),
"size_bytes": len(go_code),
},
],
"has_executable_scripts": True,
"components": ["main.go"],
}

@staticmethod
def _lp4_for_category(findings, category: str) -> list:
return [f for f in findings if f.rule_id == "LP4" and f"({category})" in (f.message or "")]

@pytest.mark.parametrize(
("permission", "category", "go_code"),
[
pytest.param(
"env: MY_TOOL_CONFIG",
"env",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tpath, ok := os.LookupEnv("MY_TOOL_CONFIG")\n\t_ = path\n\t_ = ok\n}\n',
id="lookupenv",
),
pytest.param(
"env: MY_TOOL_CONFIG",
"env",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tpath := os.ExpandEnv("$MY_TOOL_CONFIG")\n\t_ = path\n}\n',
id="expandenv",
),
pytest.param(
"env: MY_TOOL_CONFIG",
"env",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tpath := os.Getenv("MY_TOOL_CONFIG")\n\t_ = path\n}\n',
id="getenv_unchanged",
),
pytest.param(
"file_read: config.json",
"file_read",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tdata, err := os.ReadFile("config.json")\n\t_, _ = data, err\n}\n',
id="readfile",
),
pytest.param(
"file_read: config.json",
"file_read",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tf, err := os.Open("config.json")\n\t_, _ = f, err\n}\n',
id="open",
),
pytest.param(
"file_read: config.json",
"file_read",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tentries, err := os.ReadDir(".")\n\t_, _ = entries, err\n}\n',
id="readdir",
),
pytest.param(
"file_read: config.json",
"file_read",
'package main\n\nimport (\n\t"io/fs"\n\t"path/filepath"\n)\n\n'
"func main() {\n"
'\t_ = filepath.WalkDir(".", func(path string, d fs.DirEntry, '
"err error) error { return nil })\n}\n",
id="walkdir",
),
pytest.param(
"file_read: config.json",
"file_read",
'package main\n\nimport "path/filepath"\n\nfunc main() {\n'
'\tmatches, err := filepath.Glob("*.json")\n\t_, _ = matches, err\n}\n',
id="glob",
),
pytest.param(
"file_write: out.json",
"file_write",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\terr := os.WriteFile("out.json", []byte("x"), 0644)\n\t_ = err\n}\n',
id="writefile",
),
pytest.param(
"file_write: out.json",
"file_write",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tf, err := os.CreateTemp("", "tmp-")\n\t_, _ = f, err\n}\n',
id="createtemp",
),
pytest.param(
"file_write: out.json",
"file_write",
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tf, err := os.Create("out.json")\n\t_, _ = f, err\n}\n',
id="create",
),
],
)
def test_go_capability_satisfies_permission(self, permission, category, go_code):
"""The Go call covers its declared permission, so no LP4 fires."""
state = self._go_state([permission], go_code)
result = mcp_least_privilege.node(state)
findings = result["findings"]
lp4 = self._lp4_for_category(findings, category)
assert lp4 == [], (
f"Go {category} call should satisfy {permission}, got: "
f"{[(f.rule_id, f.message) for f in findings]}"
)

def test_go_skill_without_capability_calls_still_lp4(self):
"""A Go skill declaring permissions its code never uses still gets
LP4 for each one: the fix must not blanket-suppress LP4 for Go."""
state = self._go_state(
["env: MY_TOOL_CONFIG", "file_read: config.json", "file_write: out.json"],
'package main\n\nimport "fmt"\n\nfunc main() {\n\tfmt.Println("hello")\n}\n',
)
result = mcp_least_privilege.node(state)
findings = result["findings"]
lp4 = [f for f in findings if f.rule_id == "LP4"]
assert len(lp4) == 3, (
f"Expected 3 LP4 findings, got: {[(f.rule_id, f.message) for f in findings]}"
)
for category in ("env", "file_read", "file_write"):
assert self._lp4_for_category(findings, category), (
f"Expected LP4 for {category}, got: {[(f.rule_id, f.message) for f in findings]}"
)

def test_go_write_capability_without_declaration_fires_lp1(self):
"""Declaring only file_read while Go code writes via os.WriteFile
fires LP1 for file_write: the new patterns feed LP1 as well."""
state = self._go_state(
["file_read: config.json"],
'package main\n\nimport "os"\n\nfunc main() {\n'
'\tdata, _ := os.ReadFile("config.json")\n'
'\t_ = os.WriteFile("out.json", data, 0644)\n}\n',
)
result = mcp_least_privilege.node(state)
findings = result["findings"]
lp1_write = [
f for f in findings if f.rule_id == "LP1" and "file_write" in (f.message or "")
]
assert len(lp1_write) == 1, (
f"Expected one LP1 for undeclared file_write, got: "
f"{[(f.rule_id, f.message) for f in findings]}"
)

@pytest.mark.parametrize(
"go_code",
[
pytest.param(
'package main\n\nimport (\n\t"bytes"\n\t"io"\n)\n\nfunc main() {\n'
'\tdata, _ := io.ReadAll(bytes.NewBufferString("x"))\n\t_ = data\n}\n',
id="in_memory_buffer",
),
pytest.param(
'package main\n\nimport (\n\t"io"\n\t"net/http"\n)\n\nfunc main() {\n'
'\tresp, _ := http.Get("https://example.com")\n'
"\tdata, _ := io.ReadAll(resp.Body)\n\t_, _ = resp, data\n}\n",
id="network_response_body",
),
],
)
def test_go_readall_on_arbitrary_reader_is_not_file_read(self, go_code):
"""io.ReadAll consumes any io.Reader, so it proves nothing about
file access: a declared file_read permission stays over-declared
(LP4) and no LP1 fires for file_read."""
state = self._go_state(["file_read: config.json"], go_code)
result = mcp_least_privilege.node(state)
findings = result["findings"]
lp4 = self._lp4_for_category(findings, "file_read")
assert len(lp4) == 1, (
f"Expected one LP4 for file_read, got: {[(f.rule_id, f.message) for f in findings]}"
)
lp1_read = [f for f in findings if f.rule_id == "LP1" and "file_read" in (f.message or "")]
assert lp1_read == [], (
f"Expected no LP1 for file_read, got: {[(f.rule_id, f.message) for f in findings]}"
)

def test_go_readall_after_os_open_still_satisfies_via_open(self):
"""Reading a file opened with os.Open still counts as file_read,
through os.Open itself rather than through io.ReadAll."""
state = self._go_state(
["file_read: config.json"],
'package main\n\nimport (\n\t"io"\n\t"os"\n)\n\nfunc main() {\n'
'\tf, _ := os.Open("config.json")\n\tdata, _ := io.ReadAll(f)\n\t_, _ = f, data\n}\n',
)
result = mcp_least_privilege.node(state)
findings = result["findings"]
lp4 = self._lp4_for_category(findings, "file_read")
assert lp4 == [], (
f"os.Open should satisfy file_read, got: {[(f.rule_id, f.message) for f in findings]}"
)

def test_python_write_only_os_open_is_not_file_read(self):
"""Python os.open with write-only flags must not count as read
evidence: the Go os.Open pattern applies to Go files only. The
declared file_read permission stays over-declared (LP4)."""
code = 'import os\nfd = os.open("out.bin", os.O_WRONLY | os.O_CREAT)\n'
state: dict = {
"manifest": {
"name": "py-skill",
"permissions": ["file_read: config.json"],
"triggers": [],
},
"file_cache": {"agent.py": code},
"component_metadata": [
{
"path": "agent.py",
"type": "python",
"executable": True,
"lines": len(code.splitlines()),
"size_bytes": len(code),
},
],
"has_executable_scripts": True,
"components": ["agent.py"],
}
result = mcp_least_privilege.node(state)
findings = result["findings"]
lp4 = [f for f in findings if f.rule_id == "LP4" and "(file_read)" in (f.message or "")]
assert len(lp4) == 1, (
f"Expected one LP4 for file_read, got: {[(f.rule_id, f.message) for f in findings]}"
)

def test_python_write_only_os_open_fires_no_lp1(self):
"""A Python write-only os.open call with an unrelated declaration
fires no LP1 for file_read."""
code = 'import os\nfd = os.open("out.bin", os.O_WRONLY | os.O_CREAT)\n'
state: dict = {
"manifest": {
"name": "py-skill",
"permissions": ["env: MY_TOOL_CONFIG"],
"triggers": [],
},
"file_cache": {"agent.py": code},
"component_metadata": [
{
"path": "agent.py",
"type": "python",
"executable": True,
"lines": len(code.splitlines()),
"size_bytes": len(code),
},
],
"has_executable_scripts": True,
"components": ["agent.py"],
}
result = mcp_least_privilege.node(state)
findings = result["findings"]
lp1_read = [f for f in findings if f.rule_id == "LP1" and "file_read" in (f.message or "")]
assert lp1_read == [], (
f"Expected no LP1 for file_read, got: {[(f.rule_id, f.message) for f in findings]}"
)

def test_python_and_js_detection_unchanged(self):
"""Python and JavaScript capability detection is unchanged: os.getenv,
open(..., "r") and process.env still satisfy their permissions."""
cases = [
(
["env: MY_TOOL_CONFIG"],
"agent.py",
'import os\npath = os.getenv("MY_TOOL_CONFIG")\n',
"python",
),
(
["file_read: config.json"],
"agent.py",
'with open("config.json", "r") as f:\n data = f.read()\n',
"python",
),
(
["env: MY_TOOL_CONFIG"],
"agent.js",
"const path = process.env.MY_TOOL_CONFIG;\n",
"javascript",
),
]
for permissions, path, code, file_type in cases:
state: dict = {
"manifest": {"name": "py-js-skill", "permissions": permissions, "triggers": []},
"file_cache": {path: code},
"component_metadata": [
{
"path": path,
"type": file_type,
"executable": True,
"lines": len(code.splitlines()),
"size_bytes": len(code),
},
],
"has_executable_scripts": True,
"components": [path],
}
result = mcp_least_privilege.node(state)
findings = result["findings"]
lp4 = [f for f in findings if f.rule_id == "LP4"]
assert lp4 == [], (
f"{file_type} capability should satisfy {permissions}, got: "
f"{[(f.rule_id, f.message) for f in findings]}"
)


class TestCleanSkill:
def test_no_findings(self):
"""mcp_clean_skill: permissions match capabilities → zero LP findings."""
Expand Down
Loading