#!/bin/sh
# Isolated dev only: pre-kcgi admission, not a whole-runtime RSS certificate.
set -eu
T=$(mktemp -d /tmp/parser-contract.XXXXXX)
trap 'rm -rf "$T"' EXIT
request() {
 want=$1; path=$2; type=$3; shift 3
 code=$(curl --max-time 20 --path-as-is -sS -o "$T/reply" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' -H "Content-Type: $type" "$@" --data-binary "@$T/body" "http://localhost:8080/$path")
 [ "$code" = "$want" ] || { echo "FAIL - parser HTTP $code expected $want ($path, $type)" >&2; exit 1; }
}
# One byte over the dense-form transport cap must never enter kcgi.
awk 'BEGIN {for(i=0;i<5461;i++) printf "x=&"; printf "x="}' > "$T/body"
for path in api/parser-probe apiBAD pim-api/parser-probe pim-apiBAD '%61pi/parser-probe' 'dam/../api/parser-probe'; do
 for type in application/x-www-form-urlencoded text/plain application/json 'multipart/form-datax; boundary=z'; do
  request 413 "$path" "$type"
 done
done
# Ambiguous content types cannot select the large cap and a dense parser.
for first in 'multipart/form-data; boundary=z' application/x-www-form-urlencoded; do
 second=application/x-www-form-urlencoded
 [ "$first" != "$second" ] || second='multipart/form-data; boundary=z'
 code=$(curl --max-time 20 -sS -o "$T/reply" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' -H "Content-Type: $first" -H "Content-Type: $second" --data-binary "@$T/body" http://localhost:8080/api/parser-probe)
 case "$code" in 400|413) ;; *) echo "FAIL - ambiguous content type HTTP $code" >&2; exit 1;; esac
done
# Unknown-length transfer must have the same cap as a known Content-Length.
request 413 api/parser-probe application/x-www-form-urlencoded -H 'Transfer-Encoding: chunked'
# Exact dense-form limit is still accepted by the parser (the route is unknown).
awk 'BEGIN {for(i=0;i<5461;i++) printf "x=&"; printf "x"}' > "$T/body"
request 404 api/parser-probe application/x-www-form-urlencoded
# A real multipart body above16KiB remains admitted, including MIME case folding.
printf '%s\r\n' '--z' 'Content-Disposition: form-data; name="unused"' '' > "$T/body"
dd if=/dev/zero bs=1024 count=32 >> "$T/body" 2>/dev/null
printf '\r\n%s\r\n' '--z--' >> "$T/body"
request 404 api/parser-probe 'multipart/form-data; boundary=z'
request 404 api/parser-probe 'Multipart/Form-Data; boundary=z'
# Multipart itself retains the1100KiB transport cap.
dd if=/dev/zero of="$T/body" bs=1024 count=1101 2>/dev/null
request 413 api/parser-probe 'multipart/form-data; boundary=z'
echo 'parser contract: dense form cap/exact boundary, encoded prefixes, unknown-length transfer and multipart allowance passed'
