| 1 | #!/bin/sh |
| 2 | # tests/run.sh - the offline proof for plugin_websearch. |
| 3 | # |
| 4 | # Everything runs against ./plugin_websearch with the connector state directory |
| 5 | # pointed at a scratch dir and every provider pointed at tests/mockapi.py on |
| 6 | # loopback, so the suite never touches a real search service, never needs a real |
| 7 | # credential, and never depends on the internet. |
| 8 | # |
| 9 | # Sections: |
| 10 | # --meta the node's chip contract (1-2 word name, <= 15 char desc, |
| 11 | # kind/mcp/daemon/menus) and SX_PLUGIN_META=1 agreeing |
| 12 | # --schema the tool array is valid JSON, both tools carry an inputSchema |
| 13 | # --mcp initialize / notifications/initialized / ping / tools/list / |
| 14 | # tools/call and the JSON-RPC error shapes |
| 15 | # requests every provider is compared against what the mock actually |
| 16 | # RECEIVED: method, path, query, credential and JSON body |
| 17 | # errors a wrong key is the provider's own 401 text, an unreachable host |
| 18 | # is a clean error, an unknown provider is a tool error |
| 19 | # config config.json round-trips at 0600, the environment overrides it, |
| 20 | # and no response ever contains a key |
| 21 | # CGI a missing node password is 401, ?theme=/?embed= are honoured, |
| 22 | # and the page has no <script src= and no CDN reference |
| 23 | # source no popen/system, no credential literal, no LAN address |
| 24 | # |
| 25 | # Exit code 0 = everything passed. |
| 26 | |
| 27 | set -u |
| 28 | |
| 29 | ROOT=$(cd "$(dirname "$0")/.." && pwd) |
| 30 | cd "$ROOT" || exit 1 |
| 31 | |
| 32 | BIN=${BIN:-./plugin_websearch} |
| 33 | WORK=$(mktemp -d "${TMPDIR:-/tmp}/ws-suite.XXXXXX") |
| 34 | PORTFILE="$WORK/port" |
| 35 | LOG="$WORK/req.jsonl" |
| 36 | CFGDIR="$WORK/cfg" |
| 37 | MOCK_PID="" |
| 38 | |
| 39 | cleanup() { |
| 40 | [ -n "$MOCK_PID" ] && kill "$MOCK_PID" 2>/dev/null |
| 41 | rm -rf "$WORK" |
| 42 | } |
| 43 | trap cleanup EXIT INT TERM |
| 44 | |
| 45 | PASS=0 |
| 46 | FAIL=0 |
| 47 | SKIP=0 |
| 48 | |
| 49 | if [ -t 1 ]; then |
| 50 | C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m') |
| 51 | C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') |
| 52 | else |
| 53 | C_OK=; C_BAD=; C_B=; C_0= |
| 54 | fi |
| 55 | pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } |
| 56 | fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } |
| 57 | skip() { SKIP=$((SKIP + 1)); printf ' -- %s (skipped: %s)\n' "$1" "$2"; } |
| 58 | section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } |
| 59 | |
| 60 | check() { # check <label> <expected-substring> <text|file> |
| 61 | if [ -f "$3" ]; then set -- "$1" "$2" "$(cat "$3")"; fi |
| 62 | if printf '%s' "${3:-}" | grep -F -q -- "$2"; then pass "$1"; else |
| 63 | fail "$1 (want: $2)" |
| 64 | printf ' got: %s\n' "$(printf '%s' "${3:-}" | head -c 300)" |
| 65 | fi |
| 66 | } |
| 67 | check_not() { # check_not <label> <forbidden-substring> <text|file> |
| 68 | if [ -f "$3" ]; then set -- "$1" "$2" "$(cat "$3")"; fi |
| 69 | if printf '%s' "${3:-}" | grep -F -q -- "$2"; then |
| 70 | fail "$1 (must NOT contain: $2)" |
| 71 | printf ' got: %s\n' "$(printf '%s' "${3:-}" | head -c 300)" |
| 72 | else pass "$1"; fi |
| 73 | } |
| 74 | json_ok() { # json_ok <label> <json> [python expr over `d`] |
| 75 | expr=${3:-True} |
| 76 | printf '%s' "${2:-}" > "$WORK/j.json" |
| 77 | if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" \ |
| 78 | "$WORK/j.json" 2>/dev/null; then |
| 79 | pass "$1" |
| 80 | else |
| 81 | fail "$1 (invalid JSON or failed assertion)" |
| 82 | printf ' got: %s\n' "$(printf '%s' "${2:-}" | head -c 300)" |
| 83 | fi |
| 84 | } |
| 85 | body() { # strip the CGI header block, keep the payload |
| 86 | printf '%s\n' "${1:-}" | tr -d '\r' | awk 'p{print} /^$/{p=1}' |
| 87 | } |
| 88 | mcp() { # mcp <json-lines-file> -> stdout |
| 89 | ( cd "$ROOT" && "$BIN" --mcp < "$1" ) |
| 90 | } |
| 91 | call() { # call <id> <tool> <args-json> -> the structuredContent / error line |
| 92 | printf '{"jsonrpc":"2.0","id":%s,"method":"tools/call","params":{"name":"%s","arguments":%s}}\n' \ |
| 93 | "$1" "$2" "$3" > "$WORK/one.jsonl" |
| 94 | mcp "$WORK/one.jsonl" | python3 -c ' |
| 95 | import json,sys |
| 96 | d=json.loads(sys.stdin.readline()) |
| 97 | r=d.get("result") or {} |
| 98 | if r.get("isError"): |
| 99 | print("ERROR " + json.dumps(r.get("structuredContent") or {})) |
| 100 | else: |
| 101 | print(json.dumps(r.get("structuredContent") or {})) |
| 102 | ' |
| 103 | } |
| 104 | cgi() { # cgi <query> [method] [body] -> full stdout |
| 105 | qs="$1"; m="${2:-GET}"; data="${3:-}" |
| 106 | printf '%s' "$data" > "$WORK/in.bin" |
| 107 | QUERY_STRING="$qs" REQUEST_METHOD="$m" CONTENT_LENGTH="${#data}" \ |
| 108 | BOT_PASSWORD="" SWEBSEARCH_CONFIG_DIR="$CFGDIR" \ |
| 109 | WEBSEARCH_MOCK_BASE="$MOCK" "$BIN" < "$WORK/in.bin" |
| 110 | } |
| 111 | |
| 112 | export SWEBSEARCH_CONFIG_DIR="$CFGDIR" |
| 113 | export BRAVE_API_KEY=BRV-TEST-KEY-1 |
| 114 | export TAVILY_API_KEY=TVL-TEST-KEY-1 |
| 115 | export EXA_API_KEY=EXA-TEST-KEY-1 |
| 116 | export PERPLEXITY_API_KEY=PPX-TEST-KEY-1 |
| 117 | |
| 118 | mkdir -p "$CFGDIR" |
| 119 | rm -f "$LOG" |
| 120 | |
| 121 | if [ ! -x "$BIN" ]; then |
| 122 | echo "plugin_websearch is not built - run make first" >&2 |
| 123 | exit 1 |
| 124 | fi |
| 125 | |
| 126 | # ------------------------------------------------------------------ mock |
| 127 | python3 tests/mockapi.py --portfile "$PORTFILE" --log "$LOG" 2>"$WORK/mock.err" & |
| 128 | MOCK_PID=$! |
| 129 | i=0 |
| 130 | while [ ! -s "$PORTFILE" ] && [ $i -lt 100 ]; do |
| 131 | i=$((i + 1)); sleep 0.05 |
| 132 | done |
| 133 | if [ ! -s "$PORTFILE" ]; then |
| 134 | echo "the mock server did not start: $(cat "$WORK/mock.err")" >&2 |
| 135 | exit 1 |
| 136 | fi |
| 137 | MOCK="http://127.0.0.1:$(cat "$PORTFILE")" |
| 138 | export WEBSEARCH_MOCK_BASE="$MOCK" |
| 139 | export WEBSEARCH_SEARXNG_BASE="$MOCK/searxng" |
| 140 | |
| 141 | # ---------------------------------------------------------------- --meta |
| 142 | section "--meta / discovery" |
| 143 | META=$("$BIN" --meta) |
| 144 | json_ok "--meta is one line of valid JSON" "$META" |
| 145 | json_ok "name is websearch" "$META" 'd["name"]=="websearch"' |
| 146 | json_ok "desc is <= 15 chars" "$META" 'len(d["desc"])<=15' |
| 147 | json_ok "kind is mcp, mcp true, menus false" \ |
| 148 | "$META" 'd["kind"]=="mcp" and d["mcp"] is True and d["menus"] is False' |
| 149 | json_ok "daemon is false" "$META" 'd["daemon"] is False' |
| 150 | json_ok "category is network" "$META" 'd["category"]=="network"' |
| 151 | json_ok "verified is mock (an honest tier: the suite drives a mock, not a paid key)" \ |
| 152 | "$META" 'd["verified"]=="mock"' |
| 153 | check "SX_PLUGIN_META=1 agrees" '"name":"websearch"' "$(SX_PLUGIN_META=1 "$BIN")" |
| 154 | json_ok "--meta version agrees with plugin.json" "$META" \ |
| 155 | 'd["version"]==__import__("json").load(open("plugin.json"))["version"]' |
| 156 | VER=$(python3 -c 'import json;print(json.load(open("plugin.json"))["version"])') |
| 157 | check "--version agrees with plugin.json" "$VER" "$("$BIN" --version)" |
| 158 | check "--help mentions the tool names" 'web_search' "$("$BIN" --help)" |
| 159 | |
| 160 | # -------------------------------------------------------------- --schema |
| 161 | section "--schema / --mcp tool list" |
| 162 | SCHEMA=$("$BIN" --schema) |
| 163 | json_ok "--schema is valid JSON" "$SCHEMA" |
| 164 | json_ok "two tools are declared" "$SCHEMA" 'len(d["tools"])==2' |
| 165 | json_ok "every tool has an inputSchema" \ |
| 166 | "$SCHEMA" 'all("inputSchema" in t and t["inputSchema"].get("type")=="object" for t in d["tools"])' |
| 167 | json_ok "web_search requires query" \ |
| 168 | "$SCHEMA" 'any(t["name"]=="web_search" and t["inputSchema"]["required"]==["query"] for t in d["tools"])' |
| 169 | json_ok "the provider enum lists all six backends" \ |
| 170 | "$SCHEMA" 'len([e for t in d["tools"] if t["name"]=="web_search" for e in t["inputSchema"]["properties"]["provider"]["enum"]])==6' |
| 171 | |
| 172 | cat > "$WORK/mcp.jsonl" <<'EOF' |
| 173 | {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","clientInfo":{"name":"t","version":"0"}}} |
| 174 | {"jsonrpc":"2.0","method":"notifications/initialized"} |
| 175 | {"jsonrpc":"2.0","id":2,"method":"ping"} |
| 176 | {"jsonrpc":"2.0","id":3,"method":"tools/list"} |
| 177 | {"jsonrpc":"2.0","id":4,"method":"resources/list"} |
| 178 | {"jsonrpc":"2.0","id":5,"method":"prompts/list"} |
| 179 | {"jsonrpc":"2.0","id":6,"method":"no/such/method"} |
| 180 | not json at all |
| 181 | {"jsonrpc":"2.0","id":7} |
| 182 | EOF |
| 183 | MCPOUT=$(mcp "$WORK/mcp.jsonl") |
| 184 | check "initialize answers the protocol version" '"protocolVersion":"2025-06-18"' "$MCPOUT" |
| 185 | check "initialize names the server" '"name":"websearch-server"' "$MCPOUT" |
| 186 | check "ping answers an empty result" '"id":2,"result":{}' "$MCPOUT" |
| 187 | check "resources/list is empty, not an error" '"resources":[]' "$MCPOUT" |
| 188 | check "prompts/list is empty, not an error" '"prompts":[]' "$MCPOUT" |
| 189 | check "an unknown method is -32601" '"code":-32601' "$MCPOUT" |
| 190 | check "unparseable input is -32700 with id null" '"id":null,"error":{"code":-32700' "$MCPOUT" |
| 191 | check "a request without a method is -32600" '"code":-32600' "$MCPOUT" |
| 192 | N_RESP=$(printf '%s\n' "$MCPOUT" | grep -c '^{') |
| 193 | if [ "$N_RESP" = 8 ]; then |
| 194 | pass "one response per request (7 requests + 1 parse error), none for the notification" |
| 195 | else |
| 196 | fail "expected 8 responses (1 notification silent), got $N_RESP" |
| 197 | fi |
| 198 | json_ok "every response line is valid JSON" \ |
| 199 | "$(printf '%s\n' "$MCPOUT" | python3 -c 'import sys,json; print(json.dumps([json.loads(l) for l in sys.stdin if l.strip()]))')" |
| 200 | |
| 201 | # --------------------------------------------------------------- requests |
| 202 | section "each provider sends what its API requires" |
| 203 | : > "$LOG" |
| 204 | R=$(call 1 web_search '{"query":"rust lang","provider":"duckduckgo","count":3}') |
| 205 | json_ok "duckduckgo: ok, 3 results, parsed title/url/snippet" "$R" \ |
| 206 | 'd["ok"] and d["count"]==3 and d["results"][0]["url"].startswith("https://example0.test")' |
| 207 | json_ok "duckduckgo: entities decoded and tags stripped" "$R" \ |
| 208 | 'd["results"][0]["title"].startswith("Result & 0") and "b>rust" not in d["results"][0]["title"]' |
| 209 | json_ok "duckduckgo: the /l/?uddg= redirect was unwrapped" "$R" \ |
| 210 | 'd["results"][1]["url"]=="https://example1.test/page1"' |
| 211 | json_ok "duckduckgo: site is the host" "$R" 'd["results"][0]["site"]=="example0.test"' |
| 212 | |
| 213 | R=$(call 2 web_search '{"query":"rust lang","provider":"brave","count":2,"country":"NZ","freshness":"week"}') |
| 214 | json_ok "brave: ok with 2 results" "$R" 'd["ok"] and d["count"]==2' |
| 215 | R=$(call 3 web_search '{"query":"a b","provider":"tavily","count":2}') |
| 216 | json_ok "tavily: ok with 2 results" "$R" 'd["ok"] and d["count"]==2' |
| 217 | R=$(call 4 web_search '{"query":"a b","provider":"exa","count":2}') |
| 218 | json_ok "exa: ok with 2 results" "$R" 'd["ok"] and d["count"]==2' |
| 219 | json_ok "exa: the highlight became the snippet" "$R" 'd["results"][0]["snippet"].startswith("exa highlight")' |
| 220 | R=$(call 5 web_search '{"query":"a b","provider":"perplexity","count":2}') |
| 221 | json_ok "perplexity: ok with 2 results" "$R" 'd["ok"] and d["count"]==2' |
| 222 | R=$(call 6 web_search '{"query":"a b","provider":"searxng","count":2}') |
| 223 | json_ok "searxng: ok with 2 results" "$R" 'd["ok"] and d["count"]==2' |
| 224 | |
| 225 | python3 - "$LOG" <<'PY' |
| 226 | import json, sys |
| 227 | reqs = [json.loads(l) for l in open(sys.argv[1]) if l.strip()] |
| 228 | def one(path): |
| 229 | for r in reqs: |
| 230 | if r["path"] == path: |
| 231 | return r |
| 232 | return None |
| 233 | fails = [] |
| 234 | def want(desc, cond, detail=""): |
| 235 | if cond: |
| 236 | print(" ok %s" % desc) |
| 237 | else: |
| 238 | fails.append(desc) |
| 239 | print(" FAIL %s%s" % (desc, (" (" + str(detail)[:200] + ")") if detail else "")) |
| 240 | |
| 241 | d = one("/duckduckgo/html/") |
| 242 | want("duckduckgo is a POST to /html/ (a GET gets a challenge page)", |
| 243 | d and d["method"] == "POST", d) |
| 244 | want("duckduckgo sends the query urlencoded in the form body", |
| 245 | d and "q=rust%20lang" in (d["body"] or ""), d) |
| 246 | want("duckduckgo sends the safe-search parameter", d and "kp=-1" in (d["body"] or ""), d) |
| 247 | |
| 248 | b = one("/brave/res/v1/web/search") |
| 249 | want("brave is a GET to /res/v1/web/search", b and b["method"] == "GET", b) |
| 250 | want("brave sends X-Subscription-Token", b and b["cred"] == "BRV-TEST-KEY-1", b) |
| 251 | want("brave sends count, country and freshness", |
| 252 | b and b["query"].get("count") == "2" and b["query"].get("country") == "NZ" |
| 253 | and b["query"].get("freshness") == "week", b) |
| 254 | |
| 255 | t = one("/tavily/search") |
| 256 | want("tavily is a POST with a JSON body", t and t["method"] == "POST", t) |
| 257 | want("tavily sends the key as a bearer", t and t["cred"] == "Bearer TVL-TEST-KEY-1", t) |
| 258 | want("tavily sends query and max_results", |
| 259 | t and t["body"].get("query") == "a b" and t["body"].get("max_results") == 2, t) |
| 260 | |
| 261 | e = one("/exa/search") |
| 262 | want("exa is a POST with x-api-key", e and e["method"] == "POST" and e["cred"] == "EXA-TEST-KEY-1", e) |
| 263 | want("exa sends numResults and a contents block", |
| 264 | e and e["body"].get("numResults") == 2 and e["body"].get("contents", {}).get("highlights") is True, e) |
| 265 | |
| 266 | p = one("/perplexity/search") |
| 267 | want("perplexity is a POST with a bearer", p and p["method"] == "POST" |
| 268 | and p["cred"] == "Bearer PPX-TEST-KEY-1", p) |
| 269 | want("perplexity sends query and max_results", |
| 270 | p and p["body"].get("query") == "a b" and p["body"].get("max_results") == 2, p) |
| 271 | |
| 272 | s = one("/searxng/search") |
| 273 | want("searxng is a GET with format=json", s and s["method"] == "GET" |
| 274 | and s["query"].get("format") == "json", s) |
| 275 | want("searxng sends the query and categories", |
| 276 | s and s["query"].get("q") == "a b" and s["query"].get("categories") == "general", s) |
| 277 | |
| 278 | sys.exit(1 if fails else 0) |
| 279 | PY |
| 280 | if [ $? -eq 0 ]; then PASS=$((PASS + 1)); else FAIL=$((FAIL + 1)); fi |
| 281 | |
| 282 | # ----------------------------------------------------------------- errors |
| 283 | section "failures are reported, never swallowed" |
| 284 | R=$(BRAVE_API_KEY=WRONG call 7 web_search '{"query":"q","provider":"brave"}') |
| 285 | check "a wrong brave key is the provider's own 401" 'HTTP 401' "$R" |
| 286 | check "the 401 text is the provider's message, not ours" 'invalid subscription token' "$R" |
| 287 | R=$(TAVILY_API_KEY=WRONG call 8 web_search '{"query":"q","provider":"tavily"}') |
| 288 | check "a wrong tavily key is a 401 tool error" 'HTTP 401' "$R" |
| 289 | R=$(call 9 web_search '{"query":"q","provider":"nope"}') |
| 290 | check "an unknown provider explains the choices" 'unknown provider' "$R" |
| 291 | R=$(call 10 web_search '{}') |
| 292 | check "a missing query is a tool error" 'query is required' "$R" |
| 293 | R=$(call 11 web_search '{"query":"q","provider":"perplexity"}' ) |
| 294 | json_ok "a provider with no key still answers ok when one is set" "$R" 'd["ok"] or "Perplexity" in d.get("error","")' |
| 295 | R=$(PERPLEXITY_API_KEY= WEBSEARCH_PPLX_KEY= call 12 web_search '{"query":"q","provider":"perplexity"}') |
| 296 | check "a provider with no key says so, by name" 'Perplexity needs an API key' "$R" |
| 297 | # WEBSEARCH_MOCK_BASE also fills searxng_base, so it has to be cleared too for |
| 298 | # the "not configured" branch to be reachable at all. |
| 299 | R=$(WEBSEARCH_MOCK_BASE= WEBSEARCH_SEARXNG_BASE= SEARXNG_URL= \ |
| 300 | call 13 web_search '{"query":"q","provider":"searxng"}') |
| 301 | check "searxng with no base URL says so, by name" 'SearXNG needs a base URL' "$R" |
| 302 | R=$(WEBSEARCH_MOCK_BASE= WEBSEARCH_DDG_BASE=http://127.0.0.1:1 call 14 web_search '{"query":"q","provider":"duckduckgo"}') |
| 303 | check "an unreachable host is a clean error, not a hang" 'connect' "$R" |
| 304 | R=$(call 15 web_search '{"query":"q","provider":"ddg"}') |
| 305 | check "the provider id is matched exactly" 'unknown provider' "$R" |
| 306 | |
| 307 | # --------------------------------------------------------------- config |
| 308 | section "config.json round-trip and secret hygiene" |
| 309 | rm -rf "$CFGDIR"; mkdir -p "$CFGDIR" |
| 310 | SAVE=$(cgi "action=save&format=json" POST \ |
| 311 | '{"action":"save","brave_key":"BRV-SAVED-1","tavily_key":"","exa_key":"EXA-SAVED-1","provider":"exa","count":"7","safe":"strict"}') |
| 312 | json_ok "save answers the provider map" "$(body "$SAVE")" '"providers" in d' |
| 313 | body "$SAVE" > "$WORK/save.json" |
| 314 | json_ok "the saved provider became the active one" "$(cat "$WORK/save.json")" 'd["active"]=="exa"' |
| 315 | json_ok "the saved count round-trips" "$(cat "$WORK/save.json")" 'd["default_count"]==7' |
| 316 | json_ok "the saved safe-search round-trips" "$(cat "$WORK/save.json")" 'd["safe"]=="strict"' |
| 317 | check_not "the save response never echoes the key" 'BRV-SAVED-1' "$SAVE" |
| 318 | check_not "the save response never echoes the other key" 'EXA-SAVED-1' "$SAVE" |
| 319 | if [ -f "$CFGDIR/config.json" ]; then |
| 320 | pass "config.json was written in the connector dir" |
| 321 | MODE=$(stat -c '%a' "$CFGDIR/config.json" 2>/dev/null || stat -f '%Lp' "$CFGDIR/config.json") |
| 322 | if [ "$MODE" = "600" ]; then pass "config.json is mode 0600"; else fail "config.json mode is $MODE, want 600"; fi |
| 323 | check "the key really is in the file" 'BRV-SAVED-1' "$CFGDIR/config.json" |
| 324 | else |
| 325 | fail "config.json was not created" |
| 326 | fi |
| 327 | # The environment outranks the file: a saved "" for tavily must still lose to |
| 328 | # TAVILY_API_KEY, and a saved value must lose to a different env value. |
| 329 | PROV=$(SWEBSEARCH_CONFIG_DIR="$CFGDIR" BRAVE_API_KEY=ENV-WINS cgi "action=providers&format=json" GET) |
| 330 | body "$PROV" > "$WORK/prov.json" |
| 331 | json_ok "the env key outranks the saved one (brave has_key still true)" "$(cat "$WORK/prov.json")" \ |
| 332 | 'any(p["id"]=="brave" and p["has_key"] for p in d["providers"])' |
| 333 | check_not "the providers response never carries a key" 'ENV-WINS' "$PROV" |
| 334 | check_not "the providers response never carries the saved key" 'BRV-SAVED-1' "$PROV" |
| 335 | CLEAR=$(SWEBSEARCH_CONFIG_DIR="$CFGDIR" BRAVE_API_KEY= cgi "action=save&format=json" POST \ |
| 336 | '{"action":"save","clear_brave_key":1}') |
| 337 | check_not "clearing a key removes it from the file" 'BRV-SAVED-1' "$CFGDIR/config.json" |
| 338 | BAD=$(cgi "action=save&format=json" POST '{"action":"save","brave_base":"ftp://x"}') |
| 339 | check "a non-http base URL is refused" 'must start with http' "$BAD" |
| 340 | UNK=$(cgi "action=nope&format=json" GET) |
| 341 | check "an unknown action is a 404" 'unknown action' "$UNK" |
| 342 | |
| 343 | # ------------------------------------------------------------------- CGI |
| 344 | section "the page and its auth gate" |
| 345 | UNAUTH=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN") |
| 346 | check "GET with no credential is 401 when a node password is set" '401 Unauthorized' "$UNAUTH" |
| 347 | AUTHED=$(QUERY_STRING="pwd=pw" REQUEST_METHOD=GET BOT_PASSWORD=pw SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN") |
| 348 | check "GET with ?pwd= is 200" 'Content-Type: text/html' "$AUTHED" |
| 349 | HDR=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw \ |
| 350 | SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN") |
| 351 | check "GET with X-Bot-Password is 200" 'Content-Type: text/html' "$HDR" |
| 352 | BEARER=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw HTTP_AUTHORIZATION="Bearer pw" \ |
| 353 | SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN") |
| 354 | check "GET with a bearer token is 200" 'Content-Type: text/html' "$BEARER" |
| 355 | PAGE=$(QUERY_STRING="theme=light&embed=1" REQUEST_METHOD=GET BOT_PASSWORD="" \ |
| 356 | SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN") |
| 357 | check_not "the page has no external script tag" '<script src=' "$PAGE" |
| 358 | check_not "the page references no CDN" 'cdnjs' "$PAGE" |
| 359 | check_not "the page references no unpkg" 'unpkg' "$PAGE" |
| 360 | check "the page carries the bot theme tokens" '--bg:' "$PAGE" |
| 361 | check "the page carries the theme prepaint/handoff script" 'sxApplyTheme' "$PAGE" |
| 362 | check "the page has the provider list container" 'id="providers"' "$PAGE" |
| 363 | check "the page has a search box" 'id="q"' "$PAGE" |
| 364 | check "the page has the key fields" 'id="k_brave"' "$PAGE" |
| 365 | check "the page asks for an sx-theme from its host" 'sx-theme-request' "$PAGE" |
| 366 | json_ok "embed=1 does not break the page (still valid HTML head)" \ |
| 367 | "$(printf '%s' "$PAGE" | grep -c 'DOCTYPE html' >/dev/null && echo '{"ok":1}')" |
| 368 | EMBED=$(printf '%s' "$PAGE" | grep -c 'class="embedded"\|embed-hide') |
| 369 | if [ "$EMBED" -ge 1 ]; then pass "the embed-mode rules are present"; else fail "no embed-mode markup"; fi |
| 370 | INFO=$(cgi "action=info&format=json" GET) |
| 371 | body "$INFO" > "$WORK/info.json" |
| 372 | json_ok "action=info reports the id, kind and providers" "$(cat "$WORK/info.json")" \ |
| 373 | 'd["id"]=="plugin_websearch" and d["kind"]=="mcp" and len(d["providers"])==6' |
| 374 | SEARCHAPI=$(cgi "action=search&format=json&q=rust+lang&provider=duckduckgo&count=2" GET) |
| 375 | body "$SEARCHAPI" > "$WORK/api.json" |
| 376 | json_ok "action=search answers real results" "$(cat "$WORK/api.json")" \ |
| 377 | 'd["ok"] and d["count"]==2 and d["provider"]=="duckduckgo"' |
| 378 | NOPWD=$(QUERY_STRING="action=providers&format=json" REQUEST_METHOD=GET BOT_PASSWORD=pw \ |
| 379 | SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN") |
| 380 | check "the JSON API is behind the same auth gate" '401 Unauthorized' "$NOPWD" |
| 381 | |
| 382 | # ---------------------------------------------------------------- build cmd |
| 383 | section "the advertised build command actually builds the plugin" |
| 384 | # `build_cmd_posix` is what the marketplace's "copy the agent build command" |
| 385 | # button hands to a user's agent, so a wrong string is a broken promise - and |
| 386 | # the CLI's pre-1.4.0 default was a single-source `cc` line that cannot build a |
| 387 | # repo with six sources and two vendored libraries. The author declares it here |
| 388 | # (rule 1 of the CLI's own precedence) and this asserts the declaration is the |
| 389 | # one that works, not merely that it exists. |
| 390 | json_ok "plugin.json declares build_cmd_posix" "$(cat plugin.json)" \ |
| 391 | 'd.get("build_cmd_posix")=="make"' |
| 392 | json_ok "plugin.json declares build_cmd_win64" "$(cat plugin.json)" \ |
| 393 | 'd.get("build_cmd_win64")=="make win64"' |
| 394 | json_ok "the declared win64 build is a real Makefile target" "$(cat plugin.json)" \ |
| 395 | 'open("Makefile").read().find("\nwin64:") >= 0' |
| 396 | # the legacy single-source line is provably wrong here: it neither passes -I nor |
| 397 | # names the vendored translation units. Prove that rather than assert it. |
| 398 | if [ "$(ls src/*.c | wc -l)" -gt 1 ]; then |
| 399 | pass "repo has more than one translation unit (a one-line cc cannot build it)" |
| 400 | else |
| 401 | fail "expected more than one source file" |
| 402 | fi |
| 403 | if grep -q -- '-I vendor' Makefile; then |
| 404 | pass "the Makefile passes -I vendor (the one-line cc does not)" |
| 405 | else |
| 406 | fail "Makefile does not pass -I vendor" |
| 407 | fi |
| 408 | |
| 409 | # ---------------------------------------------------------------- source |
| 410 | section "source guards" |
| 411 | if grep -rn --include='*.c' --include='*.h' -E '\b(popen|system|execv|fork)\s*\(' src/ >/dev/null 2>&1; then |
| 412 | fail "src/ must not spawn a process" |
| 413 | else pass "src/ spawns no process (no popen/system/exec/fork)"; fi |
| 414 | if grep -rn --include='*.c' --include='*.h' -E 'ghp_[A-Za-z0-9]{10}|hf_[A-Za-z0-9]{10}' src/ >/dev/null 2>&1; then |
| 415 | fail "src/ carries a credential literal" |
| 416 | else pass "src/ carries no credential literal"; fi |
| 417 | if grep -rn --include='*.c' --include='*.h' -E '192[.]168[.]|10[.][0-9]+[.][0-9]+[.]' src/*.c src/*.h >/dev/null 2>&1; then |
| 418 | fail "src/ carries a private address" |
| 419 | else pass "src/ carries no private address literal"; fi |
| 420 | if grep -rn --include='*.c' 'yyjson_mut_obj_add_str(' src/ >/dev/null 2>&1; then |
| 421 | fail "yyjson_mut_obj_add_str stores the caller's pointer - use the strcpy form" |
| 422 | else pass "no non-copying yyjson string constructor is used"; fi |
| 423 | if grep -n 'require_node_auth' src/plugin_websearch.c | grep -q .; then |
| 424 | pass "the CGI path calls require_node_auth()" |
| 425 | else fail "require_node_auth() is not called"; fi |
| 426 | if python3 tools/gen_ui.py --check >/dev/null 2>&1; then |
| 427 | pass "src/ui_html.h matches src/ui.html" |
| 428 | else fail "src/ui_html.h is stale (run make ui)"; fi |
| 429 | # A one-line header edit must force a rebuild. `make` used to treat only |
| 430 | # src/*.c and the generated UI header as prerequisites, so a version bump in |
| 431 | # src/ws.h left "Nothing to be done" and the previous binary in place - the |
| 432 | # build reported success with a stale artefact (the failure this project |
| 433 | # keeps paying for). Pin the rule, not the belief. |
| 434 | if grep -q '^HDR ' Makefile && grep -q '\$(HDR)' Makefile; then |
| 435 | pass "Makefile makes every header a rebuild prerequisite" |
| 436 | else |
| 437 | fail "Makefile does not depend on src/*.h - a header edit would not rebuild" |
| 438 | fi |
| 439 | |
| 440 | # --------------------------------------------------------------- summary |
| 441 | printf '\n%s== summary ==%s\n' "$C_B" "$C_0" |
| 442 | printf 'PASS=%d FAIL=%d SKIP=%d\n' "$PASS" "$FAIL" "$SKIP" |
| 443 | if [ "$FAIL" -ne 0 ]; then |
| 444 | echo "SUITE-FAIL" |
| 445 | exit 1 |
| 446 | fi |
| 447 | echo "SUITE-OK" |