A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
fix(ci): redact macOS signing logs and preserve diagnostics
RoversX097ae925b680
diff --git a/ci/deploy.sh b/ci/deploy.shindex 9a0ac0e0..c3cc79bc 100755--- a/ci/deploy.sh+++ b/ci/deploy.sh@@ -162,51 +162,65 @@ case $OSTYPE infiset +x+ . "$(dirname "$0")/macos-signing-log.sh"# Only a Developer ID signature is eligible for notarization; the notary# service rejects adhoc and Apple Development identities outright.notarize=noif [[ -n "${MACOS_SIGNING_MODE:-}" ]] ; then- bash ci/macos-sign-local.sh "$zipdir/ThinkTerm.app" "$MACOS_SIGNING_MODE"+ signing_run "Sign app bundle" bash ci/macos-sign-local.sh "$zipdir/ThinkTerm.app" "$MACOS_SIGNING_MODE"if [[ "$MACOS_SIGNING_MODE" == developerid ]] ; thennotarize=yesfielif [ -n "$MACOS_TEAM_ID" ] ; then- MACOS_PW=$(echo $MACOS_CERT_PW | base64 --decode)- # GitHub masks the secret as stored, not what it decodes to.- if [[ "${GITHUB_ACTIONS:-}" == true ]] ; then- echo "::add-mask::$MACOS_PW"+ if ! MACOS_PW=$(printf '%s' "$MACOS_CERT_PW" | base64 --decode 2>/dev/null); then+ echo "error: MACOS_CERT_PW must contain a base64-encoded certificate password." >&2+ exit 1fi+ # GitHub masks the secret as stored, not what it decodes to.+ signing_mask "$MACOS_PW"- # Remove pesky additional quotes from default-keychain output- def_keychain=$(eval echo $(security default-keychain -d user))- echo "Default keychain is $def_keychain"# The certificate waits in a directory only this user can read. However# signing ends -- set -e stops the script at a wrong password or a# failed codesign -- the file, the keychain holding the private key and# the default keychain are put back.- cert_dir=$(mktemp -d)+ cert_dir=$(mktemp -d 2>/dev/null) || {+ echo "error: Could not create the private signing directory." >&2+ exit 1+ }+ def_keychain=+ keychain_made=sign_cleanup() {- security default-keychain -d user -s "$def_keychain" || true- security delete-keychain build.keychain >/dev/null 2>&1 || true- rm -rf "$cert_dir"+ if [[ -n "$def_keychain" ]]; then+ signing_run "Restore default keychain" security default-keychain -d user -s "$def_keychain" || true+ fi+ if [[ -n "$keychain_made" ]]; then+ signing_run "Remove signing keychain" security delete-keychain build.keychain || true+ fi+ rm -rf "$cert_dir" 2>/dev/null || echo "warning: Could not remove the private signing directory." >&2}trap sign_cleanup EXIT+ signing_capture "Read default keychain" "$cert_dir/default-keychain" security default-keychain -d user+ def_keychain=$(sed -e 's/^ *"//' -e 's/" *$//' "$cert_dir/default-keychain")echo "Speculative delete of build.keychain"- security delete-keychain build.keychain || true+ security delete-keychain build.keychain >/dev/null 2>&1 || trueecho "Create build.keychain"- security create-keychain -p "$MACOS_PW" build.keychain+ signing_run "Create signing keychain" security create-keychain -p "$MACOS_PW" build.keychain+ keychain_made=yesecho "Make build.keychain the default"- security default-keychain -d user -s build.keychain+ signing_run "Select signing keychain" security default-keychain -d user -s build.keychainecho "Unlock build.keychain"- security unlock-keychain -p "$MACOS_PW" build.keychain+ signing_run "Unlock signing keychain" security unlock-keychain -p "$MACOS_PW" build.keychainecho "Import .p12 data"- (umask 077 && printf '%s' "$MACOS_CERT" | base64 --decode > "$cert_dir/certificate.p12")- security import "$cert_dir/certificate.p12" -k build.keychain -P "$MACOS_PW" -T /usr/bin/codesign- rm "$cert_dir/certificate.p12"+ if ! (umask 077 && printf '%s' "$MACOS_CERT" | base64 --decode > "$cert_dir/certificate.p12") 2>/dev/null; then+ echo "error: Could not decode MACOS_CERT into the private certificate file." >&2+ exit 1+ fi+ signing_run "Import signing certificate" security import "$cert_dir/certificate.p12" -k build.keychain -P "$MACOS_PW" -T /usr/bin/codesign+ signing_run "Remove temporary certificate" rm "$cert_dir/certificate.p12"echo "Grant apple tools access to build.keychain"- security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$MACOS_PW" build.keychain+ signing_run "Grant signing access" security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$MACOS_PW" build.keychainecho "Codesign"- /usr/bin/codesign --keychain build.keychain --force --options runtime \+ signing_run "Sign app bundle" /usr/bin/codesign --keychain build.keychain --force --options runtime \--entitlements ci/macos-entitlement.plist --deep --sign "$MACOS_TEAM_ID" $zipdir/ThinkTerm.app/echo "Restore default keychain and remove build.keychain"sign_cleanup@@ -216,7 +230,7 @@ case $OSTYPE in# A normal local package should still be a correctly sealed app bundle.# Development/Developer ID identities remain opt-in, but ad-hoc signing# is a safer and less surprising default than producing an invalid app.- bash ci/macos-sign-local.sh "$zipdir/ThinkTerm.app" adhoc+ signing_run "Sign app bundle" bash ci/macos-sign-local.sh "$zipdir/ThinkTerm.app" adhocfi# Notarize and staple before packing, not after. Stapling rewrites thediff --git a/ci/macos-check-signing.sh b/ci/macos-check-signing.shindex 2051e9b9..c96e5eae 100755--- a/ci/macos-check-signing.sh+++ b/ci/macos-check-signing.sh@@ -10,8 +10,11 @@# Reads the environment the package step gets. Without a certificate there is# nothing to check: ci/deploy.sh then signs ad hoc.+set +xset -euo pipefail+. "$(dirname "$0")/macos-signing-log.sh"+fail() {echo "::error::$*" >&2exit 1@@ -41,15 +44,20 @@ fi[[ ${#missing[@]} -eq 0 ]] ||fail "signing needs all of MACOS_CERT, MACOS_CERT_PW and MACOS_TEAM_ID; not set: ${missing[*]}"-WORK_DIR=$(mktemp -d)+WORK_DIR=$(mktemp -d 2>/dev/null) || fail "cannot create the private signing directory"KEYCHAIN="$WORK_DIR/signing-check.keychain-db"+KEYCHAIN_MADE=ORIGINAL_KEYCHAIN=cleanup() {if [[ -n "$ORIGINAL_KEYCHAIN" ]]; then- security default-keychain -d user -s "$ORIGINAL_KEYCHAIN" || true+ signing_run "Restore default keychain" security default-keychain -d user -s "$ORIGINAL_KEYCHAIN" || true+ fi+ # A keychain that was never made cannot be deleted, and saying so would+ # read as a second failure after the real one.+ if [[ -n "$KEYCHAIN_MADE" ]]; then+ signing_run "Remove signing keychain" security delete-keychain "$KEYCHAIN" || truefi- security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || true- rm -rf "$WORK_DIR"+ rm -rf "$WORK_DIR" 2>/dev/null || echo "warning: Could not remove the private signing directory." >&2}trap cleanup EXIT@@ -61,20 +69,18 @@ trap cleanup EXITfail "MACOS_TEAM_ID is not a team ID: ten letters and digits, from developer.apple.com > Membership"CERT="$WORK_DIR/cert.p12"-if ! printf '%s' "$MACOS_CERT" | base64 --decode >"$CERT" 2>/dev/null || [[ ! -s "$CERT" ]]; then+if ! (umask 077; printf '%s' "$MACOS_CERT" | base64 --decode >"$CERT") 2>/dev/null || [[ ! -s "$CERT" ]]; thenfail "MACOS_CERT is not base64: set it to the output of base64 -i cert.p12"fi# A .p12 is DER, which opens with an ASN.1 sequence.-[[ "$(head -c 1 "$CERT" | od -An -tx1 | tr -d ' \n')" == "30" ]] ||+[[ "$(head -c 1 "$CERT" 2>/dev/null | od -An -tx1 | tr -d ' \n')" == "30" ]] ||fail "MACOS_CERT is not a .p12 file: export the certificate with its private key as .p12, then base64 -i cert.p12"if ! CERT_PW=$(printf '%s' "$MACOS_CERT_PW" | base64 --decode 2>/dev/null); thenfail "MACOS_CERT_PW is not base64: set it to the output of printf '%s' 'the .p12 password' | base64"fi# GitHub masks the secret as stored, not what it decodes to.-if [[ "${GITHUB_ACTIONS:-}" == true ]]; then- echo "::add-mask::$CERT_PW"-fi+signing_mask "$CERT_PW"NOTARY_AUTH=()if [[ -n "${MACOS_NOTARY_KEY:-}" || -n "${MACOS_NOTARY_KEY_ID:-}" || -n "${MACOS_NOTARY_ISSUER:-}" ]]; then@@ -84,9 +90,9 @@ if [[ -n "${MACOS_NOTARY_KEY:-}" || -n "${MACOS_NOTARY_KEY_ID:-}" || -n "${MACOSfail "MACOS_NOTARY_ISSUER is not an issuer ID: the UUID above the keys in App Store Connect > Users and Access > Integrations"[[ "$MACOS_NOTARY_KEY_ID" =~ ^[A-Z0-9]{8,12}$ ]] ||fail "MACOS_NOTARY_KEY_ID is not a key ID: the short ID on the key's own row, not the issuer ID"- KEY_FILE="$WORK_DIR/AuthKey_${MACOS_NOTARY_KEY_ID}.p8"- if ! (umask 077 && printf '%s' "$MACOS_NOTARY_KEY" | base64 --decode >"$KEY_FILE" 2>/dev/null) ||- [[ "$(head -n 1 "$KEY_FILE" | tr -d '\r')" != "-----BEGIN PRIVATE KEY-----" ]]; then+ KEY_FILE="$WORK_DIR/notary-key.p8"+ if ! (umask 077 && printf '%s' "$MACOS_NOTARY_KEY" | base64 --decode >"$KEY_FILE") 2>/dev/null ||+ [[ "$(head -n 1 "$KEY_FILE" 2>/dev/null | tr -d '\r')" != "-----BEGIN PRIVATE KEY-----" ]]; thenfail "MACOS_NOTARY_KEY is not a .p8 key: set it to the output of base64 -i AuthKey_<key id>.p8"fiNOTARY_AUTH=(--key "$KEY_FILE" --key-id "$MACOS_NOTARY_KEY_ID" --issuer "$MACOS_NOTARY_ISSUER")@@ -100,28 +106,28 @@ elsefi# --- the certificate signs, as ci/deploy.sh will sign the app ---------------KEYCHAIN_PW=$(uuidgen)-security create-keychain -p "$KEYCHAIN_PW" "$KEYCHAIN"-security unlock-keychain -p "$KEYCHAIN_PW" "$KEYCHAIN"-security import "$CERT" -k "$KEYCHAIN" -P "$CERT_PW" -T /usr/bin/codesign >/dev/null 2>&1 ||+KEYCHAIN_PW=$(uuidgen 2>/dev/null) || fail "cannot generate a temporary keychain password"+signing_run "Create signing keychain" security create-keychain -p "$KEYCHAIN_PW" "$KEYCHAIN"+KEYCHAIN_MADE=yes+signing_run "Unlock signing keychain" security unlock-keychain -p "$KEYCHAIN_PW" "$KEYCHAIN"+signing_run "Import signing certificate" security import "$CERT" -k "$KEYCHAIN" -P "$CERT_PW" -T /usr/bin/codesign ||fail "MACOS_CERT does not open with MACOS_CERT_PW: check the .p12 password, base64-encoded as above"-security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PW" "$KEYCHAIN" >/dev/null 2>&1-ORIGINAL_KEYCHAIN=$(security default-keychain -d user | sed -e 's/^ *"//' -e 's/" *$//')-security default-keychain -d user -s "$KEYCHAIN"+signing_run "Grant signing access" security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PW" "$KEYCHAIN"+signing_capture "Read default keychain" "$WORK_DIR/default-keychain" security default-keychain -d user+ORIGINAL_KEYCHAIN=$(sed -e 's/^ *"//' -e 's/" *$//' "$WORK_DIR/default-keychain")+signing_run "Select signing keychain" security default-keychain -d user -s "$KEYCHAIN"# ci/deploy.sh names the identity by the team ID, which codesign matches# against the certificate's name.PROBE="$WORK_DIR/probe"-cp /usr/bin/true "$PROBE"-if ! codesign --keychain "$KEYCHAIN" --force --options runtime --sign "$MACOS_TEAM_ID" "$PROBE" \- >/dev/null 2>"$WORK_DIR/codesign.err"; then- echo "codesign: $(tail -n 1 "$WORK_DIR/codesign.err")" >&2+signing_run "Prepare signing probe" cp /usr/bin/true "$PROBE"+if ! signing_run "Sign certificate probe" codesign --keychain "$KEYCHAIN" --force --options runtime --sign "$MACOS_TEAM_ID" "$PROBE"; thenfail "the certificate does not sign for MACOS_TEAM_ID: it has to be a Developer ID Application certificate of that team, exported with its private key"ficodesign -dv "$PROBE" 2>&1 | grep -q '^Authority=Developer ID Application:' ||fail "the certificate is not a Developer ID Application certificate, the only kind Apple notarizes"-if ! security find-certificate -c "Developer ID Application" -p "$KEYCHAIN" |- openssl x509 -noout -checkend $((60 * 24 * 3600)) >/dev/null 2>&1; then+if ! (security find-certificate -c "Developer ID Application" -p "$KEYCHAIN" |+ openssl x509 -noout -checkend $((60 * 24 * 3600))) >/dev/null 2>&1; thenecho "::warning::The Developer ID certificate expires within 60 days: make a new one at developer.apple.com and replace MACOS_CERT and MACOS_CERT_PW"fiecho "==> The certificate signs as a Developer ID Application of the team"@@ -129,8 +135,7 @@ echo "==> The certificate signs as a Developer ID Application of the team"# --- the notary service takes the credentials -----------------------------# Lists past submissions, which needs the same sign-in as a submission and# submits nothing.-if ! xcrun notarytool history "${NOTARY_AUTH[@]}" >/dev/null 2>"$WORK_DIR/notary.err"; then- echo "notarytool: $(tail -n 1 "$WORK_DIR/notary.err")" >&2+if ! signing_run "Check notarization authentication" xcrun notarytool history "${NOTARY_AUTH[@]}"; thenfail "the notary service does not accept $NOTARY_WHAT"fiecho "==> The notary service accepts $NOTARY_WHAT"diff --git a/ci/macos-notarize-local.sh b/ci/macos-notarize-local.shindex 7d5e74af..191df320 100755--- a/ci/macos-notarize-local.sh+++ b/ci/macos-notarize-local.sh@@ -1,17 +1,23 @@#!/bin/bash+set +xset -euo pipefail+. "$(dirname "$0")/macos-signing-log.sh"+APP_PATH=${1:?usage: macos-notarize-local.sh path/to/ThinkTerm.app [keychain-profile]}PROFILE=${2:-${MACOS_NOTARY_PROFILE:-thinkterm}}if [[ ! -d "$APP_PATH" ]]; then- echo "App bundle not found: ${APP_PATH}" >&2+ echo "error: App bundle not found; check the supplied bundle path." >&2exit 1fi-WORK_DIR=$(mktemp -d)-trap 'rm -rf "$WORK_DIR"' EXIT+WORK_DIR=$(mktemp -d 2>/dev/null) || {+ echo "error: Could not create the private notarization directory." >&2+ exit 1+}+trap 'rm -rf "$WORK_DIR" 2>/dev/null || echo "warning: Could not remove the private notarization directory." >&2' EXIT# Locally the credentials live in a keychain profile created once with# `notarytool store-credentials`. A CI runner has no such keychain, so prefer@@ -20,8 +26,11 @@ trap 'rm -rf "$WORK_DIR"' EXIT# person's Apple ID and can be revoked on its own; else an Apple ID with an# app-specific password.if [[ -n "${MACOS_NOTARY_KEY:-}" && -n "${MACOS_NOTARY_KEY_ID:-}" && -n "${MACOS_NOTARY_ISSUER:-}" ]]; then- KEY_FILE="$WORK_DIR/AuthKey_${MACOS_NOTARY_KEY_ID}.p8"- (umask 077 && printf '%s' "$MACOS_NOTARY_KEY" | base64 --decode >"$KEY_FILE")+ KEY_FILE="$WORK_DIR/notary-key.p8"+ if ! (umask 077 && printf '%s' "$MACOS_NOTARY_KEY" | base64 --decode >"$KEY_FILE") 2>/dev/null; then+ echo "error: Could not decode MACOS_NOTARY_KEY into the private key file." >&2+ exit 1+ fiNOTARY_AUTH=(--key "$KEY_FILE" --key-id "$MACOS_NOTARY_KEY_ID" --issuer "$MACOS_NOTARY_ISSUER")echo "==> Using an App Store Connect API key from the environment"elif [[ -n "${MACOS_APPLEID:-}" && -n "${MACOS_APP_PW:-}" && -n "${MACOS_TEAM_ID:-}" ]]; then@@ -29,7 +38,7 @@ elif [[ -n "${MACOS_APPLEID:-}" && -n "${MACOS_APP_PW:-}" && -n "${MACOS_TEAM_IDecho "==> Using notarization credentials from the environment"elseNOTARY_AUTH=(--keychain-profile "$PROFILE")- echo "==> Using notarization credentials from keychain profile '$PROFILE'"+ echo "==> Using notarization credentials from a keychain profile"fi# Notarization only accepts a container, never a bare .app, and it has to be@@ -38,26 +47,43 @@ fiSUBMISSION_ZIP="$WORK_DIR/submission.zip"RESULT_PLIST="$WORK_DIR/result.plist"-echo "==> Packing $APP_PATH for submission"-/usr/bin/ditto -c -k --keepParent "$APP_PATH" "$SUBMISSION_ZIP"+echo "==> Packing the app bundle for submission"+signing_run "Pack notarization submission" /usr/bin/ditto -c -k --keepParent "$APP_PATH" "$SUBMISSION_ZIP"echo "==> Submitting to Apple (this usually takes 1-5 minutes)"-xcrun notarytool submit "$SUBMISSION_ZIP" \+# A rejected submission may end notarytool with an error, yet the result still+# names the submission whose log says why: read the result first, and report+# the exit only when there is no result to read.+submit_exit=0+(umask 077; xcrun notarytool submit "$SUBMISSION_ZIP" \"${NOTARY_AUTH[@]}" \--wait \- --output-format plist >"$RESULT_PLIST"+ --output-format plist >"$RESULT_PLIST") 2>"$WORK_DIR/submit-diagnostic" || submit_exit=$?-status=$(plutil -extract status raw -o - "$RESULT_PLIST")-submission_id=$(plutil -extract id raw -o - "$RESULT_PLIST")-echo "==> Submission $submission_id finished with status: $status"+if ! status=$(plutil -extract status raw -o - "$RESULT_PLIST" 2>/dev/null) ||+ ! submission_id=$(plutil -extract id raw -o - "$RESULT_PLIST" 2>/dev/null); then+ if [[ "$submit_exit" -ne 0 ]]; then+ echo "error: Submit for notarization failed (exit $submit_exit)." >&2+ signing_error_reason "$WORK_DIR/submit-diagnostic" "$RESULT_PLIST"+ else+ echo "error: Could not read the notarization result; the service returned an unexpected response." >&2+ fi+ exit 1+fiif [[ "$status" != "Accepted" ]]; then- # The submit output only says Invalid; the per-issue reasons live in the log,- # which is the only thing that makes a rejection actionable.- echo "==> Notarization failed, fetching the log" >&2- xcrun notarytool log "$submission_id" "${NOTARY_AUTH[@]}" >&2 || true+ # Read the diagnostic privately and emit only recognized, fixed reasons and+ # the rejected files' names inside the bundle: never print the log itself.+ echo "error: Notarization was not accepted; checking the service diagnostics." >&2+ if signing_capture "Fetch notarization diagnostics" "$WORK_DIR/notary-log" \+ xcrun notarytool log "$submission_id" "${NOTARY_AUTH[@]}"; then+ signing_error_reason "$WORK_DIR/notary-log"+ signing_rejected_files "$WORK_DIR/notary-log" "$APP_PATH"+ fi+ echo " Apple's full report: find the submission with 'xcrun notarytool history' on your Mac, then run 'xcrun notarytool log <id>'." >&2exit 1fi+echo "==> Notarization accepted"# Apple recorded the result server-side; stapling copies that ticket into the# bundle so first launch does not depend on reaching Apple over the network.@@ -69,10 +95,15 @@ echo "==> Stapling the ticket into the bundle"staple_attempts=6attempt=1while true; do- if xcrun stapler staple "$APP_PATH"; then+ # Only the last attempt explains its failure: the ones before it are that+ # race, which a successful run should not log as errors.+ if [[ "$attempt" -lt "$staple_attempts" ]]; then+ if xcrun stapler staple "$APP_PATH" >/dev/null 2>&1; then+ break+ fi+ elif signing_run "Staple notarization ticket" xcrun stapler staple "$APP_PATH"; thenbreak- fi- if [[ "$attempt" -ge "$staple_attempts" ]]; then+ elseecho "==> Ticket still not available after ${staple_attempts} attempts" >&2exit 1fi@@ -82,11 +113,11 @@ while true; dodoneecho "==> Verifying"-xcrun stapler validate "$APP_PATH"-codesign --verify --deep --strict --verbose=2 "$APP_PATH"-spctl --assess --verbose=4 --type exec "$APP_PATH"+signing_run "Validate notarization ticket" xcrun stapler validate "$APP_PATH"+signing_run "Verify bundle signature" codesign --verify --deep --strict --verbose=2 "$APP_PATH"+signing_run "Assess Gatekeeper acceptance" spctl --assess --verbose=4 --type exec "$APP_PATH"echo-echo "Notarized and stapled: $APP_PATH"+echo "Notarized and stapled successfully."echo "Re-package it now -- the bundle gained a ticket, so any archive made"echo "before this point is the unstapled version."diff --git a/ci/macos-signing-log.sh b/ci/macos-signing-log.shnew file mode 100644index 00000000..28eb114a--- /dev/null+++ b/ci/macos-signing-log.sh@@ -0,0 +1,117 @@+#!/bin/bash++signing_mask() {+ if [[ "${GITHUB_ACTIONS:-}" == true ]]; then+ local value=$1+ value=${value//%/%25}+ value=${value//$'\r'/%0D}+ value=${value//$'\n'/%0A}+ printf '::add-mask::%s\n' "$value"+ fi+}++# Only fixed descriptions reach the log. Tool output can contain identities,+# paths and credentials, including on success, so never echo excerpts of it.+signing_error_reason() {+ local matched=no+ while IFS='|' read -r pattern message; do+ if LC_ALL=C grep -Eiq -- "$pattern" "$@" 2>/dev/null; then+ printf ' %s\n' "$message" >&2+ matched=yes+ fi+ done <<'REASONS'+HTTP[^0-9]*401|Authentication was rejected; check the notarization credentials.+HTTP[^0-9]*403|Access was denied; check the API key permissions and team membership.+unauthorized|Authentication was rejected; check the notarization credentials.+invalid credentials|Authentication was rejected; check the notarization credentials.+keychain password item.*not found|The notarization keychain profile is missing; configure the requested profile.+invalid (private )?key|The key or key identifier was rejected; check its format and credential configuration.+password.*incorrect|The password was rejected; check the certificate password or keychain credentials.+MAC verification failed|The certificate could not be decrypted; check its password and PKCS12 format.+no identity found|No matching signing identity was found; check the certificate and its private key.+item could not be found in the keychain|A required keychain item is missing; check the certificate and its private key.+private key.*not found|The signing private key is missing from the keychain.+certificate.*expired|The signing certificate has expired.+certificate.*revoked|The signing certificate has been revoked.+interaction is not allowed|Keychain access was denied; check that it is unlocked and allows codesign.+unable to build chain|The certificate trust chain is incomplete; check the signing certificate and intermediates.+not signed|A bundled executable is unsigned; check nested code signing.+signature.*invalid|A code signature is invalid; re-sign the complete bundle.+sealed resource|The signed bundle was modified or has missing resources; rebuild and re-sign it.+hardened runtime|Hardened Runtime is missing or invalid; check the signing options.+secure timestamp|A secure signing timestamp is missing or invalid.+SDK older|A bundled binary was built with an unsupported SDK; rebuild it with a supported SDK.+entitlement|The signing entitlements need attention.+timed? out|The request timed out; check connectivity and retry.+could not resolve|Name resolution failed; check connectivity and retry.+network|A network request failed; check connectivity and retry.+connection|A connection failed; check connectivity and retry.+service unavailable|The notarization service is unavailable; retry later.+ticket.*not found|The notarization ticket is not available yet; retry stapling after acceptance.+file does not exist|A required input or notarization ticket is missing.+permission denied|File or keychain access was denied; check access permissions.+Unsupported signing mode|MACOS_SIGNING_MODE has to be adhoc, development or developerid.+App bundle not found|The app bundle is missing; check the packaging step.+No ".*" certificate found|No matching certificate is in the keychain; create one at developer.apple.com or in Xcode.+More than one ".*" certificate|More than one matching certificate is in the keychain; set MACOS_SIGNING_IDENTITY to the one to use.+REASONS+ if [[ "$matched" == no ]]; then+ echo " No recognized diagnostic; check this step's inputs and tool availability. Raw output was withheld." >&2+ fi+}++# signing_rejected_files <notary log> <app bundle>+#+# Apple's notarization log names each rejected file by its path inside the+# submission. A path is shown only when it names a file shipped in the bundle,+# under Contents/ and without stepping out of it: those names are the app's+# own, public with it. Any other path is withheld.+signing_rejected_files() {+ local count i path seen=' ' withheld=0+ count=$(plutil -extract issues raw -o - "$1" 2>/dev/null) || return 0+ [[ "$count" =~ ^[0-9]+$ ]] || return 0+ for ((i = 0; i < count && i < 50; i++)); do+ path=$(plutil -extract "issues.$i.path" raw -o - "$1" 2>/dev/null) || continue+ path=${path#*.app/}+ if [[ "$path" =~ ^Contents(/[A-Za-z0-9_+-][A-Za-z0-9._+-]*)+$ && -e "$2/$path" ]]; then+ if [[ "$seen" != *" $path "* ]]; then+ seen+="$path "+ printf ' Rejected file: %s\n' "$path" >&2+ fi+ else+ withheld=$((withheld + 1))+ fi+ done+ if [[ "$withheld" -gt 0 ]]; then+ printf ' %s rejected file name(s) withheld.\n' "$withheld" >&2+ fi+}++# The optional output file is private scratch data for callers that need a+# plist, certificate or keychain path. It must never be uploaded or printed.+signing_capture() {+ local label=$1 output=$2 diagnostic result+ shift 2+ diagnostic=$(mktemp 2>/dev/null) || {+ echo "error: Could not create a private signing diagnostic file." >&2+ return 1+ }+ if [[ "$output" == /dev/null ]]; then+ if ("$@") >"$diagnostic" 2>&1; then result=0; else result=$?; fi+ else+ if (umask 077; "$@" >"$output") 2>"$diagnostic"; then result=0; else result=$?; fi+ fi+ if [[ "$result" -ne 0 ]]; then+ printf 'error: %s failed (exit %s).\n' "$label" "$result" >&2+ signing_error_reason "$diagnostic" "$output"+ fi+ rm -f "$diagnostic" 2>/dev/null ||+ echo "warning: Could not remove a private signing diagnostic file." >&2+ return "$result"+}++signing_run() {+ local label=$1+ shift+ signing_capture "$label" /dev/null "$@"+}diff --git a/ci/test_macos_signing_logs.py b/ci/test_macos_signing_logs.pynew file mode 100644index 00000000..d46d4728--- /dev/null+++ b/ci/test_macos_signing_logs.py@@ -0,0 +1,251 @@+#!/usr/bin/env python3+"""Exercise signing logs with fake tools and credentials, never a real keychain."""++import base64+from pathlib import Path+import subprocess+import sys+import tempfile+import unittest+++ROOT = Path(__file__).resolve().parents[1]+PAYLOAD = "Example Person /home/user/private [email protected] example-key-material"+MOCK = r'''+import json+import os+from pathlib import Path+import plistlib+import sys++tool = Path(sys.argv[0]).name+args = sys.argv[1:]+if tool == "sleep":+ sys.exit(0)+stage = tool + " " + " ".join(args[:2] if tool == "xcrun" else args[:1])+payload = os.environ["MOCK_PAYLOAD"]+home = Path(os.environ["HOME"])+print(payload, file=sys.stderr)+print(" ".join(args), file=sys.stderr)+if stage == os.environ.get("MOCK_FAIL_STAGE"):+ print(payload)+ print(os.environ.get("MOCK_REASON", "unrecognized example failure"), file=sys.stderr)+ sys.exit(42)+if stage == os.environ.get("MOCK_FAIL_ONCE") and not (home / "failed-once").exists():+ (home / "failed-once").touch()+ print(os.environ.get("MOCK_REASON", "unrecognized example failure"), file=sys.stderr)+ sys.exit(42)+if tool == "security" and args == ["default-keychain", "-d", "user"]:+ print('"/home/user/example.keychain"')+elif tool == "security" and args[0] == "create-keychain":+ (home / "created").touch()+elif tool == "security" and args[0] == "delete-keychain":+ # Like the real tool, deleting a keychain that was never made fails.+ if not (home / "created").exists():+ print("The specified keychain could not be found.", file=sys.stderr)+ sys.exit(50)+ (home / "deleted").touch()+elif tool == "security" and args[0] == "default-keychain" and args[-1] == "/home/user/example.keychain":+ Path(os.environ["HOME"], "restored").touch()+elif tool == "uuidgen":+ print("00000000-0000-0000-0000-000000000000")+elif tool == "codesign" and args[0] == "-dv":+ print("Authority=Developer ID Application: Example Person", file=sys.stderr)+elif tool == "xcrun" and args[:2] == ["notarytool", "submit"]:+ sys.stdout.buffer.write(plistlib.dumps({"status": os.environ.get("MOCK_STATUS", "Accepted"), "id": payload}))+ sys.exit(int(os.environ.get("MOCK_SUBMIT_EXIT", "0")))+elif tool == "xcrun" and args[:2] == ["notarytool", "log"]:+ bundle = "submission.zip/Example Person.app/"+ issue = {"severity": "error", "code": None, "message": os.environ.get("MOCK_REASON", "The signature is invalid.")}+ paths = [+ bundle + "Contents/MacOS/example", # shipped, so named+ bundle + "Contents/MacOS/example", # the same file's other architecture+ bundle + "Contents/" + payload,+ "../../home/user/private-note.txt",+ bundle + "Contents/MacOS/../../../home/user/private-note.txt",+ bundle + "Contents/../../bin/uuidgen", # exists, but outside the bundle+ bundle + "Contents/Resources/ExamplePerson.txt", # not in the bundle+ ]+ print(json.dumps({"status": "Invalid", "ticketContents": None,+ "issues": [{**issue, "path": path} for path in paths]}))+else:+ print(payload)+'''+++class SigningLogTests(unittest.TestCase):+ def setUp(self):+ self.directory = tempfile.TemporaryDirectory(prefix="tt-signing-", dir="/tmp")+ self.addCleanup(self.directory.cleanup)+ self.root = Path(self.directory.name)+ self.home = self.root / "home"+ self.scratch = self.root / "scratch"+ self.bin = self.root / "bin"+ for path in (self.home, self.scratch, self.bin):+ path.mkdir()+ for tool in ("security", "codesign", "uuidgen", "openssl", "xcrun", "spctl", "sleep"):+ path = self.bin / tool+ path.write_text("#!" + sys.executable + "\n" + MOCK)+ path.chmod(0o755)+ self.env = {+ "PATH": str(self.bin) + ":/usr/bin:/bin",+ "HOME": str(self.home),+ "TMPDIR": str(self.scratch),+ "MOCK_PAYLOAD": PAYLOAD,+ }+ self.credentials = {+ "MACOS_CERT": base64.b64encode(b"0example").decode(),+ "MACOS_CERT_PW": base64.b64encode(b"example-password").decode(),+ "MACOS_TEAM_ID": "EXAMPLE123",+ "MACOS_NOTARY_KEY": base64.b64encode(b"-----BEGIN PRIVATE KEY-----\nexample\n").decode(),+ "MACOS_NOTARY_KEY_ID": "EXAMPLE1234",+ "MACOS_NOTARY_ISSUER": "00000000-0000-0000-0000-000000000000",+ }++ def run_script(self, name, *args, extra=None):+ return subprocess.run(+ ["/bin/bash", str(ROOT / "ci" / name), *map(str, args)],+ env={**self.env, **self.credentials, **(extra or {})},+ text=True, capture_output=True, timeout=30,+ )++ def assert_private(self, result):+ output = result.stdout + result.stderr+ for marker in ("Example Person", "/home/user", "[email protected]", "example-key-material", "example-password", "EXAMPLE123", str(self.root)):+ self.assertNotIn(marker, output)+ self.assertEqual(list(self.scratch.iterdir()), [])+ return output++ def clear_markers(self):+ for marker in ("created", "deleted", "restored", "failed-once"):+ (self.home / marker).unlink(missing_ok=True)++ def test_preflight_success_hides_success_output(self):+ result = self.run_script("macos-check-signing.sh")+ output = self.assert_private(result)+ self.assertEqual(result.returncode, 0, output)+ self.assertTrue((self.home / "restored").exists())+ self.assertTrue((self.home / "deleted").exists())++ def test_preflight_failures_keep_reason_and_cleanup(self):+ cases = [+ # (environment, expected reason, whether a keychain was made)+ ({"MACOS_TEAM_ID": "example"}, "MACOS_TEAM_ID is not a team ID", False),+ ({"MOCK_FAIL_STAGE": "security create-keychain", "MOCK_REASON": "permission denied"}, "access was denied", False),+ ({"MOCK_FAIL_STAGE": "security import", "MOCK_REASON": "MAC verification failed"}, "could not be decrypted", True),+ ({"MOCK_FAIL_STAGE": "codesign --keychain", "MOCK_REASON": "no identity found"}, "No matching signing identity", True),+ ({"MOCK_FAIL_STAGE": "xcrun notarytool history", "MOCK_REASON": "HTTP status code: 401"}, "Authentication was rejected", True),+ ({"MOCK_FAIL_STAGE": "xcrun notarytool history", "MOCK_REASON": "connection timed out"}, "request timed out", True),+ ({"MOCK_FAIL_STAGE": "xcrun notarytool history", "MOCK_REASON": "::error::" + PAYLOAD}, "No recognized diagnostic", True),+ ]+ for extra, expected, made in cases:+ with self.subTest(extra=extra):+ self.clear_markers()+ result = self.run_script("macos-check-signing.sh", extra=extra)+ output = self.assert_private(result)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn(expected, output)+ # Cleanup removes only what the run made, without a second error.+ self.assertNotIn("Remove signing keychain", output)+ self.assertEqual((self.home / "deleted").exists(), made)++ def app(self):+ app = self.root / "Example Person.app"+ (app / "Contents/MacOS").mkdir(parents=True, exist_ok=True)+ (app / "Contents/MacOS/example").write_text("example")+ return app++ def test_notarization_success_hides_ids_paths_and_verification_output(self):+ result = self.run_script("macos-notarize-local.sh", self.app())+ output = self.assert_private(result)+ self.assertEqual(result.returncode, 0, output)+ self.assertIn("Notarized and stapled successfully", output)++ def test_notarization_failures_are_classified(self):+ cases = [+ ({"MOCK_FAIL_STAGE": "xcrun notarytool submit", "MOCK_REASON": "HTTP status code: 403"}, "Access was denied"),+ ({"MOCK_STATUS": "Invalid", "MOCK_REASON": "The signature is invalid; hardened runtime is missing"}, "Hardened Runtime"),+ ({"MOCK_STATUS": PAYLOAD, "MOCK_REASON": PAYLOAD}, "No recognized diagnostic"),+ ({"MOCK_FAIL_STAGE": "xcrun stapler staple", "MOCK_REASON": "ticket not found"}, "ticket is not available"),+ ({"MOCK_FAIL_STAGE": "xcrun stapler validate", "MOCK_REASON": "signature invalid"}, "signature is invalid"),+ ({"MOCK_FAIL_STAGE": "codesign --verify", "MOCK_REASON": "sealed resource is missing"}, "missing resources"),+ ({"MOCK_FAIL_STAGE": "spctl --assess", "MOCK_REASON": PAYLOAD}, "Assess Gatekeeper acceptance"),+ ]+ for extra, expected in cases:+ with self.subTest(extra=extra):+ result = self.run_script("macos-notarize-local.sh", self.app(), extra=extra)+ output = self.assert_private(result)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn(expected, output)++ def test_notarization_rejection_names_only_shipped_files(self):+ # The submit itself may or may not fail on a rejected submission.+ for submit_exit in ("0", "1"):+ with self.subTest(submit_exit=submit_exit):+ result = self.run_script("macos-notarize-local.sh", self.app(), extra={+ "MOCK_STATUS": "Invalid", "MOCK_SUBMIT_EXIT": submit_exit, "MOCK_REASON": "The binary is not signed."})+ output = self.assert_private(result)+ self.assertNotEqual(result.returncode, 0)+ self.assertNotIn("Submit for notarization failed", output)+ self.assertIn("unsigned", output)+ self.assertEqual(output.count("Rejected file: Contents/MacOS/example\n"), 1, output)+ self.assertIn("5 rejected file name(s) withheld", output)+ for name in ("private-note", "uuidgen", "ExamplePerson"):+ self.assertNotIn(name, output)++ def test_notarization_staple_retry_logs_no_error(self):+ result = self.run_script("macos-notarize-local.sh", self.app(), extra={"MOCK_FAIL_ONCE": "xcrun stapler staple", "MOCK_REASON": "file does not exist"})+ output = self.assert_private(result)+ self.assertEqual(result.returncode, 0, output)+ self.assertIn("retrying", output)+ self.assertNotIn("error", output)++ def test_local_signing_failures_are_named(self):+ for mode, expected in (("typo", "MACOS_SIGNING_MODE has to be"), ("development", "No matching certificate")):+ with self.subTest(mode=mode):+ result = subprocess.run(+ ["/bin/bash", "-c", '. "$1"; signing_run "Sign app bundle" bash "$2" "$3" "$4"', "example",+ str(ROOT / "ci/macos-signing-log.sh"), str(ROOT / "ci/macos-sign-local.sh"), str(self.app()), mode],+ env={**self.env, **self.credentials}, text=True, capture_output=True, timeout=30,+ )+ output = self.assert_private(result)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn(expected, output)++ def test_deploy_failures_hide_output_and_clean_up(self):+ source = (ROOT / "ci/deploy.sh").read_text()+ # Execute the actual signing branch, stopping at a mocked error.+ # This avoids packaging or invoking the absolute codesign executable.+ branch = source.split(' elif [ -n "$MACOS_TEAM_ID" ] ; then\n', 1)[1].split(' else\n', 1)[0]+ cases = [+ # (failing stage, its output, expected reason, whether a keychain was made)+ ("security default-keychain", "permission denied", "access was denied", False),+ ("security import", "MAC verification failed", "could not be decrypted", True),+ ]+ for stage, reason, expected, made in cases:+ with self.subTest(stage=stage):+ self.clear_markers()+ result = subprocess.run(+ ["/bin/bash", "-c", 'set -e\n. "$1"\n' + branch, "example", str(ROOT / "ci/macos-signing-log.sh")],+ env={**self.env, **self.credentials, "MOCK_FAIL_STAGE": stage, "MOCK_REASON": reason},+ text=True, capture_output=True, timeout=30,+ )+ output = self.assert_private(result)+ self.assertEqual(result.returncode, 42, output)+ self.assertIn(expected, output)+ self.assertNotIn("Remove signing keychain", output)+ self.assertEqual((self.home / "restored").exists(), made)+ self.assertEqual((self.home / "deleted").exists(), made)++ def test_multiline_mask_is_one_workflow_command(self):+ result = subprocess.run(+ ["/bin/bash", "-c", '. "$1"; signing_mask "$2"', "example", str(ROOT / "ci/macos-signing-log.sh"), "example%\r\n::error::example"],+ env={**self.env, "GITHUB_ACTIONS": "true"}, text=True, capture_output=True, timeout=30,+ )+ self.assertEqual(result.returncode, 0)+ self.assertEqual(result.stdout, "::add-mask::example%25%0D%0A::error::example\n")+ self.assertEqual(result.stderr, "")+++if __name__ == "__main__":+ unittest.main()