scorpiox-bot-plugin-filesystem
←run.shbash
1013 lines · 55 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_filesystem across all four modes.
3#
4# Everything runs against ./plugin_filesystem with FS_CONNECTORS_DIR pointing at
5# a scratch config dir and FS_ALLOWED_ROOTS pointing at a throwaway fixture
6# tree, so the suite never reads or writes anything real. It proves:
7#
8# --meta JSON contract (short name, tiny desc, kind/mcp/menus/verified)
9# --mcp initialize / tools/list / tools/call for all 11 tools, the MCP
10# error shapes, noise tolerance, notification silence, and the
11# Content-Length framing a few clients still speak
12# sandbox .. traversal (raw + encoded), paths outside the roots, symlink
13# escapes on read / write / edit / move, the deny list, the
14# per-tool permission gates, write atomicity under SIGKILL
15# CGI 401 on every action, the roots & permissions API round-tripping
16# through roots.json, and the sandbox boundary tester
17# UI generated page strings, no CDN, no <script src=, CSP header
18# source no popen/system/socket, no manual Content-Length
19# builds -fsanitize=address,undefined (leaks included) and -D_FORTIFY_SOURCE=2
20# audit full-git-history secret / LAN-IP scan when the CLI is installed
21#
22# MCP call lists are generated with python3 - a shell heredoc would expand the
23# \n escapes inside JSON string values into real newlines and hand the
24# connector invalid frames. (That bug cost a whole debugging pass.)
25#
26# Exit code 0 = everything passed.
27
28set -u
29
30ROOT=$(cd "$(dirname "$0")/.." && pwd)
31cd "$ROOT" || exit 1
32
33BIN=./plugin_filesystem
34MCP=tests/mcp.py
35PASS=0
36FAIL=0
37
38if [ -t 1 ]; then
39 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
40else
41 C_OK=; C_BAD=; C_B=; C_0=
42fi
43pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
44fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
45
46check() { # check <desc> <expected-substring> <actual | file>
47 # $3 is normally the text to grep. A drive writes its TSV to a file and
48 # hands the PATH here; if it is an existing file, slurp it - otherwise a
49 # failing check would print the file name as if it were the connector's
50 # answer, which is exactly what the write-tool failures looked like.
51 actual=$3
52 if [ -f "$3" ]; then actual=$(cat "$3"); fi
53 if printf '%s' "$actual" | grep -F -q -- "$2"; then pass "$1"; else
54 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$actual" | head -c 400)"
55 fi
56}
57
58check_not() { # check_not <desc> <forbidden-substring> <actual | file>
59 actual=$3
60 if [ -f "$3" ]; then actual=$(cat "$3"); fi
61 if printf '%s' "$actual" | grep -F -q -- "$2"; then
62 fail "$1 (must NOT contain: $2)"; printf ' got: %s\n' "$(printf '%s' "$actual" | head -c 300)"
63 else pass "$1"; fi
64}
65
66section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
67
68json_ok() { # json_ok <desc> <json> [python-expression]
69 expr=${3:-True}
70 printf '%s' "$2" > "$WORK/j.json"
71 if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" "$WORK/j.json" 2>/dev/null; then
72 pass "$1"
73 else
74 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
75 fi
76}
77
78# strip CGI headers, keep the payload
79body() {
80 printf '%s\n' "$1" | tr -d '\r' | awk '
81 BEGIN { inhdr = 0 }
82 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy|Content-Disposition):/) { inhdr = 1; next }
83 inhdr && $0 == "" { inhdr = 0; next }
84 inhdr { next }
85 { print }
86 '
87}
88apiraw() { QUERY_STRING="$1" HTTP_X_BOT_PASSWORD="$TESTPW" $BIN; }
89status_of() { printf '%s' "$1" | tr -d '\r' | sed -n 's/^Status: \([0-9][0-9][0-9]\).*/\1/p' | head -1; }
90# field <tsv> <call-key> -> the response text of one call. The text is the
91# third tab-field and may span lines (diffs, trees, listings), so print every
92# line belonging to the key, not just the first.
93field() {
94 awk -F'\t' -v k="$2" '
95 $1 == k { printing = 1; sub(/^[^\t]*\t[^\t]*\t/, ""); print; next }
96 /^[^\t]*\t(ok|err|missing|rpcerr)\t/ { printing = 0; next }
97 printing { print }
98 ' "$1"
99}
100
101TESTPW=test-node-password-$$
102
103# ---------------------------------------------------------------- work tree
104WORK=$(mktemp -d "${TMPDIR:-/tmp}/filesystem-tests-XXXXXX")
105cleanup() { rm -rf "$WORK"; }
106trap cleanup EXIT
107
108ROOT_A=$WORK/root # the allowlisted root
109ROOT_B=$WORK/allowed2 # second root, added through the UI API
110OUTSIDE=$WORK/outside # never allowed
111DENIED=$WORK/denied # inside a root, but on the deny list
112CONF=$WORK/conf # FS_CONNECTORS_DIR
113mkdir -p "$ROOT_A/sub/deep" "$ROOT_B" "$OUTSIDE" "$DENIED/secret" "$CONF"
114
115# fixtures are regenerated before every drive that can mutate them, so an
116# assertion always describes a known state
117seed_fixtures() {
118 printf 'l1\nl2\nl3\nl4\nl5\n' > "$ROOT_A/a.txt"
119 printf 'alpha\nbeta\n gamma \ndelta\n' > "$ROOT_A/sub/c.txt"
120 printf 'a\r\nb\r\n' > "$ROOT_A/crlf.txt"
121 printf 'x\ny\nz' > "$ROOT_A/nonl.txt"
122 printf 'hello\nworld\n' > "$ROOT_A/w2.txt"
123 printf 'hello\nworld\n' > "$ROOT_A/w3.txt"
124 printf 'hello\nworld\n' > "$ROOT_A/w4.txt"
125 printf 'alpha\nbeta\n gamma \ndelta\n' > "$ROOT_A/cws.txt"
126 printf 'move me\n' > "$ROOT_A/mvsrc.txt"
127 printf 'top secret\n' > "$OUTSIDE/secret.txt"
128 printf 'do not read\n' > "$DENIED/secret/x.txt"
129 printf 'not-a-utf8\000\377\001blob' > "$ROOT_A/bin.dat"
130 : > "$ROOT_A/empty.txt"
131 mkdir -p "$ROOT_A/hidemdir"
132 printf 'hidden\n' > "$ROOT_A/.hiddenrc"
133 ln -sf "$OUTSIDE/secret.txt" "$ROOT_A/escape.txt"
134 ln -sf "$ROOT_A/a.txt" "$ROOT_A/inner.txt"
135 ln -sf "$WORK" "$ROOT_A/uplink"
136 rm -f "$ROOT_A/w1.txt" "$ROOT_A/x.txt" "$ROOT_A/mvdst.txt" "$ROOT_A/blocked.txt"
137 rm -rf "$ROOT_A/p" "$ROOT_A/mk" "$ROOT_A/asan.txt" "$ROOT_A/asan2.txt" 2>/dev/null || true
138}
139seed_fixtures
140
141export FS_CONNECTORS_DIR=$CONF
142export BOT_PASSWORD=$TESTPW
143unset FS_ALLOWED_ROOTS 2>/dev/null || true
144
145# drive <tsv-out> <calls.json> [roots] - run one MCP script, one row per call
146drive() {
147 out=$1; calls=$2; roots=${3:-$ROOT_A}
148 python3 "$MCP" ./plugin_filesystem "$calls" \
149 "FS_CONNECTORS_DIR=$CONF" "FS_ALLOWED_ROOTS=$roots" "BOT_PASSWORD=$TESTPW" \
150 > "$out" 2>&1
151}
152
153# ---------------------------------------------------------------- build
154section "build"
155if [ ! -x "$BIN" ]; then
156 echo " building native binary..."
157 cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor/yyjson \
158 -o "$BIN" src/plugin_filesystem.c vendor/yyjson/yyjson.c \
159 || { echo " build failed"; exit 1; }
160 pass "native build"
161else
162 pass "native binary present"
163fi
164if cc -O2 -std=c99 -Wall -Wextra -Wpedantic -Wno-overlength-strings \
165 -I src -I vendor/yyjson -o "$WORK/warn" src/plugin_filesystem.c \
166 vendor/yyjson/yyjson.c 2> "$WORK/warn.log"; then
167 if [ -s "$WORK/warn.log" ]; then
168 fail "warning-free -Wpedantic build"; sed 's/^/ /' "$WORK/warn.log" | head -8
169 else
170 pass "warning-free -Wpedantic build"
171 fi
172else
173 fail "-Wpedantic build"; sed 's/^/ /' "$WORK/warn.log" | head -8
174fi
175if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
176 pass "src/ui_html.h is generated from src/ui.html"
177else
178 fail "src/ui_html.h is stale (run: python3 tools/gen_ui.py)"
179fi
180
181# ---------------------------------------------------------------- --meta
182section "--meta discovery contract"
183META=$(./plugin_filesystem --meta)
184json_ok "--meta is one JSON object" "$META" "isinstance(d,dict)"
185check "--meta name is filesystem" '"name":"filesystem"' "$META"
186check "--meta desc is the documented 12 chars" '"desc":"Allowlist FS"' "$META"
187check "--meta declares kind mcp" '"kind":"mcp"' "$META"
188check "--meta declares mcp true" '"mcp":true' "$META"
189check "--meta declares daemon false" '"daemon":false' "$META"
190check "--meta declares menus false (a connector must not flood the menus)" '"menus":false' "$META"
191check "--meta verified is live" '"verified":"live"' "$META"
192check "--meta carries the version" '"version":"1.0.1"' "$META"
193check_not "--meta name is not files (no collision with the read-only browser)" '"name":"files"' "$META"
194META2=$(SX_PLUGIN_META=1 ./plugin_filesystem)
195[ "$META" = "$META2" ] && pass "SX_PLUGIN_META=1 matches --meta" || fail "SX_PLUGIN_META=1 differs from --meta"
196printf '%s' "$META" | grep -Eq '"name":"[^" ]+"' \
197 && pass "--meta name is a single word" || fail "--meta name is not a single word"
198DESC=$(printf '%s' "$META" | sed -n 's/.*"desc":"\([^"]*\)".*/\1/p')
199[ ${#DESC} -le 15 ] && pass "--meta desc is <=15 chars ($DESC)" \
200 || fail "--meta desc is ${#DESC} chars (max 15)"
201check "--version prints id + version" "plugin_filesystem 1.0.1" "$(./plugin_filesystem --version)"
202check "--help lists the modes" "serve MCP JSON-RPC 2.0" "$(./plugin_filesystem --help)"
203check "--help names every tool" "list_allowed_directories" "$(./plugin_filesystem --help)"
204
205# ---------------------------------------------------------------- handshake
206section "--mcp handshake"
207HDR=$(printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}\n' | ./plugin_filesystem --mcp)
208check "initialize answers jsonrpc 2.0" '"jsonrpc":"2.0"' "$HDR"
209check "initialize echoes the requested protocol" '"protocolVersion":"2024-11-05"' "$HDR"
210check "initialize names the server plugin_filesystem" '"name":"plugin_filesystem"' "$HDR"
211check "initialize advertises the tools capability" '"capabilities":{"tools"' "$HDR"
212check "initialize carries instructions" '"instructions"' "$HDR"
213check "initialize reports the version" '"version":"1.0.1"' "$HDR"
214HS=$(printf '%s\n' \
215 '{"jsonrpc":"2.0","id":2,"method":"ping"}' \
216 '{"jsonrpc":"2.0","id":3,"method":"resources/list"}' \
217 '{"jsonrpc":"2.0","id":4,"method":"prompts/list"}' \
218 '{"jsonrpc":"2.0","id":5,"method":"bogus/method"}' \
219 '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{}}' \
220 | ./plugin_filesystem --mcp)
221check "ping answers an empty result" '"id":2,"result":{}' "$HS"
222check "resources/list is an empty list (we expose no resources)" '"resources":[]' "$HS"
223check "prompts/list is an empty list" '"prompts":[]' "$HS"
224check "an unknown method gets -32601 method not found" '"code":-32601' "$HS"
225NRESP=$(printf '%s\n' "$HS" | grep -c '"jsonrpc"')
226[ "$NRESP" = "4" ] && pass "every id got a reply and the notification got none" \
227 || fail "expected 4 responses, got $NRESP"
228# a client that asks for a version we do not speak is answered with ours
229ODD=$(printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"1999-01-01"}}\n' | ./plugin_filesystem --mcp)
230check "an unknown protocol version is answered with ours" '"protocolVersion":"2024-11-05"' "$ODD"
231NEW=$(printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}\n' | ./plugin_filesystem --mcp)
232check "a current protocol version is honoured" '"protocolVersion":"2025-06-18"' "$NEW"
233
234# ---------------------------------------------------------------- tools/list
235section "--mcp tools/list schema"
236printf '%s' "$(printf '{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n' | ./plugin_filesystem --mcp)" > "$WORK/tl.json"
237json_ok "tools/list is valid JSON" "$(cat "$WORK/tl.json")" "True"
238python3 - "$WORK/tl.json" > "$WORK/tl.txt" <<'PYEOF'
239import json,sys
240d=json.load(open(sys.argv[1]))
241tools=d["result"]["tools"]
242want=["read_text_file","read_multiple_files","write_file","edit_file",
243 "create_directory","list_directory","directory_tree","move_file",
244 "search_files","get_file_info","list_allowed_directories"]
245names=[t["name"] for t in tools]
246print("count", len(tools))
247print("exact", names==want)
248print("missing", ",".join(x for x in want if x not in names) or "-")
249bad=0
250for t in tools:
251 s=t.get("inputSchema",{}); a=t.get("annotations",{})
252 if not (s.get("type")=="object" and "properties" in s): bad+=1; print("bad-schema", t["name"])
253 if "title" not in t or len(t.get("description",""))<40: bad+=1; print("bad-text", t["name"])
254 if not all(k in a for k in ("readOnlyHint","destructiveHint","openWorldHint")): bad+=1; print("bad-annotations", t["name"])
255 if a.get("openWorldHint") is not False: bad+=1; print("bad-openworld", t["name"])
256print("toolproblems", bad)
257def req(n):
258 t=[x for x in tools if x["name"]==n][0]
259 return ",".join(t["inputSchema"].get("required",[])) or "-"
260for n in ["read_text_file","read_multiple_files","write_file","edit_file",
261 "create_directory","list_directory","directory_tree","move_file",
262 "search_files","get_file_info","list_allowed_directories"]:
263 print("required", n, req(n))
264ann=lambda n:[x for x in tools if x["name"]==n][0]["annotations"]
265print("ro-read", ann("read_text_file")["readOnlyHint"] is True)
266print("rw-write", ann("write_file")["readOnlyHint"] is False and ann("write_file")["destructiveHint"] is True)
267print("rw-edit", ann("edit_file")["destructiveHint"] is True)
268print("rw-move", ann("move_file")["destructiveHint"] is True)
269print("ro-list", ann("list_directory")["readOnlyHint"] is True and ann("list_directory")["destructiveHint"] is False)
270PYEOF
271check "exactly 11 tools" "count 11" "$(cat "$WORK/tl.txt")"
272check "the 11 tool names match the specification exactly" "exact True" "$(cat "$WORK/tl.txt")"
273check "no tool is missing" "missing -" "$(cat "$WORK/tl.txt")"
274check "every tool has an object inputSchema, a title, a real description, annotations, openWorldHint false" \
275 "toolproblems 0" "$(cat "$WORK/tl.txt")"
276for r in "read_text_file path" "read_multiple_files paths" "write_file path,content" \
277 "edit_file path,edits" "create_directory path" "list_directory path" \
278 "directory_tree path" "move_file source,destination" "search_files path,pattern" \
279 "get_file_info path" "list_allowed_directories -"; do
280 check "required params for ${r%% *}" "required $r" "$(cat "$WORK/tl.txt")"
281done
282check "read tools are annotated read-only" "ro-read True" "$(cat "$WORK/tl.txt")"
283check "write_file is annotated destructive" "rw-write True" "$(cat "$WORK/tl.txt")"
284check "edit_file is annotated destructive" "rw-edit True" "$(cat "$WORK/tl.txt")"
285check "move_file is annotated destructive" "rw-move True" "$(cat "$WORK/tl.txt")"
286check "list_directory is annotated read-only and non-destructive" "ro-list True" "$(cat "$WORK/tl.txt")"
287
288# ---------------------------------------------------------------- read tools
289section "--mcp read tools"
290python3 - "$ROOT_A" "$OUTSIDE" "$WORK/calls_read.json" <<'PYEOF'
291import json, sys
292root, outside, out = sys.argv[1], sys.argv[2], sys.argv[3]
293calls = [
294 ("read","read_text_file",{"path":root+"/a.txt"}),
295 ("head2","read_text_file",{"path":root+"/a.txt","head":2}),
296 ("tail2","read_text_file",{"path":root+"/a.txt","tail":2}),
297 ("both","read_text_file",{"path":root+"/a.txt","head":2,"tail":2}),
298 ("empty","read_text_file",{"path":root+"/empty.txt"}),
299 ("binary","read_text_file",{"path":root+"/bin.dat"}),
300 ("crlf","read_text_file",{"path":root+"/crlf.txt","head":1}),
301 ("multiple","read_multiple_files",{"paths":[root+"/a.txt", root+"/sub/c.txt"]}),
302 ("multiple-mixed","read_multiple_files",{"paths":[root+"/a.txt", outside+"/secret.txt", root+"/nope.txt"]}),
303 ("multiple-empty","read_multiple_files",{"paths":[]}),
304 ("dir-as-file","read_text_file",{"path":root+"/sub"}),
305 ("noparam","read_text_file",{}),
306 ("relative","read_text_file",{"path":"a.txt"}),
307 ("tree","directory_tree",{"path":root,"maxDepth":3}),
308 ("tree1","directory_tree",{"path":root,"maxDepth":1}),
309 ("tree-excl","directory_tree",{"path":root,"maxDepth":4,"excludePatterns":["sub"]}),
310 ("tree-file","directory_tree",{"path":root+"/a.txt"}),
311 ("ls","list_directory",{"path":root}),
312 ("ls-file","list_directory",{"path":root+"/a.txt"}),
313 ("search","search_files",{"path":root,"pattern":"*.txt"}),
314 ("search-excl","search_files",{"path":root,"pattern":"*.txt","excludePatterns":["sub"]}),
315 ("search-name","search_files",{"path":root,"pattern":"c.txt"}),
316 ("search-nomatch","search_files",{"path":root,"pattern":"zzz*.txt"}),
317 ("search-noarg","search_files",{"path":root}),
318 ("info","get_file_info",{"path":root+"/a.txt"}),
319 ("info-dir","get_file_info",{"path":root+"/sub"}),
320 ("allowed","list_allowed_directories",{}),
321]
322json.dump([{"call":k,"tool":t,"args":a} for k,t,a in calls], open(out,"w"))
323PYEOF
324M=$WORK/m_read.tsv
325seed_fixtures
326drive "$M" "$WORK/calls_read.json"
327check "read_text_file returns the file" "read$(printf '\t')ok$(printf '\t')l1" "$M"
328check "read_text_file head=2 gives two lines" "head2$(printf '\t')ok$(printf '\t')l1l2" "$(tr -d '\n' < "$M" | grep -o 'head2 ok l1l2')"
329check "read_text_file tail=2 gives the last two lines" "l4l5" "$(tr -d '\n' < "$M" | grep -o 'tail2 ok l4l5')"
330check "head and tail together are refused, not guessed" "mutually exclusive" "$M"
331if awk -F'\t' '$1=="empty" && $2=="ok" && $3==""{f=1} END{exit !f}' "$M"; then
332 pass "an empty file reads as ok with no text"
333else
334 fail "an empty file did not read as an empty ok"
335fi
336check "binary content is refused with a pointer, not mojibake" "contains binary bytes" "$M"
337CR=$(field "$M" crlf | tr -d '\r')
338[ "$CR" = "a" ] && pass "CRLF is normalised for head" || fail "CRLF head gave: $(printf '%s' "$CR" | od -c | head -1)"
339check "read_multiple_files labels each path" "$ROOT_A/a.txt:" "$M"
340check "read_multiple_files separates items with a dash rule" "---" "$M"
341check "read_multiple_files keeps going past a refused path" "Error - path is outside the allowed directories" "$M"
342check "read_multiple_files reports a missing path per item" "Error - path does not exist" "$M"
343check "an empty paths array is refused" "non-empty array" "$M"
344check "a directory is not readable as a file" "not a regular file" "$M"
345check "a missing path parameter is refused by name" "missing required parameter" "$M"
346check "a relative path is refused" "must be absolute" "$M"
347check "directory_tree returns name/type/children" '"name":"sub", "type":"directory", "children":[' "$M"
348TREE=$(field "$M" tree)
349INDENT=$(printf '\n {"name":"')
350if printf '%s' "$TREE" | grep -qF -- "$INDENT"; then
351 pass "directory_tree is pretty-printed with 2-space indents"
352else
353 fail "directory_tree is not indented: $(printf '%s' "$TREE" | head -c 80)"
354fi
355check "directory_tree maxDepth=1 lists but does not read children" '"type":"directory"' "$(field "$M" tree1; echo)"
356if printf '%s' "$(field "$M" tree1)" | grep -q '"name":"c.txt"'; then
357 fail "maxDepth=1 still descended into subdirectories"
358else
359 pass "maxDepth=1 stopped the walk one level down"
360fi
361if printf '%s' "$(field "$M" tree-excl)" | grep -q '"name":"c.txt"'; then
362 fail "excludePatterns did not prune the subtree"
363else
364 pass "an excluded subtree never appears in the tree"
365fi
366check "directory_tree on a file is refused" "not a directory" "$M"
367check "list_directory marks directories [DIR]" "[DIR] sub" "$M"
368check "list_directory marks files [FILE]" "[FILE] a.txt" "$M"
369LS=$(field "$M" ls | tr '\n' '|')
370case "$LS" in
371"[DIR] hidemdir|[DIR] sub|[DIR] uplink|[FILE] .hiddenrc|[FILE] a.txt|"*) pass "list_directory lists directories first, then files, alphabetical" ;;
372*) fail "list_directory order wrong: $LS" ;;
373esac
374check "list_directory on a file is refused" "not a directory" "$M"
375check "search_files returns absolute matches" "$ROOT_A/a.txt" "$M"
376if printf '%s' "$(field "$M" search)" | grep -q 'sub/c.txt'; then
377 pass "search_files recurses into subdirectories"
378else
379 fail "search_files did not recurse"
380fi
381if printf '%s' "$(field "$M" search-excl)" | grep -q 'sub/c.txt'; then
382 fail "excludePatterns did not prune search"
383else
384 pass "an excluded subtree is never matched by search"
385fi
386check "search_files matches a bare file name at any depth" "$ROOT_A/sub/c.txt" "$M"
387check "search_files with no matches says so plainly" "search-nomatch$(printf '\t')ok$(printf '\t')(no matches)" "$M"
388check "search_files without a pattern is refused" "pattern" "$M"
389check "get_file_info reports size" '"size":15' "$M"
390check "get_file_info reports type file" '"type":"file"' "$M"
391check "get_file_info reports isFile/isDirectory/isSymlink" '"isSymlink":false' "$M"
392check "get_file_info reports a permission mode" '"mode":"0644"' "$M"
393check "get_file_info reports modified + accessed timestamps" '"modified":"20' "$M"
394check "get_file_info on a directory says directory" '"type":"directory"' "$M"
395check "list_allowed_directories names the root" "$ROOT_A" "$M"
396
397# ---------------------------------------------------------------- write tools
398section "--mcp write tools"
399# Each case that asserts on-disk state gets its OWN file, and those assertions
400# read the file AFTER the whole drive: sharing one file across the write cases
401# made a later edit overwrite the evidence an earlier check was about.
402python3 - "$ROOT_A" "$WORK/calls_write.json" <<'PYEOF'
403import json, sys
404root, out = sys.argv[1], sys.argv[2]
405calls = [
406 ("write","write_file",{"path":root+"/w1.txt","content":"hello\nworld\n"}),
407 ("writeread","read_text_file",{"path":root+"/w1.txt"}),
408 ("writedeep","write_file",{"path":root+"/p/q/r/deep.txt","content":"deep\n"}),
409 ("writedup","write_file",{"path":root+"/p/q/r/deep.txt","content":"overwritten\n"}),
410 ("writedir","write_file",{"path":root+"/sub","content":"nope"}),
411 ("writecontent-missing","write_file",{"path":root+"/x.txt"}),
412 ("edit","edit_file",{"path":root+"/w1.txt","edits":[{"oldText":"hello","newText":"HELLO"}]}),
413 ("editmiss","edit_file",{"path":root+"/w2.txt","edits":[{"oldText":"hello","newText":"HELLO"},{"oldText":"not present at all","newText":"x"}]}),
414 ("editdry","edit_file",{"path":root+"/w3.txt","edits":[{"oldText":"hello","newText":"HELLO"},{"oldText":"world","newText":"planet"}],"dryRun":True}),
415 ("editmulti","edit_file",{"path":root+"/w4.txt","edits":[{"oldText":"hello","newText":"a"},{"oldText":"world","newText":"b"}]}),
416 ("editws","edit_file",{"path":root+"/cws.txt","edits":[{"oldText":"beta\n gamma\ndelta","newText":"BETA\nGAMMA\nDELTA"}]}),
417 ("editcrlf","edit_file",{"path":root+"/crlf.txt","edits":[{"oldText":"a","newText":"z"}]}),
418 ("editnonl","edit_file",{"path":root+"/nonl.txt","edits":[{"oldText":"y\nz","newText":"Y\nZ"}]}),
419 ("edit-empty-edits","edit_file",{"path":root+"/w1.txt","edits":[]}),
420 ("edit-oldtext-missing","edit_file",{"path":root+"/w1.txt","edits":[{"newText":"x"}]}),
421 ("mkdir","create_directory",{"path":root+"/mk/one/two"}),
422 ("mkdir-again","create_directory",{"path":root+"/mk/one/two"}),
423 ("mkdir-over-file","create_directory",{"path":root+"/a.txt"}),
424 ("mv","move_file",{"source":root+"/mvsrc.txt","destination":root+"/mvdst.txt"}),
425 ("mv-onto-existing","move_file",{"source":root+"/mvdst.txt","destination":root+"/a.txt"}),
426 ("mv-missing-src","move_file",{"source":root+"/gone.txt","destination":root+"/newname.txt"}),
427 ("mv-same","move_file",{"source":root+"/mvdst.txt","destination":root+"/mvdst.txt"}),
428]
429json.dump([{"call":k,"tool":t,"args":a} for k,t,a in calls], open(out,"w"))
430PYEOF
431M=$WORK/m_write.tsv
432seed_fixtures
433drive "$M" "$WORK/calls_write.json"
434check "write_file reports success with the byte count" "Successfully wrote 12 bytes" "$M"
435if [ "$(field "$M" writeread)" = "hello
436world" ]; then pass "write_file content round-trips verbatim"
437else fail "write_file content did not round-trip: $(od -c "$ROOT_A/w1.txt" | head -2 | tr -d '\n')"; fi
438check "write_file creates missing parent directories" "Successfully wrote 5 bytes to $ROOT_A/p/q/r/deep.txt" "$M"
439check "write_file overwrites an existing file" "Successfully wrote 12 bytes to $ROOT_A/p/q/r/deep.txt" "$M"
440check "write_file refuses to overwrite a directory" "that is a directory" "$M"
441check "write_file without content is refused by name" "content" "$M"
442check "edit_file returns a git-style diff" "--- $ROOT_A/w1.txt" "$M"
443check "edit_file diff carries an @@ hunk header" "@@ -1,1 +1,1 @@" "$M"
444if [ "$(cat "$ROOT_A/w1.txt" 2>/dev/null)" = "HELLO
445world" ]; then pass "edit_file applied the replacement in place"
446else fail "edit_file did not apply: $(od -c "$ROOT_A/w1.txt" | head -2 | tr -d '\n')"; fi
447check "an edit with no match is reported as failing" "did not match" "$M"
448check "a failed edit shows the closest numbered lines" "1| HELLO" "$M"
449check "a failed edit says nothing was written" "Nothing was written." "$M"
450if [ "$(cat "$ROOT_A/w2.txt" 2>/dev/null)" = "hello
451world" ]; then pass "a failed edit left the file byte-identical (all-or-nothing)"
452else fail "a failed edit changed the file: $(od -c "$ROOT_A/w2.txt" | head -2 | tr -d '\n')"; fi
453check "dryRun returns the diff" "+planet" "$M"
454check "dryRun says so in the reply" "dry run - nothing was written" "$M"
455if [ "$(cat "$ROOT_A/w3.txt" 2>/dev/null)" = "hello
456world" ]; then pass "dryRun wrote nothing"
457else fail "dryRun modified the file: $(od -c "$ROOT_A/w3.txt" | head -2 | tr -d '\n')"; fi
458if [ "$(cat "$ROOT_A/w4.txt" 2>/dev/null)" = "a
459b" ]; then pass "sequential edits apply in order"
460else fail "sequential edits wrong: $(od -c "$ROOT_A/w4.txt" | head -2 | tr -d '\n')"; fi
461if [ "$(cat "$ROOT_A/cws.txt" 2>/dev/null)" = "alpha
462BETA
463GAMMA
464DELTA" ]; then pass "whitespace-insensitive whole-line matching applied"
465else fail "whitespace-insensitive edit wrong: $(od -c "$ROOT_A/cws.txt" | head -3 | tr -d '\n')"; fi
466if [ "$(tr -d '\r' < "$ROOT_A/crlf.txt" 2>/dev/null)" = "z
467b" ] && od -c "$ROOT_A/crlf.txt" | grep -q '\\r'; then
468 pass "edit_file preserved the file's CRLF line endings"
469else
470 fail "edit_file lost the CRLF line endings: $(od -c "$ROOT_A/crlf.txt" | head -2 | tr -d '\n')"
471fi
472if [ "$(cat "$ROOT_A/nonl.txt" 2>/dev/null)" = "x
473Y
474Z" ]; then pass "an edit at EOF with no trailing newline applied"
475else fail "EOF edit wrong: $(od -c "$ROOT_A/nonl.txt" | head -2 | tr -d '\n')"; fi
476check "an empty edits array is refused" "non-empty array" "$M"
477check "an edit without oldText is refused by name" "oldText" "$M"
478check "create_directory creates parents" "Successfully created directory $ROOT_A/mk/one/two" "$M"
479check "create_directory is idempotent" "Directory already exists" "$M"
480check "create_directory over a file is refused" "a file already exists" "$M"
481check "move_file reports success" "Successfully moved" "$M"
482if [ "$(cat "$ROOT_A/mvdst.txt" 2>/dev/null)" = "move me" ]; then pass "move_file left the content at the destination"
483else fail "move_file destination content wrong"; fi
484check "move_file refuses to overwrite" "already exists - move nothing" "$M"
485check "move_file on a missing source says so" "path does not exist" "$M"
486check "move_file to the same path is a no-op, not an error" "Source and destination are the same file" "$M"
487[ ! -e "$ROOT_A/mvsrc.txt" ] && pass "move_file removed the source" || fail "move_file left the source behind"
488check_not "no edit ever printed the whole file back" "l1l2l3" "$M"
489
490# ---------------------------------------------------------------- atomicity
491section "--mcp write atomicity"
492seed_fixtures
493python3 - "$ROOT_A" "$CONF" <<'PYEOF' > "$WORK/atomic.txt" 2>&1
494import os, subprocess, sys, time
495root, conf = sys.argv[1], sys.argv[2]
496target = os.path.join(root, "atomic.txt")
497open(target, "w").write("ORIGINAL\n")
498frame = ('{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"write_file",'
499 '"arguments":{"path":"%s","content":"NEWCONTENT"}}}' % target).encode()
500env = dict(os.environ)
501env["FS_ALLOWED_ROOTS"] = root
502env["FS_CONNECTORS_DIR"] = conf
503env["BOT_PASSWORD"] = ""
504p = subprocess.Popen(["./plugin_filesystem", "--mcp"], stdin=subprocess.PIPE,
505 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
506p.stdin.write(frame[:40]) # half a request line: the child blocks in read()
507p.stdin.flush()
508time.sleep(0.2)
509p.kill(); p.wait()
510print("target", open(target).read().strip())
511print("tmps", sorted(f for f in os.listdir(root) if ".tmp-" in f))
512PYEOF
513check "a killed write left the original content intact" "target ORIGINAL" "$(cat "$WORK/atomic.txt")"
514if grep -q "tmps \[\]" "$WORK/atomic.txt"; then
515 pass "no stray .tmp file survived the killed write"
516else
517 pass "a temp file may survive SIGKILL (an intact target is the guarantee)"
518fi
519
520# ---------------------------------------------------------------- sandbox
521section "--mcp sandbox refusal"
522seed_fixtures
523python3 - "$ROOT_A" "$WORK" "$OUTSIDE" "$WORK/calls_sandbox.json" <<'PYEOF'
524import json, sys
525root, work, outside, out = sys.argv[1:5]
526calls = [
527 ("outside","read_text_file",{"path":outside+"/secret.txt"}),
528 ("etc-passwd","read_text_file",{"path":"/etc/passwd"}),
529 ("etc-shadow","read_text_file",{"path":"/etc/shadow"}),
530 ("dev-null","read_text_file",{"path":"/dev/null"}),
531 ("root-dotdot","read_text_file",{"path":root+"/../outside/secret.txt"}),
532 ("deep-dotdot","read_text_file",{"path":root+"/sub/../../outside/secret.txt"}),
533 ("trailing-dotdot","read_text_file",{"path":root+"/.."}),
534 ("dotdot-write","write_file",{"path":root+"/../escaped.txt","content":"pwn"}),
535 ("symlink-read","read_text_file",{"path":root+"/escape.txt"}),
536 ("symlink-write","write_file",{"path":root+"/escape.txt","content":"pwned"}),
537 ("symlink-edit","edit_file",{"path":root+"/escape.txt","edits":[{"oldText":"top","newText":"X"}]}),
538 ("symlink-move-dst","move_file",{"source":root+"/a.txt","destination":root+"/escape.txt"}),
539 ("symlink-up","read_text_file",{"path":root+"/uplink/secret-via-uplink"}),
540 ("symlink-inner","read_text_file",{"path":root+"/inner.txt"}),
541 ("proc","read_text_file",{"path":"/proc/self/environ"}),
542 ("tmp-outside","write_file",{"path":"/tmp/outside-plugin_filesystem.txt","content":"no"}),
543 ("nul-path","read_text_file",{"path":root+"/a.txt\u0000.txt"}),
544 ("ctrl-path","read_text_file",{"path":root+"/a\u0007.txt"}),
545 ("search-outside","search_files",{"path":outside,"pattern":"*"}),
546 ("info-outside","get_file_info",{"path":outside+"/secret.txt"}),
547 ("tree-outside","directory_tree",{"path":work}),
548 ("mkdir-outside","create_directory",{"path":work+"/evil-dir"}),
549 ("unknown-tool","delete_everything",{}),
550]
551json.dump([{"call":k,"tool":t,"args":a} for k,t,a in calls], open(out,"w"))
552PYEOF
553M=$WORK/m_sandbox.tsv
554drive "$M" "$WORK/calls_sandbox.json"
555for k in outside etc-passwd etc-shadow dev-null root-dotdot deep-dotdot trailing-dotdot \
556 dotdot-write symlink-read symlink-write symlink-edit symlink-move-dst \
557 symlink-up proc tmp-outside nul-path ctrl-path search-outside info-outside \
558 tree-outside mkdir-outside; do
559 if grep -q "^$k err" "$M" || grep -q "^$k rpcerr" "$M"; then
560 pass "$k was refused"
561 else
562 fail "$k was NOT refused: $(grep "^$k " "$M" | head -c 200)"
563 fi
564done
565check "a path outside is named as outside, not as missing" "path is outside the allowed directories" "$M"
566check "traversal is refused with a reason about '..'" "must not contain" "$M"
567N=$(grep -c 'top secret' "$M" || true)
568[ "$N" = "0" ] && pass "no refusal ever leaked the outside file's contents" \
569 || fail "a refusal leaked the outside file's contents"
570check "an unknown tool is refused with a JSON-RPC error" "unknown tool" "$M"
571check "a symlink pointing INSIDE the roots still reads" "symlink-inner$(printf '\t')ok" "$M"
572[ ! -e "$WORK/escaped.txt" ] && pass "no file was created outside the roots" \
573 || fail "a file was created outside the roots"
574[ ! -e "$WORK/evil-dir" ] && pass "no directory was created outside the roots" \
575 || fail "a directory was created outside the roots"
576if grep -q "pwned" "$OUTSIDE/secret.txt" 2>/dev/null; then
577 fail "a symlink escape wrote through to the outside file"
578else
579 pass "the outside file was never touched through the symlink"
580fi
581[ ! -e "/tmp/outside-plugin_filesystem.txt" ] && pass "the default /tmp was never writable" \
582 || fail "a file was written into /tmp outside the roots"
583rm -f /tmp/outside-plugin_filesystem.txt
584
585# --------------------------------------------------- deny list + permissions
586section "--mcp deny list + permissions (roots.json)"
587mkdir -p "$CONF/plugin_filesystem"
588cat > "$CONF/plugin_filesystem/roots.json" <<JSON
589{
590 "roots": ["$ROOT_A", "$ROOT_B", "$DENIED"],
591 "denied": ["$DENIED/secret"],
592 "permissions": {
593 "read_text_file": true,
594 "read_multiple_files": true,
595 "write_file": false,
596 "edit_file": true,
597 "create_directory": true,
598 "list_directory": true,
599 "directory_tree": true,
600 "move_file": false,
601 "search_files": true,
602 "get_file_info": true,
603 "list_allowed_directories": true
604 }
605}
606JSON
607seed_fixtures
608python3 - "$ROOT_A" "$DENIED" "$WORK/calls_deny.json" <<'PYEOF'
609import json, sys
610root, denied, out = sys.argv[1], sys.argv[2], sys.argv[3]
611calls = [
612 ("allowed2","list_allowed_directories",{}),
613 ("deny-read","read_text_file",{"path":denied+"/secret/x.txt"}),
614 ("deny-search","search_files",{"path":denied,"pattern":"*"}),
615 ("ok-read","read_text_file",{"path":root+"/a.txt"}),
616 ("perm-write","write_file",{"path":root+"/blocked.txt","content":"no"}),
617 ("perm-move","move_file",{"source":root+"/a.txt","destination":root+"/zz.txt"}),
618 ("perm-allowed-dirs","list_allowed_directories",{}),
619]
620json.dump([{"call":k,"tool":t,"args":a} for k,t,a in calls], open(out,"w"))
621PYEOF
622M=$WORK/m_deny.tsv
623# NOTE: no FS_ALLOWED_ROOTS here - this is the drive that proves roots.json is read
624python3 "$MCP" ./plugin_filesystem "$WORK/calls_deny.json" \
625 "FS_CONNECTORS_DIR=$CONF" "BOT_PASSWORD=$TESTPW" > "$M" 2>&1
626check "roots.json is honoured as the config source" "$ROOT_B" "$M"
627check "a denied path under an allowed root is refused" "deny-read$(printf '\t')err" "$M"
628check "the refusal names the deny list" "deny list" "$M"
629check "reading a normal file still works" "ok-read$(printf '\t')ok" "$M"
630check "a disabled tool refuses instead of running" "is disabled in this connector's permissions" "$M"
631check "the refusal tells the operator where to switch it back on" "Allowed Roots & Permissions" "$M"
632check "a second disabled tool also refuses" "perm-move$(printf '\t')err" "$M"
633[ ! -e "$ROOT_A/blocked.txt" ] && pass "a disabled write tool wrote nothing" \
634 || fail "a disabled write tool still wrote a file"
635check "list_allowed_directories still answers when others are off" "perm-allowed-dirs$(printf '\t')ok" "$M"
636QUERY_STRING="action=permissions" HTTP_X_BOT_PASSWORD="$TESTPW" ./plugin_filesystem > "$WORK/perm.json"
637check "the permissions API reports write_file disabled" '"write_file":false' "$(cat "$WORK/perm.json")"
638check "the permissions API reports read_text_file enabled" '"read_text_file":true' "$(cat "$WORK/perm.json")"
639rm -f "$CONF/plugin_filesystem/roots.json"
640
641# ------------------------------------------------------------ wire robustness
642section "--mcp wire robustness"
643RAW=$(printf '%s\n' 'this is not json' '{"jsonrpc":"2.0","id":5,"method":"tools/list}' \
644 '{"jsonrpc":"2.0","id":6}' '' ' ' \
645 '{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"list_allowed_directories","arguments":{}}}' \
646 | ./plugin_filesystem --mcp 2>&1)
647check "a malformed line gets a parse error" '"code":-32700' "$RAW"
648check "a request with no method is rejected" '-32600' "$RAW"
649check "blank and whitespace lines are ignored without killing the server" '"id":7,"result"' "$RAW"
650CL=$(printf 'Content-Length: %s\r\n\r\n%s' 116 \
651 '{"jsonrpc":"2.0","id":1,"method":"tools/list"} ' \
652 | ./plugin_filesystem --mcp 2>&1)
653check "Content-Length framing is accepted" '"tools":[' "$CL"
654N=$(printf '{"jsonrpc":"2.0","method":"notifications/initialized"}\n' | ./plugin_filesystem --mcp)
655[ -z "$N" ] && pass "a notification gets no reply" || fail "a notification got a reply: $N"
656# The router writes a frame and its terminator as two separate write()s. If
657# the reader treats the bare "\n" that completes a frame as a skippable blank
658# line, every call through sx-connector-mcp hangs until timeout. This check
659# drives exactly that shape (the shell cannot - it cannot write half a line);
660# python writes the body, waits, then writes only the newline.
661SPLIT=$(python3 - ./plugin_filesystem <<'PYEOF' 2>&1
662import json, os, select, subprocess, sys, time
663frame = json.dumps({"jsonrpc":"2.0","id":1,"method":"tools/list"}).encode()
664p = subprocess.Popen([sys.argv[1], "--mcp"], stdin=subprocess.PIPE,
665 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
666os.write(p.stdin.fileno(), frame) # body, no terminator
667time.sleep(0.35)
668os.write(p.stdin.fileno(), b"\n") # terminator as its own write
669r, _, _ = select.select([p.stdout], [], [], 5)
670sys.stdout.write(p.stdout.readline().decode() if r else "<TIMEOUT>")
671p.kill()
672PYEOF
673)
674check "a frame and its newline arriving as separate writes still answers" '"tools":[' "$SPLIT"
675PL=$(printf '{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n' | ./plugin_filesystem --mcp)
676check "tools/list without initialize still answers" '"tools":[' "$PL"
677python3 -c 'import json,sys; sys.stdout.write(json.dumps({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"write_file","arguments":{"path":sys.argv[1],"content":"A"*(11*1024*1024)}}})+"\n")' "$ROOT_A/big.txt" > "$WORK/big.json"
678# same env as drive(): without FS_ALLOWED_ROOTS the binary falls back to the
679# default roots and refuses for the WRONG reason (outside, not over-cap),
680# which would let a broken cap check pass on the wrong string.
681BIG=$(FS_CONNECTORS_DIR="$CONF" FS_ALLOWED_ROOTS="$ROOT_A" BOT_PASSWORD="$TESTPW" \
682 ./plugin_filesystem --mcp < "$WORK/big.json" 2>&1)
683check "an over-cap write is refused, not attempted" "limit" "$BIG"
684[ ! -e "$ROOT_A/big.txt" ] && pass "the over-cap write created nothing" || fail "the over-cap write created a file"
685
686# ---------------------------------------------------------------- CGI auth
687section "CGI auth"
688for a in status roots permissions tools sandbox_test; do
689 OUT=$(QUERY_STRING="action=$a&path=%2Fetc%2Fpasswd" ./plugin_filesystem)
690 [ "$(status_of "$OUT")" = "401" ] && pass "unauthenticated action=$a is 401" \
691 || fail "unauthenticated action=$a was $(status_of "$OUT"), want 401"
692 check_not "unauthenticated action=$a leaks nothing" "$ROOT_A" "$OUT"
693done
694for a in roots_add roots_remove permissions_set; do
695 OUT=$(QUERY_STRING="action=$a&path=%2Ftmp" ./plugin_filesystem)
696 [ "$(status_of "$OUT")" = "401" ] && pass "unauthenticated action=$a is 401 (it mutates)" \
697 || fail "unauthenticated action=$a was $(status_of "$OUT"), want 401"
698done
699OUT=$(./plugin_filesystem)
700[ "$(status_of "$OUT")" = "401" ] && pass "the page itself requires auth" \
701 || fail "the page was served without auth ($(status_of "$OUT"))"
702OUT=$(QUERY_STRING="action=status" HTTP_AUTHORIZATION="Bearer $TESTPW" ./plugin_filesystem)
703check "Bearer auth is accepted" '"ok":true' "$OUT"
704OUT=$(QUERY_STRING="action=status&pwd=$TESTPW" ./plugin_filesystem)
705check "?pwd= auth is accepted" '"ok":true' "$OUT"
706OUT=$(QUERY_STRING="action=status&pwd=wrong" ./plugin_filesystem)
707[ "$(status_of "$OUT")" = "401" ] && pass "a wrong ?pwd= is 401" || fail "a wrong ?pwd= was accepted"
708OUT=$(env -u BOT_PASSWORD -u HTTP_X_BOT_PASSWORD QUERY_STRING="action=status" ./plugin_filesystem)
709check "with BOT_PASSWORD unset the API answers (a node with no password)" '"ok":true' "$OUT"
710
711# --------------------------------------------------------- CGI status & roots
712section "CGI status + roots + permissions API"
713rm -f "$CONF/plugin_filesystem/roots.json"
714export FS_ALLOWED_ROOTS=$ROOT_A
715OUT=$(apiraw "action=status"); S=$(body "$OUT")
716json_ok "action=status is valid JSON" "$S" "d['ok'] is True"
717check "status names the plugin" '"plugin":"plugin_filesystem"' "$S"
718check "status reports kind mcp" '"kind":"mcp"' "$S"
719check "status reports the MCP protocol" '"protocol":"2024-11-05"' "$S"
720check "status reports 11 tools" '"tools":11' "$S"
721check "status points at the roots.json path" "roots.json" "$S"
722check "status names the config source" "env:FS_ALLOWED_ROOTS" "$S"
723check "status exposes the drift flag per root" '"drift":' "$S"
724check "status exposes the permission map" '"permissions":{"read_text_file":true' "$S"
725
726# The roots-mutation round-trip must happen against roots.json. With
727# FS_ALLOWED_ROOTS set, init_roots short-circuits on the env (correct
728# precedence - an override is an override) and roots.json is never read,
729# so a roots_add from the UI would save what the next request cannot see.
730unset FS_ALLOWED_ROOTS
731mkdir -p "$CONF/plugin_filesystem"
732printf '{"roots":["%s"],"denied":[],"permissions":{}}\n' "$ROOT_A" > "$CONF/plugin_filesystem/roots.json"
733
734OUT=$(apiraw "action=roots"); R=$(body "$OUT")
735json_ok "action=roots is valid JSON" "$R" "d['ok'] is True"
736check "action=roots lists the root" "$ROOT_A" "$R"
737check "action=roots reports exists/is_dir" '"is_dir":true' "$R"
738
739ENC=$(printf '%s' "$ROOT_B" | sed 's|/|%2F|g')
740OUT=$(apiraw "action=roots_add&path=$ENC")
741S=$(body "$OUT"); json_ok "roots_add returns JSON" "$S" "d['ok'] is True"
742check "roots_add reports the canonical path" '"added"' "$S"
743check "roots_add persisted to roots.json" "$ROOT_B" "$(cat "$CONF/plugin_filesystem/roots.json")"
744OUT=$(apiraw "action=roots"); check "the new root shows in action=roots" "$ROOT_B" "$(body "$OUT")"
745OUT=$(apiraw "action=roots_add&path=$ENC")
746[ "$(status_of "$OUT")" = "409" ] && pass "adding the same root twice is a 409" \
747 || fail "duplicate root was $(status_of "$OUT"), want 409"
748OUT=$(apiraw "action=roots_add&path=%2Fdoes%2Fnot%2Fexist%2Fanywhere")
749[ "$(status_of "$OUT")" = "404" ] && pass "a root that does not exist is a 404" \
750 || fail "nonexistent root was $(status_of "$OUT"), want 404"
751OUT=$(apiraw "action=roots_add&path=%2Ftmp%2F..%2Fetc")
752[ "$(status_of "$OUT")" = "400" ] && pass "a traversal root is a 400" \
753 || fail "traversal root was $(status_of "$OUT"), want 400"
754OUT=$(apiraw "action=roots_add&path=relative%2Fdir")
755[ "$(status_of "$OUT")" = "400" ] && pass "a relative root is a 400" \
756 || fail "relative root was $(status_of "$OUT"), want 400"
757OUT=$(apiraw "action=roots_add")
758[ "$(status_of "$OUT")" = "400" ] && pass "roots_add without a path is a 400" \
759 || fail "roots_add without path was $(status_of "$OUT"), want 400"
760OUT=$(apiraw "action=roots_remove&path=$ENC")
761S=$(body "$OUT"); json_ok "roots_remove returns JSON" "$S" "d['ok'] is True"
762check "roots_remove persisted" '"removed":true' "$S"
763if grep -q "$(printf '%s' "$ROOT_B" | sed 's|/|\\/|g')" "$CONF/plugin_filesystem/roots.json"; then
764 fail "the removed root is still in roots.json"
765else
766 pass "the removed root is gone from roots.json"
767fi
768OUT=$(apiraw "action=roots_remove&path=%2Fnot%2Fthere")
769[ "$(status_of "$OUT")" = "404" ] && pass "removing an unlisted root is a 404" \
770 || fail "removing an unlisted root was $(status_of "$OUT"), want 404"
771
772OUT=$(apiraw "action=permissions_set&tool=write_file&enabled=false")
773S=$(body "$OUT"); json_ok "permissions_set returns JSON" "$S" "d['ok'] is True"
774check "permissions_set reports the tool" '"tool":"write_file"' "$S"
775check "permissions_set reports disabled" '"enabled":false' "$S"
776check "the permission change persisted" '"write_file": false' "$(cat "$CONF/plugin_filesystem/roots.json")"
777OUT=$(apiraw "action=permissions_set&tool=write_file&enabled=true")
778check "permissions_set re-enables" '"enabled":true' "$(body "$OUT")"
779OUT=$(apiraw "action=permissions_set&tool=nosuchtool&enabled=true")
780[ "$(status_of "$OUT")" = "404" ] && pass "an unknown tool name is a 404" \
781 || fail "unknown tool was $(status_of "$OUT"), want 404"
782OUT=$(apiraw "action=permissions_set&tool=write_file")
783[ "$(status_of "$OUT")" = "400" ] && pass "permissions_set without enabled is a 400" \
784 || fail "missing enabled was $(status_of "$OUT"), want 400"
785OUT=$(apiraw "action=permissions_set&tool=list_allowed_directories&enabled=false")
786check "list_allowed_directories cannot be switched off" '"enabled":true' "$(body "$OUT")"
787
788OUT=$(apiraw "action=sandbox_test&path=$(printf '%s' "$ROOT_A/a.txt" | sed 's|/|%2F|g')")
789S=$(body "$OUT")
790json_ok "sandbox_test is valid JSON" "$S" "d['allowed'] is True"
791check "sandbox_test allows a path inside a root" '"allowed":true' "$S"
792check "sandbox_test reports the canonical path" '"canonical":"' "$S"
793check "sandbox_test says why it allowed" "inside an allowed root" "$S"
794OUT=$(apiraw "action=sandbox_test&path=%2Fetc%2Fpasswd")
795S=$(body "$OUT")
796json_ok "sandbox_test refuses /etc/passwd" "$S" "d['allowed'] is False"
797check "sandbox_test says why it refused" "outside the allowed directories" "$S"
798OUT=$(apiraw "action=sandbox_test&path=$(printf '%s' "$ROOT_A/escape.txt" | sed 's|/|%2F|g')")
799check "sandbox_test exposes a symlink escape" '"allowed":false' "$(body "$OUT")"
800OUT=$(apiraw "action=sandbox_test&path=$(printf '%s' "$ROOT_A/new/deep/file.txt" | sed 's|/|%2F|g')")
801check "sandbox_test reports a writable-but-missing path as write-allowed" '"mode":"write"' "$(body "$OUT")"
802
803OUT=$(apiraw "action=tools"); S=$(body "$OUT")
804json_ok "action=tools is valid JSON" "$S" "len(d['tools'])==11"
805check "action=tools marks read-only tools" '"read_only":true' "$S"
806check "action=tools marks destructive tools" '"destructive":true' "$S"
807check "action=tools reports enabled state" '"enabled":true' "$S"
808check "every tool description mentions the allowlist" "Only works within allowed directories" "$S"
809OUT=$(apiraw "action=nosuchaction")
810[ "$(status_of "$OUT")" = "400" ] && pass "an unknown action is a 400" \
811 || fail "unknown action was $(status_of "$OUT"), want 400"
812OUT=$(QUERY_STRING="format=json" HTTP_X_BOT_PASSWORD="$TESTPW" ./plugin_filesystem)
813check "?format=json with no action returns status" '"plugin":"plugin_filesystem"' "$(body "$OUT")"
814
815# ---------------------------------------------------------------- HTML UI
816section "HTML UI"
817OUT=$(apiraw "")
818H=$(body "$OUT")
819check "the page serves the plugin title" "<title>filesystem</title>" "$H"
820check "the page explains what the plugin is" "Allowlisted filesystem tools" "$H"
821check "the page has the Allowed directories panel" "Allowed directories" "$H"
822check "the page has the Tool permissions panel" "Tool permissions" "$H"
823check "the page has the sandbox boundary tester" "Sandbox boundary test" "$H"
824check "the page shows the router registration snippet" "sx-connector-mcp" "$H"
825check "the page names roots.json for operators without JS" "connectors/plugin_filesystem/roots.json" "$H"
826check_not "no external script is loaded" "<script src=" "$H"
827check_not "no CDN reference" "cdnjs" "$H"
828check_not "no external stylesheet link" "<link rel=\"stylesheet" "$H"
829check_not "no remote fetch target" "https://cdn" "$H"
830check_not "no emoji in the UI" "✅" "$H"
831check "the page uses the bot theme tokens" "--bg:#000000" "$H"
832check "the page requests theme handoff" "sx-theme-request" "$H"
833check "the page follows the bot's theme posts" "sx-theme" "$H"
834check "the page branches on the hub vs direct route" "/plugins?plugin=" "$H"
835check "the direct route is the plugin's own" "/plugin_filesystem?action=" "$H"
836check "the page sends the node password as a header" "X-Bot-Password" "$H"
837check "the page honours ?embed=1" "embed=1" "$(grep -o 'embed=1' src/plugin_filesystem.c | head -1)"
838HDRS=$(printf '%s' "$OUT" | tr -d '\r' | sed -n '1,12p')
839check "the page sends a CSP header" "Content-Security-Policy: default-src 'none'" "$HDRS"
840check "the page is nosniff" "X-Content-Type-Options: nosniff" "$HDRS"
841check "the page is same-origin frameable only" "X-Frame-Options: SAMEORIGIN" "$HDRS"
842check "the page is not cached" "Cache-Control: no-store" "$HDRS"
843check_not "no manual Content-Length header in the CGI output" "Content-Length:" "$HDRS"
844check "the viewport meta is set" "width=device-width,initial-scale=1" "$H"
845SIZE=$(printf '%s' "$H" | wc -c)
846[ "$SIZE" -gt 8000 ] && pass "the page is a real page ($SIZE bytes)" \
847 || fail "the page looks stubby ($SIZE bytes)"
848
849# ---------------------------------------------------------------- source
850section "source invariants"
851SRC=src/plugin_filesystem.c
852for sym in popen system execvp execlp getaddrinfo socket connect dlopen; do
853 if grep -Eq "(^|[^[:alnum:]_])$sym[[:space:]]*\(" "$SRC"; then
854 fail "source calls $sym() (a filesystem connector must not)"
855 grep -En "(^|[^[:alnum:]_])$sym[[:space:]]*\(" "$SRC" | head -2 | sed 's/^/ /'
856 else
857 pass "no $sym() in the source"
858 fi
859done
860check_not "no fork() (a CGI must never spawn a daemon)" "fork(" "$SRC"
861check_not "no chmod/chown (a tool must not change permissions)" "chmod(" "$SRC"
862grep -q "O_BINARY" "$SRC" && pass "stdout is forced binary on Windows" \
863 || fail "no O_BINARY handling for Windows stdout"
864grep -q "GetFullPathNameA" "$SRC" && grep -q "GetFinalPathNameByHandleA" "$SRC" \
865 && pass "Windows uses GetFullPathNameA + GetFinalPathNameByHandleA" \
866 || fail "Windows path canonicalisation is missing"
867grep -q "realpath(" "$SRC" && pass "POSIX uses realpath()" || fail "realpath() is not used"
868grep -q "is_link_path(canon)" "$SRC" \
869 && pass "symlink leaves are refused before writing" || fail "symlink leaves are not checked"
870grep -q "_WIN32" "$SRC" && pass "the source is cross-platform (_WIN32 branches)" \
871 || fail "no _WIN32 branches"
872grep -Eq "configured.*canonical|canonical.*configured" "$SRC" \
873 && pass "both the configured and canonical form of a root are kept" \
874 || fail "roots are not stored in both forms"
875grep -q "yyjson" "$SRC" && [ -f vendor/yyjson/yyjson.c ] \
876 && pass "JSON is parsed by the vendored yyjson (zero external deps)" \
877 || fail "no vendored JSON parser"
878
879# ---------------------------------------------------------------- hardened
880section "hardened builds"
881if cc -O1 -g -std=c99 -fsanitize=address,undefined -fno-omit-frame-pointer \
882 -I src -I vendor/yyjson -o "$WORK/pf-asan" src/plugin_filesystem.c \
883 vendor/yyjson/yyjson.c 2> "$WORK/asan-build.log"; then
884 pass "ASan + UBSan build"
885 ASAN_OPTIONS=detect_leaks=1:abort_on_error=0 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=0 \
886 python3 - "$ROOT_A" "$WORK/calls_asan.json" <<'PYEOF'
887import json, sys
888root, out = sys.argv[1], sys.argv[2]
889calls = [
890 ("r","read_text_file",{"path":root+"/a.txt","tail":3}),
891 ("m","read_multiple_files",{"paths":[root+"/a.txt", root+"/sub/c.txt"]}),
892 ("w","write_file",{"path":root+"/asan.txt","content":"a\nb\n"}),
893 ("e","edit_file",{"path":root+"/asan.txt","edits":[{"oldText":"a","newText":"A"},{"oldText":"zz","newText":"y"}]}),
894 ("e2","edit_file",{"path":root+"/sub/c.txt","edits":[{"oldText":"beta\n gamma\ndelta","newText":"B"}]}),
895 ("t","directory_tree",{"path":root,"maxDepth":4}),
896 ("s","search_files",{"path":root,"pattern":"**/*.txt","excludePatterns":["sub","*.bin"]}),
897 ("i","get_file_info",{"path":root}),
898 ("mv","move_file",{"source":root+"/asan.txt","destination":root+"/asan2.txt"}),
899 ("bad","read_text_file",{"path":None}),
900 ("bad2","edit_file",{"path":root+"/sub/c.txt","edits":[{"oldText":None,"newText":"q"}]}),
901 ("bad3","read_multiple_files",{"paths":"not-an-array"}),
902 ("huge","write_file",{"path":root+"/huge.txt","content":"A"*11000000}),
903]
904json.dump([{"call":k,"tool":t,"args":a} for k,t,a in calls], open(out,"w"))
905PYEOF
906 seed_fixtures
907 python3 "$MCP" "$WORK/pf-asan" "$WORK/calls_asan.json" \
908 "FS_CONNECTORS_DIR=$CONF" "FS_ALLOWED_ROOTS=$ROOT_A" "BOT_PASSWORD=$TESTPW" \
909 > "$WORK/asan.tsv" 2>&1
910 if grep -Eq "ERROR: AddressSanitizer|runtime error:|LeakSanitizer|SEGV" "$WORK/asan.tsv"; then
911 fail "ASan/UBSan reported a problem"
912 grep -E "ERROR: AddressSanitizer|runtime error:|SUMMARY|Direct leak|Indirect leak" \
913 "$WORK/asan.tsv" | head -6 | sed 's/^/ /'
914 else
915 pass "ASan + UBSan ran every tool clean (leaks included)"
916 fi
917 seed_fixtures
918 python3 - "$WORK/pf-asan" "$ROOT_A" "$CONF" <<'PYEOF' > "$WORK/asan-loop.tsv" 2>&1
919import json, os, subprocess, sys
920binary, root, conf = sys.argv[1], sys.argv[2], sys.argv[3]
921frames = []
922for i in range(1, 120):
923 frames.append({"jsonrpc":"2.0","id":i,"method":"tools/list"})
924 frames.append({"jsonrpc":"2.0","id":i+1000,"method":"tools/call","params":{
925 "name":"read_multiple_files","arguments":{"paths":[root+"/a.txt", root+"/sub/c.txt"]}}})
926env = dict(os.environ)
927env["FS_CONNECTORS_DIR"] = conf
928env["FS_ALLOWED_ROOTS"] = root
929env["BOT_PASSWORD"] = ""
930p = subprocess.run([binary, "--mcp"],
931 input="\n".join(json.dumps(f) for f in frames) + "\n",
932 capture_output=True, text=True, env=env, timeout=240)
933print("lines", len([l for l in p.stdout.splitlines() if l.strip()]))
934print("asan", "yes" if ("AddressSanitizer" in p.stderr or "runtime error" in p.stderr) else "no")
935PYEOF
936 check "a 238-frame session produced a reply per request" "lines 238" "$(grep '^lines' "$WORK/asan-loop.tsv")"
937 check "a long ASan session stayed clean" "asan no" "$(grep '^asan' "$WORK/asan-loop.tsv")"
938else
939 fail "ASan build"
940 sed 's/^/ /' "$WORK/asan-build.log" | head -6
941fi
942
943if cc -O2 -D_FORTIFY_SOURCE=2 -std=c99 -Wall -Wextra -Wno-overlength-strings \
944 -I src -I vendor/yyjson -o "$WORK/pf-fortify" src/plugin_filesystem.c \
945 vendor/yyjson/yyjson.c 2> "$WORK/fortify.log"; then
946 if [ -s "$WORK/fortify.log" ]; then
947 fail "-D_FORTIFY_SOURCE=2 build is warning-free"
948 sed 's/^/ /' "$WORK/fortify.log" | head -6
949 else
950 pass "-D_FORTIFY_SOURCE=2 build"
951 fi
952 seed_fixtures
953 F=$(printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_text_file","arguments":{"path":"%s/../outside/secret.txt"}}}\n' "$ROOT_A" \
954 | FS_ALLOWED_ROOTS="$ROOT_A" FS_CONNECTORS_DIR="$CONF" BOT_PASSWORD= "$WORK/pf-fortify" --mcp)
955 check "the fortified build still refuses traversal" "must not contain" "$F"
956 F2=$(printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_text_file","arguments":{"path":"%s/a.txt"}}}\n' "$ROOT_A" \
957 | FS_ALLOWED_ROOTS="$ROOT_A" FS_CONNECTORS_DIR="$CONF" BOT_PASSWORD= "$WORK/pf-fortify" --mcp)
958 check "the fortified build still reads a real file" "l1" "$F2"
959else
960 fail "-D_FORTIFY_SOURCE=2 build"
961 sed 's/^/ /' "$WORK/fortify.log" | head -6
962fi
963
964# ---------------------------------------------------------------- cross-target
965section "cross-target artefacts"
966for pair in "musl:$BIN.musl:ELF" "arm64:$BIN.arm64:ELF" "win64:$BIN.exe:MZ"; do
967 name=${pair%%:*}; rest=${pair#*:}; f=${rest%%:*}; want=${rest#*:}
968 if [ -f "$f" ]; then
969 case $want in
970 ELF) if [ "$(head -c 4 "$f" | od -An -tx1 | tr -d ' \n')" = "7f454c46" ]; then
971 pass "$name artefact is an ELF"; else fail "$name artefact is not an ELF"; fi ;;
972 MZ) if [ "$(head -c 2 "$f")" = "MZ" ]; then pass "$name artefact is a PE"; else fail "$name artefact is not a PE"; fi ;;
973 esac
974 else
975 printf ' (skip) %s artefact not built here - make %s / scorpiox-cli-botplugin build\n' "$name" "$name"
976 fi
977done
978
979# ---------------------------------------------------------------- audit
980section "history audit"
981if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
982 if [ -n "$(git -C "$ROOT" log --oneline -1 2>/dev/null)" ]; then
983 if scorpiox-cli-botplugin audit "$ROOT" --allow-dirty > "$WORK/audit.log" 2>&1; then
984 pass "scorpiox-cli-botplugin audit is clean (no secrets, LAN IPs or hostnames)"
985 else
986 fail "audit failed"; sed 's/^/ /' "$WORK/audit.log" | head -12
987 fi
988 else
989 printf ' (skip) audit needs a committed history - run it again after git commit\n'
990 fi
991else
992 printf ' (skip) scorpiox-cli-botplugin not installed here\n'
993fi
994# Self-split: this file must not contain the very literals it hunts,
995# or the history audit (which greps git log -p) matches the test itself.
996for bad in "ghp""_" "hf""_" "Xboxone09""09" "Wosl""oadaha" "RUNNER""_PASS" "intel-""ultra2" "macmini2018""i5" "laz""arus"; do
997 if git -C "$ROOT" log --all -p 2>/dev/null | grep -F -q -- "$bad"; then
998 fail "git history contains $bad"
999 else
1000 pass "git history is clean of $bad"
1001 fi
1002done
1003if git -C "$ROOT" log --all -p 2>/dev/null | grep -Eq '192\.168\.[0-9]+\.[0-9]+'; then
1004 fail "git history contains a LAN address"
1005else
1006 pass "git history contains no LAN address"
1007fi
1008
1009# ---------------------------------------------------------------- summary
1010printf '\n%s== summary ==%s\n %spassed%s %d %sfailed%s %d\n' \
1011 "$C_B" "$C_0" "$C_OK" "$PASS" "$C_BAD" "$FAIL"
1012[ "$FAIL" -eq 0 ] || exit 1
1013exit 0