This repository has been archived on 2026-09-16. You can view files and clone it, but cannot push or open issues or pull requests.
win-diagnostics-analysis/tools/validate.sh

23 lines
2.2 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
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
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P); 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 query --root "$stage" --input diagnostic=diagnostic.json "$stage/validate.typ" '<validated>' --one >/dev/null 2>&1||fail "invalid diagnostic v1: $input"
if [[ -n "$evidence_root" ]]; then
artifact=$(json_string "$(typst query --root "$stage" --input diagnostic=diagnostic.json "$stage/validate.typ" '<source>' --field value --one 2>/dev/null)")
expected=$(json_string "$(typst query --root "$stage" --input diagnostic=diagnostic.json "$stage/validate.typ" '<hash>' --field value --one 2>/dev/null)")
[[ "$artifact" != /* && "$artifact" != *..* ]]||fail "source artifact escapes evidence root"
source=$(realpath "$evidence_root/$artifact"); evidence_base=$(realpath "$evidence_root")
[[ "$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 query --root "$stage" --input diagnostic=diagnostic.json --input raw=raw.json "$stage/verify-evidence.typ" '<verified>' --one >/dev/null 2>&1||fail "observation differs from referenced raw evidence"
fi
echo "Valid diagnostic v1: $input"