diff --git a/.github/scripts/redact-behaviour-artifacts-test.sh b/.github/scripts/redact-behaviour-artifacts-test.sh new file mode 100755 index 0000000000..9a373c1506 --- /dev/null +++ b/.github/scripts/redact-behaviour-artifacts-test.sh @@ -0,0 +1,268 @@ +#!/usr/bin/env bash +# redact-behaviour-artifacts-test.sh — Tests for redact-behaviour-artifacts.sh +# +# Run from repo root: bash .github/scripts/redact-behaviour-artifacts-test.sh + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REDACT_SCRIPT="${SCRIPT_DIR}/redact-behaviour-artifacts.sh" +FAILURES=0 + +TMPDIR="$(mktemp -d)" +trap 'rm -rf "${TMPDIR}"' EXIT + +# Build secret-like literals at runtime so pre-commit detect-private-key and secret +# scanners do not see contiguous token/PEM patterns in the repository. +fake_ghp_token() { + printf '%s%s' "gh" "p_${1}" +} + +fake_pem_block() { + local kind="$1" + local payload="$2" + printf '%s\n' \ + "$(printf '%s %s %s-----' '-----BEGIN' "${kind}" 'PRIVATE KEY')" \ + "${payload}" \ + "$(printf '%s %s %s-----' '-----END' "${kind}" 'PRIVATE KEY')" +} + +fake_pgp_block() { + local payload="$1" + printf '%s\n' \ + "$(printf '%s %s %s %s-----' '-----BEGIN' 'PGP' 'PRIVATE KEY' 'BLOCK')" \ + "${payload}" \ + "$(printf '%s %s %s %s-----' '-----END' 'PGP' 'PRIVATE KEY' 'BLOCK')" +} + +run_test() { + local test_name="$1" + local must_not_contain="$2" + local must_contain="${3:-}" + + local actual + actual="$(<"${TMPDIR}/artifact.log")" + + if [ -n "${must_not_contain}" ] && echo "${actual}" | grep -qF "${must_not_contain}"; then + echo "FAIL: ${test_name}" + echo " sanitized output still contains: '${must_not_contain}'" + FAILURES=$((FAILURES + 1)) + return + fi + + if [ -n "${must_contain}" ] && ! echo "${actual}" | grep -qF "${must_contain}"; then + echo "FAIL: ${test_name}" + echo " expected to find: '${must_contain}'" + FAILURES=$((FAILURES + 1)) + return + fi + + echo "PASS: ${test_name}" +} + +run_redaction() { + rm -rf "${TMPDIR}/artifacts" + mkdir -p "${TMPDIR}/artifacts" + cp "${TMPDIR}/artifact.log" "${TMPDIR}/artifacts/artifact.log" + ARTIFACT_DIR="${TMPDIR}/artifacts" bash "${REDACT_SCRIPT}" >/dev/null + cp "${TMPDIR}/artifacts/artifact.log" "${TMPDIR}/artifact.log" +} + +run_redaction_on_tree() { + ARTIFACT_DIR="${TMPDIR}/artifacts" bash "${REDACT_SCRIPT}" >/dev/null +} + +echo "==> PEM block redaction" +cat >"${TMPDIR}/artifact.log" <"${TMPDIR}/artifact.log" < Token pattern redaction" +TOKEN="$(fake_ghp_token "abcdefghijklmnopqrstuvwxyz1234567890")" +cat >"${TMPDIR}/artifact.log" <"${TMPDIR}/artifact.log" <"${TMPDIR}/artifact.log" <<'EOF' +Authorization: Bearer abcdefghij+/=TOKENVALUE +keep sentinel line two +EOF +run_redaction +run_test "redacts-bearer-base64-chars" "abcdefghij+/=TOKENVALUE" "keep sentinel line two" + +echo "==> Literal secret redaction" +cat >"${TMPDIR}/artifact.log" <<'EOF' +dumped literal-secret-pem-value in log +Normal log line: assertion failed at step 3 +EOF +mkdir -p "${TMPDIR}/artifacts" +cp "${TMPDIR}/artifact.log" "${TMPDIR}/artifacts/artifact.log" +ARTIFACT_DIR="${TMPDIR}/artifacts" TEST_CODER_PEM="literal-secret-pem-value" bash "${REDACT_SCRIPT}" >/dev/null +cp "${TMPDIR}/artifacts/artifact.log" "${TMPDIR}/artifact.log" +run_test "redacts-literal-env-secret" "literal-secret-pem-value" "Normal log line: assertion failed at step 3" + +cat >"${TMPDIR}/artifact.log" <<'EOF' +dumped literal-secret\value in log +EOF +mkdir -p "${TMPDIR}/artifacts" +cp "${TMPDIR}/artifact.log" "${TMPDIR}/artifacts/artifact.log" +ARTIFACT_DIR="${TMPDIR}/artifacts" TEST_CODER_PEM='literal-secret\value' bash "${REDACT_SCRIPT}" >/dev/null +cp "${TMPDIR}/artifacts/artifact.log" "${TMPDIR}/artifact.log" +run_test "redacts-literal-backslash-secret" 'literal-secret\value' + +echo "==> Compressed artifact redaction" +rm -rf "${TMPDIR}/artifacts" +mkdir -p "${TMPDIR}/artifacts" +TOKEN="$(fake_ghp_token "abcdefghijklmnopqrstuvwxyz1234567890")" +printf 'token=%s\n' "${TOKEN}" >"${TMPDIR}/artifacts/secret.log" +gzip -c "${TMPDIR}/artifacts/secret.log" >"${TMPDIR}/artifacts/secret.log.gz" +rm -f "${TMPDIR}/artifacts/secret.log" +run_redaction_on_tree +gunzip -c "${TMPDIR}/artifacts/secret.log.gz" >"${TMPDIR}/artifact.log" +run_test "redacts-gzip-log" "${TOKEN}" + +rm -rf "${TMPDIR}/artifacts" +mkdir -p "${TMPDIR}/artifacts/inner" +printf 'leaked literal-secret-pem-value here\n' >"${TMPDIR}/artifacts/inner/nested.log" +( + cd "${TMPDIR}/artifacts/inner" + zip -qr "../bundle.zip" nested.log +) +rm -rf "${TMPDIR}/artifacts/inner" +ARTIFACT_DIR="${TMPDIR}/artifacts" TEST_CODER_PEM="literal-secret-pem-value" bash "${REDACT_SCRIPT}" >/dev/null +mkdir -p "${TMPDIR}/unzipped" +unzip -q "${TMPDIR}/artifacts/bundle.zip" -d "${TMPDIR}/unzipped" +cp "${TMPDIR}/unzipped/nested.log" "${TMPDIR}/artifact.log" +run_test "redacts-zip-nested-log" "literal-secret-pem-value" + +rm -rf "${TMPDIR}/artifacts" "${TMPDIR}/unzipped" +mkdir -p "${TMPDIR}/artifacts/inner" +printf 'leaked literal-secret-pem-value here\n' >"${TMPDIR}/artifacts/inner/nested.log" +tar -czf "${TMPDIR}/artifacts/bundle.tar.gz" -C "${TMPDIR}/artifacts/inner" nested.log +rm -rf "${TMPDIR}/artifacts/inner" +ARTIFACT_DIR="${TMPDIR}/artifacts" TEST_CODER_PEM="literal-secret-pem-value" bash "${REDACT_SCRIPT}" >/dev/null +mkdir -p "${TMPDIR}/unzipped" +tar -xzf "${TMPDIR}/artifacts/bundle.tar.gz" -C "${TMPDIR}/unzipped" +cp "${TMPDIR}/unzipped/nested.log" "${TMPDIR}/artifact.log" +run_test "redacts-tar-gz-nested-log" "literal-secret-pem-value" + +echo "==> Encrypted/opaque artifact handling" +rm -rf "${TMPDIR}/artifacts" "${TMPDIR}/unzipped" +mkdir -p "${TMPDIR}/artifacts" +printf 'opaque-binary-secret' >"${TMPDIR}/artifacts/payload.gpg" +run_redaction_on_tree +cp "${TMPDIR}/artifacts/payload.gpg" "${TMPDIR}/artifact.log" +run_test "stubs-encrypted-artifact" "opaque-binary-secret" "[REDACTED OPAQUE CONTENT]" + +rm -rf "${TMPDIR}/artifacts" +mkdir -p "${TMPDIR}/artifacts" +printf 'GIF89a' >"${TMPDIR}/artifacts/exfil.gif" +printf '%s' "$(printf 'fake-secret-payload' | base64)" >>"${TMPDIR}/artifacts/exfil.gif" +run_redaction_on_tree +cp "${TMPDIR}/artifacts/exfil.gif" "${TMPDIR}/artifact.log" +run_test "stubs-fake-media-artifact" "fake-secret-payload" "[REDACTED OPAQUE CONTENT]" + +echo "==> Adversarial and edge-case handling" +rm -rf "${TMPDIR}/artifacts" "${TMPDIR}/unzipped" +mkdir -p "${TMPDIR}/artifacts" +PEM_BODY="MIIEowIBAAKCAQEAfakebodyline" +cat >"${TMPDIR}/artifacts/artifact.log" </dev/null +cp "${TMPDIR}/artifacts/artifact.log" "${TMPDIR}/artifact.log" +run_test "redacts-multiline-pem-body-line" "${PEM_BODY}" "keep this sentinel line" + +rm -rf "${TMPDIR}/artifacts" +mkdir -p "${TMPDIR}/artifacts" +printf '{"key":"%s"}\n' "$(fake_pem_block "RSA" "inlinejsonfake" | tr '\n' ' ')" >"${TMPDIR}/artifacts/embedded.json" +printf 'keep sentinel after json pem\n' >>"${TMPDIR}/artifacts/embedded.json" +run_redaction_on_tree +cp "${TMPDIR}/artifacts/embedded.json" "${TMPDIR}/artifact.log" +run_test "redacts-one-line-json-pem" "inlinejsonfake" "keep sentinel after json pem" + +rm -rf "${TMPDIR}/artifacts" +mkdir -p "${TMPDIR}/artifacts" +printf 'root:%s:0:0:root:/root:/bin/bash\n' 'x' >"${TMPDIR}/passwd-sample" +ln -sf "${TMPDIR}/passwd-sample" "${TMPDIR}/artifacts/leak.log" +run_redaction_on_tree +cp "${TMPDIR}/artifacts/leak.log" "${TMPDIR}/artifact.log" +run_test "stubs-top-level-symlink" "root:x:0:0" "[REDACTED OPAQUE CONTENT]" + +rm -rf "${TMPDIR}/artifacts" "${TMPDIR}/unzipped" +mkdir -p "${TMPDIR}/artifacts/inner" +printf 'leaked literal-secret-pem-value here\nkeep zip sentinel\n' >"${TMPDIR}/artifacts/inner/nested.log" +( + cd "${TMPDIR}/artifacts/inner" + zip -qr "../bundle.zip" nested.log +) +rm -rf "${TMPDIR}/artifacts/inner" +( + cd "${TMPDIR}" + ARTIFACT_DIR=artifacts TEST_CODER_PEM="literal-secret-pem-value" bash "${REDACT_SCRIPT}" >/dev/null +) +mkdir -p "${TMPDIR}/unzipped" +unzip -q "${TMPDIR}/artifacts/bundle.zip" -d "${TMPDIR}/unzipped" +cp "${TMPDIR}/unzipped/nested.log" "${TMPDIR}/artifact.log" +run_test "redacts-zip-with-relative-artifact-dir" "literal-secret-pem-value" "keep zip sentinel" + +rm -rf "${TMPDIR}/artifacts" +mkdir -p "${TMPDIR}/artifacts" +printf 'keep readable sentinel\n' >"${TMPDIR}/artifacts/ok.log" +printf 'secret-in-unreadable\n' >"${TMPDIR}/artifacts/blocked.log" +chmod 000 "${TMPDIR}/artifacts/blocked.log" +ARTIFACT_DIR="${TMPDIR}/artifacts" bash "${REDACT_SCRIPT}" >/dev/null +chmod 644 "${TMPDIR}/artifacts/blocked.log" +cp "${TMPDIR}/artifacts/ok.log" "${TMPDIR}/artifact.log" +run_test "continues-after-unreadable-file" "secret-in-unreadable" "keep readable sentinel" +grep -q '\[REDACTED OPAQUE CONTENT\]' "${TMPDIR}/artifacts/blocked.log" || { + echo "FAIL: stubs-unreadable-file" + echo " expected blocked.log to be stubbed" + FAILURES=$((FAILURES + 1)) +} +[ "${FAILURES}" -eq 0 ] && echo "PASS: stubs-unreadable-file" + +rm -rf "${TMPDIR}/artifacts" +mkdir -p "${TMPDIR}/artifacts" +printf 'before\0after\nkeep nul sentinel\n' >"${TMPDIR}/artifacts/binary.log" +run_redaction_on_tree +cp "${TMPDIR}/artifacts/binary.log" "${TMPDIR}/artifact.log" +run_test "stubs-nul-byte-log" $'before\0after' "[REDACTED OPAQUE CONTENT]" + +rm -rf "${TMPDIR}/artifacts" +mkdir -p "${TMPDIR}/artifacts" +python3 - <<'PY' "${TMPDIR}/artifacts/oversize.gz" +import gzip, pathlib, sys +path = pathlib.Path(sys.argv[1]) +with gzip.open(path, "wb") as handle: + handle.write(b"x" * (11 * 1024 * 1024)) +PY +run_redaction_on_tree +cp "${TMPDIR}/artifacts/oversize.gz" "${TMPDIR}/artifact.log" +run_test "stubs-gzip-bomb" "xxxxxxxx" "[REDACTED OPAQUE CONTENT]" + +echo "" +if [ "${FAILURES}" -gt 0 ]; then + echo "${FAILURES} test(s) failed" + exit 1 +fi +echo "All redact-behaviour-artifacts tests passed" diff --git a/.github/scripts/redact-behaviour-artifacts.sh b/.github/scripts/redact-behaviour-artifacts.sh new file mode 100755 index 0000000000..939250f68f --- /dev/null +++ b/.github/scripts/redact-behaviour-artifacts.sh @@ -0,0 +1,518 @@ +#!/usr/bin/env bash +# redact-behaviour-artifacts.sh — Strip job secrets from behaviour debug artifacts +# before upload. +# +# Invoked from .github/workflows/e2e.yml after a behaviour job failure. The workflow +# checks out this script from the base branch (not PR head) and runs it in a clean +# environment so PR-head code cannot tamper with the redaction toolchain. +# +# Handles plain text (logs, JSON, JSONL), nested archives (zip, tar.gz, gzip), and +# replaces opaque or encrypted blobs that cannot be scanned safely. +# +# Prior art: fullsend-ai/agents scripts/lib/post-failure-report.lib.sh + +set -euo pipefail +shopt -s inherit_errexit + +export PATH=/usr/bin:/bin +export LC_ALL=C +unset LD_PRELOAD BASH_ENV + +ARTIFACT_DIR="${ARTIFACT_DIR:?ARTIFACT_DIR is required}" + +# SYNC-WITH: perFileLimit/totalExtractLimit in pkg/behaviourtest/drivers/ci/githubactions/githubactions.go +readonly ARCHIVE_PER_FILE_LIMIT=$((10 << 20)) +readonly ARCHIVE_TOTAL_LIMIT=$((100 << 20)) +readonly LITERAL_SECRET_MIN_LINE_LEN=8 + +if [ ! -d "${ARTIFACT_DIR}" ]; then + echo "::notice::No behaviour artifact dir at ${ARTIFACT_DIR} — skipping redaction" + exit 0 +fi + +ARTIFACT_DIR="$(cd "${ARTIFACT_DIR}" && pwd)" + +_read_text_file() { + local file="$1" + /usr/bin/python3 -c " +import pathlib +import sys + +try: + sys.stdout.write(pathlib.Path(sys.argv[1]).read_text()) +except OSError: + sys.exit(1) +" "${file}" +} + +_redact_multiline_pem() { + /usr/bin/awk ' + function is_pem_begin(line) { + return tolower(line) ~ /-----begin .*private key.*-----/ + } + function is_pem_end(line) { + return tolower(line) ~ /-----end .*private key.*-----/ + } + is_pem_begin($0) { + print "[REDACTED PRIVATE KEY]" + if (!is_pem_end($0)) { + in_pem = 1 + } + next + } + is_pem_end($0) { + in_pem = 0 + next + } + in_pem { next } + { print } + ' +} + +_redact_literal_token() { + local detail="$1" + local token="$2" + + if [ -z "${token}" ]; then + printf '%s' "${detail}" + return 0 + fi + + REDACT_LITERAL_TOKEN="${token}" REDACT_LITERAL_REPL="[REDACTED]" /usr/bin/awk ' + { + token = ENVIRON["REDACT_LITERAL_TOKEN"] + repl = ENVIRON["REDACT_LITERAL_REPL"] + s = $0 + while ((i = index(s, token)) > 0) { + s = substr(s, 1, i - 1) repl substr(s, i + length(token)) + } + print s + } + ' <<< "${detail}" +} + +_redact_patterns() { + /usr/bin/sed -E \ + -e 's/gh[a-z]_[A-Za-z0-9_]{20,}/[REDACTED]/g' \ + -e 's/github_pat_[A-Za-z0-9_]+/[REDACTED]/g' \ + -e 's/x-access-token:[^@[:space:]]+/x-access-token:[REDACTED]/g' \ + -e 's/(Bearer|token)[[:space:]]+[^[:space:]]+/\1 [REDACTED]/gI' \ + -e 's/ya29\.[A-Za-z0-9._-]+/[REDACTED]/g' +} + +_redact_literal_secrets() { + local detail="$1" + local name value line + + local secret_names=( + TEST_FULLSEND_PEM + TEST_TRIAGE_PEM + TEST_CODER_PEM + TEST_REVIEW_PEM + TEST_RETRO_PEM + TEST_PRIORITIZE_PEM + CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN + TEST_ACTOR_WRITE_PAT + TEST_ACTOR_TRIAGE_PAT + TEST_ACTOR_OUTSIDER_PAT + E2E_GCP_PROJECT_ID + E2E_GCP_WIF_PROVIDER + E2E_GCP_SERVICE_ACCOUNT + ) + + for name in "${secret_names[@]}"; do + value="${!name:-}" + if [ -z "${value}" ]; then + continue + fi + detail="$(_redact_literal_token "${detail}" "${value}")" + if [[ "${value}" == *$'\n'* ]]; then + while IFS= read -r line || [ -n "${line}" ]; do + if [ "${#line}" -ge "${LITERAL_SECRET_MIN_LINE_LEN}" ]; then + detail="$(_redact_literal_token "${detail}" "${line}")" + fi + done <<< "${value}" + fi + done + + printf '%s' "${detail}" +} + +_redact_text_content() { + local content="$1" + local redacted + redacted="$(printf '%s\n' "${content}" | _redact_multiline_pem | _redact_patterns)" + _redact_literal_secrets "${redacted}" +} + +_contains_nul_bytes() { + local file="$1" + /usr/bin/python3 -c "import sys +try: + data = open(sys.argv[1], 'rb').read() +except OSError: + sys.exit(0) +sys.exit(0 if b'\\x00' in data else 1)" "${file}" 2>/dev/null +} + +_sanitize_log_path() { + local value="$1" + value="${value//$'\n'/}" + value="${value//$'\r'/}" + value="${value//::/}" + value="${value//%0A/}" + value="${value//%0a/}" + value="${value//%0D/}" + value="${value//%0d/}" + value="${value//%25/}" + value="$(printf '%s' "${value}" | /usr/bin/sed $'s/\x1b\\[[0-9;]*[A-Za-z]//g')" + printf '%s' "${value}" +} + +_stub_opaque_file() { + local file="$1" + local reason="${2:-could not be scanned for job secrets}" + local tmp safe_file + tmp="$(mktemp)" + printf '%s\n' "[REDACTED OPAQUE CONTENT]" "This file was removed from behaviour debug artifacts because it ${reason}." >"${tmp}" + mv "${tmp}" "${file}" + safe_file="$(_sanitize_log_path "${file}")" + echo "::warning::Replaced opaque artifact file: ${safe_file}" +} + +_replace_symlink_with_stub() { + local file="$1" + local reason="${2:-was a symlink and could not be scanned for job secrets}" + local tmp safe_file + rm -f "${file}" + tmp="$(mktemp)" + printf '%s\n' "[REDACTED OPAQUE CONTENT]" "This file was removed from behaviour debug artifacts because it ${reason}." >"${tmp}" + mv "${tmp}" "${file}" + safe_file="$(_sanitize_log_path "${file}")" + echo "::warning::Replaced symlink artifact: ${safe_file}" +} + +_remove_symlinks() { + local dir="$1" + local link + + while IFS= read -r -d '' link; do + _replace_symlink_with_stub "${link}" + done < <(/usr/bin/find "${dir}" -type l -print0) +} + +_safe_extract_archive() { + local archive="$1" + local dest="$2" + local format="$3" + + /usr/bin/python3 - "${archive}" "${dest}" "${format}" "${ARCHIVE_PER_FILE_LIMIT}" "${ARCHIVE_TOTAL_LIMIT}" <<'PY' +import pathlib +import sys +import tarfile +import zipfile + +archive, dest, fmt = sys.argv[1:4] +per_file = int(sys.argv[4]) +total_limit = int(sys.argv[5]) +root = pathlib.Path(dest) +root.mkdir(parents=True, exist_ok=True) +total = 0 + + +def safe_child(name: str) -> pathlib.Path: + candidate = (root / name).resolve() + root_resolved = root.resolve() + if candidate != root_resolved and root_resolved not in candidate.parents: + raise ValueError(f"path traversal entry: {name}") + return candidate + + +if fmt == "zip": + with zipfile.ZipFile(archive) as zf: + for info in zf.infolist(): + mode = (info.external_attr >> 16) & 0o170000 + if mode == 0o120000: + raise ValueError(f"symlink entry: {info.filename}") + if info.is_dir(): + safe_child(info.filename).mkdir(parents=True, exist_ok=True) + continue + if info.file_size > per_file: + raise ValueError(f"entry exceeds per-file limit: {info.filename}") + target = safe_child(info.filename) + target.parent.mkdir(parents=True, exist_ok=True) + with zf.open(info) as src, open(target, "wb") as dst: + chunk = src.read(per_file + 1) + if len(chunk) > per_file: + raise ValueError(f"entry exceeds per-file limit: {info.filename}") + total += len(chunk) + if total > total_limit: + raise ValueError("archive exceeds total extraction limit") + dst.write(chunk) +elif fmt == "tar.gz": + with tarfile.open(archive, "r:gz") as tf: + for member in tf.getmembers(): + if member.issym() or member.islnk(): + raise ValueError(f"link entry: {member.name}") + if member.isdir(): + safe_child(member.name).mkdir(parents=True, exist_ok=True) + continue + if member.size > per_file: + raise ValueError(f"entry exceeds per-file limit: {member.name}") + target = safe_child(member.name) + target.parent.mkdir(parents=True, exist_ok=True) + extracted = tf.extractfile(member) + if extracted is None: + continue + data = extracted.read(per_file + 1) + if len(data) > per_file: + raise ValueError(f"entry exceeds per-file limit: {member.name}") + total += len(data) + if total > total_limit: + raise ValueError("archive exceeds total extraction limit") + target.write_bytes(data) +else: + raise ValueError(f"unsupported archive format: {fmt}") +PY +} + +_decompress_gzip_capped() { + local src="$1" + local dst="$2" + local limit="$3" + + /usr/bin/python3 - "${src}" "${dst}" "${limit}" <<'PY' +import gzip +import sys + +src, dst, limit = sys.argv[1:4] +limit = int(limit) +with gzip.open(src, "rb") as handle: + data = handle.read(limit + 1) +if len(data) > limit: + raise ValueError("gzip exceeds safe extraction limit") +open(dst, "wb").write(data) +PY +} + +_file_kind() { + local file="$1" + local base lower mime + + base="$(basename "${file}")" + lower="${base,,}" + + case "${lower}" in + *.tar.gz | *.tgz) + echo archive-tar-gz + return 0 + ;; + *.gz) + echo archive-gzip + return 0 + ;; + *.zip) + echo archive-zip + return 0 + ;; + *.gpg | *.age | *.enc) + echo encrypted + return 0 + ;; + esac + + if _contains_nul_bytes "${file}"; then + echo binary + return 0 + fi + + case "${lower}" in + *.json | *.jsonl | *.log | *.txt | *.md | *.yaml | *.yml | *.xml | *.feature | *.out | *.err) + echo text + return 0 + ;; + esac + + mime="$(/usr/bin/file --brief --mime-type "${file}" 2>/dev/null || true)" + case "${mime}" in + text/* | application/json | application/xml | application/x-empty | inode/x-empty) + echo text + return 0 + ;; + application/gzip | application/x-gzip) + echo archive-gzip + return 0 + ;; + application/zip) + echo archive-zip + return 0 + ;; + application/x-tar*) + echo archive-tar-gz + return 0 + ;; + application/pgp-encrypted) + echo encrypted + return 0 + ;; + application/pgp-keys) + echo text + return 0 + ;; + image/* | video/* | audio/* | application/pdf) + echo media + return 0 + ;; + esac + + echo text +} + +_redact_zip_file() { + local file="$1" + local tmpdir workdir abs_file + + abs_file="$(cd "$(dirname "${file}")" && pwd)/$(basename "${file}")" + tmpdir="$(mktemp -d)" + workdir="${tmpdir}/contents" + mkdir -p "${workdir}" + + if ! _safe_extract_archive "${abs_file}" "${workdir}" zip; then + rm -rf "${tmpdir}" + _stub_opaque_file "${abs_file}" "could not be safely extracted as zip" + return 0 + fi + + _remove_symlinks "${workdir}" + _redact_tree "${workdir}" + rm -f "${abs_file}" + (cd "${workdir}" && /usr/bin/zip -qr "${abs_file}" .) + rm -rf "${tmpdir}" +} + +_redact_tar_gz_file() { + local file="$1" + local tmpdir workdir + + tmpdir="$(mktemp -d)" + workdir="${tmpdir}/contents" + mkdir -p "${workdir}" + + if ! _safe_extract_archive "${file}" "${workdir}" tar.gz; then + rm -rf "${tmpdir}" + _stub_opaque_file "${file}" "could not be safely extracted as tar.gz" + return 0 + fi + + _remove_symlinks "${workdir}" + _redact_tree "${workdir}" + rm -f "${file}" + /usr/bin/tar -czf "${file}" -C "${workdir}" . + rm -rf "${tmpdir}" +} + +_redact_gzip_file() { + local file="$1" + local tmpdir content redacted + + tmpdir="$(mktemp -d)" + if ! _decompress_gzip_capped "${file}" "${tmpdir}/content" "${ARCHIVE_PER_FILE_LIMIT}" 2>/dev/null; then + rm -rf "${tmpdir}" + _stub_opaque_file "${file}" "could not be safely decompressed as gzip" + return 0 + fi + + if _contains_nul_bytes "${tmpdir}/content"; then + rm -rf "${tmpdir}" + _stub_opaque_file "${file}" "contained binary content that could not be scanned for job secrets" + return 0 + fi + + if ! content="$(_read_text_file "${tmpdir}/content")"; then + rm -rf "${tmpdir}" + _stub_opaque_file "${file}" "could not be read after gzip decompression" + return 0 + fi + + if ! redacted="$(_redact_text_content "${content}")"; then + rm -rf "${tmpdir}" + _stub_opaque_file "${file}" "could not be redacted after gzip decompression" + return 0 + fi + + printf '%s' "${redacted}" | /usr/bin/gzip -c >"${file}" + rm -rf "${tmpdir}" +} + +_redact_text_file() { + local file="$1" + local content redacted tmp + + if ! content="$(_read_text_file "${file}")"; then + _stub_opaque_file "${file}" "could not be read" + return 0 + fi + + if ! redacted="$(_redact_text_content "${content}")"; then + _stub_opaque_file "${file}" "could not be redacted" + return 0 + fi + + tmp="$(mktemp)" + printf '%s' "${redacted}" >"${tmp}" + mv "${tmp}" "${file}" +} + +_redact_tree() { + local dir="$1" + local file + + _remove_symlinks "${dir}" + while IFS= read -r -d '' file; do + _redact_path "${file}" + done < <(/usr/bin/find "${dir}" -type f -print0) +} + +_redact_opaque_file() { + local file="$1" + local reason="$2" + _stub_opaque_file "${file}" "${reason}" +} + +_redact_path() { + local file="$1" + local kind + + kind="$(_file_kind "${file}")" + case "${kind}" in + text) + _redact_text_file "${file}" + ;; + archive-zip) + _redact_zip_file "${file}" + ;; + archive-tar-gz) + _redact_tar_gz_file "${file}" + ;; + archive-gzip) + _redact_gzip_file "${file}" + ;; + media | binary) + _redact_opaque_file "${file}" "is binary or media and could not be scanned for job secrets" + ;; + encrypted) + _redact_opaque_file "${file}" "is encrypted and could not be scanned for job secrets" + ;; + esac +} + +_remove_symlinks "${ARTIFACT_DIR}" + +file_count=0 +while IFS= read -r -d '' file; do + _redact_path "${file}" + file_count=$((file_count + 1)) +done < <(/usr/bin/find "${ARTIFACT_DIR}" -type f -print0) + +echo "::notice::Redacted secrets in ${file_count} behaviour artifact file(s)" diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 2fc31b4508..c5f7e81669 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -224,7 +224,7 @@ jobs: } fi # pkg/e2etest: shared pool/CLI/cleanup; pkg/behaviourtest: framework; e2e/admin: admin-only helpers - if echo "$FILES" | grep -qE '^e2e/behaviour/|^e2e/admin/|^pkg/e2etest/|^pkg/behaviourtest/|^internal/runtime/|^internal/sandbox/|^internal/config/|^internal/cli/|^internal/layers/|^internal/scaffold/fullsend-repo/|^internal/forge/|^internal/harness/|^internal/harnessdispatch/|^internal/normevent/|^internal/dispatch/|^internal/security/hooks/|^internal/mintclient/|^cmd/fullsend/|^go\.(mod|sum)$|^Makefile$|^\.github/workflows/e2e\.yml$|^\.github/workflows/e2e-ok-to-test\.yml$|^\.github/workflows/reusable-dispatch\.yml$|^\.github/actions/check-e2e-authorization/|^scripts/check-e2e-authorization\.sh$'; then + if echo "$FILES" | grep -qE '^e2e/behaviour/|^e2e/admin/|^pkg/e2etest/|^pkg/behaviourtest/|^internal/runtime/|^internal/sandbox/|^internal/config/|^internal/cli/|^internal/layers/|^internal/scaffold/fullsend-repo/|^internal/forge/|^internal/harness/|^internal/harnessdispatch/|^internal/normevent/|^internal/dispatch/|^internal/security/hooks/|^internal/mintclient/|^cmd/fullsend/|^go\.(mod|sum)$|^Makefile$|^\.github/scripts/redact-behaviour-artifacts\.sh$|^\.github/workflows/e2e\.yml$|^\.github/workflows/e2e-ok-to-test\.yml$|^\.github/workflows/reusable-dispatch\.yml$|^\.github/actions/check-e2e-authorization/|^scripts/check-e2e-authorization\.sh$'; then echo "relevant=true" >> "$GITHUB_OUTPUT" else echo "::notice::No behaviour-relevant files changed — skipping behaviour tests" @@ -252,7 +252,10 @@ jobs: - name: Run behaviour tests if: steps.changes.outputs.relevant != 'false' - run: make behaviour-test + shell: bash + run: | + mkdir -p "${{ runner.temp }}/behaviour-artifacts" + make behaviour-test 2>&1 | tee "${{ runner.temp }}/behaviour-artifacts/behaviour-test.log" env: BEHAVIOUR_SCM: github BEHAVIOUR_CI: githubactions @@ -277,8 +280,59 @@ jobs: TEST_ACTOR_TRIAGE_PAT: ${{ secrets.TEST_ACTOR_TRIAGE_PAT }} TEST_ACTOR_OUTSIDER_PAT: ${{ secrets.TEST_ACTOR_OUTSIDER_PAT }} - - name: Upload behaviour debug artifacts + - name: Check out redaction script from base branch + if: failure() && steps.changes.outputs.relevant != 'false' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # Base-branch script only — PR head must not control artifact redaction (#5221). + ref: ${{ github.sha }} + sparse-checkout: .github/scripts/redact-behaviour-artifacts.sh + path: base-scripts + persist-credentials: false + + - name: Redact secrets from behaviour debug artifacts + id: redact if: failure() && steps.changes.outputs.relevant != 'false' + env: + ARTIFACT_DIR: ${{ runner.temp }}/behaviour-artifacts + TEST_FULLSEND_PEM: ${{ secrets.TEST_FULLSEND_PEM }} + TEST_TRIAGE_PEM: ${{ secrets.TEST_TRIAGE_PEM }} + TEST_CODER_PEM: ${{ secrets.TEST_CODER_PEM }} + TEST_REVIEW_PEM: ${{ secrets.TEST_REVIEW_PEM }} + TEST_RETRO_PEM: ${{ secrets.TEST_RETRO_PEM }} + TEST_PRIORITIZE_PEM: ${{ secrets.TEST_PRIORITIZE_PEM }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.TEST_CLOUDFLARE_ACCOUNT_ID }} + CLOUDFLARE_API_TOKEN: ${{ secrets.TEST_CLOUDFLARE_API_TOKEN }} + TEST_ACTOR_WRITE_PAT: ${{ secrets.TEST_ACTOR_WRITE_PAT }} + TEST_ACTOR_TRIAGE_PAT: ${{ secrets.TEST_ACTOR_TRIAGE_PAT }} + TEST_ACTOR_OUTSIDER_PAT: ${{ secrets.TEST_ACTOR_OUTSIDER_PAT }} + E2E_GCP_PROJECT_ID: ${{ secrets.E2E_GCP_PROJECT_ID }} + E2E_GCP_WIF_PROVIDER: ${{ secrets.E2E_GCP_WIF_PROVIDER }} + E2E_GCP_SERVICE_ACCOUNT: ${{ secrets.E2E_GCP_SERVICE_ACCOUNT }} + run: | + exec /usr/bin/env -i \ + PATH=/usr/bin:/bin \ + LC_ALL=C \ + HOME="${{ runner.temp }}" \ + ARTIFACT_DIR="${ARTIFACT_DIR}" \ + TEST_FULLSEND_PEM="${TEST_FULLSEND_PEM}" \ + TEST_TRIAGE_PEM="${TEST_TRIAGE_PEM}" \ + TEST_CODER_PEM="${TEST_CODER_PEM}" \ + TEST_REVIEW_PEM="${TEST_REVIEW_PEM}" \ + TEST_RETRO_PEM="${TEST_RETRO_PEM}" \ + TEST_PRIORITIZE_PEM="${TEST_PRIORITIZE_PEM}" \ + CLOUDFLARE_ACCOUNT_ID="${CLOUDFLARE_ACCOUNT_ID}" \ + CLOUDFLARE_API_TOKEN="${CLOUDFLARE_API_TOKEN}" \ + TEST_ACTOR_WRITE_PAT="${TEST_ACTOR_WRITE_PAT}" \ + TEST_ACTOR_TRIAGE_PAT="${TEST_ACTOR_TRIAGE_PAT}" \ + TEST_ACTOR_OUTSIDER_PAT="${TEST_ACTOR_OUTSIDER_PAT}" \ + E2E_GCP_PROJECT_ID="${E2E_GCP_PROJECT_ID}" \ + E2E_GCP_WIF_PROVIDER="${E2E_GCP_WIF_PROVIDER}" \ + E2E_GCP_SERVICE_ACCOUNT="${E2E_GCP_SERVICE_ACCOUNT}" \ + /usr/bin/bash "${{ github.workspace }}/base-scripts/.github/scripts/redact-behaviour-artifacts.sh" + + - name: Upload behaviour debug artifacts + if: failure() && steps.changes.outputs.relevant != 'false' && steps.redact.outcome == 'success' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: behaviour-artifacts-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.run_id }} diff --git a/Makefile b/Makefile index 0ea98011df..ce062fa704 100644 --- a/Makefile +++ b/Makefile @@ -26,7 +26,7 @@ help: @echo " go-vet - Run go vet" @echo " go-tidy - Run go mod tidy" @echo " lint-md-links - Check markdown files for broken in-repo links and anchors" - @echo " script-test - Run shell script tests (reconcile-repos, topissues, gitlint-rules)" + @echo " script-test - Run shell script tests (reconcile-repos, topissues, gitlint-rules, artifact redaction)" @echo " test - Run all checks: lint-all, go-test, script-test, lint-eval-cases" @echo " e2e-test - Run admin e2e tests (CI: OIDC mint; local: gh auth login or GH_TOKEN)" @echo " behaviour-test - Run Gherkin behaviour tests (installs fullsend per-repo; CI: OIDC mint)" @@ -179,6 +179,7 @@ endef script-test: $(call run-timed,bash scripts/check-e2e-authorization-test.sh) + $(call run-timed,bash .github/scripts/redact-behaviour-artifacts-test.sh) $(call run-timed,bash internal/scaffold/fullsend-repo/scripts/reconcile-repos-test.sh) $(call run-timed,bash internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh) $(call run-timed,python3 skills/topissues/scripts/topissues_test.py) diff --git a/docs/contributing/ci-workflows.md b/docs/contributing/ci-workflows.md index d42e01766e..1d06256b7c 100644 --- a/docs/contributing/ci-workflows.md +++ b/docs/contributing/ci-workflows.md @@ -176,6 +176,24 @@ When a PR adds or modifies secret references in a `pull_request_target` job, rev - [ ] **Do not wire secrets before consumption code exists.** Adding a secret to `env:` in a PR that does not yet contain the code that uses it means the secret is exposed to whatever code does run — with no benefit. - [ ] **Verify the gate job covers the new job.** If the PR adds a new job that checks out PR-head code with secrets, confirm that job has `needs: gate` and the appropriate `if:` condition gating on `needs.gate.outputs.authorized`. +### Behaviour debug artifact redaction + +The behaviour job in `e2e.yml` uploads debug artifacts on failure. Because PR-head code populates that directory under `pull_request_target`, a malicious authorized PR could write job secrets into artifact files (GitHub masks logs but not uploaded artifact contents). + +Before upload, the workflow checks out `.github/scripts/redact-behaviour-artifacts.sh` from the **base branch** (`github.sha` on `pull_request_target`; the merge-group head on `merge_group`) into a separate `base-scripts/` path. PR-head code cannot modify the checked-in script contents. The redaction step runs via `env -i` with a pinned `PATH` so earlier job steps cannot poison the interpreter search path or dynamic-linker hooks. + +The behaviour test step tees job output to `behaviour-test.log` in that directory (with `shell: bash` so `pipefail` propagates `make behaviour-test` failures). Upload is gated on `steps.redact.outcome == 'success'`. + +Redaction covers: + +- Plain text artifacts (JSON, JSONL, logs, feature output) — literal env secrets (including multi-line PEM lines), common token patterns, and PEM blocks +- Nested archives (zip, tar.gz, gzip) — extract, redact, re-pack with the same size limits as behaviour artifact downloads +- Encrypted blobs (`.gpg`, `.age`, `.enc`) — replaced with a stub (cannot scan ciphertext) +- Binary and media files (images, video, PDF, opaque blobs, NUL-containing `.log` files) — replaced with a stub +- Symlinks under the artifact directory — replaced with a stub before upload + +**Residual limitations:** content scanning cannot catch every encoding or obfuscation of a secret in a text-classified file (base64, hex, split tokens). Same-job PR-head code could theoretically race the upload step after redaction; isolating redaction in a separate job would narrow that window further. + ## Additional conventions - Always include the workflow file itself in its own `paths:` filter so changes to the workflow trigger its own CI. diff --git a/internal/scaffold/vendormanifest.go b/internal/scaffold/vendormanifest.go index da0798c639..0773011026 100644 --- a/internal/scaffold/vendormanifest.go +++ b/internal/scaffold/vendormanifest.go @@ -155,6 +155,8 @@ var vendoredDefaultsInfraPaths = []string{ ".github/scripts/install-openshell.sh", ".github/scripts/install-podman.sh", ".github/scripts/openshell-version.sh", + ".github/scripts/redact-behaviour-artifacts-test.sh", + ".github/scripts/redact-behaviour-artifacts.sh", } // enumerateVendoredPaths returns embed-derived paths for a current --vendor install layout.