#!/bin/sh
# The web_search tool, against the fake server (no network): Brave's web search endpoint as
# results text, the key sealed in the credential store or taken from BRAVE_API_KEY and sent only
# as the token header, count and size caps, control characters dropped, errors that name the cause
# and never the key, and offline. With no Brave key it searches Stack Overflow through Stack
# Exchange's keyless API: gzip replies, its backoff kept between calls, its quota errors explained.
# PIC_TEST_WEB_SEARCH_URL and PIC_TEST_STACKEXCHANGE_URL (the endpoints, dev builds only) point
# the tool at the fake server; --no-faults (the release build) checks the real endpoints are the
# only ones.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
D=$(cd "$(dirname "$0")/web" && pwd)
T=$(cd "$(mktemp -d "${TMPDIR:-/tmp}/pic-websearch.XXXXXX")" && pwd -P)
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
export HOME="$T/home" PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline
mkdir -p "$HOME/.pic" "$T/ws"
"$PIC" settings loops.tool false > /dev/null
KEY="BSA-test-key-$$-9f3"
n=0
fresh() { n=$((n + 1)); DB="$T/$n.sqlite"; WS="$T/ws$n"; mkdir "$WS"; }
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
serve() {
[ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || :
rm -rf "$T/log" "$T/port"
mkdir "$T/log"
"$SERVER" "$T/port" "$T/log" 120 "$@" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server"; sleep 0.05; done
PORT=$(cat "$T/port")
}
# search INPUT_JSON: a fresh conversation whose one call is web_search; its result in $T/out.
search() {
fresh
printf 'tool raw web_search %s\ntext done\n' "$1" > "$T/script"
pic --tools +web_search submit job search > /dev/null
env ${SENV:-} PIC_TEST_WEB_SEARCH_URL="http://127.0.0.1:${PORT:-1}/res/v1/web/search" \
PIC_TEST_STACKEXCHANGE_URL="http://127.0.0.1:${PORT:-1}/2.3/search/excerpts" "$PIC" --db "$DB" --workspace "$WS" --tools +web_search run --script "$T/script" > /dev/null 2>&1 || :
pic dump | awk '/^entry [0-9]+ [0-9]+ tool_result/ { on = 1; sub(/^[^|]*\| ?/, ""); print; next }
/^(entry|effect|generation|submission) / { on = 0 } on { print }' > "$T/out"
}
has() { grep -qF -- "$1" "$T/out" || { cat "$T/out" >&2; fail "$2: no '$1'"; }; }
lacks() { ! grep -qF -- "$1" "$T/out" || { cat "$T/out" >&2; fail "$2: has '$1'"; }; }
if [ "$FAULTS" = no ]; then
# A search here would reach the real Stack Exchange: release builds are checked for their
# endpoints and the absence of the seams instead.
! grep -aq 'PIC_TEST_WEB_SEARCH_URL\|PIC_TEST_STACKEXCHANGE_URL' "$PIC" || fail "release: an endpoint seam is compiled in"
grep -aq 'https://api.stackexchange.com/2.3/search/excerpts' "$PIC" || fail "release: no Stack Exchange endpoint"
grep -aq 'https://api.search.brave.com/res/v1/web/search' "$PIC" || fail "release: no Brave endpoint"
printf 'PASS: release builds have no endpoint seam\n'
exit 0
fi
# No Brave key: Stack Overflow through Stack Exchange's keyless search, whose replies are gzip.
SE_HDRS="Content-Type: application/json; charset=utf-8|Content-Encoding: gzip"
gzip -c < "$D/stackexchange.json" > "$T/se.json.gz"
serve "head:200:$T/se.json.gz:$SE_HDRS"
search '{"query":"segmentation fault c","count":3}'
has "Stack Overflow results (no Brave Search key is set" "se"
has '1. What is a "segmentation fault"?' "se"
has " https://stackoverflow.com/a/2346849" "se"
has " Accepted answer, score 63: A segmentation fault means you touched memory you do not own" "se"
has "2. Segmentation fault (core dumped) in C" "se"
has " https://stackoverflow.com/q/777" "se"
has " Question, has answers, score 5: I get Segmentation fault (core dumped) when I run it" "se"
has "3. Third question" "se"
lacks "<span" "se"
lacks "left today" "se: plenty of quota"
! LC_ALL=C grep -q "$(printf '[\001-\010\013-\037\177]')" "$T/out" || fail "se: a control byte reached the output"
R=$(head -1 "$T/log/1.req")
case $R in "GET /2.3/search/excerpts?order=desc&sort=relevance&site=stackoverflow&pagesize=3&q=segmentation%20fault%20c HTTP/1.1"*) ;; *) fail "se: request line: $R" ;; esac
grep -qi "^Accept-Encoding: gzip" "$T/log/1.req" || fail "se: no Accept-Encoding"
! grep -qi "^X-Subscription-Token" "$T/log/1.req" || fail "se: a Brave token header was sent"
[ "$("$(dirname "$SERVER")/sqlite3" "$DB" "SELECT replay_safe FROM pic_effect")" = 1 ] || fail "se: not replay-safe"
printf 'PASS: with no Brave key, Stack Overflow answers through a gzip reply\n'
# A reply that is not compressed is read as it is; few searches left are counted out.
sed 's/"quota_remaining":297/"quota_remaining":7/' "$D/stackexchange.json" > "$T/se-low.json"
serve "head:200:$T/se-low.json:Content-Type: application/json"
search '{"query":"x"}'
has "1. What is a" "se plain"
has "(7 Stack Exchange searches left today from this address; add a Brave Search API key" "se low quota"
printf 'PASS: a plain reply is read and a low quota is named\n'
# backoff: the reply is used, and the next search waits without asking.
sed 's/"quota_remaining":297/"quota_remaining":296,"backoff":30/' "$D/stackexchange.json" | gzip -c > "$T/se-back.json.gz"
serve "head:200:$T/se-back.json.gz:$SE_HDRS"
search '{"query":"x"}'
has "1. What is a" "se backoff reply"
serve "head:200:$T/se.json.gz:$SE_HDRS"
search '{"query":"x"}'
has "Stack Exchange asked for a pause; try again in" "se backoff"
has "pic login brave-search" "se backoff"
[ ! -e "$T/log/1.req" ] || fail "se backoff: the server was reached"
"$(dirname "$SERVER")/sqlite3" "$HOME/.pic/pic.sqlite" "DELETE FROM picu_meta WHERE key = 'stackexchange_backoff_until'"
search '{"query":"x"}'
has "1. What is a" "se after backoff"
printf 'PASS: a backoff is kept and honoured\n'
# Errors: the day's quota (throttle_violation), another error, bad gzip, not JSON.
printf '{"error_id":502,"error_message":"too many requests from this IP, more requests available in 80000 seconds","error_name":"throttle_violation"}' | gzip -c > "$T/se-throttle.gz"
serve "head:400:$T/se-throttle.gz:$SE_HDRS"
search '{"query":"x"}'
has "Stack Exchange's quota for this address is used up (300 searches a day without a key): too many requests" "se throttle"
has "pic login brave-search" "se throttle"
printf '{"error_id":400,"error_message":"q is \\u001b[31mbad","error_name":"bad_parameter"}' | gzip -c > "$T/se-bad.gz"
serve "head:400:$T/se-bad.gz:$SE_HDRS"
search '{"query":"x"}'
has "Stack Exchange answered HTTP 400: bad_parameter: q is" "se error"
! LC_ALL=C grep -q "$(printf '\033')" "$T/out" || fail "se error: an escape reached the output"
printf 'not gzip' > "$T/se-notgz"
serve "head:200:$T/se-notgz:$SE_HDRS"
search '{"query":"x"}'
has "bad gzip" "se bad gzip"
printf '{"items":[],"quota_remaining":200}' | gzip -c > "$T/se-none.gz"
serve "head:200:$T/se-none.gz:$SE_HDRS"
search '{"query":"x"}'
has "no results on Stack Overflow" "se none"
serve "status:502:-"
search '{"query":"x"}'
has "Stack Exchange answered HTTP 502" "se 502"
printf 'PASS: Stack Exchange failures are explained\n'
# A key from the environment: results as numbered title, URL and snippet; the token goes in the
# header and nowhere else.
serve "head:200:$D/brave.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"c language & more","count":3}'
has "1. The C Programming Language & more" env
has " https://example.org/c" env
has " A book about C — classic." env
has "2. ISO C" env
has " https://example.net/iso?a=1&b=2" env
has "3. Third" env
lacks "Fourth" "count"
lacks "<strong>" env
! LC_ALL=C grep -q "$(printf '[\001-\010\013-\037\177]')" "$T/out" || fail "a control byte reached the output"
! LC_ALL=C grep -q "$(printf '\302[\200-\237]')" "$T/out" || fail "a C1 control reached the output"
lacks "$KEY" "key in the result"
grep -q '^GET /res/v1/web/search?q=c%20language%20%26%20more&count=3 HTTP/1.1' "$T/log/1.req" || fail "request line: $(head -1 "$T/log/1.req")"
grep -qi "^X-Subscription-Token: $KEY" "$T/log/1.req" || fail "the token header was not sent"
grep -qi "^Accept: application/json" "$T/log/1.req" || fail "no Accept header"
! pic dump | grep -qF "$KEY" || fail "the key is journaled"
printf 'PASS: results come back as text, the key only in the header\n'
# The default count is 5 and a count over 10 is 10; the results asked for are the ones shown.
serve "head:200:$D/brave.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x"}'
grep -q 'count=5 ' "$T/log/1.req" || fail "default count"
has "4. Fourth" default
serve "head:200:$D/brave.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x","count":99}'
grep -q 'count=10 ' "$T/log/1.req" || fail "count clamp"
printf 'PASS: the result count is bounded\n'
# A key sealed in the credential store by pic login brave-search.
export PIC_TEST_PASSPHRASE="pic-ws-passphrase-$$"
printf '%s\n' "$KEY" | "$PIC" login brave-search > "$T/login.out" 2>&1 || { cat "$T/login.out" >&2; fail "login brave-search"; }
! grep -qF "$KEY" "$T/login.out" || fail "login printed the key"
serve "head:200:$D/brave.json:Content-Type: application/json"
search '{"query":"sealed"}'
has "1. The C Programming Language & more" sealed
grep -qi "^X-Subscription-Token: $KEY" "$T/log/1.req" || fail "the sealed key was not sent"
"$PIC" logout brave-search > /dev/null 2>&1 || "$PIC" auth logout brave-search > /dev/null 2>&1 || fail "logout"
printf 'PASS: a key sealed by pic login brave-search is used\n'
unset PIC_TEST_PASSPHRASE
# Errors name the cause and never the key.
for c in "401|key" "403|key" "429|rate" "500|HTTP 500"; do
code=${c%%|*} want=${c#*|}
printf '{"error":{"detail":"echo %s"}}' "$KEY" > "$T/err.json"
serve "status:$code:$T/err.json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x"}'
has "web_search:" "http $code"
has "HTTP $code" "http $code"
has "$want" "http $code"
lacks "$KEY" "http $code"
done
printf 'PASS: failures are explained without the key\n'
# Bad bodies: not JSON, no results, too large.
printf 'not json at all' > "$T/bad.json"
serve "head:200:$T/bad.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x"}'
has "not understood" "not json"
printf '{"web":{"results":[]}}' > "$T/none.json"
serve "head:200:$T/none.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"nothing"}'
has "no results" "empty"
printf '{"x":"%s"}' "$(head -c 3000000 /dev/zero | tr '\0' a)" > "$T/huge.json"
serve "head:200:$T/huge.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x"}'
has "too large" "huge"
printf 'PASS: odd replies are explained\n'
# A long snippet is cut.
printf '{"web":{"results":[{"title":"T","url":"https://e.org/","description":"%s"}]}}' "$(head -c 5000 /dev/zero | tr '\0' s)" > "$T/long.json"
serve "head:200:$T/long.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x"}'
[ "$(wc -c < "$T/out")" -lt 1500 ] || fail "snippet not cut: $(wc -c < "$T/out") bytes"
printf 'PASS: snippets are cut\n'
# A long query in a wide script is sent whole, with its count: 300 CJK characters encode to 2700
# bytes, which no fixed buffer should cut.
cjk=$(perl -CS -e 'print "\x{65e5}" x 300')
serve "head:200:$D/brave.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search "{\"query\":\"$cjk\",\"count\":3}"
grep -q '&count=3 HTTP/1.1' "$T/log/1.req" || fail "the count was cut off: $(head -1 "$T/log/1.req" | tail -c 80)"
[ "$(head -1 "$T/log/1.req" | grep -o '%E6%97%A5' | wc -l | tr -d ' ')" = 300 ] || fail "the query was cut"
printf 'PASS: a long encoded query is sent whole\n'
# The tool is offered with no key at all (Stack Overflow answers it), and --tools +web_search
# still names it.
fresh
pic submit job x > /dev/null
printf 'text done\n' > "$T/script"
pic run --script "$T/script" > /dev/null
SQL=$(dirname "$SERVER")/sqlite3
names() { "$SQL" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)"; }
names | grep -qw web_search || fail "not offered with no key: $(names)"
fresh
pic --tools +web_search submit job x > /dev/null
pic --tools +web_search run --script "$T/script" > /dev/null
names | grep -qw web_search || fail "--tools +web_search did not offer it: $(names)"
printf 'PASS: the tool is offered with no key\n'
# brave-search holds a key and serves no model: it takes no routing rule and no import, and
# auth status names it.
export PIC_TEST_PASSPHRASE="pic-ws-passphrase-$$"
printf '%s\n' "$KEY" | "$PIC" login brave-search > /dev/null 2>&1 || fail "login brave-search"
"$PIC" auth status > "$T/status" 2>&1 || :
grep -q 'brave-search.*Brave Search' "$T/status" || fail "status: $(cat "$T/status")"
! grep -qF "unknown provider" "$T/status" || fail "status calls it unknown: $(cat "$T/status")"
if "$PIC" auth use brave-search default --for 'x*' > "$T/use.out" 2>&1; then fail "auth use --for took brave-search"; fi
grep -q "not a model provider" "$T/use.out" || fail "auth use: $(cat "$T/use.out")"
if BRAVE_API_KEY=$KEY "$PIC" auth import BRAVE_API_KEY brave-search --as other > "$T/imp.out" 2>&1; then fail "auth import took brave-search"; fi
grep -q "not a model provider" "$T/imp.out" || fail "auth import: $(cat "$T/imp.out")"
"$PIC" auth logout brave-search > /dev/null 2>&1 || "$PIC" logout brave-search > /dev/null 2>&1 || :
unset PIC_TEST_PASSPHRASE
printf 'PASS: brave-search is a key and not a model provider\n'
# A Retry-After with control characters is shown without them.
printf '{"error":"x"}' > "$T/err.json"
serve "head:429:$T/err.json:Retry-After: 5$(printf '\033]8;;x\007')s"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x"}'
has "HTTP 429" "retry-after"
! LC_ALL=C grep -q "$(printf '[\001-\010\013-\037\177]')" "$T/out" || fail "a control byte of Retry-After reached the output"
printf 'PASS: Retry-After is filtered\n'
# Bad input.
for inp in '{}' '{"query":""}' '{"query":5}' '{"query":"x","count":0}' '{"query":"x","count":"a"}'; do
serve "head:200:$D/brave.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search "$inp"
has "web_search:" "bad input $inp"
[ ! -e "$T/log/1.req" ] || fail "bad input $inp: the server was reached"
done
long=$(head -c 500 /dev/zero | tr '\0' q)
serve "head:200:$D/brave.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search "{\"query\":\"$long\"}"
has "too long" "long query"
printf 'PASS: bad input is refused\n'
# Offline refuses, and nothing is sent.
serve "head:200:$D/brave.json:Content-Type: application/json"
"$PIC" settings offline true > /dev/null
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x"}'
has "offline" offline
[ ! -e "$T/log/1.req" ] || fail "offline: the server was reached"
"$PIC" settings --unset offline > /dev/null
printf 'PASS: offline refuses\n'
# A permission mode counts it as a change: read-only refuses it and nothing is sent.
serve "head:200:$D/brave.json:Content-Type: application/json"
fresh
printf 'tool raw web_search {"query":"x"}\ntext done\n' > "$T/script"
pic --permission-mode read-only submit job ro > /dev/null
SENV="BRAVE_API_KEY=$KEY"
env BRAVE_API_KEY="$KEY" PIC_TEST_WEB_SEARCH_URL="http://127.0.0.1:$PORT/res/v1/web/search" "$PIC" --db "$DB" --workspace "$WS" --permission-mode read-only run --script "$T/script" > /dev/null 2>&1 || :
pic dump | grep -q 'read-only.*web_search was not run' || fail "read-only did not refuse: $(pic dump)"
[ ! -e "$T/log/1.req" ] || fail "read-only: the server was reached"
printf 'PASS: read-only refuses web_search\n'
# Offered by default with a key, replay-safe, left out by the flags.
SQL=$(dirname "$SERVER")/sqlite3
fresh
pic submit job x > /dev/null
printf 'text done\n' > "$T/script"
BRAVE_API_KEY=$KEY pic run --script "$T/script" > /dev/null
"$SQL" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)" | grep -qw web_search || fail "not declared by default with a key"
fresh
pic --exclude-tools web_search submit job x > /dev/null
BRAVE_API_KEY=$KEY pic --exclude-tools web_search run --script "$T/script" > /dev/null
! "$SQL" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)" | grep -qw web_search || fail "--exclude-tools web_search still declared it"
serve "head:200:$D/brave.json:Content-Type: application/json"
SENV="BRAVE_API_KEY=$KEY" search '{"query":"x"}'
[ "$("$SQL" "$DB" "SELECT replay_safe FROM pic_effect")" = 1 ] || fail "not replay-safe"
printf 'PASS: on by default, replay-safe, chosen by the flags\n'