Merge pull request #387 from benmcollins/354-verify-msg-unify

jwt: surface the specific reason on JWS JSON/keyring verify failure
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5fb4b3d..d93febd 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -253,7 +253,13 @@
 	set(oneValueArgs NAME SRC DIR)
 	cmake_parse_arguments(Tool "" "${oneValueArgs}" "" ${ARGN})
 
+	# Hand the accumulated tool list back to the directory scope. list(APPEND)
+	# mutates only this function's own copy of TOOLS, so without the
+	# PARENT_SCOPE set() the `check` and `check-code-coverage` targets below
+	# depended on an empty ${TOOLS} and `make check` ran the CLI test before
+	# the tools were built (issue #367).
 	list(APPEND TOOLS ${Tool_NAME})
+	set(TOOLS ${TOOLS} PARENT_SCOPE)
 	add_executable(${Tool_NAME} ${Tool_SRC})
 	# Tools use only the public libjwt API; they need no crypto backend link.
 	target_link_libraries(${Tool_NAME}
diff --git a/tests/jwt-cli.bats b/tests/jwt-cli.bats
index bc7aee0..db4e2dd 100755
--- a/tests/jwt-cli.bats
+++ b/tests/jwt-cli.bats
@@ -18,6 +18,22 @@
 	return 0
 }
 
+# Issue #367: every key fixture must be found wherever the build directory
+# sits, so key paths resolve through ${SRCDIR} (exported by ctest), never a
+# build-dir-relative path that only works when the build directory is a direct
+# child of the source root. A depth-1 CI build (which always runs "make all"
+# first) would not catch a regression back to the latter, so pin it here: no
+# top-level key variable may be assigned such a path. The grep is anchored to
+# an assignment at column 0, so this test's own indented grep line and the
+# comment lines above it do not match themselves.
+@test "key fixtures resolve through \$SRCDIR, not a build-relative path (#367)" {
+	[ -n "${SRCDIR}" ]
+	[ -d "${SRCDIR}/tests/keys" ]
+	run grep -nE '^[A-Za-z_][A-Za-z_0-9]*=.*\.\./tests/keys' \
+		"${BATS_TEST_DIRNAME}/jwt-cli.bats"
+	[ "${status}" -ne 0 ]
+}
+
 @test "Generate a JWT with alg none" {
 	result="$(./tools/jwt-generate -v -a none -n)"
 	[ "$result" = ${BASIC_RES} ]
@@ -37,7 +53,7 @@
 }
 
 HS256_RES="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.CM4dD95Nj0vSfMGtDas432AUW1HAo7feCiAbt5Yjuds"
-HS256_KEY="../tests/keys/oct_key_256.json"
+HS256_KEY="${SRCDIR}/tests/keys/oct_key_256.json"
 
 @test "Generate a JWT with alg HS256" {
 	result="$(./tools/jwt-generate -v -a HS256 -n -k ${HS256_KEY})"
@@ -76,7 +92,7 @@
 }
 
 # A key without an "alg" needs -a/--algorithm, and both spellings must work.
-NOALG_KEY="../tests/keys/oct_key_256_sig.json"
+NOALG_KEY="${SRCDIR}/tests/keys/oct_key_256_sig.json"
 
 @test "Verify with -a ALG as well as --algorithm=ALG" {
 	token="$(./tools/jwt-generate -q -n -a HS256 -k ${NOALG_KEY})"
@@ -209,9 +225,9 @@
 
 # JWE tools
 
-OCT256="../tests/keys/oct_dir_256.json"
-OCT256B="../tests/keys/oct_key_256_enc.json"
-RSAENC="../tests/keys/rsa_key_2048_enc.json"
+OCT256="${SRCDIR}/tests/keys/oct_dir_256.json"
+OCT256B="${SRCDIR}/tests/keys/oct_key_256_enc.json"
+RSAENC="${SRCDIR}/tests/keys/rsa_key_2048_enc.json"
 
 @test "JWE dir + A256GCM round-trip" {
 	tok="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM -j '{"a":1}')"
@@ -219,6 +235,125 @@
 	[ "${result}" = '{"a":1}' ]
 }
 
+# Issue #375: jwe-decrypt reads the one token correctly. stdin is read whole,
+# never truncated at a NUL byte and never with its lines joined; a Compact
+# token is one line (a second token or a token split over lines is an error),
+# while a JSON token may span lines. Exactly one token argument is accepted.
+# Modeled on the jwt-verify stdin cases above.
+@test "jwe-decrypt stdin rejects a NUL byte and decrypts nothing" {
+	tok="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM -j '{"a":1}')"
+	tok2="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM -j '{"b":2}')"
+	# A token, a NUL byte, then junk used to decrypt the token with exit 0.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM \
+		< <(printf '%s\0junk\n' "${tok}")
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q 'NUL byte'
+	[ "$(echo "${output}" | grep -c '{"a":1}')" -eq 0 ]
+	refute_sanitizer
+	# A NUL byte then a whole second token: the token in front is not used.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM \
+		< <(printf '%s\0%s\n' "${tok}" "${tok2}")
+	[ "${status}" -eq 1 ]
+	[ "$(echo "${output}" | grep -c '{"a":1}')" -eq 0 ]
+	# A NUL byte inside the token, and as the very first byte, both error.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM \
+		< <(printf '%s\0%s\n' "${tok:0:20}" "${tok:20}")
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q 'NUL byte'
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM \
+		< <(printf '\0%s\n' "${tok}")
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q 'NUL byte'
+	refute_sanitizer
+}
+
+@test "jwe-decrypt stdin rejects an over-long token (distinct from NUL)" {
+	# More than MAX_TOKEN_LEN (1 MiB) of input, no NUL: read_stdin_token()
+	# returns -4 and the tool says it is too long, not a NUL-byte error.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM \
+		< <(head -c 1100000 /dev/zero | tr '\000' 'a')
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q 'too long'
+	[ "$(echo "${output}" | grep -c 'NUL byte')" -eq 0 ]
+	refute_sanitizer
+}
+
+@test "jwe-decrypt stdin rejects a second token or a split Compact token" {
+	tok="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM -j '{"a":1}')"
+	tok2="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM -j '{"b":2}')"
+	# Two Compact tokens on two lines used to be joined into one bad token.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM \
+		< <(printf '%s\n%s\n' "${tok}" "${tok2}")
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q 'more than one token'
+	refute_sanitizer
+	# A Compact token split over two lines used to be rejoined and decrypt.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM \
+		< <(printf '%s\n%s\n' "${tok:0:30}" "${tok:30}")
+	[ "${status}" -eq 1 ]
+	[ "$(echo "${output}" | grep -c '{"a":1}')" -eq 0 ]
+	refute_sanitizer
+}
+
+@test "jwe-decrypt stdin decrypts with or without a trailing newline" {
+	tok="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM -j '{"a":1}')"
+	result="$(printf '%s\n' "${tok}" | \
+		./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM)"
+	[ "${result}" = '{"a":1}' ]
+	result="$(printf '%s' "${tok}" | \
+		./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM)"
+	[ "${result}" = '{"a":1}' ]
+	# A trailing CRLF is a line end too and is dropped.
+	result="$(printf '%s\r\n' "${tok}" | \
+		./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM)"
+	[ "${result}" = '{"a":1}' ]
+}
+
+@test "jwe-decrypt stdin accepts a pretty-printed JSON token" {
+	# jq . reformats the JSON serialization across several lines; both the
+	# Flattened and General forms must still decrypt from stdin.
+	ftok="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM \
+		-f json-flat -j '{"j":1}')"
+	gtok="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM \
+		-f json-general -j '{"g":2}')"
+	result="$(jq . <<< "${ftok}" | \
+		./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM)"
+	[ "${result}" = '{"j":1}' ]
+	result="$(jq . <<< "${gtok}" | \
+		./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM)"
+	[ "${result}" = '{"g":2}' ]
+}
+
+@test "jwe-decrypt accepts only one token argument" {
+	tok="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM -j '{"a":1}')"
+	tok2="$(./tools/jwe-encrypt -k ${OCT256} -a dir -e A256GCM -j '{"b":2}')"
+	# A second argument used to be silently ignored, with exit 0.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM "${tok}" "${tok2}"
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q 'Only one token argument'
+	[ "$(echo "${output}" | grep -c '{"a":1}')" -eq 0 ]
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM "${tok}" junk
+	[ "${status}" -eq 1 ]
+	[ "$(echo "${output}" | grep -c '{"a":1}')" -eq 0 ]
+	refute_sanitizer
+	# One argument still decrypts.
+	result="$(./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM "${tok}")"
+	[ "${result}" = '{"a":1}' ]
+}
+
+@test "jwe-decrypt tells empty stdin from a read error" {
+	# Empty stdin and a read error both exit 1, with distinct messages.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM < /dev/null
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q 'No token read from stdin'
+	refute_sanitizer
+	# A directory cannot be read: the errno is reported, not taken for empty.
+	run ./tools/jwe-decrypt -k ${OCT256} -a dir -e A256GCM < .
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q 'Could not read stdin'
+	refute_sanitizer
+}
+
 @test "JWE A256KW + A256CBC-HS512 round-trip" {
 	tok="$(./tools/jwe-encrypt -k ${OCT256} -a A256KW -e A256CBC-HS512 -j '{"b":2}')"
 	result="$(echo "${tok}" | ./tools/jwe-decrypt -k ${OCT256} -a A256KW -e A256CBC-HS512)"
@@ -238,7 +373,7 @@
 }
 
 # The same key as OCT256B, flagged in error when loaded (a malformed "x5c").
-OCT256B_ERR="../tests/keys/oct_key_256_enc_bad_x5c.json"
+OCT256B_ERR="${SRCDIR}/tests/keys/oct_key_256_enc_bad_x5c.json"
 
 @test "JWE tools refuse a key in error" {
 	run ./tools/jwe-encrypt -k ${OCT256B_ERR} -a A256KW -e A256GCM -j '{}'
@@ -256,7 +391,7 @@
 	[ "${status}" -ne 0 ]
 }
 
-ECENC="../tests/keys/ec_key_prime256v1_enc.json"
+ECENC="${SRCDIR}/tests/keys/ec_key_prime256v1_enc.json"
 
 @test "JWE Flattened JSON round-trip (auto-detect on decrypt)" {
 	tok="$(./tools/jwe-encrypt -k ${OCT256B} -a A256KW -e A256GCM \
@@ -510,6 +645,244 @@
 	[ "${have_out}" -eq 1 ]
 }
 
+# --- jwk2key exit status and error reporting (#374) ----------------------
+#
+# jwk2key used to exit 0 even when nothing was written: a bad input file, a key
+# that did not load, a skipped key, a missing/unwritable output directory, an
+# existing output file or a failed write all passed silently. It now exits 1
+# and names each key it could not write, and never passes a NULL PEM to
+# fputs() (which crashes on glibc). Each case works in its own ${BATS_TMPDIR}
+# directory with keys from ${SRCDIR}/tests/keys (#367).
+
+@test "jwk2key exits 1 on a missing input file" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_miss_$$"
+	mkdir -p "${dir}"
+	run ./tools/jwk2key -d "${dir}" "${dir}/nosuch.json"
+	nfiles=$(ls "${dir}" | wc -l)
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q "Error reading"
+	[ "${nfiles}" -eq 0 ]
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 on an input that is not JSON" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_njson_$$"
+	mkdir -p "${dir}"
+	printf 'not json\n' > "${dir}/notjson.json"
+	run ./tools/jwk2key -d "${dir}" "${dir}/notjson.json"
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q "Error reading"
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 when every key is bad and names each one" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_bad_$$"
+	mkdir -p "${dir}"
+	run ./tools/jwk2key -d "${dir}" ${SRCDIR}/tests/keys/bad_keys.json
+	nfiles=$(ls "${dir}" | wc -l)
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	[ "${nfiles}" -eq 0 ]
+	# bad_keys.json holds 14 keys; every one is reported.
+	[ "$(echo "${output}" | grep -c 'key [0-9]')" -eq 14 ]
+	refute_sanitizer
+}
+
+@test "jwk2key writes the good key, reports the bad one, exits 1" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_mix_$$"
+	mkdir -p "${dir}"
+	# One good RSA key and one EC key that cannot load (bogus x/y).
+	jq -c '{keys: [., {kty:"EC",crv:"P-256",x:"AA",y:"AA"}]}' \
+		${SRCDIR}/tests/keys/rsa_key_1024.json > "${dir}/mixed.json"
+	run ./tools/jwk2key -d "${dir}" "${dir}/mixed.json"
+	have_good=0
+	ls "${dir}"/rsa_1024_*.pem >/dev/null 2>&1 && have_good=1
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	[ "${have_good}" -eq 1 ]
+	# The second key (index 1) is the one reported.
+	echo "${output}" | grep -q "key 1"
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 on a key set with no keys" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_empty_$$"
+	mkdir -p "${dir}"
+	echo '{"keys":[]}' > "${dir}/empty.json"
+	run ./tools/jwk2key -d "${dir}" "${dir}/empty.json"
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q "No keys found"
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 on a missing output directory" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_nodir_$$"
+	rm -rf "${dir}"
+	run ./tools/jwk2key -d "${dir}" ${SRCDIR}/tests/keys/rsa_key_1024.json
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q "not an existing writable directory"
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 on an output path that is not a directory" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_notdir_$$"
+	mkdir -p "${dir}"
+	# A regular file is not a writable directory, so -d must reject it.
+	printf '' > "${dir}/afile"
+	run ./tools/jwk2key -d "${dir}/afile" ${SRCDIR}/tests/keys/rsa_key_1024.json
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q "not an existing writable directory"
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 on a read-only output directory" {
+	[ "$(id -u)" -ne 0 ] || skip "root can write to a read-only directory"
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_ro_$$"
+	mkdir -p "${dir}"
+	chmod 555 "${dir}"
+	run ./tools/jwk2key -d "${dir}" ${SRCDIR}/tests/keys/rsa_key_1024.json
+	chmod 755 "${dir}"
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q "not an existing writable directory"
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 when the output file already exists" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_exists_$$"
+	mkdir -p "${dir}"
+	./tools/jwk2key -d "${dir}" ${SRCDIR}/tests/keys/rsa_key_1024.json
+	run ./tools/jwk2key -d "${dir}" ${SRCDIR}/tests/keys/rsa_key_1024.json
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q "cannot create"
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 and writes nothing for an unsafe kid" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_unsafe_$$"
+	mkdir -p "${dir}"
+	printf '{"kty":"oct","kid":"../x","k":"%s"}' \
+		"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" > "${dir}/unsafe.json"
+	run ./tools/jwk2key -d "${dir}" "${dir}/unsafe.json"
+	# Only the input file is left; no key file escaped the directory.
+	nfiles=$(ls "${dir}" | wc -l)
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	echo "${output}" | grep -q "unsafe key id"
+	[ "${nfiles}" -eq 1 ]
+	refute_sanitizer
+}
+
+@test "jwk2key reports only the failed file and still writes the good one" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_isolate_$$"
+	mkdir -p "${dir}"
+	run ./tools/jwk2key -d "${dir}" "${dir}/nosuch.json" \
+		${SRCDIR}/tests/keys/rsa_key_1024.json
+	have_good=0
+	ls "${dir}"/rsa_1024_*.pem >/dev/null 2>&1 && have_good=1
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	[ "${have_good}" -eq 1 ]
+	# The good file's load is not reported with the missing file's error:
+	# exactly one "Error reading" line.
+	[ "$(echo "${output}" | grep -c 'Error reading')" -eq 1 ]
+	refute_sanitizer
+}
+
+@test "jwk2key exits 1 on a failed write and leaves no file behind" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_wfail_$$"
+	mkdir -p "${dir}"
+	# RLIMIT_FSIZE 0 with SIGXFSZ ignored makes the write fail; bats captures
+	# output through a pipe, so only the key file (not the test) is limited.
+	run bash -c "trap '' XFSZ; ulimit -f 0; \
+		./tools/jwk2key -d '${dir}' ${SRCDIR}/tests/keys/rsa_key_1024.json"
+	nfiles=$(ls "${dir}" | wc -l)
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	[ "${nfiles}" -eq 0 ]
+	refute_sanitizer
+}
+
+@test "jwk2key reads a JWK from stdin with -" {
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_stdin_$$"
+	mkdir -p "${dir}"
+	run bash -c "./tools/jwk2key -d '${dir}' - \
+		< ${SRCDIR}/tests/keys/oct_key_384.json"
+	have=0
+	ls "${dir}"/oct_384_*.bin >/dev/null 2>&1 && have=1
+	rm -rf "${dir}"
+	[ "${status}" -eq 0 ]
+	[ "${have}" -eq 1 ]
+	refute_sanitizer
+}
+
+# The existing "Convert JWK to PEM" cases above must still exit 0; add an AKP
+# (ML-DSA) conversion when the default backend can export it, so every key-type
+# branch of jwk2key is exercised.
+@test "jwk2key converts an ML-DSA key and exits 0" {
+	mldsa_supported || skip "ML-DSA not built in"
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_akp_$$"
+	mkdir -p "${dir}"
+	run ./tools/jwk2key -d "${dir}" ${SRCDIR}/tests/keys/mldsa_key_44.json
+	have_out=0
+	ls "${dir}"/mldsa_44_*.pem >/dev/null 2>&1 && have_out=1
+	rm -rf "${dir}"
+	[ "${status}" -eq 0 ]
+	[ "${have_out}" -eq 1 ]
+	refute_sanitizer
+}
+
+# With JWT_CRYPTO=mbedtls the OKP/ML-DSA export paths differ: MbedTLS has no PEM
+# for an Ed25519 key (a NULL that once reached fputs() and crashed on glibc),
+# and it cannot load an ML-DSA key at all. Both must exit 1, not crash, and
+# leave no file. Skipped when MbedTLS is not compiled in (it falls back and
+# prints "No such crypto ops").
+@test "jwk2key under MbedTLS: Ed25519 exits 1 without crashing or a file" {
+	env JWT_CRYPTO=mbedtls ./tools/jwk2key -h >/dev/null 2>/tmp/jwk2key_mb_$$ \
+		|| true
+	if grep -q "No such crypto ops" "/tmp/jwk2key_mb_$$"; then
+		rm -f "/tmp/jwk2key_mb_$$"
+		skip "MbedTLS backend not built in"
+	fi
+	rm -f "/tmp/jwk2key_mb_$$"
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_mbed_$$"
+	mkdir -p "${dir}"
+	run env JWT_CRYPTO=mbedtls ./tools/jwk2key -d "${dir}" \
+		${SRCDIR}/tests/keys/eddsa_key_ed25519.json
+	nfiles=$(ls "${dir}" | wc -l)
+	rm -rf "${dir}"
+	# Exit 1 (not 0 as on macOS, not a SIGSEGV 139 as on glibc), no file.
+	[ "${status}" -eq 1 ]
+	[ "${nfiles}" -eq 0 ]
+	echo "${output}" | grep -q "no PEM available"
+	refute_sanitizer
+}
+
+@test "jwk2key under MbedTLS: an ML-DSA key exits 1 with its error" {
+	env JWT_CRYPTO=mbedtls ./tools/jwk2key -h >/dev/null 2>/tmp/jwk2key_mb2_$$ \
+		|| true
+	if grep -q "No such crypto ops" "/tmp/jwk2key_mb2_$$"; then
+		rm -f "/tmp/jwk2key_mb2_$$"
+		skip "MbedTLS backend not built in"
+	fi
+	rm -f "/tmp/jwk2key_mb2_$$"
+	dir="${BATS_TMPDIR:-/tmp}/jwk2key_mbed2_$$"
+	mkdir -p "${dir}"
+	run env JWT_CRYPTO=mbedtls ./tools/jwk2key -d "${dir}" \
+		${SRCDIR}/tests/keys/mldsa_key_44.json
+	nfiles=$(ls "${dir}" | wc -l)
+	rm -rf "${dir}"
+	[ "${status}" -eq 1 ]
+	[ "${nfiles}" -eq 0 ]
+	echo "${output}" | grep -q "key 0"
+	refute_sanitizer
+}
+
 # --- ML-DSA (FIPS 204 / RFC 9964) ----------------------------------------
 #
 # These only run when the library was built with WITH_ML_DSA against a capable
@@ -551,9 +924,9 @@
 }
 
 # JWS JSON Serialization (multi-signature, RFC 7515 7.2) — issue #308
-EC_KEY="../tests/keys/ec_key_prime256v1.json"
-RS_KEY="../tests/keys/rsa_key_2048.json"
-JWS_RING="../tests/keys/jwks_jws_pair.json"
+EC_KEY="${SRCDIR}/tests/keys/ec_key_prime256v1.json"
+RS_KEY="${SRCDIR}/tests/keys/rsa_key_2048.json"
+JWS_RING="${SRCDIR}/tests/keys/jwks_jws_pair.json"
 
 @test "Generate a Flattened JWS and verify it" {
 	token="$(./tools/jwt-generate -q -n -F flat -k ${EC_KEY})"
@@ -628,7 +1001,7 @@
 # GHSA-mhc9-xvg5-qg29: --keyring verifies a Compact token as a one-signature
 # JWS (kid binding or a scan of the compatible keys), never as a keyless
 # checker that accepts an unsigned token.
-KEYRING="../tests/keys/jwks_keyring.json"
+KEYRING="${SRCDIR}/tests/keys/jwks_keyring.json"
 # {"alg":"none"} . {"sub":"admin","iss":"trusted","aud":"api"} . (unsigned)
 NONE_TOK="eyJhbGciOiJub25lIn0.eyJzdWIiOiJhZG1pbiIsImlzcyI6InRydXN0ZWQiLCJhdWQiOiJhcGkifQ."
 
@@ -794,15 +1167,26 @@
 	[ "$(echo "${output}" | grep -c 'Verified')" -eq 1 ]
 }
 
-# GHSA-g7xw-4cjw-2247: -h/-l print and exit 0 only as the sole argument. In a
-# token position (getopt permutes argv) they once exited 0 while the tokens
-# went unverified. Given with anything else they are now a usage error.
+# GHSA-g7xw-4cjw-2247: -h/-l print and exit 0 only as the sole argument and the
+# only option in it. In a token position (getopt permutes argv) they once exited
+# 0 while the tokens went unverified; clustered with another option into the one
+# argument (getopt reads -hv as -h -v) they likewise exited 0. Given with
+# anything else -- a token, a key, or another option, whether separate (-h -v)
+# or clustered (-hv) -- they are a usage error.
 @test "-h or -l alone exits 0, but with other arguments it is an error" {
 	run ./tools/jwt-verify -h
 	[ "${status}" -eq 0 ]
 	run ./tools/jwt-verify -l
 	[ "${status}" -eq 0 ]
 	echo "${output}" | grep -q 'Algorithms supported'
+	# The long forms, and a unique prefix, are also fine as the sole option.
+	run ./tools/jwt-verify --help
+	[ "${status}" -eq 0 ]
+	run ./tools/jwt-verify --list
+	[ "${status}" -eq 0 ]
+	echo "${output}" | grep -q 'Algorithms supported'
+	run ./tools/jwt-verify --he
+	[ "${status}" -eq 0 ]
 	# As the token argument, next to a key.
 	run ./tools/jwt-verify -q -k ${HS256_KEY} -h
 	[ "${status}" -eq 1 ]
@@ -816,6 +1200,14 @@
 	# A forged token spelled as an option (-l<forged>) is not a listing.
 	run ./tools/jwt-verify -q -k ${HS256_KEY} "-l${FORGED_TOK}"
 	[ "${status}" -eq 1 ]
+	# Clustered into the one argument: -h/-l must be the only option in it, so
+	# these are the same usage error as -h -v (exit 1), not a help/list at
+	# exit 0. -hk<file> and -hr<file> never open the file.
+	for opt in -hv -vh -lq -ql "-hk${HS256_KEY}" -laHS256 -hl; do
+		run ./tools/jwt-verify "${opt}"
+		[ "${status}" -eq 1 ]
+		echo "${output}" | grep -q 'take no other arguments'
+	done
 }
 
 # GHSA-g7xw-4cjw-2247: a key set with no keys (as after a rotation) must exit 1,
@@ -835,24 +1227,63 @@
 
 # The --print command is a validator: a token passes only if the command runs
 # to its end and exits 0. One that a signal ends has no exit status, which
-# read as 0. Each command reads its input first, so that the tool never
-# writes to a pipe nobody reads.
+# read as 0. Since issue #371 the command need not read its input first: the
+# tool ignores SIGPIPE while writing, so a command that stops reading is not
+# killed off, and its exit status alone decides.
 @test "A --print command that fails or is killed fails the token" {
-	run ./tools/jwt-verify -v -p 'cat > /dev/null' -k ${HS256_KEY} \
-		${HS256_RES}
+	run ./tools/jwt-verify -v -p true -k ${HS256_KEY} ${HS256_RES}
 	[ "${status}" -eq 0 ]
-	run ./tools/jwt-verify -v -p 'cat > /dev/null; exit 3' \
-		-k ${HS256_KEY} ${HS256_RES}
+	run ./tools/jwt-verify -v -p 'exit 3' -k ${HS256_KEY} ${HS256_RES}
 	[ "${status}" -eq 1 ]
-	run ./tools/jwt-verify -v -p 'cat > /dev/null; kill -9 $$' \
-		-k ${HS256_KEY} ${HS256_RES}
+	run ./tools/jwt-verify -v -p 'kill -9 $$' -k ${HS256_KEY} ${HS256_RES}
 	[ "${status}" -eq 1 ]
 	[ "$(echo "${output}" | grep -c 'Verified')" -eq 0 ]
-	run ./tools/jwt-generate -v -p 'cat > /dev/null; kill -9 $$' \
-		-a HS256 -k ${HS256_KEY}
+	run ./tools/jwt-generate -v -p 'kill -9 $$' -a HS256 -k ${HS256_KEY}
 	[ "${status}" -ne 0 ]
 }
 
+# Issue #371: the JSON is written to the --print command through a pipe, once
+# for the header and once for the payload. A payload larger than the pipe
+# buffer blocks in write() until the command reads it, and a command that
+# stops reading first (true, false, head -c) once killed the tool with SIGPIPE
+# (exit 141) in mid-run: the tokens after the big one were never processed and
+# buffered output was lost. The tool now ignores SIGPIPE while writing, so a
+# stopped reader no longer ends it and the command's exit status decides at any
+# size, exactly as for a token that fits the buffer. The 70000-byte claim makes
+# the payload exceed the 64 KiB pipe buffer; a good token sits before and after
+# the big one to prove the run is not cut short.
+BIG_CLAIM="s:pad=$(printf '%070000d' 0)"
+
+@test "A --print command surviving a payload larger than the pipe buffer (#371)" {
+	big="$(./tools/jwt-generate -q -n -k ${HS256_KEY} -c "${BIG_CLAIM}")"
+	[ "$(printf '%s' "${big}" | wc -c)" -gt 65536 ]
+	# -p true reads nothing and exits 0: all three tokens pass, none lost.
+	run ./tools/jwt-verify -v -p true -k ${HS256_KEY} \
+		${HS256_RES} "${big}" ${HS256_RES}
+	[ "${status}" -eq 0 ]
+	[ "$(echo "${output}" | grep -c 'Verified')" -eq 3 ]
+	# -p false reads nothing and exits 1: every token fails, with a [BAD].
+	run ./tools/jwt-verify -v -p false -k ${HS256_KEY} \
+		${HS256_RES} "${big}" ${HS256_RES}
+	[ "${status}" -eq 1 ]
+	[ "$(echo "${output}" | grep -c '\[BAD\]')" -eq 3 ]
+	# The same through stdin, one token per line.
+	run bash -c "printf '%s\n' ${HS256_RES} '${big}' ${HS256_RES} | \
+		./tools/jwt-verify -v -p true -k ${HS256_KEY} -"
+	[ "${status}" -eq 0 ]
+	[ "$(echo "${output}" | grep -c 'Verified')" -eq 3 ]
+	run bash -c "printf '%s\n' ${HS256_RES} '${big}' ${HS256_RES} | \
+		./tools/jwt-verify -v -p false -k ${HS256_KEY} -"
+	[ "${status}" -eq 1 ]
+	[ "$(echo "${output}" | grep -c '\[BAD\]')" -eq 3 ]
+	# jwt-generate shares write_json(): -p true passes, -p false fails.
+	run ./tools/jwt-generate -v -p true -n -k ${HS256_KEY} -c "${BIG_CLAIM}"
+	[ "${status}" -eq 0 ]
+	run ./tools/jwt-generate -v -p false -n -k ${HS256_KEY} -c "${BIG_CLAIM}"
+	[ "${status}" -eq 1 ]
+	refute_sanitizer
+}
+
 # GHSA-g7xw-4cjw-2247: --print runs its validator only with --verbose. Without
 # -v the validator was silently skipped and the token passed on its signature
 # alone; it is now a usage error.
diff --git a/tools/jwe-decrypt.1 b/tools/jwe-decrypt.1
index 08fdedb..2c8397c 100644
--- a/tools/jwe-decrypt.1
+++ b/tools/jwe-decrypt.1
@@ -1,4 +1,4 @@
-.\" Automatically generated by Pandoc 3.9.0.2
+.\" Automatically generated by Pandoc 3.10
 .\"
 .TH "JWE\-DECRYPT" "1" "" "jwe\-decrypt User Manual" "LibJWT C Library"
 .SH NAME
@@ -25,8 +25,14 @@
 algorithm matches \f[B]\-a\f[R] and whose key is \f[B]\-k\f[R] is
 selected.
 .PP
-The token may be given as the final argument or, if omitted, read from
-standard input.
+The token is given as the single argument or, with no argument, read as
+the whole of standard input.
+When it is read from standard input, one trailing newline is removed,
+and a NUL byte anywhere in the input is an error, as are empty input and
+a read error.
+A Compact token must be on one line: a second token, or a token split
+across lines, is an error rather than being joined.
+A JSON token may span lines.
 On success the decrypted plaintext is written to standard output.
 On any failure the program prints an error and exits non\-zero.
 .SH OPTIONS
diff --git a/tools/jwe-decrypt.1.md b/tools/jwe-decrypt.1.md
index 757887d..7e66b92 100644
--- a/tools/jwe-decrypt.1.md
+++ b/tools/jwe-decrypt.1.md
@@ -23,9 +23,14 @@
 algorithm. For a General JSON token with several recipients, the recipient
 whose algorithm matches **-a** and whose key is **-k** is selected.
 
-The token may be given as the final argument or, if omitted, read from
-standard input. On success the decrypted plaintext is written to standard
-output. On any failure the program prints an error and exits non-zero.
+The token is given as the single argument or, with no argument, read as the
+whole of standard input. When it is read from standard input, one trailing
+newline is removed, and a NUL byte anywhere in the input is an error, as are
+empty input and a read error. A Compact token must be on one line: a second
+token, or a token split across lines, is an error rather than being joined.
+A JSON token may span lines. On success the decrypted plaintext is written
+to standard output. On any failure the program prints an error and exits
+non-zero.
 
 # OPTIONS
 
diff --git a/tools/jwe-decrypt.c b/tools/jwe-decrypt.c
index b314aac..b9e53b7 100644
--- a/tools/jwe-decrypt.c
+++ b/tools/jwe-decrypt.c
@@ -10,6 +10,7 @@
 #include <jwt.h>
 #include <getopt.h>
 #include <string.h>
+#include <errno.h>
 
 #include "jwt-util.h"
 
@@ -30,21 +31,80 @@
 \n\
 The serialization (Compact or JSON, Flattened or General) is detected\n\
 automatically. For a General JSON token the recipient matching the given\n\
-key and --algorithm is selected. The token may be given as the final\n\
-argument or, if omitted, read from stdin. The configured --algorithm and\n\
---enc act as an allow-list: a token whose header does not match is\n\
-rejected. On success the decrypted plaintext is written to stdout.\n",
+key and --algorithm is selected. The configured --algorithm and --enc act\n\
+as an allow-list: a token whose header does not match is rejected. On\n\
+success the decrypted plaintext is written to stdout.\n\
+\n\
+The token is the one argument or, with no argument, the whole of stdin.\n\
+From stdin a trailing newline is dropped; a NUL byte anywhere, or (for a\n\
+Compact token) a second token or a token split over lines, is an error. A\n\
+JSON token may span lines. Empty stdin, or a read error, is an error.\n",
 		get_progname());
 
 	exit(exit_state);
 }
 
+/* The buffer for the one token read from stdin, so the token can be up to one
+ * byte shorter. Generous for a CLI; a longer token is rejected whole. */
+#define MAX_TOKEN_LEN (1024 * 1024)
+
+/* Read the whole of stdin as the single token into @buf (NUL-terminated).
+ * One trailing line end (LF, CRLF or a lone CR) is dropped. The serialization
+ * is detected as the library does it, from the first non-space byte: a
+ * Compact token is one line, so a CR or LF left in it -- a second token, or a
+ * token split over lines -- is an error rather than being joined; a JSON
+ * token ('{') may span lines and is left as read, so the parser rejects
+ * anything after it. A NUL byte anywhere, a token too long for @buf, or a
+ * read error rejects the whole input and nothing is decrypted. Returns 1 for
+ * a token, 0 for empty stdin, -1 for a NUL byte, -4 for an over-long token,
+ * -2 for a read error, and -3 for a CR or LF inside a Compact token. */
+static int read_stdin_token(char *buf, size_t size)
+{
+	size_t len = 0;
+	int c, nul = 0, toolong = 0;
+	const char *p;
+
+	while ((c = fgetc(stdin)) != EOF) {
+		if (c == '\0')
+			nul = 1;
+		else if (len + 1 >= size)
+			toolong = 1;
+		else
+			buf[len++] = (char)c;
+	}
+
+	if (ferror(stdin))
+		return -2;
+	if (nul)			/* a NUL takes priority over over-length */
+		return -1;
+	if (toolong)
+		return -4;
+
+	/* Drop one trailing line end, so a token with or without one both
+	 * decrypt; anything else left in a Compact token is caught below. */
+	if (len && buf[len - 1] == '\n')
+		len--;
+	if (len && buf[len - 1] == '\r')
+		len--;
+	buf[len] = '\0';
+
+	if (len == 0)
+		return 0;
+
+	for (p = buf; *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'; p++)
+		;
+	if (*p != '{' && strcspn(buf, "\r\n") != len)
+		return -3;
+
+	return 1;
+}
+
 int main(int argc, char *argv[])
 {
 	jwe_checker_auto_t *checker = NULL;
 	jwk_set_auto_t *jwk_set = NULL;
 	const jwk_item_t *item = NULL;
-	char *key_file = NULL, *token = NULL, *tokbuf = NULL;
+	char *key_file = NULL, *token = NULL;
 	jwe_key_alg_t alg = JWE_ALG_NONE;
 	jwe_enc_t enc = JWE_ENC_NONE;
 	unsigned char *pt = NULL;
@@ -89,29 +149,38 @@
 	if (enc == JWE_ENC_NONE)
 		usage("A content encryption algorithm is required (-e)", EXIT_FAILURE);
 
-	/* Token from argv or stdin. */
+	/* The token is the one argument, or the whole of stdin. More than one
+	 * argument used to decrypt the first and silently ignore the rest. */
 	if (optind < argc) {
+		if (argc - optind > 1)
+			usage("Only one token argument is allowed", EXIT_FAILURE);
 		token = argv[optind];
 	} else {
-		size_t cap = 4096, len = 0;
-		int c;
+		static char tokbuf[MAX_TOKEN_LEN];
 
-		tokbuf = malloc(cap);
-		if (tokbuf == NULL)
-			exit(EXIT_FAILURE);
-		while ((c = fgetc(stdin)) != EOF) {
-			if (c == '\n' || c == '\r')
-				continue;
-			if (len + 1 >= cap) {
-				cap *= 2;
-				tokbuf = realloc(tokbuf, cap);
-				if (tokbuf == NULL)
-					exit(EXIT_FAILURE);
-			}
-			tokbuf[len++] = (char)c;
+		switch (read_stdin_token(tokbuf, sizeof(tokbuf))) {
+		case 1:
+			token = tokbuf;
+			break;
+		case 0:
+			fprintf(stderr, "ERROR: No token read from stdin\n");
+			return EXIT_FAILURE;
+		case -2:
+			fprintf(stderr, "ERROR: Could not read stdin: %s\n",
+				strerror(errno));
+			return EXIT_FAILURE;
+		case -3:
+			fprintf(stderr, "ERROR: stdin has more than one token "
+				"(a second token, or a token split over "
+				"lines)\n");
+			return EXIT_FAILURE;
+		case -4:
+			fprintf(stderr, "ERROR: Token is too long\n");
+			return EXIT_FAILURE;
+		default: /* -1 */
+			fprintf(stderr, "ERROR: Token has a NUL byte\n");
+			return EXIT_FAILURE;
 		}
-		tokbuf[len] = '\0';
-		token = tokbuf;
 	}
 
 	jwk_set = jwks_create_fromfile(key_file);
@@ -157,6 +226,5 @@
 	 * borrows item from jwk_set, so free it before the set it borrows. */
 	jwe_checker_freep(&checker);
 	free(pt);
-	free(tokbuf);
 	return ret;
 }
diff --git a/tools/jwk2key.1 b/tools/jwk2key.1
index 959511c..d44c362 100644
--- a/tools/jwk2key.1
+++ b/tools/jwk2key.1
@@ -58,6 +58,22 @@
 .TP
 \f[B]\-d\f[R] \f[I]DIR\f[R], \f[B]\-\-dir\f[R]=\f[I]DIR\f[R]
 Directory to write key files to (default is `\f[B].\f[R]').
+.SH EXIT STATUS
+.TP
+\f[B]0\f[R]
+Every key in every input file was written.
+.TP
+\f[B]1\f[R]
+An input file could not be read or parsed, or held no keys; or a key was
+skipped, did not load, or its file could not be created or fully
+written.
+The keys that do convert are still written.
+.PP
+Each key that is not written is reported on \f[B]stderr\f[R], naming the
+input file and the key (by index, and by \f[B]kid\f[R] when it has one)
+and the reason.
+The output \f[B]\-d\f[R] directory must already exist, be a directory,
+and be writable; this is checked before any input is read.
 .SH BUGS
 See GitHub Issues: \c
 .UR https://github.com/benmcollins/libjwt/issues
diff --git a/tools/jwk2key.1.md b/tools/jwk2key.1.md
index 5272263..b0ce2f6 100644
--- a/tools/jwk2key.1.md
+++ b/tools/jwk2key.1.md
@@ -51,6 +51,21 @@
 **\-d** _DIR_, **\-\-dir**=_DIR_
   ~ Directory to write key files to (default is '**.**').
 
+# EXIT STATUS
+
+**0**
+  ~ Every key in every input file was written.
+
+**1**
+  ~ An input file could not be read or parsed, or held no keys; or a key was
+  skipped, did not load, or its file could not be created or fully written.
+  The keys that do convert are still written.
+
+Each key that is not written is reported on **stderr**, naming the input file
+and the key (by index, and by **kid** when it has one) and the reason. The
+output **\-d** directory must already exist, be a directory, and be writable;
+this is checked before any input is read.
+
 # BUGS
 
 See GitHub Issues: <https://github.com/benmcollins/libjwt/issues>
diff --git a/tools/jwk2key.c b/tools/jwk2key.c
index 0c7a610..31334bf 100644
--- a/tools/jwk2key.c
+++ b/tools/jwk2key.c
@@ -33,18 +33,43 @@
 	return 1;
 }
 
-static void write_key_file(const jwk_item_t *item)
+/* A human-readable tag for one key in a file: the input file and the key's
+ * position in it, plus its "kid" when it has one, so every per-key message
+ * names which key it is about. */
+static void key_label(char *buf, size_t len, const char *file, int idx,
+		      const jwk_item_t *item)
 {
-	const char *pre, *name;
+	const char *kid = jwks_item_kid(item);
+
+	if (kid != NULL)
+		snprintf(buf, len, "%s: key %d (kid \"%s\")", file, idx, kid);
+	else
+		snprintf(buf, len, "%s: key %d", file, idx);
+}
+
+/* Write one key to its own file. Returns 0 on success, 1 if the key was not
+ * written (it did not load, was skipped, or its file could not be created or
+ * fully written) with a message naming the file and the key. */
+static int write_key_file(const jwk_item_t *item, const char *file, int idx)
+{
+	const char *pre, *name, *pem, *reason = "write failed";
 	int priv = jwks_item_is_private(item);
 	char file_name[BUFSIZ];
+	char label[BUFSIZ];
 	char *ext = ".pem";
 	char bits[8];
+	int werr = 0;
 	FILE *fp;
 	int i;
 
-	if (jwks_item_error(item))
-		return;
+	key_label(label, sizeof(label), file, idx, item);
+
+	/* A key the backend could not load (e.g. an ML-DSA key under a backend
+	 * without ML-DSA, or a malformed key) carries its own reason. */
+	if (jwks_item_error(item)) {
+		fprintf(stderr, "%s: %s\n", label, jwks_item_error_msg(item));
+		return 1;
+	}
 
 	switch (jwks_item_kty(item)) {
 	case JWK_KEY_TYPE_OCT:
@@ -93,14 +118,20 @@
 		break;
 #endif
 	default:
-		fprintf(stderr, "Unknown kty\n");
-		return;
+		// LCOV_EXCL_START - a key that loaded (no item error, checked
+		// above) always has a kty this switch handles.
+		fprintf(stderr, "%s: unsupported key type\n", label);
+		return 1;
+		// LCOV_EXCL_STOP
 	}
 
 	if (!is_safe_filename_part(name)) {
-		fprintf(stderr, "Skipping key with unsafe name: %s\n",
+		// LCOV_EXCL_START - name is the key type, curve or bit length,
+		// which never carries a path separator or "..".
+		fprintf(stderr, "%s: unsafe key name \"%s\"\n", label,
 			name ? name : "(null)");
-		return;
+		return 1;
+		// LCOV_EXCL_STOP
 	}
 
 	{
@@ -118,9 +149,10 @@
 		}
 
 		if (id != NULL && !is_safe_filename_part(id)) {
-			fprintf(stderr, "Skipping key with unsafe id: %s\n", id);
+			fprintf(stderr, "%s: unsafe key id, refusing to write\n",
+				label);
 			free(tp);
-			return;
+			return 1;
 		}
 
 		if (id == NULL)
@@ -153,34 +185,62 @@
 	}
 
 	if (fp == NULL) {
-		perror(file_name);
-		return;
+		fprintf(stderr, "%s: cannot create %s: %s\n", label, file_name,
+			strerror(errno));
+		return 1;
 	}
 
 	if (jwks_item_kty(item) == JWK_KEY_TYPE_OCT) {
 		const unsigned char *buf;
 		size_t len;
 
-		jwks_item_key_oct(item, &buf, &len);
-		fwrite(buf, 1, len, fp);
+		if (jwks_item_key_oct(item, &buf, &len) == 0) {
+			fwrite(buf, 1, len, fp);
+		} else {
+			// LCOV_EXCL_START - a loaded oct key always has octets.
+			reason = "no key material";
+			werr = 1;
+			// LCOV_EXCL_STOP
+		}
 	} else {
-		fputs(jwks_item_pem(item), fp);
+		/* PEM is a backend-dependent convenience and can be absent
+		 * (e.g. MbedTLS has no PEM for an OKP/Ed25519 key): never pass
+		 * a NULL to fputs(), which crashes on glibc. */
+		pem = jwks_item_pem(item);
+		if (pem == NULL) {
+			reason = "no PEM available for this key "
+				 "(the active backend cannot export it)";
+			werr = 1;
+		} else {
+			fputs(pem, fp);
+		}
 	}
 
-	fclose(fp);
+	/* A buffered write (small keys) is only flushed at fclose(), so a
+	 * write error (a full disk, or an RLIMIT_FSIZE hit with SIGXFSZ
+	 * ignored) can surface at the write itself (ferror) or at fclose().
+	 * Both are always evaluated so neither becomes an untested branch. */
+	werr |= (ferror(fp) != 0);
+	werr |= (fclose(fp) != 0);
+
+	if (werr) {
+		fprintf(stderr, "%s: %s\n", label, reason);
+		unlink(file_name);
+		return 1;
+	}
+
+	return 0;
 }
 
 static int check_directory(const char *path)
 {
 	struct stat info;
 
-	if (stat(path, &info) != 0)
-		return 0;
-
-	if (!(info.st_mode & S_IFDIR))
-		return 0;
-
-	if (access(path, R_OK | X_OK) != 0)
+	/* It must exist, be a directory (S_ISDIR(), not merely have the
+	 * S_IFDIR bit, which a socket's mode also ANDs to), and be readable,
+	 * writable and searchable so that key files can be created in it. */
+	if (stat(path, &info) != 0 || !S_ISDIR(info.st_mode) ||
+	    access(path, R_OK | W_OK | X_OK) != 0)
 		return 0;
 
 	return 1;
@@ -217,16 +277,19 @@
 \n\
 By default, existing files will not be overwritten. If you use the --retry\n\
 option, an attempt will be made to add -X to the file name, up to -9, in\n\
-an attempt to create the file.\n", get_progname());
+an attempt to create the file.\n\
+\n\
+Exit status is 0 only when every key was written. It is 1 if any input file\n\
+could not be read or parsed or held no keys, or if any key was skipped, did\n\
+not load, or could not be created or fully written. The keys that do convert\n\
+are written whatever the status.\n", get_progname());
 
         exit(exit_state);
 }
 
 int main(int argc, char **argv)
 {
-	jwk_set_auto_t *jwk_set = NULL;
-	const jwk_item_t *item;
-	int i, oc;
+	int i, oc, ret = EXIT_SUCCESS;
 
 	char *optstr = "hd:r";
         struct option opttbl[] = {
@@ -264,35 +327,59 @@
 	if (out_dir == NULL || out_dir[0] == '\0')
 		out_dir = ".";
 
+	/* The output directory has to be usable before anything is read. */
 	if (!check_directory(out_dir)) {
-		fprintf(stderr, "%s: doesn't exist or no access\n",
+		fprintf(stderr, "%s: not an existing writable directory\n",
 			out_dir);
+		return EXIT_FAILURE;
 	}
 
-	jwk_set = jwks_create(NULL);
-	if (jwk_set == NULL) {
-		perror("Failed to create JWKS");
-		exit(EXIT_FAILURE);
-	}
-
+	/* Load each file into its own set, so a file that fails to load never
+	 * taints the next one's error, and every key can be named with the
+	 * file it came from. */
 	for (i = 0; i < argc; i++) {
+		jwk_set_auto_t *jwk_set = NULL;
+		const jwk_item_t *item;
 		char *file = argv[i];
+		int j;
 
-		if (file[0] == '-' && file[1] == '\0')
-			jwks_load_fromfp(jwk_set, stdin);
-		else
-			jwks_load_fromfile(jwk_set, file);
+		if (file[0] == '-' && file[1] == '\0') {
+			file = "(stdin)";
+			jwk_set = jwks_load_fromfp(NULL, stdin);
+		} else {
+			jwk_set = jwks_load_fromfile(NULL, file);
+		}
+
+		if (jwk_set == NULL) {
+			// LCOV_EXCL_START - only on an allocation failure.
+			fprintf(stderr, "Error reading %s: out of memory\n",
+				file);
+			ret = EXIT_FAILURE;
+			continue;
+			// LCOV_EXCL_STOP
+		}
 
 		if (jwks_error(jwk_set)) {
 			fprintf(stderr, "Error reading %s: %s\n", file,
 				jwks_error_msg(jwk_set));
+			ret = EXIT_FAILURE;
+			continue;
 		}
+
+		if (jwks_item_count(jwk_set) == 0) {
+			fprintf(stderr, "%s: No keys found\n", file);
+			ret = EXIT_FAILURE;
+			continue;
+		}
+
+		for (j = 0; (item = jwks_item_get(jwk_set, j)); j++) {
+			if (write_key_file(item, file, j))
+				ret = EXIT_FAILURE;
+		}
+
+		/* jwk_set is freed by its jwk_set_auto_t cleanup at the end of
+		 * each iteration (so exit() is avoided; see #364). */
 	}
 
-	for (i = 0; (item = jwks_item_get(jwk_set, i)); i++)
-		write_key_file(item);
-
-	/* Return rather than exit() so the jwk_set_auto_t cleanup frees the
-	 * set (exit() skips __attribute__((cleanup)) handlers). */
-	return EXIT_SUCCESS;
+	return ret;
 }
diff --git a/tools/jwt-generate.1 b/tools/jwt-generate.1
index db09ebc..55dbd9e 100644
--- a/tools/jwt-generate.1
+++ b/tools/jwt-generate.1
@@ -41,6 +41,11 @@
 \f[I]PAYLOAD\f[R] contents.
 A non\-0 exit status from the program will cause generating the token to
 fail, and so will the program being ended by a signal.
+.PP
+The command need not read all of its input: if it stops reading,
+\f[B]jwt\-generate\f[R] is not ended (no matter how large the JSON is),
+and the program\(cqs exit status, or a signal that ends it, still
+decides whether the token passes.
 .SS Options
 .TP
 \f[B]\-h\f[R], \f[B]\-\-help\f[R]
diff --git a/tools/jwt-generate.1.md b/tools/jwt-generate.1.md
index f5cf772..8cb6c94 100644
--- a/tools/jwt-generate.1.md
+++ b/tools/jwt-generate.1.md
@@ -37,6 +37,10 @@
 exit status from the program will cause generating the token to fail, and so
 will the program being ended by a signal.
 
+The command need not read all of its input: if it stops reading, **jwt-generate**
+is not ended (no matter how large the JSON is), and the program's exit status,
+or a signal that ends it, still decides whether the token passes.
+
 ## Options
 
 **\-h**, **\-\-help**
diff --git a/tools/jwt-util.h b/tools/jwt-util.h
index 1c4ef40..728303c 100644
--- a/tools/jwt-util.h
+++ b/tools/jwt-util.h
@@ -6,6 +6,8 @@
    file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <stdio.h>
+#include <string.h>
+#include <errno.h>
 #include <unistd.h>
 
 static char *pipe_cmd;
@@ -16,6 +18,7 @@
 #include <windows.h>
 #else
 #include <sys/wait.h>
+#include <signal.h>
 #endif
 
 /* The length of the well-formed UTF-8 sequence (RFC 3629) that starts the
@@ -139,7 +142,11 @@
 	}
 
 	if (pipe_fp) {
-		if (fwrite(str, 1, strlen(str), pipe_fp) < strlen(str)) {
+		/* A reader that stops reading (a short write with EPIPE) does
+		 * not by itself fail the token, matching the POSIX path: the
+		 * command's exit status decides. Any other write error does. */
+		if (fwrite(str, 1, strlen(str), pipe_fp) < strlen(str) &&
+		    errno != EPIPE) {
 			perror("fwrite");
 			exit_code = EXIT_FAILURE;
 		}
@@ -160,13 +167,20 @@
 
 		if (pipe(pipe_fd)) {
 			perror(pipe_cmd);
-			exit(EXIT_FAILURE);
+			return EXIT_FAILURE;	// LCOV_EXCL_LINE
 		}
 
 		argv[2] = pipe_cmd;
 		pid = fork();
 
-		if (pid == 0) {
+		if (pid == -1) {
+			/* No child was made: close both ends and fail this
+			 * token rather than write to a pipe no one reads. */
+			perror(pipe_cmd);		// LCOV_EXCL_LINE
+			close(pipe_fd[0]);		// LCOV_EXCL_LINE
+			close(pipe_fd[1]);		// LCOV_EXCL_LINE
+			return EXIT_FAILURE;		// LCOV_EXCL_LINE
+		} else if (pid == 0) {
 			close(pipe_fd[1]);
 
 			if (json_fp == stderr)
@@ -184,10 +198,43 @@
 	}
 
 	if (myfd) {
-		if (write(myfd, str, strlen(str)) < 0) {
-			perror(pipe_cmd);
-			exit(EXIT_FAILURE);
+		struct sigaction act, old;
+		size_t len = strlen(str), off = 0;
+
+		/* Ignore SIGPIPE only while writing, and only here in the
+		 * parent (set after fork() so the command does not inherit a
+		 * SIG_IGN that would outlive its execvp()). A command that
+		 * stops reading then gives write() EPIPE instead of killing
+		 * the tool, and its exit status still decides the token, as it
+		 * already does for a payload that fits the pipe buffer. */
+		memset(&act, 0, sizeof(act));
+		act.sa_handler = SIG_IGN;
+		sigemptyset(&act.sa_mask);
+		sigaction(SIGPIPE, &act, &old);
+
+		while (off < len) {
+			ssize_t n = write(myfd, str + off, len - off);
+
+			if (n < 0) {
+				if (errno == EINTR)
+					continue;	// LCOV_EXCL_LINE
+				/* The reader going away (EPIPE) is not an error:
+				 * the command's exit status decides. Any other
+				 * write error fails the token, but cannot be
+				 * produced reliably from a test. */
+				// LCOV_EXCL_START
+				if (errno != EPIPE) {
+					perror(pipe_cmd);
+					exit_code = EXIT_FAILURE;
+				}
+				// LCOV_EXCL_STOP
+				break;
+			}
+
+			off += (size_t)n;
 		}
+
+		sigaction(SIGPIPE, &old, NULL);
 	}
 #endif
 	else {
@@ -204,10 +251,12 @@
 		close(myfd);
 		/* Only a command that ran to its end and exited 0 passes. One
 		 * that a signal ended (a crash, say) has no exit status, and
-		 * WEXITSTATUS() reads 0 for it. */
+		 * WEXITSTATUS() reads 0 for it. A write error above has already
+		 * failed the token, so a command that still exits 0 does not
+		 * clear that failure. */
 		if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status))
 			exit_code = EXIT_FAILURE;
-		else
+		else if (WEXITSTATUS(status))
 			exit_code = WEXITSTATUS(status);
 	}
 #endif
diff --git a/tools/jwt-verify.1 b/tools/jwt-verify.1
index b6eb0e9..45fd9b6 100644
--- a/tools/jwt-verify.1
+++ b/tools/jwt-verify.1
@@ -54,6 +54,11 @@
 \f[I]PAYLOAD\f[R] contents.
 A non\-0 exit status from the program will cause verification to fail,
 and so will the program being ended by a signal.
+.PP
+The command need not read all of its input: if it stops reading,
+\f[B]jwt\-verify\f[R] is not ended (no matter how large the JSON is),
+and the program\(cqs exit status, or a signal that ends it, still
+decides whether the token passes.
 .SS Options
 .TP
 \f[B]\-h\f[R], \f[B]\-\-help\f[R]
diff --git a/tools/jwt-verify.1.md b/tools/jwt-verify.1.md
index 169c6f9..703c9b0 100644
--- a/tools/jwt-verify.1.md
+++ b/tools/jwt-verify.1.md
@@ -46,6 +46,10 @@
 exit status from the program will cause verification to fail, and so will the
 program being ended by a signal.
 
+The command need not read all of its input: if it stops reading, **jwt-verify**
+is not ended (no matter how large the JSON is), and the program's exit status,
+or a signal that ends it, still decides whether the token passes.
+
 ## Options
 
 **\-h**, **\-\-help**
diff --git a/tools/jwt-verify.c b/tools/jwt-verify.c
index 2bd2993..86ae7bc 100644
--- a/tools/jwt-verify.c
+++ b/tools/jwt-verify.c
@@ -218,7 +218,7 @@
 	int oc, err, verbose = 0;
 	int quiet = 0;
 	int signed_only;
-	int want_help = 0, want_list = 0;
+	int want_help = 0, want_list = 0, nopts = 0;
 
 	char *optstr = "hk:r:P:a:lvqp:";
 	struct option opttbl[] = {
@@ -235,6 +235,7 @@
 	};
 
 	while ((oc = getopt_long(argc, argv, optstr, opttbl, NULL)) != -1) {
+		nopts++;
 		switch (oc) {
 		case 'h':
 			want_help = 1;
@@ -296,12 +297,15 @@
 		}
 	}
 
-	/* -h/-l print and exit 0 only when they are the sole argument. Given
-	 * with a token (or a key, or any other option) they would otherwise
-	 * exit 0 while the tokens went unverified (GHSA-g7xw-4cjw-2247), so
-	 * that is now a usage error. A later bad option still fails first. */
+	/* -h/-l print and exit 0 only when they are the sole argument and the
+	 * only option in it. Given with a token (or a key, or any other option)
+	 * they would otherwise exit 0 while the tokens went unverified
+	 * (GHSA-g7xw-4cjw-2247), so that is now a usage error. argc != 2 catches
+	 * a separate argument (a token, or -h -v); nopts != 1 catches options
+	 * clustered into the one argument (getopt reads -hv as -h -v), which
+	 * leave argc at 2. A later bad option still fails first. */
 	if (want_help || want_list) {
-		if (argc != 2)
+		if (argc != 2 || nopts != 1)
 			usage("--help and --list take no other arguments",
 			      EXIT_FAILURE);
 		if (want_help)