Przeglądaj źródła

fix(deploy): preserve pre-existing service identities

root 3 miesięcy temu
rodzic
commit
6362e01f6d

+ 144 - 30
deploy/amd64-release/install.sh

@@ -47,6 +47,53 @@ json_string() {
   sed -n "s/^[[:space:]]*\"${key}\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$file" | head -n 1
 }
 
+safe_product_path() {
+  local kind="$1" path="$2" resolved
+  [[ "$path" == /* ]] || fail "non-absolute product path: $path"
+  resolved="$(realpath -m -s -- "$path")"
+  [[ "$resolved" == "$path" ]] || fail "unresolved product path rejected: $path -> $resolved"
+  case "$kind:$resolved" in
+    file:/usr/local/bin/hthd|file:/usr/local/bin/hthctl|file:/usr/local/bin/hth-capture|\
+    file:/etc/systemd/system/hthd.service|file:/etc/systemd/system/hthd@.service|\
+    file:/usr/lib/sysusers.d/hth.conf|file:/usr/lib/tmpfiles.d/hth.conf|\
+    config:/etc/hth/hthd.yaml|config:/etc/hth/release-metadata.json|\
+    config:/etc/hth/install-manifest.txt|\
+    config:/etc/hth/profiles/6400-control/profile.json|\
+    config:/etc/hth/profiles/prod2u-door-temp/profile.json|\
+    symlink:/etc/systemd/system/multi-user.target.wants/hthd.service|\
+    managed_tree:/run/hth|owned_dir:/etc/hth/profiles/prod2u-door-temp) return 0 ;;
+    file:/usr/local/share/hth/sdk/hth_sdk-*.whl)
+      [[ "${resolved#/usr/local/share/hth/sdk/}" != */* ]] ||
+        fail "nested SDK wheel path rejected: $resolved"
+      return 0
+      ;;
+    *) fail "product path outside upgrade allowlist: $kind $resolved" ;;
+  esac
+}
+
+remove_product_path() {
+  local kind="$1" path="$2"
+  safe_product_path "$kind" "$path"
+  case "$kind" in
+    file|config|symlink) rm -f -- "$path" ;;
+    managed_tree)
+      if [[ -e "$path" || -L "$path" ]]; then
+        rm -rf --one-file-system -- "$path"
+      fi
+      ;;
+    owned_dir) rmdir -- "$path" 2>/dev/null || true ;;
+    *) fail "unsupported product removal kind: $kind" ;;
+  esac
+}
+
+identity_allowed() {
+  case "$1:$2" in
+    created_account:hth|created_account:hth-observe|created_account:hth-control|\
+    created_group:hth|created_group:hth-observe|created_group:hth-control) return 0 ;;
+    *) fail "identity outside product allowlist: $1 $2" ;;
+  esac
+}
+
 [[ "$(uname -m)" == x86_64 ]] || fail "this release targets x86_64 Linux (found $(uname -m))"
 [[ "$(id -u)" -eq 0 ]] || fail "run as root, for example: sudo ./install.sh"
 [[ -f "$ROOT/RELEASE-METADATA.json" ]] || fail "package is missing RELEASE-METADATA.json"
@@ -58,15 +105,20 @@ case "$BACKEND" in mock|serial) ;; *) fail "--backend must be mock or serial" ;;
 if [[ "$BACKEND" == serial && ! -e "$SERIAL_PATH" ]]; then
   fail "serial device does not exist: $SERIAL_PATH"
 fi
-for command_name in realpath readlink sha256sum systemctl systemd-sysusers systemd-tmpfiles base64 find; do
+for command_name in realpath readlink sha256sum systemctl systemd-sysusers systemd-tmpfiles base64 find getent groupadd; do
   command -v "$command_name" >/dev/null 2>&1 || fail "required command is missing: $command_name"
 done
+shopt -s nullglob
+PACKAGE_WHEELS=("$ROOT"/sdk/*.whl)
+shopt -u nullglob
+[[ "${#PACKAGE_WHEELS[@]}" -eq 1 ]] || fail "package must contain exactly one Python SDK wheel"
+PACKAGE_WHEEL="${PACKAGE_WHEELS[0]}"
 for required in \
   "$ROOT/bin/hthd" "$ROOT/bin/hthctl" "$ROOT/bin/hth-capture" \
   "$ROOT/config/hthd.6400-mock.yaml" "$ROOT/config/hthd.6400-serial.yaml" \
   "$ROOT/service/hthd.service" "$ROOT/service/hth.conf" \
   "$ROOT/service/hthd-tmpfiles.conf" "$ROOT/profiles/6400-control/profile.json" \
-  "$ROOT/sdk"/*.whl "$ROOT/verify-install.sh"; do
+  "$PACKAGE_WHEEL" "$ROOT/verify-install.sh"; do
   [[ -f "$required" ]] || fail "package is incomplete: $required"
 done
 if [[ -f "$ROOT/SHA256SUMS" ]]; then
@@ -79,6 +131,7 @@ for absolute_dir in "$BINDIR" "$SHAREDIR" "$ETCDIR" "$UNITDIR" "$STATEDIR" "$RUN
 done
 
 INSTALLED_META="$ETCDIR/release-metadata.json"
+OLD_MANIFEST="$ETCDIR/install-manifest.txt"
 INSTALLED_VERSION=""
 INSTALLED_COMMIT=""
 if [[ -f "$INSTALLED_META" ]]; then
@@ -90,6 +143,51 @@ for path in "$BINDIR/hthd" "$UNITDIR/hthd.service" "$ETCDIR/hthd.yaml"; do
   [[ -e "$path" || -L "$path" ]] && FOOTPRINT=1
 done
 
+IDENTITY_NAMES=(hth hth-observe hth-control)
+declare -A PREEXISTING_ACCOUNTS=()
+declare -A PREEXISTING_GROUPS=()
+declare -A OWNED_ACCOUNTS=()
+declare -A OWNED_GROUPS=()
+declare -a OWNED_WHEELS=()
+for identity_name in "${IDENTITY_NAMES[@]}"; do
+  if getent passwd "$identity_name" >/dev/null 2>&1; then
+    PREEXISTING_ACCOUNTS["$identity_name"]=1
+  else
+    PREEXISTING_ACCOUNTS["$identity_name"]=0
+  fi
+  if getent group "$identity_name" >/dev/null 2>&1; then
+    PREEXISTING_GROUPS["$identity_name"]=1
+  else
+    PREEXISTING_GROUPS["$identity_name"]=0
+  fi
+done
+if [[ -f "$OLD_MANIFEST" ]]; then
+  while read -r old_kind old_value old_extra; do
+    [[ -z "$old_kind" || "$old_kind" == \#* ]] && continue
+    case "$old_kind" in
+      created_account)
+        [[ -n "$old_value" && -z "${old_extra:-}" ]] || fail "malformed created_account in old manifest"
+        identity_allowed "$old_kind" "$old_value"
+        OWNED_ACCOUNTS["$old_value"]=1
+        ;;
+      created_group)
+        [[ -n "$old_value" && -z "${old_extra:-}" ]] || fail "malformed created_group in old manifest"
+        identity_allowed "$old_kind" "$old_value"
+        OWNED_GROUPS["$old_value"]=1
+        ;;
+      file)
+        case "$old_value" in
+          "$SHAREDIR"/sdk/hth_sdk-*.whl)
+            [[ -z "${old_extra:-}" ]] || fail "malformed SDK wheel in old manifest"
+            safe_product_path file "$old_value"
+            OWNED_WHEELS+=("$old_value")
+            ;;
+        esac
+        ;;
+    esac
+  done <"$OLD_MANIFEST"
+fi
+
 ACTION=install
 FROM_VERSION=none
 PRESERVE_CONFIG=0
@@ -121,22 +219,20 @@ if systemctl is-active --quiet "$SERVICE"; then
 fi
 
 if [[ "$ACTION" == upgrade ]]; then
-  rm -f -- \
-    "$BINDIR/hthd" "$BINDIR/hthctl" "$BINDIR/hth-capture" \
-    "$UNITDIR/hthd.service" "$UNITDIR/hthd@.service" \
-    "$UNITDIR/multi-user.target.wants/hthd.service" \
-    "$LIBDIR/sysusers.d/hth.conf" "$LIBDIR/tmpfiles.d/hth.conf"
-  rm -f -- \
-    "$ETCDIR/hthd.yaml" "$ETCDIR/release-metadata.json" \
-    "$ETCDIR/install-manifest.txt" \
-    "$ETCDIR/profiles/prod2u-door-temp/profile.json" \
-    "$ETCDIR/profiles/6400-control/profile.json"
-  rmdir "$ETCDIR/profiles/prod2u-door-temp" 2>/dev/null || true
-  if [[ -d "$RUNDIR" ]]; then
-    resolved="$(realpath -m -s -- "$RUNDIR")"
-    [[ "$resolved" == /run/hth ]] || fail "unsafe runtime path during upgrade: $resolved"
-    rm -rf --one-file-system -- "$resolved"
-  fi
+  for path in "$BINDIR/hthd" "$BINDIR/hthctl" "$BINDIR/hth-capture" \
+              "$UNITDIR/hthd.service" "$UNITDIR/hthd@.service" \
+              "$LIBDIR/sysusers.d/hth.conf" "$LIBDIR/tmpfiles.d/hth.conf"; do
+    remove_product_path file "$path"
+  done
+  remove_product_path symlink "$UNITDIR/multi-user.target.wants/hthd.service"
+  for path in "$ETCDIR/hthd.yaml" "$ETCDIR/release-metadata.json" \
+              "$ETCDIR/install-manifest.txt" \
+              "$ETCDIR/profiles/prod2u-door-temp/profile.json" \
+              "$ETCDIR/profiles/6400-control/profile.json"; do
+    remove_product_path config "$path"
+  done
+  remove_product_path owned_dir "$ETCDIR/profiles/prod2u-door-temp"
+  remove_product_path managed_tree "$RUNDIR"
   systemctl daemon-reload
 fi
 
@@ -151,8 +247,8 @@ install -m 0644 "$ROOT/service/hth.conf" "$LIBDIR/sysusers.d/hth.conf"
 install -m 0644 "$ROOT/service/hthd-tmpfiles.conf" "$LIBDIR/tmpfiles.d/hth.conf"
 install -m 0644 "$ROOT/RELEASE-METADATA.json" "$ETCDIR/release-metadata.json"
 install -m 0644 "$ROOT/profiles/6400-control/profile.json" "$ETCDIR/profiles/6400-control/profile.json"
-rm -f -- "$SHAREDIR/sdk"/*.whl
-install -m 0644 "$ROOT"/sdk/*.whl "$SHAREDIR/sdk/"
+for path in "${OWNED_WHEELS[@]}"; do remove_product_path file "$path"; done
+install -m 0644 "$PACKAGE_WHEEL" "$SHAREDIR/sdk/"
 
 if [[ "$PRESERVE_CONFIG" -eq 0 || ! -f "$ETCDIR/hthd.yaml" ]]; then
   template="$ROOT/config/hthd.6400-${BACKEND}.yaml"
@@ -166,6 +262,18 @@ if [[ "$PRESERVE_CONFIG" -eq 0 || ! -f "$ETCDIR/hthd.yaml" ]]; then
   install -m 0640 "$temp_config" "$ETCDIR/hthd.yaml"
 fi
 
+getent group dialout >/dev/null 2>&1 || groupadd --system dialout
+systemd-sysusers "$LIBDIR/sysusers.d/hth.conf"
+for identity_name in "${IDENTITY_NAMES[@]}"; do
+  if [[ "${PREEXISTING_ACCOUNTS[$identity_name]}" -eq 0 ]] && getent passwd "$identity_name" >/dev/null 2>&1; then
+    OWNED_ACCOUNTS["$identity_name"]=1
+  fi
+  if [[ "${PREEXISTING_GROUPS[$identity_name]}" -eq 0 ]] && getent group "$identity_name" >/dev/null 2>&1; then
+    OWNED_GROUPS["$identity_name"]=1
+  fi
+done
+systemd-tmpfiles --create "$LIBDIR/tmpfiles.d/hth.conf"
+
 cat >"$ETCDIR/install-manifest.txt" <<EOF
 # HTH owned paths; generated by ${VERSION} (${SOURCE_COMMIT})
 file $BINDIR/hthd
@@ -175,7 +283,7 @@ file $UNITDIR/hthd.service
 symlink $UNITDIR/multi-user.target.wants/hthd.service
 file $LIBDIR/sysusers.d/hth.conf
 file $LIBDIR/tmpfiles.d/hth.conf
-file $SHAREDIR/sdk/$(basename "$ROOT"/sdk/*.whl)
+file $SHAREDIR/sdk/$(basename "$PACKAGE_WHEEL")
 config $ETCDIR/hthd.yaml
 config $ETCDIR/release-metadata.json
 config $ETCDIR/install-manifest.txt
@@ -185,18 +293,24 @@ managed_tree $RUNDIR
 managed_tree $STATEDIR/captures
 managed_tree $STATEDIR/replay
 managed_tree $STATEDIR/receipts
-account hth
-account hth-observe
-account hth-control
-group hth
-group hth-observe
-group hth-control
+owned_dir $SHAREDIR/sdk
+owned_dir $SHAREDIR
+owned_dir $ETCDIR/profiles/6400-control
+owned_dir $ETCDIR/profiles/prod2u-door-temp
+owned_dir $ETCDIR/profiles
+owned_dir $ETCDIR
+owned_dir $STATEDIR
 EOF
+for identity_name in "${IDENTITY_NAMES[@]}"; do
+  if [[ "${OWNED_ACCOUNTS[$identity_name]:-0}" -eq 1 ]]; then
+    echo "created_account $identity_name" >>"$ETCDIR/install-manifest.txt"
+  fi
+  if [[ "${OWNED_GROUPS[$identity_name]:-0}" -eq 1 ]]; then
+    echo "created_group $identity_name" >>"$ETCDIR/install-manifest.txt"
+  fi
+done
 chmod 0644 "$ETCDIR/install-manifest.txt"
 
-getent group dialout >/dev/null 2>&1 || groupadd --system dialout
-systemd-sysusers "$LIBDIR/sysusers.d/hth.conf"
-systemd-tmpfiles --create "$LIBDIR/tmpfiles.d/hth.conf"
 chown root:hth "$ETCDIR" "$ETCDIR/hthd.yaml" "$ETCDIR/profiles" "$ETCDIR/profiles/6400-control" 2>/dev/null || true
 chown hth:hth "$STATEDIR" "$STATEDIR/captures" "$STATEDIR/replay" "$STATEDIR/receipts" 2>/dev/null || true
 chmod 0750 "$ETCDIR" "$ETCDIR/profiles" "$ETCDIR/profiles/6400-control"

+ 88 - 26
deploy/amd64-release/uninstall.sh

@@ -39,21 +39,61 @@ safe_path() {
   [[ "$resolved" == "$path" ]] || { echo "uninstall: unresolved path rejected: $path -> $resolved" >&2; return 1; }
   case "$kind:$resolved" in
     file:/usr/local/bin/hthd|file:/usr/local/bin/hthctl|file:/usr/local/bin/hth-capture|\
-    file:/etc/systemd/system/hthd.service|file:/usr/lib/sysusers.d/hth.conf|\
-    file:/usr/lib/tmpfiles.d/hth.conf|file:/usr/local/share/hth/sdk/hth_sdk-*.whl|\
+    file:/etc/systemd/system/hthd.service|file:/etc/systemd/system/hthd@.service|\
+    file:/usr/lib/sysusers.d/hth.conf|\
+    file:/usr/lib/tmpfiles.d/hth.conf|\
     config:/etc/hth/hthd.yaml|config:/etc/hth/release-metadata.json|\
     config:/etc/hth/install-manifest.txt|config:/etc/hth/profiles/6400-control/profile.json|\
     config:/etc/hth/profiles/prod2u-door-temp/profile.json|\
     symlink:/etc/systemd/system/multi-user.target.wants/hthd.service|\
     managed_tree:/run/hth|managed_tree:/var/lib/hth/captures|\
-    managed_tree:/var/lib/hth/replay|managed_tree:/var/lib/hth/receipts) return 0 ;;
+    managed_tree:/var/lib/hth/replay|managed_tree:/var/lib/hth/receipts|\
+    owned_dir:/usr/local/share/hth/sdk|owned_dir:/usr/local/share/hth|\
+    owned_dir:/etc/hth/profiles/6400-control|\
+    owned_dir:/etc/hth/profiles/prod2u-door-temp|owned_dir:/etc/hth/profiles|\
+    owned_dir:/etc/hth|owned_dir:/var/lib/hth) return 0 ;;
+    file:/usr/local/share/hth/sdk/hth_sdk-*.whl)
+      [[ "${resolved#/usr/local/share/hth/sdk/}" != */* ]] || {
+        echo "uninstall: nested SDK wheel path rejected: $resolved" >&2
+        return 1
+      }
+      return 0
+      ;;
     *) echo "uninstall: manifest path outside product allowlist: $kind $resolved" >&2; return 1 ;;
   esac
 }
 
+remove_owned_path() {
+  local kind="$1" path="$2"
+  safe_path "$kind" "$path" || return 1
+  case "$kind" in
+    file|config|symlink) rm -f -- "$path" ;;
+    managed_tree)
+      if [[ -e "$path" || -L "$path" ]]; then
+        rm -rf --one-file-system -- "$path"
+      fi
+      ;;
+    owned_dir)
+      # Product-owned roots are never recursively removed. Unknown content keeps
+      # the directory in place and cannot be mistaken for an HTH-owned tree.
+      rmdir -- "$path" 2>/dev/null || true
+      ;;
+    *) echo "uninstall: unsupported removal kind: $kind" >&2; return 1 ;;
+  esac
+}
+
+identity_allowed() {
+  case "$1:$2" in
+    created_account:hth|created_account:hth-observe|created_account:hth-control|\
+    created_group:hth|created_group:hth-observe|created_group:hth-control) return 0 ;;
+    *) echo "uninstall: identity outside product allowlist: $1 $2" >&2; return 1 ;;
+  esac
+}
+
 declare -a FILES=(
   "$BINDIR/hthd" "$BINDIR/hthctl" "$BINDIR/hth-capture"
-  "$UNITDIR/hthd.service" "$UNITDIR/multi-user.target.wants/hthd.service"
+  "$UNITDIR/hthd.service" "$UNITDIR/hthd@.service"
+  "$UNITDIR/multi-user.target.wants/hthd.service"
   "$LIBDIR/sysusers.d/hth.conf" "$LIBDIR/tmpfiles.d/hth.conf"
 )
 declare -a CONFIGS=(
@@ -61,20 +101,41 @@ declare -a CONFIGS=(
   "$ETCDIR/profiles/6400-control/profile.json" "$ETCDIR/profiles/prod2u-door-temp/profile.json"
 )
 declare -a TREES=("$RUNDIR" "$STATEDIR/captures" "$STATEDIR/replay" "$STATEDIR/receipts")
+declare -a OWNED_DIRS=("$SHAREDIR/sdk" "$SHAREDIR")
+declare -a PURGE_OWNED_DIRS=(
+  "$ETCDIR/profiles/6400-control" "$ETCDIR/profiles/prod2u-door-temp"
+  "$ETCDIR/profiles" "$ETCDIR" "$STATEDIR"
+)
+declare -a CREATED_ACCOUNTS=()
+declare -a CREATED_GROUPS=()
 
 if [[ -f "$MANIFEST" ]]; then
   while read -r kind path extra; do
     [[ -z "$kind" || "$kind" == \#* ]] && continue
     [[ -n "$path" && -z "${extra:-}" ]] || { echo "uninstall: malformed manifest line: $kind $path ${extra:-}" >&2; exit 1; }
     case "$kind" in
-      file|config|symlink|managed_tree) safe_path "$kind" "$path" || exit 1 ;;
-      account|group) [[ "$path" == hth || "$path" == hth-observe || "$path" == hth-control ]] || exit 1; continue ;;
+      file|config|symlink|managed_tree|owned_dir) safe_path "$kind" "$path" || exit 1 ;;
+      created_account|created_group) identity_allowed "$kind" "$path" || exit 1 ;;
+      account|group)
+        # Legacy manifests did not record whether an identity predated HTH.
+        # Keep it rather than guessing ownership.
+        [[ "$path" == hth || "$path" == hth-observe || "$path" == hth-control ]] || exit 1
+        continue
+        ;;
       *) echo "uninstall: unknown manifest kind: $kind" >&2; exit 1 ;;
     esac
     case "$kind" in
       file|symlink) FILES+=("$path") ;;
       config) CONFIGS+=("$path") ;;
       managed_tree) TREES+=("$path") ;;
+      owned_dir)
+        case "$path" in
+          "$SHAREDIR"|"$SHAREDIR/sdk") OWNED_DIRS+=("$path") ;;
+          *) PURGE_OWNED_DIRS+=("$path") ;;
+        esac
+        ;;
+      created_account) CREATED_ACCOUNTS+=("$path") ;;
+      created_group) CREATED_GROUPS+=("$path") ;;
     esac
   done <"$MANIFEST"
 fi
@@ -88,38 +149,27 @@ fi
 
 for path in "${FILES[@]}"; do
   case "$path" in
-    "$BINDIR"/*) safe_path file "$path" ;;
-    "$UNITDIR"/multi-user.target.wants/*) safe_path symlink "$path" ;;
-    *) safe_path file "$path" ;;
+    "$UNITDIR"/multi-user.target.wants/*) remove_owned_path symlink "$path" ;;
+    *) remove_owned_path file "$path" ;;
   esac
-  rm -f -- "$path"
 done
-rm -f -- "$UNITDIR/hthd@.service"
 systemctl daemon-reload >/dev/null 2>&1 || true
 
 if [[ "$PURGE" -eq 1 ]]; then
-  for path in "${CONFIGS[@]}"; do safe_path config "$path"; rm -f -- "$path"; done
-  for path in "${TREES[@]}"; do
-    safe_path managed_tree "$path"
-    if [[ -d "$path" ]]; then rm -rf --one-file-system -- "$path"; fi
-  done
-  rmdir "$ETCDIR/profiles/6400-control" "$ETCDIR/profiles/prod2u-door-temp" \
-        "$ETCDIR/profiles" "$ETCDIR" 2>/dev/null || true
-  rmdir "$STATEDIR" 2>/dev/null || true
-  for account_name in hth hth-control hth-observe; do
+  for path in "${CONFIGS[@]}"; do remove_owned_path config "$path"; done
+  for path in "${TREES[@]}"; do remove_owned_path managed_tree "$path"; done
+  for path in "${PURGE_OWNED_DIRS[@]}"; do remove_owned_path owned_dir "$path"; done
+  for account_name in "${CREATED_ACCOUNTS[@]}"; do
     if getent passwd "$account_name" >/dev/null 2>&1; then userdel "$account_name"; fi
   done
-  for group_name in hth-control hth-observe hth; do
+  for group_name in "${CREATED_GROUPS[@]}"; do
     if getent group "$group_name" >/dev/null 2>&1; then groupdel "$group_name"; fi
   done
 fi
-rmdir "$SHAREDIR/sdk" "$SHAREDIR" 2>/dev/null || true
+for path in "${OWNED_DIRS[@]}"; do remove_owned_path owned_dir "$path"; done
 
 failures=0
-for path in "$BINDIR/hthd" "$BINDIR/hthctl" "$BINDIR/hth-capture" \
-            "$UNITDIR/hthd.service" "$UNITDIR/hthd@.service" \
-            "$UNITDIR/multi-user.target.wants/hthd.service" \
-            "$LIBDIR/sysusers.d/hth.conf" "$LIBDIR/tmpfiles.d/hth.conf"; do
+for path in "${FILES[@]}"; do
   if [[ -e "$path" || -L "$path" ]]; then echo "uninstall residual: $path" >&2; failures=1; fi
 done
 for proc_dir in /proc/[0-9]*; do
@@ -136,6 +186,18 @@ if [[ "$PURGE" -eq 1 ]]; then
               "$STATEDIR/captures" "$STATEDIR/replay" "$STATEDIR/receipts"; do
     if [[ -e "$path" || -L "$path" ]]; then echo "purge residual: $path" >&2; failures=1; fi
   done
+  for account_name in "${CREATED_ACCOUNTS[@]}"; do
+    if getent passwd "$account_name" >/dev/null 2>&1; then
+      echo "purge residual: created account $account_name" >&2
+      failures=1
+    fi
+  done
+  for group_name in "${CREATED_GROUPS[@]}"; do
+    if getent group "$group_name" >/dev/null 2>&1; then
+      echo "purge residual: created group $group_name" >&2
+      failures=1
+    fi
+  done
 fi
 [[ "$failures" -eq 0 ]] || exit 1
 echo "HTH_UNINSTALL_PASS purge=$PURGE residual_conflicts=0"

+ 29 - 0
tools/run_amd64_release_matrix.sh

@@ -69,6 +69,34 @@ run_guest SCENARIO_PURGE_REINSTALL '
   ./install.sh
   ./verify-install.sh --no-escalate
 '
+run_guest SCENARIO_PREEXISTING_IDENTITIES '
+  set -e
+  cd /opt/matrix/new/*
+  ./uninstall.sh --purge --yes
+  for identity_name in hth hth-observe hth-control; do
+    groupadd --system "$identity_name"
+    if [ "$identity_name" = hth ]; then identity_home=/var/lib/hth; else identity_home=/nonexistent; fi
+    useradd --system --gid "$identity_name" --home-dir "$identity_home" \
+      --shell /usr/sbin/nologin --no-create-home "$identity_name"
+  done
+  identity_snapshot() {
+    for identity_name in hth hth-observe hth-control; do
+      printf "%s:%s:%s\n" "$identity_name" "$(id -u "$identity_name")" \
+        "$(getent group "$identity_name" | cut -d: -f3)"
+    done
+  }
+  identities_before="$(identity_snapshot)"
+  ./install.sh
+  if grep -Eq "^created_(account|group) (hth|hth-observe|hth-control)$" /etc/hth/install-manifest.txt; then
+    echo "pre-existing identity was incorrectly claimed by HTH" >&2
+    exit 1
+  fi
+  ./uninstall.sh --purge --yes
+  identities_after="$(identity_snapshot)"
+  [ "$identities_before" = "$identities_after" ]
+  for identity_name in hth hth-observe hth-control; do userdel "$identity_name"; done
+  for identity_name in hth-control hth-observe hth; do groupdel "$identity_name"; done
+'
 run_guest SCENARIO_UPGRADE '
   set -e
   cd /opt/matrix/new/*
@@ -120,6 +148,7 @@ run_guest SCENARIO_UPGRADE_FROM_FAILED_OLD '
   echo "fresh_install=PASS"
   echo "same_version_reinstall=PASS"
   echo "purge_reinstall=PASS"
+  echo "preexisting_identity_preservation=PASS"
   echo "previous_release_upgrade=PASS"
   echo "upgrade_from_failed_previous_install=PASS"
   echo "hardware_validation=NOT RUN"

+ 123 - 0
tools/test_amd64_release_script_safety.py

@@ -0,0 +1,123 @@
+from __future__ import annotations
+
+import re
+import subprocess
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+INSTALL = ROOT / "deploy" / "amd64-release" / "install.sh"
+UNINSTALL = ROOT / "deploy" / "amd64-release" / "uninstall.sh"
+MATRIX = ROOT / "tools" / "run_amd64_release_matrix.sh"
+
+
+def _text(path: Path) -> str:
+    return path.read_text(encoding="utf-8")
+
+
+def _assert_removals_are_inside_helper(
+    script: Path, helper: str, next_helper: str, allowed_outside: tuple[str, ...] = ()
+) -> None:
+    source = _text(script)
+    helper_start = source.index(f"{helper}() {{")
+    helper_end = source.index(f"\n{next_helper}() {{", helper_start)
+    offset = 0
+    for line_number, line in enumerate(source.splitlines(keepends=True), start=1):
+        stripped = line.lstrip()
+        if not stripped.startswith("#") and re.search(r"(?<![A-Za-z0-9_])(rm|rmdir)\s", line):
+            inside = helper_start <= offset < helper_end
+            explicitly_allowed = any(fragment in line for fragment in allowed_outside)
+            assert inside or explicitly_allowed, (
+                f"unguarded removal in {script.name}:{line_number}: {line.rstrip()}"
+            )
+        offset += len(line)
+
+
+def test_release_shell_entrypoints_parse() -> None:
+    for script in (INSTALL, UNINSTALL, MATRIX):
+        subprocess.run(["bash", "-n", str(script)], check=True)
+
+
+def test_uninstall_allowlist_covers_every_owned_target_type() -> None:
+    source = _text(UNINSTALL)
+    expected = {
+        "file:/usr/local/bin/hthd",
+        "file:/usr/local/bin/hthctl",
+        "file:/usr/local/bin/hth-capture",
+        "file:/etc/systemd/system/hthd.service",
+        "file:/etc/systemd/system/hthd@.service",
+        "file:/usr/lib/sysusers.d/hth.conf",
+        "file:/usr/lib/tmpfiles.d/hth.conf",
+        "file:/usr/local/share/hth/sdk/hth_sdk-*.whl",
+        "config:/etc/hth/hthd.yaml",
+        "config:/etc/hth/release-metadata.json",
+        "config:/etc/hth/install-manifest.txt",
+        "config:/etc/hth/profiles/6400-control/profile.json",
+        "config:/etc/hth/profiles/prod2u-door-temp/profile.json",
+        "symlink:/etc/systemd/system/multi-user.target.wants/hthd.service",
+        "managed_tree:/run/hth",
+        "managed_tree:/var/lib/hth/captures",
+        "managed_tree:/var/lib/hth/replay",
+        "managed_tree:/var/lib/hth/receipts",
+        "owned_dir:/usr/local/share/hth/sdk",
+        "owned_dir:/usr/local/share/hth",
+        "owned_dir:/etc/hth/profiles/6400-control",
+        "owned_dir:/etc/hth/profiles/prod2u-door-temp",
+        "owned_dir:/etc/hth/profiles",
+        "owned_dir:/etc/hth",
+        "owned_dir:/var/lib/hth",
+    }
+    missing = sorted(entry for entry in expected if entry not in source)
+    assert not missing, f"uninstall allowlist is missing: {missing}"
+    assert 'resolved="$(realpath -m -s -- "$path")"' in source
+    assert '[[ "$resolved" == "$path" ]]' in source
+    assert '${resolved#/usr/local/share/hth/sdk/}' in source
+    assert '!= */*' in source
+
+
+def test_product_removals_use_the_guarded_dispatchers() -> None:
+    _assert_removals_are_inside_helper(UNINSTALL, "remove_owned_path", "identity_allowed")
+    _assert_removals_are_inside_helper(
+        INSTALL,
+        "remove_product_path",
+        "identity_allowed",
+        allowed_outside=('temp_config:-',),
+    )
+    assert 'rm -f -- "$SHAREDIR/sdk"/*.whl' not in _text(INSTALL)
+
+
+def test_manifest_records_only_created_identity_ownership() -> None:
+    install = _text(INSTALL)
+    marker = 'cat >"$ETCDIR/install-manifest.txt" <<EOF'
+    manifest = install.split(marker, 1)[1].split("\nEOF", 1)[0]
+    assert "\naccount " not in manifest
+    assert "\ngroup " not in manifest
+    assert 'echo "created_account $identity_name"' in install
+    assert 'echo "created_group $identity_name"' in install
+    assert 'OWNED_ACCOUNTS["$old_value"]=1' in install
+    assert 'OWNED_GROUPS["$old_value"]=1' in install
+
+
+def test_purge_deletes_only_manifest_claimed_identities() -> None:
+    uninstall = _text(UNINSTALL)
+    assert 'created_account) CREATED_ACCOUNTS+=("$path")' in uninstall
+    assert 'created_group) CREATED_GROUPS+=("$path")' in uninstall
+    assert 'for account_name in "${CREATED_ACCOUNTS[@]}"' in uninstall
+    assert 'for group_name in "${CREATED_GROUPS[@]}"' in uninstall
+    assert "for account_name in hth hth-control hth-observe" not in uninstall
+    assert "for group_name in hth-control hth-observe hth" not in uninstall
+    for line in uninstall.splitlines():
+        if "userdel " in line:
+            assert 'userdel "$account_name"' in line
+        if "groupdel " in line:
+            assert 'groupdel "$group_name"' in line
+
+
+def test_matrix_preserves_preexisting_identities() -> None:
+    matrix = _text(MATRIX)
+    assert "SCENARIO_PREEXISTING_IDENTITIES" in matrix
+    assert 'identities_before="$(identity_snapshot)"' in matrix
+    assert 'identities_after="$(identity_snapshot)"' in matrix
+    assert '[ "$identities_before" = "$identities_after" ]' in matrix
+    assert "pre-existing identity was incorrectly claimed by HTH" in matrix
+    assert "preexisting_identity_preservation=PASS" in matrix