Просмотр исходного кода

增加 inotify 事件驱动防篡改同步

发布器改为事件驱动:内网文件变化只同步对应路径,删除文件通过受限 rsync 移入外网隔离区;每小时执行全量 xxh128 对账作为兜底。\n\n增加目录事件回退、事件批处理锁、inotify 存活检查和 systemd 文件句柄限制。

Validation:\n- publisher 脚本通过 bash -n\n- targeted delete + backup 语义已通过真实受限 rrsync 通道验证\n- 基线 dry-run 文件级计划变更数为 0
非繁 2 недель назад
Родитель
Сommit
8e2834d04d

+ 1 - 1
local-run/anti-tamper/README.md

@@ -13,7 +13,7 @@
 
 ```bash
 zq-artifact-publisher.sh once    # 单次同步
-zq-artifact-publisher.sh watch   # 持续同步
+zq-artifact-publisher.sh watch   # inotify 事件同步 + 每小时全量对账
 ```
 
 安全开关:

+ 2 - 1
local-run/anti-tamper/zq-artifact-publisher.service

@@ -8,9 +8,10 @@ Conflicts=zq-upload-sync.service
 Type=simple
 User=root
 Group=root
-Environment=ZQ_SYNC_INTERVAL=5
+Environment=ZQ_EVENT_DEBOUNCE=2
 Environment=ZQ_FULL_CHECK_INTERVAL=3600
 Environment=ZQ_DRY_RUN=0
+LimitNOFILE=65536
 ExecStart=/usr/local/sbin/zq-artifact-publisher.sh watch
 Restart=always
 RestartSec=5

+ 220 - 17
local-run/anti-tamper/zq-artifact-publisher.sh

@@ -11,21 +11,28 @@ STATE_DIR="${ZQ_ANTITAMPER_STATE_DIR:-/var/lib/zq-antitamper}"
 LOG="${ZQ_ANTITAMPER_LOG:-/var/log/zq-artifact-publisher.log}"
 STATUS="${ZQ_ANTITAMPER_STATUS:-/run/zq-artifact-publisher.status}"
 LOCK_FILE="${ZQ_ANTITAMPER_LOCK:-/run/zq-artifact-publisher.lock}"
-SYNC_INTERVAL="${ZQ_SYNC_INTERVAL:-5}"
+EVENT_QUEUE="${ZQ_EVENT_QUEUE:-/run/zq-artifact-events.queue}"
+EVENT_LOCK="${ZQ_EVENT_LOCK:-/run/zq-artifact-events.lock}"
+EVENT_DEBOUNCE="${ZQ_EVENT_DEBOUNCE:-2}"
 FULL_CHECK_INTERVAL="${ZQ_FULL_CHECK_INTERVAL:-3600}"
 TRANSACTION_RETENTION_DAYS="${ZQ_TRANSACTION_RETENTION_DAYS:-14}"
 DRY_RUN="${ZQ_DRY_RUN:-0}"
 FORCE_CHECKSUM="${ZQ_FORCE_CHECKSUM:-0}"
+WATCH_PID=""
 
 SSH_CMD="ssh -i ${SSH_KEY} -o BatchMode=yes -o StrictHostKeyChecking=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=3"
-mkdir -p "${STATE_DIR}/transactions" "$(dirname "${LOG}")"
+mkdir -p "${STATE_DIR}/transactions" "${STATE_DIR}/events" "$(dirname "${LOG}")"
+: > "${EVENT_QUEUE}"
 
+exec 8>"${EVENT_LOCK}"
 exec 9>"${LOCK_FILE}"
 flock -n 9 || {
     printf '%s another publisher is already running\n' "$(date '+%F %T')" >> "${LOG}"
     exit 0
 }
 
+trap '[[ -n "${WATCH_PID}" ]] && kill "${WATCH_PID}" 2>/dev/null || true' EXIT INT TERM
+
 log_line() {
     printf '%s %s\n' "$(date '+%F %T')" "$*" >> "${LOG}"
 }
@@ -35,10 +42,29 @@ count_itemized() {
     grep -Ec "${pattern}" "${file}" 2>/dev/null || true
 }
 
+is_ignored_relative() {
+    local rel="$1" base
+    base="$(basename "${rel}")"
+    case "/${rel}/" in
+        */.zq-quarantine/*|*/.zq-stage-*/*) return 0 ;;
+    esac
+    case "${base}" in
+        .DS_Store|._*|Thumbs.db|*.tmp) return 0 ;;
+    esac
+    return 1
+}
+
+base_filter_args() {
+    printf '%s\n' \
+        '--exclude=.DS_Store' '--exclude=._*' '--exclude=.AppleDouble' \
+        '--exclude=Thumbs.db' '--exclude=*.tmp' '--exclude=.zq-stage-*' \
+        '--exclude=.zq-quarantine/'
+}
+
 sync_path() {
     local label="$1" src_rel="$2" dest_rel="$3" rules="$4" checksum="$5" txn="$6"
     local out rc updated deleted newfiles backup_dir summary_file
-    out="${STATE_DIR}/transactions/${txn}-${label}.log"
+    out="${STATE_DIR}/transactions/${txn}-${label}-full.log"
     summary_file="/run/zq-artifact-publisher-${label}.status"
     backup_dir=".zq-quarantine/${txn}/${label}"
     local -a args=(
@@ -53,7 +79,7 @@ sync_path() {
     [[ "${checksum}" == "1" ]] && args+=(--checksum --checksum-choice=xxh128)
     [[ "${DRY_RUN}" == "1" ]] && args+=(--dry-run)
 
-    log_line "BEGIN label=${label} txn=${txn} checksum=${checksum} dry_run=${DRY_RUN}"
+    log_line "FULL_BEGIN label=${label} txn=${txn} checksum=${checksum} dry_run=${DRY_RUN}"
     rsync "${args[@]}" -e "${SSH_CMD}" \
         "${INTERNAL_ROOT}/${src_rel}" "${REMOTE}:${dest_rel}" >"${out}" 2>&1
     rc=$?
@@ -62,19 +88,78 @@ sync_path() {
     deleted=$(count_itemized '^\*deleting' "${out}")
     newfiles=$(count_itemized '^<f\+' "${out}")
     if [[ "${rc}" -eq 0 ]]; then
-        log_line "OK label=${label} txn=${txn} new=${newfiles} updated=${updated} deleted_or_quarantined=${deleted} log=${out}"
+        log_line "FULL_OK label=${label} txn=${txn} new=${newfiles} updated=${updated} deleted_or_quarantined=${deleted} log=${out}"
     else
-        log_line "ERROR label=${label} txn=${txn} rc=${rc} log=${out}"
+        log_line "FULL_ERROR label=${label} txn=${txn} rc=${rc} log=${out}"
         tail -n 80 "${out}" | sed 's/^/  /' >> "${LOG}"
     fi
 
-    printf 'label=%s txn=%s rc=%s new=%s updated=%s deleted_or_quarantined=%s checksum=%s dry_run=%s\n' \
+    printf 'label=%s txn=%s rc=%s new=%s updated=%s deleted_or_quarantined=%s checksum=%s dry_run=%s mode=full\n' \
         "${label}" "${txn}" "${rc}" "${newfiles}" "${updated}" "${deleted}" "${checksum}" "${DRY_RUN}" > "${summary_file}"
     return "${rc}"
 }
 
+sync_selected_files() {
+    local label="$1" src_rel="$2" dest_rel="$3" rules="$4" list="$5" txn="$6"
+    [[ -s "${list}" ]] || return 0
+    local out backup_dir rc updated newfiles
+    out="${STATE_DIR}/transactions/${txn}-${label}-events.log"
+    backup_dir=".zq-quarantine/${txn}/${label}-events"
+    local -a args=(
+        -aHR --omit-dir-times --partial --delay-updates --itemize-changes
+        --ignore-missing-args --files-from="${list}"
+        --exclude=.DS_Store --exclude='._*' --exclude=.AppleDouble
+        --exclude=Thumbs.db --exclude='*.tmp' --exclude='.zq-stage-*'
+        --exclude='.zq-quarantine/' --filter="merge ${rules}"
+    )
+    [[ "${DRY_RUN}" == "1" ]] && args+=(--dry-run)
+    log_line "EVENT_SYNC_BEGIN label=${label} txn=${txn} paths=$(wc -l < "${list}")"
+    rsync "${args[@]}" -e "${SSH_CMD}" \
+        "${INTERNAL_ROOT}/${src_rel}" "${REMOTE}:${dest_rel}" >>"${out}" 2>&1
+    rc=$?
+    updated=$(count_itemized '^<f' "${out}")
+    newfiles=$(count_itemized '^<f\+' "${out}")
+    if [[ "${rc}" -eq 0 ]]; then
+        log_line "EVENT_SYNC_OK label=${label} txn=${txn} new=${newfiles} updated=${updated} log=${out}"
+    else
+        log_line "EVENT_SYNC_ERROR label=${label} txn=${txn} rc=${rc} log=${out}"
+        tail -n 80 "${out}" | sed 's/^/  /' >> "${LOG}"
+    fi
+    return "${rc}"
+}
+
+sync_deleted_files() {
+    local label="$1" src_rel="$2" dest_rel="$3" rules="$4" list="$5" txn="$6"
+    [[ -s "${list}" ]] || return 0
+    local out backup_dir rc deleted
+    out="${STATE_DIR}/transactions/${txn}-${label}-deletes.log"
+    backup_dir=".zq-quarantine/${txn}/${label}-deletes"
+    local -a args=(
+        -aHR --omit-dir-times --delete-missing-args --ignore-missing-args
+        --backup --backup-dir="${backup_dir}" --itemize-changes
+        --files-from="${list}"
+        --exclude=.DS_Store --exclude='._*' --exclude=.AppleDouble
+        --exclude=Thumbs.db --exclude='*.tmp' --exclude='.zq-stage-*'
+        --exclude='.zq-quarantine/' --filter="merge ${rules}"
+    )
+    [[ "${DRY_RUN}" == "1" ]] && args+=(--dry-run)
+    log_line "EVENT_DELETE_BEGIN label=${label} txn=${txn} paths=$(wc -l < "${list}")"
+    rsync "${args[@]}" -e "${SSH_CMD}" \
+        "${INTERNAL_ROOT}/${src_rel}" "${REMOTE}:${dest_rel}" >>"${out}" 2>&1
+    rc=$?
+    deleted=$(count_itemized '^\*deleting' "${out}")
+    if [[ "${rc}" -eq 0 ]]; then
+        log_line "EVENT_DELETE_OK label=${label} txn=${txn} quarantined=${deleted} log=${out}"
+    else
+        log_line "EVENT_DELETE_ERROR label=${label} txn=${txn} rc=${rc} log=${out}"
+        tail -n 80 "${out}" | sed 's/^/  /' >> "${LOG}"
+    fi
+    return "${rc}"
+}
+
 prune_transactions() {
     find "${STATE_DIR}/transactions" -type f -mtime "+${TRANSACTION_RETENTION_DAYS}" -delete 2>/dev/null || true
+    find "${STATE_DIR}/events" -type f -mtime "+${TRANSACTION_RETENTION_DAYS}" -delete 2>/dev/null || true
 }
 
 run_cycle() {
@@ -85,32 +170,150 @@ run_cycle() {
         "${CONFIG_DIR}/baseline-upload.rules" "${checksum}" "${txn}" || errors=$((errors + 1))
     sync_path subassembly "web/subassembly/website/" "subassembly/website/" \
         "${CONFIG_DIR}/baseline-subassembly.rules" "${checksum}" "${txn}" || errors=$((errors + 1))
-    printf 'time=%s txn=%s errors=%s checksum=%s dry_run=%s\n' \
+    printf 'time=%s txn=%s errors=%s checksum=%s dry_run=%s mode=full\n' \
         "$(date '+%F %T')" "${txn}" "${errors}" "${checksum}" "${DRY_RUN}" > "${STATUS}"
-    if [[ "${errors}" -ne 0 ]]; then
-        log_line "CYCLE_ERROR txn=${txn} errors=${errors}"
-    fi
+    [[ "${errors}" -ne 0 ]] && log_line "CYCLE_ERROR txn=${txn} errors=${errors}"
     prune_transactions
     return "${errors}"
 }
 
+queue_event() {
+    local line="$1"
+    flock -x 8
+    printf '%s\n' "${line}" >> "${EVENT_QUEUE}"
+    flock -u 8
+}
+
+watch_events() {
+    inotifywait -m -r -q --format '%e|%w%f' \
+        -e close_write,create,moved_to,moved_from,delete \
+        "${INTERNAL_ROOT}/web/upload" "${INTERNAL_ROOT}/web/subassembly/website" 2>>"${LOG}" |
+    while IFS='|' read -r events abs_path; do
+        local label="" rel="" kind="changed"
+        case "${abs_path}" in
+            "${INTERNAL_ROOT}/web/upload/"*) label="upload"; rel="${abs_path#${INTERNAL_ROOT}/web/upload/}" ;;
+            "${INTERNAL_ROOT}/web/subassembly/website/"*) label="subassembly"; rel="${abs_path#${INTERNAL_ROOT}/web/subassembly/website/}" ;;
+            *) continue ;;
+        esac
+        is_ignored_relative "${rel}" && continue
+        case ",${events}," in
+            *,DELETE,*|*,MOVED_FROM,*) kind="deleted" ;;
+        esac
+        if [[ "${events}" == *ISDIR* ]]; then
+            queue_event $'full\t0\t.'
+            continue
+        fi
+        queue_event "${label}"$'\t'"${kind}"$'\t'"${rel}"
+    done
+}
+
+drain_events() {
+    local processing="$1"
+    : > "${processing}"
+    flock -x 8
+    if [[ -s "${EVENT_QUEUE}" ]]; then
+        cat "${EVENT_QUEUE}" > "${processing}"
+        : > "${EVENT_QUEUE}"
+    fi
+    flock -u 8
+    [[ -s "${processing}" ]]
+}
+
+process_events() {
+    local processing="$1" txn="$2"
+    local line label kind rel key need_full=0 errors=0
+    declare -A state=()
+    while IFS=$'\t' read -r label kind rel; do
+        [[ -n "${label}" ]] || continue
+        if [[ "${label}" == "full" ]]; then
+            need_full=1
+            continue
+        fi
+        key="${label}|${rel}"
+        case "${label}" in
+            upload) [[ -f "${INTERNAL_ROOT}/web/upload/${rel}" ]] && kind="changed" || kind="deleted" ;;
+            subassembly) [[ -f "${INTERNAL_ROOT}/web/subassembly/website/${rel}" ]] && kind="changed" || kind="deleted" ;;
+        esac
+        state["${key}"]="${kind}"
+    done < "${processing}"
+
+    if [[ "${need_full}" -eq 1 || "${#state[@]}" -eq 0 ]]; then
+        return 2
+    fi
+
+    local work="${STATE_DIR}/events/${txn}"
+    mkdir -p "${work}"
+    : > "${work}/upload-changed"
+    : > "${work}/upload-deleted"
+    : > "${work}/subassembly-changed"
+    : > "${work}/subassembly-deleted"
+    for key in "${!state[@]}"; do
+        label="${key%%|*}"
+        rel="${key#*|}"
+        kind="${state[${key}]}"
+        printf '%s\n' "${rel}" >> "${work}/${label}-${kind}"
+    done
+    sort -u -o "${work}/upload-changed" "${work}/upload-changed"
+    sort -u -o "${work}/upload-deleted" "${work}/upload-deleted"
+    sort -u -o "${work}/subassembly-changed" "${work}/subassembly-changed"
+    sort -u -o "${work}/subassembly-deleted" "${work}/subassembly-deleted"
+
+    sync_selected_files upload "web/upload/" "upload/" \
+        "${CONFIG_DIR}/baseline-upload.rules" "${work}/upload-changed" "${txn}" || errors=$((errors + 1))
+    sync_deleted_files upload "web/upload/" "upload/" \
+        "${CONFIG_DIR}/baseline-upload.rules" "${work}/upload-deleted" "${txn}" || errors=$((errors + 1))
+    sync_selected_files subassembly "web/subassembly/website/" "subassembly/website/" \
+        "${CONFIG_DIR}/baseline-subassembly.rules" "${work}/subassembly-changed" "${txn}" || errors=$((errors + 1))
+    sync_deleted_files subassembly "web/subassembly/website/" "subassembly/website/" \
+        "${CONFIG_DIR}/baseline-subassembly.rules" "${work}/subassembly-deleted" "${txn}" || errors=$((errors + 1))
+
+    printf 'time=%s txn=%s errors=%s mode=event events=%s\n' \
+        "$(date '+%F %T')" "${txn}" "${errors}" "${#state[@]}" > "${STATUS}"
+    return "${errors}"
+}
+
 mode="${1:-watch}"
 case "${mode}" in
     once)
         run_cycle "${FORCE_CHECKSUM}"
         ;;
     watch)
+        log_line "START event_driven=1 full_interval=${FULL_CHECK_INTERVAL}s dry_run=${DRY_RUN}"
+        watch_events &
+        WATCH_PID=$!
         last_full=0
-        log_line "START interval=${SYNC_INTERVAL}s full_interval=${FULL_CHECK_INTERVAL}s dry_run=${DRY_RUN}"
         while true; do
+            if [[ -s "${EVENT_QUEUE}" ]]; then
+                sleep "${EVENT_DEBOUNCE}"
+                processing="$(mktemp "${STATE_DIR}/events/batch.XXXXXX")"
+                if drain_events "${processing}"; then
+                    txn="$(date '+%Y%m%dT%H%M%S%z')"
+                    process_events "${processing}" "${txn}"
+                    rc=$?
+                    if [[ "${rc}" -eq 2 ]]; then
+                        run_cycle 0
+                        last_full="$(date +%s)"
+                    elif [[ "${rc}" -ne 0 ]]; then
+                        log_line "EVENT_BATCH_FALLBACK txn=${txn} rc=${rc}"
+                        run_cycle 0
+                        last_full="$(date +%s)"
+                    fi
+                fi
+                continue
+            fi
+
+            if ! kill -0 "${WATCH_PID}" 2>/dev/null; then
+                log_line "ERROR inotify watcher exited"
+                exit 1
+            fi
+
             now="$(date +%s)"
-            checksum=0
             if [[ "${last_full}" -eq 0 || $((now - last_full)) -ge "${FULL_CHECK_INTERVAL}" ]]; then
-                checksum=1
-                last_full="${now}"
+                run_cycle 1
+                last_full="$(date +%s)"
+            else
+                sleep 1
             fi
-            run_cycle "${checksum}"
-            sleep "${SYNC_INTERVAL}"
         done
         ;;
     *)