diff --git a/.github/workflows/scripts-test.yml b/.github/workflows/scripts-test.yml index 7313aedf43..4bec3cba72 100644 --- a/.github/workflows/scripts-test.yml +++ b/.github/workflows/scripts-test.yml @@ -31,3 +31,5 @@ jobs: run: python3 -m unittest discover -s scripts/tests -p 'test_update_nixpkgs_inputs.py' -v - name: Run worker preflight contract tests (#4862) run: python3 -m unittest discover -s scripts/tests -p 'test_worker_preflight.py' -v + - name: Run bitwarden-load-secrets multiline contract tests (#5650) + run: python3 -m unittest discover -s scripts/tests -p 'test_bitwarden_load_secrets.py' -v diff --git a/lib/bitwarden-load-secrets.sh b/lib/bitwarden-load-secrets.sh index 543d243310..01c2f1ec29 100755 --- a/lib/bitwarden-load-secrets.sh +++ b/lib/bitwarden-load-secrets.sh @@ -182,20 +182,41 @@ sanitize_var_name() { echo "$clean" } -# Temporary associative-like storage using newline-delimited pairs -# Format: KEYVALUE +# Temporary associative-like storage using newline-delimited pairs. +# Format: KEYBASE64_VALUE -- values are base64-encoded so a +# multiline secret (private key, certificate) can never split into +# bogus variables (#5650). Values are decoded only at output time. +# jq (already a hard dependency) does the codec, so this is portable. PAIRS="" -add_pair() { +# Encode a raw value for PAIRS storage (single line, no wrapping). +b64_encode_value() { + jq -jn --arg v "$1" '$v | @base64' +} + +# Decode a PAIRS value into $DECODED_VALUE (a global, so a trailing +# newline in the value survives command-substitution stripping). +DECODED_VALUE="" +b64_decode_value() { + local tmp + tmp="$(jq -jn --arg v "$1" '$v | @base64d'; printf 'x')" + DECODED_VALUE="${tmp%x}" +} + +add_pair_encoded() { local k="$1" - local v="$2" + local v_enc="$2" local safe_k safe_k="$(sanitize_var_name "${VAR_PREFIX}${k}")" if [ -n "$safe_k" ]; then - PAIRS+="${safe_k}"$'\t'"${v}"$'\n' + PAIRS+="${safe_k}"$'\t'"${v_enc}"$'\n' fi } +add_pair() { + add_pair_encoded "$1" "$(b64_encode_value "$2")" +} + # ------------------------------------------------------------- # MODE 1: Bitwarden Secrets Manager (bws) # ------------------------------------------------------------- @@ -220,9 +241,9 @@ if [ "$USE_BWS" = true ]; then ARGS+=("$BWS_PROJECT_QUERY") fi RAW_JSON="$(bws secret list "${ARGS[@]}" 2>/dev/null)" || die "Failed to list secrets from bws." - while IFS=$'\t' read -r k v; do - [ -n "$k" ] && add_pair "$k" "$v" - done < <(echo "$RAW_JSON" | jq -r '.[] | "\(.key)\t\(.value)"') + while IFS=$'\t' read -r k v_enc; do + [ -n "$k" ] && add_pair_encoded "$k" "$v_enc" + done < <(echo "$RAW_JSON" | jq -r '.[] | "\(.key)\t\((.value // "") | @base64)"') fi # ------------------------------------------------------------- @@ -268,9 +289,9 @@ else # Extract all custom fields and optional login/notes else # 1. Custom fields - while IFS=$'\t' read -r k v; do - [ -n "$k" ] && add_pair "$k" "$v" - done < <(echo "$ITEM_JSON" | jq -r '(.fields // [])[] | "\(.name)\t\(.value)"') + while IFS=$'\t' read -r k v_enc; do + [ -n "$k" ] && add_pair_encoded "$k" "$v_enc" + done < <(echo "$ITEM_JSON" | jq -r '(.fields // [])[] | "\(.name)\t\((.value // "") | @base64)"') # 2. Login fields if requested or if no custom fields exist NUM_CUSTOM="$(echo "$ITEM_JSON" | jq '(.fields // []) | length')" @@ -301,9 +322,10 @@ LOADED_NAMES=() case "$FORMAT" in source) - while IFS=$'\t' read -r k v; do + while IFS=$'\t' read -r k v_enc; do if [ -n "$k" ]; then - export "$k"="$v" + b64_decode_value "$v_enc" + export "$k"="$DECODED_VALUE" LOADED_NAMES+=("$k") COUNT=$((COUNT + 1)) fi @@ -312,18 +334,20 @@ source) ;; export) - while IFS=$'\t' read -r k v; do + while IFS=$'\t' read -r k v_enc; do if [ -n "$k" ]; then - escaped_val="$(printf '%s' "$v" | jq -Rr @sh)" + b64_decode_value "$v_enc" + escaped_val="$(printf '%s' "$DECODED_VALUE" | jq -Rsr @sh)" printf 'export %s=%s\n' "$k" "$escaped_val" fi done <<<"$PAIRS" ;; env) - while IFS=$'\t' read -r k v; do + while IFS=$'\t' read -r k v_enc; do if [ -n "$k" ]; then - escaped_val="$(printf '%s' "$v" | jq -Rr @sh)" + b64_decode_value "$v_enc" + escaped_val="$(printf '%s' "$DECODED_VALUE" | jq -Rsr @sh)" printf '%s=%s\n' "$k" "$escaped_val" fi done <<<"$PAIRS" @@ -333,7 +357,7 @@ json) # Build JSON object from pairs jq -n -R ' [inputs | select(length > 0) | split("\t")] | - map({(.[0]): .[1]}) | add // {} + map({(.[0]): (.[1] | @base64d)}) | add // {} ' <<<"$PAIRS" ;; diff --git a/scripts/tests/test_bitwarden_load_secrets.py b/scripts/tests/test_bitwarden_load_secrets.py new file mode 100644 index 0000000000..55d6233393 --- /dev/null +++ b/scripts/tests/test_bitwarden_load_secrets.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Contract tests for lib/bitwarden-load-secrets.sh multiline values (#5650). + +A multiline secret value (private key, certificate) must survive +end-to-end in every output mode: the loaders, the PAIRS store, and the +output dispatchers must never split it into bogus variables. +Oracle: the exact stubbed values below, compared byte-for-byte. +""" + +import json +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "lib" / "bitwarden-load-secrets.sh" + +MULTILINE = "BEGIN CERT\nPRIVATE KEY\nEND CERT" +CONTROL = "hello" + +STUB = """#!/usr/bin/env python3 +import json, sys +name = sys.argv[0].rsplit("/", 1)[-1] +args = sys.argv[1:] +if name == "bws": + if args[:2] == ["secret", "list"]: + print(json.dumps([ + {"key": "TLS_CERT", "value": "BEGIN CERT\\nPRIVATE KEY\\nEND CERT"}, + {"key": "PLAIN", "value": "hello"}, + ])) + elif args[:2] == ["secret", "get"]: + print(json.dumps({"key": "TLS_CERT", + "value": "BEGIN CERT\\nPRIVATE KEY\\nEND CERT"})) + else: + sys.exit(1) +elif name == "bw": + if args[:1] == ["status"]: + print(json.dumps({"status": "unlocked"})) + elif args[:2] == ["get", "item"]: + print(json.dumps({"name": "Item", "fields": [ + {"name": "TLS_CERT", "value": "BEGIN CERT\\nPRIVATE KEY\\nEND CERT"}, + {"name": "PLAIN", "value": "hello"}, + ]})) + else: + sys.exit(1) +""" + + +class TestBitwardenLoadSecrets(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="bw-load-") + bindir = Path(self.tmp.name) / "bin" + bindir.mkdir() + for tool in ("bws", "bw"): + stub = bindir / tool + stub.write_text(STUB) + stub.chmod(0o755) + self.env = os.environ.copy() + self.env["PATH"] = f"{bindir}:{self.env['PATH']}" + self.env["BWS_ACCESS_TOKEN"] = "test-token" + self.env["BW_SESSION"] = "test-session" + + def tearDown(self): + self.tmp.cleanup() + + def run_script(self, *args): + return subprocess.run( + ["bash", str(SCRIPT), *args], + env=self.env, capture_output=True, text=True, check=True, + ).stdout + + def eval_format(self, fmt, source_args): + # Evaluate the script's export/env output (or source it) in a + # fresh shell and print the resulting variables byte-exactly. + if fmt == "source": + cmd = ( + f'source "{SCRIPT}" {source_args} >/dev/null; ' + 'printf "%s\\x00%s" "$TLS_CERT" "$PLAIN"' + ) + else: + cmd = ( + f'eval "$("{SCRIPT}" {source_args})"; ' + 'printf "%s\\x00%s" "$TLS_CERT" "$PLAIN"' + ) + out = subprocess.run( + ["bash", "-c", cmd], env=self.env, + capture_output=True, text=True, check=True, + ).stdout + cert, plain = out.split("\x00") + self.assertEqual(cert, MULTILINE) + self.assertEqual(plain, CONTROL) + + def test_bws_list_json(self): + data = json.loads(self.run_script("--bws", "--format", "json")) + self.assertEqual(data, {"TLS_CERT": MULTILINE, "PLAIN": CONTROL}) + + def test_bws_list_export_env_source(self): + for fmt in ("export", "env"): + with self.subTest(fmt=fmt): + self.eval_format(fmt, f"--bws --format {fmt}") + self.eval_format("source", "--bws") + + def test_bws_single_secret_json(self): + data = json.loads( + self.run_script("--bws", "--secret", "x", "--format", "json")) + self.assertEqual(data, {"TLS_CERT": MULTILINE}) + + def test_vault_fields_json_and_source(self): + data = json.loads( + self.run_script("--item", "Item", "--format", "json")) + self.assertEqual(data, {"TLS_CERT": MULTILINE, "PLAIN": CONTROL}) + self.eval_format("source", "--item Item") + + +if __name__ == "__main__": + unittest.main()