#!/bin/sh
# The web_fetch tool, against the fake server (no network): HTML to text, plain text and JSON
# passed through, redirects and their limit, the size and time caps, refusals of private and
# metadata addresses (also on a redirect), binary types, and offline. The test seams
# PIC_TEST_WEB_LOOPBACK=PORT (the one loopback port the fetch may reach) and
# PIC_TEST_WEB_DEADLINE=SECONDS exist in dev builds only; --no-faults (the release build)
# checks that loopback stays refused.
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-webfetch.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; }
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
printf 'hello\n' > "$T/hello.txt"

n=0
fresh() { n=$((n + 1)); DB="$T/$n.sqlite"; WS="$T/ws$n"; mkdir "$WS"; }
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
# serve SPEC...: a fresh fake server; PORT and its requests in $T/log.
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")
}
# fetch URL [MAX_CHARS]: a fresh conversation whose one call is web_fetch; the result text in
# $T/out. Extra environment goes in $WENV.
fetch() {
    fresh
    inp="{\"url\":\"$1\"${2:+,\"max_chars\":$2}}"
    printf 'tool raw web_fetch %s\ntext done\n' "$inp" > "$T/script"
    pic submit job fetch > /dev/null
    # shellcheck disable=SC2086
    env ${WENV:-} PIC_TEST_WEB_LOOPBACK="${PORT:-0}" "$PIC" --db "$DB" --workspace "$WS" 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
    serve "head:200:$T/hello.txt:Content-Type: text/plain"
    PORT=$PORT fetch "http://127.0.0.1:$PORT/a"
    has "private" "release: loopback"
    [ ! -e "$T/log/1.req" ] || fail "release: the server was reached"
    printf 'PASS: release builds refuse loopback\n'
    exit 0
fi

# HTML becomes readable text: scripts, styles, navigation and comments go; headings, links,
# lists, code, quotes and tables stay; entities are decoded; relative links are made absolute.
serve "head:200:$D/page.html:Content-Type: text/html; charset=utf-8"
fetch "http://127.0.0.1:$PORT/dir/page"
has "# Main Heading" html
has "**bold**" html
has "*soft*" html
has "[relative link](http://127.0.0.1:$PORT/docs/start)" html
has "[absolute one](https://other.example/x?a=1&b=2)" html
has "- apple" html
has "- pear" html
has "  1. one" html
has "  2. two" html
has '```c' html
has "    return 0 < 1;" html
has "> quoted words" html
has "Name | Qty" html
has "nut | 3" html
has "Café © — done" html
has "next line" html
has "Example & Co" html
lacks "SCRIPTBODY" html
lacks "MORESCRIPT" html
lacks "color: red" html
lacks "NAVMENU" html
lacks "NAVITEM" html
lacks "COMMENTBODY" html
grep -q '^GET /dir/page HTTP/1.1' "$T/log/1.req" || fail "html: request line"
grep -qi "^Host: 127.0.0.1:$PORT" "$T/log/1.req" || fail "html: Host header has no port"
printf 'PASS: HTML is converted to text\n'

# Sloppy HTML: tags unclosed or in capitals, nested navigation, a stray '<', a script that
# mentions tags, javascript: and fragment links, and a data: image.
serve "head:200:$D/sloppy.html:Content-Type: text/html"
fetch "http://127.0.0.1:$PORT/dir/sub/page"
has "One never closed" sloppy
has "Two with 3 < 4 and a &b; &unknown; A stray" sloppy
has "- c" sloppy
has "use \`make test\` now." sloppy
has "![logo](http://127.0.0.1:$PORT/i.png)" sloppy
has "[up](http://127.0.0.1:$PORT/dir/up/x.html)" sloppy
has "### [Linked heading](http://127.0.0.1:$PORT/h)" sloppy
has "deep spans" sloppy
lacks "outer" sloppy
lacks "inner" sloppy
lacks "still nav" sloppy
lacks "SCRIPT" sloppy
lacks "javascript:" sloppy
lacks "#top" sloppy
lacks "base64" sloppy
printf 'PASS: sloppy HTML is read\n'

# Plain text and JSON pass through untouched.
printf 'line one\n<b>not html</b>\n' > "$T/plain.txt"
printf '{"a":[1,2],"b":"<i>x</i>"}' > "$T/data.json"
serve "head:200:$T/plain.txt:Content-Type: text/plain" "head:200:$T/data.json:Content-Type: application/json"
fetch "http://127.0.0.1:$PORT/p"
has "<b>not html</b>" plain
serve "head:200:$T/data.json:Content-Type: application/json"
fetch "http://127.0.0.1:$PORT/d"
has '{"a":[1,2],"b":"<i>x</i>"}' json
printf 'PASS: plain text and JSON pass through\n'

# Redirects are followed, relative and absolute.
printf 'landed here\n' > "$T/landed.txt"
serve "head:302:-:Location: /b/x" "head:301:-:Location: y?q=1#frag" "head:200:$T/landed.txt:Content-Type: text/plain"
fetch "http://127.0.0.1:$PORT/a"
has "landed here" redirect
grep -q '^GET /b/x HTTP/1.1' "$T/log/2.req" || fail "redirect: second request not for /b/x"
grep -q '^GET /b/y?q=1 HTTP/1.1' "$T/log/3.req" || fail "redirect: third request not for /b/y?q=1"
printf 'PASS: redirects are followed\n'

# Five redirects are followed, the sixth is not.
serve "head:302:-:Location: /next"
fetch "http://127.0.0.1:$PORT/a"
has "too many redirects" loop
[ "$(ls "$T/log" | wc -l | tr -d ' ')" = 6 ] || fail "loop: $(ls "$T/log" | wc -l) requests, wanted 6 (the first and five redirects)"
printf 'PASS: redirects are limited to five\n'

# Private, loopback, link-local and metadata addresses are refused, before any connection.
serve "head:200:$T/hello.txt:Content-Type: text/plain"
for u in "http://10.0.0.1/" "http://127.0.0.1:1/" "http://localhost:1/" "http://0.0.0.0/" "http://100.64.0.1/" \
    "http://172.16.5.5/" "http://192.168.1.1/x" "http://169.254.169.254/latest/meta-data/" \
    "http://[::1]/" "http://[fc00::1]/" "http://[fd12:3456::1]/" "http://[fe80::1]/" \
    "http://[::ffff:127.0.0.1]/" "http://[::ffff:a9fe:a9fe]/" "https://[fd00:ec2::254]/" "http://224.0.0.1/" \
    "http://2130706433/" "http://0x7f.1/" "http://127.1/"; do
    fetch "$u"
    has "refused" "private $u"
    has "not a public address" "private $u"
done
[ ! -e "$T/log/1.req" ] || fail "private: the fake server was reached"
printf 'PASS: private addresses are refused\n'

# A redirect to one is refused too, and nothing past it is fetched.
serve "head:302:-:Location: http://127.0.0.1:1/secret" "head:200:$T/hello.txt:Content-Type: text/plain"
fetch "http://127.0.0.1:$PORT/a"
has "refused" "redirect to loopback"
lacks "hello" "redirect to loopback"
serve "head:302:-:Location: http://169.254.169.254/latest/meta-data/"
fetch "http://127.0.0.1:$PORT/a"
has "refused" "redirect to metadata"
serve "head:302:-:Location: http://localhost:1/"
fetch "http://127.0.0.1:$PORT/a"
has "refused" "redirect to localhost"
serve "head:302:-:Location: file:///etc/passwd"
fetch "http://127.0.0.1:$PORT/a"
has "http and https" "redirect to a file"
printf 'PASS: a redirect to a private address is refused\n'

# The size cap: refused by Content-Length, and when a chunked body outgrows it.
head -c 6000000 /dev/zero | tr '\0' 'a' > "$T/big.txt"
serve "head:200:$T/big.txt:Content-Type: text/plain"
fetch "http://127.0.0.1:$PORT/big"
has "5 MB" "size (length)"
serve "sse:$T/big.txt"
fetch "http://127.0.0.1:$PORT/big"
has "5 MB" "size (chunked)"
printf 'PASS: the size cap holds\n'

# The deadline: a server that trickles its answer is cut off.
head -c 1000 /dev/zero | tr '\0' 'b' > "$T/slow.txt"
serve "slow:$T/slow.txt:1000"
WENV="PIC_TEST_WEB_DEADLINE=2" fetch "http://127.0.0.1:$PORT/slow"
has "deadline" "deadline"
printf 'PASS: the deadline holds\n'

# Binary types are refused with their type and size.
head -c 4096 /dev/zero > "$T/blob.bin"
serve "head:200:$T/blob.bin:Content-Type: image/png"
fetch "http://127.0.0.1:$PORT/i.png"
has "image/png" binary
has "4096 bytes" binary
serve "head:200:$T/blob.bin:Content-Type: application/pdf"
fetch "http://127.0.0.1:$PORT/f.pdf"
has "application/pdf" binary
serve "head:200:$T/blob.bin:Content-Type: application/octet-stream"
fetch "http://127.0.0.1:$PORT/f"
has "application/octet-stream" binary
printf 'PASS: binary types are refused\n'

# Output is bounded and the whole is kept for read.
awk 'BEGIN { for (i = 1; i <= 3000; i++) printf "line %d of the long page\n", i }' > "$T/long.txt"
serve "head:200:$T/long.txt:Content-Type: text/plain"
fetch "http://127.0.0.1:$PORT/long" 1000
has "line 1 of the long page" bound
lacks "line 2999 of the long page" bound
has "pic:output/1" bound
fresh
printf 'tool raw web_fetch {"url":"http://127.0.0.1:%s/long","max_chars":1000}\ntext done\n' "$PORT" > "$T/script"
pic submit job fetch > /dev/null
PIC_TEST_WEB_LOOPBACK=$PORT pic run --script "$T/script" > /dev/null
printf 'tool raw read {"path":"pic:output/1","offset":2999,"limit":2}\ntext done\n' > "$T/script"
pic submit job2 read > /dev/null
pic run --script "$T/script" > /dev/null
pic dump | grep -q 'line 2999 of the long page' || fail "bound: the whole is not kept for read"
printf 'PASS: output is bounded and kept whole\n'

# Hooks and the secret guard apply as to any tool: a PreToolUse hook can refuse a URL, and a
# required PostToolUse hook can redact what the page said before the model sees it.
printf 'the key is sk-web-SECRET-4242\n' > "$T/leak.txt"
cat > "$T/pre.sh" <<'SH'
if grep -q '/blocked' ; then echo "that site is not allowed" >&2; exit 2; fi
SH
cat > "$T/post.sh" <<'SH'
text=$(sed 's/.*"content":"\(.*\)","is_error".*/\1/; s/sk-web-SECRET-[0-9]*/[REDACTED]/g')
printf '{"hookSpecificOutput":{"hookEventName":"PostToolUse","updatedToolOutput":{"content":[{"type":"text","text":"%s"}]}}}\n' "$text"
SH
printf '{"hooks":{"PreToolUse":[{"matcher":"WebFetch","hooks":[{"type":"command","command":"sh %s/pre.sh","timeout":5}]}],"PostToolUse":[{"matcher":"web_fetch","hooks":[{"type":"command","command":"sh %s/post.sh","timeout":5,"required":true}]}]}}\n' "$T" "$T" > "$HOME/.pic/hooks.json"
serve "head:200:$T/leak.txt:Content-Type: text/plain"
fetch "http://127.0.0.1:$PORT/leak"
has "the key is [REDACTED]" "post hook"
lacks "sk-web-SECRET" "post hook"
! pic dump | grep -q "sk-web-SECRET" || fail "post hook: the secret is journaled"
serve "head:200:$T/leak.txt:Content-Type: text/plain"
fetch "http://127.0.0.1:$PORT/blocked"
[ ! -e "$T/log/1.req" ] || fail "pre hook: the URL was fetched"
pic dump | grep -q 'that site is not allowed' || fail "pre hook: no reason: $(pic dump)"
rm -f "$HOME/.pic/hooks.json"
printf 'PASS: hooks apply to web_fetch\n'

# Hostile input must not crash the tool or run away: a very long bracketed host (in the URL, in a
# redirect, in a link on the page), thousands of unclosed anchors and comments, a deeply nested
# quote, a list that starts at the largest number, and escape characters written as entities or
# bytes. A CPU limit makes a runaway fail the test instead of hanging it.
long_host=$(head -c 290 /dev/zero | tr '\0' a)
serve "head:200:$T/hello.txt:Content-Type: text/plain"
fetch "http://[$long_host]/"
has "web_fetch:" "long host in the URL"
serve "head:302:-:Location: http://[$long_host]/x"
fetch "http://127.0.0.1:$PORT/a"
has "web_fetch:" "long host in a redirect"
printf '<p>before <a href="http://[%s]/x">the link</a> after <img src="https://[%s]/i" alt="pic"></p>\n' "$long_host" "$long_host" > "$T/longhref.html"
serve "head:200:$T/longhref.html:Content-Type: text/html"
fetch "http://127.0.0.1:$PORT/p"
has "the link" "long host in a link"
has "after" "long host in a link"
printf 'PASS: long hosts are bounded\n'

limited() { ( ulimit -t 120; fetch "$@" ); n=$((n + 1)); }
perl -e 'print "<p>start</p>", "<a href=x>link " x 150000, "<!-- open " x 150000, "<p>end</p>"' > "$T/quad.html"
serve "head:200:$T/quad.html:Content-Type: text/html"
limited "http://127.0.0.1:$PORT/q"
has "start" "unclosed anchors"
perl -e 'print "<p>start</p><a href=x>", "<!-- open " x 300000, "</a><p>end</p>"' > "$T/quad2.html"
serve "head:200:$T/quad2.html:Content-Type: text/html"
limited "http://127.0.0.1:$PORT/q"
has "start" "unclosed comments in an anchor"
printf 'PASS: unclosed tags are read in linear time\n'

perl -e 'print "<blockquote>x<br>" x 300000' > "$T/quote.html"
serve "head:200:$T/quote.html:Content-Type: text/html"
limited "http://127.0.0.1:$PORT/q" 100
has "x" "nested quotes"
[ "$(pic dump | wc -c)" -lt 30000000 ] || fail "nested quotes: the output is $(pic dump | wc -c) bytes"
printf 'PASS: nesting and output size are capped\n'

printf '<p>a&#27;]8;;http://evil&#27;\\b &#155;31m c&#x7f;d &#128;e &#x9f;f &#7;g</p><ol start=2147483647><li>one<li>two</ol>\n' > "$T/esc.html"
printf '<p>raw \302\233[31m cp \233 \200 end</p>' > "$T/c1.html"
serve "head:200:$T/esc.html:Content-Type: text/html" "head:200:$T/c1.html:Content-Type: text/html" "head:200:$T/c1.html:Content-Type: text/html; charset=windows-1252"
fetch "http://127.0.0.1:$PORT/e"
has "two" "list start"
has "a]8;;http://evil\\b 31m cd e f g" "entities"
! LC_ALL=C grep -q "$(printf '\033')" "$T/out" || fail "escape entity: an ESC reached the output"
! LC_ALL=C grep -q "$(printf '\302[\200-\237]')" "$T/out" || fail "C1 entity: a C1 control reached the output"
! LC_ALL=C grep -q "$(printf '\007')" "$T/out" || fail "BEL entity reached the output"
fetch "http://127.0.0.1:$PORT/e"
! LC_ALL=C grep -q "$(printf '\302[\200-\237]')" "$T/out" || fail "raw C1: a C1 control reached the output"
has "raw" "raw C1"
fetch "http://127.0.0.1:$PORT/e"
! LC_ALL=C grep -q "$(printf '\302[\200-\237]')" "$T/out" || fail "windows-1252: a C1 control reached the output"
has "€" "windows-1252"
printf 'PASS: control characters are dropped\n'

# Bad input.
for inp in '{}' '{"url":"ftp://example.com/x"}' '{"url":"file:///etc/passwd"}' '{"url":"http://user:pw@example.com/"}' \
    '{"url":"example.com"}' '{"url":"http://example.com/","max_chars":0}'; do
    fresh
    printf 'tool raw web_fetch %s\ntext done\n' "$inp" > "$T/script"
    pic submit job bad > /dev/null
    PIC_TEST_WEB_LOOPBACK=$PORT pic run --script "$T/script" > /dev/null 2>&1 || :
    pic dump | grep -q 'web_fetch:' || fail "bad input $inp: no refusal: $(pic dump)"
done
printf 'PASS: bad input is refused\n'

# Offline: refused with a clear message, and nothing is fetched.
serve "head:200:$T/hello.txt:Content-Type: text/plain"
"$PIC" settings offline true > /dev/null
fetch "http://127.0.0.1:$PORT/a"
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'

# It is on by default, replay-safe, and the tool flags choose it like any tool.
fresh
pic submit job x > /dev/null
printf 'text done\n' > "$T/script"
pic run --script "$T/script" > /dev/null
SQL=$(dirname "$SERVER")/sqlite3
"$SQL" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)" | grep -qw web_fetch ||
    fail "not declared by default"
fresh
pic --exclude-tools web_fetch submit job x > /dev/null
pic --exclude-tools web_fetch run --script "$T/script" > /dev/null
! "$SQL" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)" | grep -qw web_fetch ||
    fail "--exclude-tools web_fetch still declared it"
serve "head:200:$T/hello.txt:Content-Type: text/plain"
fetch "http://127.0.0.1:$PORT/a"
[ "$("$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'
