reportist/plugins/diagnostics/tools/validate.sh

94 lines
2.4 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
usage() {
echo "Usage: $0 INPUT [--evidence-root DIR]" >&2
exit 2
}
fail() {
echo "error: $*" >&2
exit 1
}
sha256_file() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1" | awk '{print $1}'
elif command -v sha256 >/dev/null 2>&1; then
sha256 -q "$1"
else
openssl dgst -sha256 "$1" | awk '{print $NF}'
fi
}
json_string() {
local value=$1
[[ "$value" == \"*\" ]] || fail "Typst returned a non-string value"
value=${value:1:${#value}-2}
[[ "$value" != *\\* && "$value" != *\"* ]] || fail "unsupported escaped path"
printf '%s' "$value"
}
input=${1:-}
[[ -n "$input" ]] || usage
shift
evidence_root=
while (($#)); do
case $1 in
--evidence-root)
(($# >= 2)) || usage
evidence_root=$2
shift 2
;;
*)
usage
;;
esac
done
input=$(realpath "$input")
stage=$(mktemp -d "${TMPDIR:-/tmp}/diagnostic-validate.XXXXXXXX")
trap 'rm -rf "$stage"' EXIT
cp "$input" "$stage/diagnostic.json"
cp "$root/tools/validate.typ" "$stage/validate.typ"
typst eval 'query(<validated>).first().value' \
--root "$stage" \
--input diagnostic=diagnostic.json \
--in "$stage/validate.typ" >/dev/null 2>&1 || fail "invalid diagnostic v1: $input"
if [[ -n "$evidence_root" ]]; then
artifact=$(json_string "$(typst eval 'query(<source>).first().value' \
--root "$stage" \
--input diagnostic=diagnostic.json \
--in "$stage/validate.typ" 2>/dev/null)")
expected=$(json_string "$(typst eval 'query(<hash>).first().value' \
--root "$stage" \
--input diagnostic=diagnostic.json \
--in "$stage/validate.typ" 2>/dev/null)")
[[ "$artifact" != /* && "$artifact" != *..* ]] || fail "source artifact escapes evidence root"
evidence_base=$(realpath "$evidence_root")
source=$(realpath "$evidence_root/$artifact")
[[ "$source" == "$evidence_base"/* && -f "$source" ]] || fail "source artifact escapes evidence root"
[[ $(sha256_file "$source") == "$expected" ]] || fail "evidence checksum differs"
cp "$source" "$stage/raw.json"
cp "$root/tools/verify-evidence.typ" "$stage/verify-evidence.typ"
typst eval 'query(<verified>).first().value' \
--root "$stage" \
--input diagnostic=diagnostic.json \
--input raw=raw.json \
--in "$stage/verify-evidence.typ" >/dev/null 2>&1 || fail "observation differs from referenced raw evidence"
fi
echo "Valid diagnostic v1: $input"