Skip to content

fix(k8s): harden execCpFromPod against truncated tar streams - #78

Merged
Goalina merged 13 commits into
mainfrom
fix/cpfrompod-stream-resilience
Nov 28, 2026
Merged

Goalina merged 13 commits into
mainfrom
fix/cpfrompod-stream-resilience

Conversation

@Longwt123

@Longwt123 Longwt123 commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

execCpFromPod streams a tar archive of the job pod's /__w/_temp over the k8s exec channel. On nodes without a locally installed runner the channel is very slow (~0.13 MiB/s) and the peer eventually closes it. tar-stream reports the truncated archive asynchronously as Unexpected end of data; with no listener it became an uncaught exception that killed the hook process, so job retries never ran.

HOOKS_SYNC_MODE=direct moves the tar payload off the exec channel entirely: the runner listens on its pod IP, exec only starts a small bash command, and the job container connects back over the pod network (one-time token handshake) to stream the archive. Both directions are covered.

Changes

  • Attach error listeners to the tar extract stream and to every entry stream; turn stderr / non-Success exec status into rejections. No transfer failure can escape as an uncaught exception.
  • Treat truncated archives and early EOF as retryable with 1s..30s exponential backoff; bound each attempt and the whole sync; never publish a torn copy (staging + atomic rename swap).
  • Skip the transfer when pod-side and runner-side directories already match. The signature uses file count, total bytes and max mtime at second granularity, so an in-place rewrite with the same size within the same second can still be missed (the old flow always re-transferred; this shortcut is new).
  • Direct sync, pod → runner (execCpFromPod): opt-in via HOOKS_SYNC_MODE=direct. Runner listens on HOOKS_SYNC_LISTEN_IP (defaults to its own pod IP); the job container pushes tar via /dev/tcp after a one-time token handshake. Falls back to exec on any direct failure; after HOOKS_SYNC_DIRECT_MAX_FAILURES consecutive failures the mode is disabled for the process.
  • Direct sync, runner → pod (execCpToPod): the reverse direction, so the large prepare-job workspace push and the per-step _temp push also bypass the apiserver. Same token handshake and exec fallback.
  • Bug fix: the consecutive-failure counter used to be cleared whenever the exec fallback succeeded, so the disable-after-N guard never tripped. Only a successful direct transfer clears the streak now (both directions). The counter is intentionally shared by both directions (same channel, same process-wide budget).
  • Unauthenticated probes are dropped, not fatal: a connection with an invalid / oversized / early-closed token handshake is destroyed and removed from the socket set while the listener keeps waiting for the real job connection. Only the single authenticated peer may feed the tar stream. Previously any in-cluster port prober could permanently disable direct mode in two hits, and a silent first connection could evict the real job connection and burn the 15-minute timeout.
  • Reuse the constant-time tokenMatchesHex helper instead of an inline duplicate.

Both tar and nc-free (/dev/tcp) paths require a bash in the job container; direct mode falls back safely if it is absent.

Behavior change (user-visible)

On main, a failed _temp copy was swallowed with core.warning and the step still succeeded. This PR rethrows the error in run-script-step.ts:113, so a persistently failing sync now fails the step (a missing _temp means missing step outputs, which would otherwise produce garbage downstream). run-container-step.ts:94 calls execCpFromPod('/__w', ...) without a try/catch as before, so those errors bubble up too — now as typed errors. This is intentional, but it is a semantic change for users who relied on the old silent behavior.

Threat model

The one-time 32-hex-char token travels in the exec command string (printf '%s\n' '<token>' >&3), so it is visible in apiserver audit logs and exec request parameters. This is acceptable because it is generated per attempt, single-use, and paired with an ephemeral listener port; an unauthenticated peer cannot reach the staging directory. The listener binds to the pod IP, which is reachable by other pods in the cluster, hence the strict token check and the drop-not-fail handling of unauthenticated connections.

Configuration

Variable Default
HOOKS_SYNC_MAX_ATTEMPTS 5
HOOKS_SYNC_BACKOFF_BASE_MS / HOOKS_SYNC_BACKOFF_MAX_MS 1000 / 30000
HOOKS_SYNC_ATTEMPT_TIMEOUT_MS 900000 (15 min)
HOOKS_SYNC_DEADLINE_MS 7200000 (2 h)
HOOKS_SYNC_SLOW_WARN_MS 60000
HOOKS_SYNC_EXCLUDE empty
HOOKS_SYNC_MODE exec (set direct to opt in)
HOOKS_SYNC_LISTEN_IP runner pod IP
HOOKS_SYNC_DIRECT_MAX_FAILURES 2
HOOKS_SYNC_DIRECT_TIMEOUT_MS 900000 (15 min)

Tests

npm run test --prefix packages/k8s -- --runInBand --testTimeout=20000 tests/cp-from-pod-test.ts tests/cp-to-pod-test.ts → 9 passed.

  • from-pod: stale-file removal, first publish, direct channel, unauthenticated probe is dropped and the real connection still succeeds, disable-after-N guard (driven by a truncated direct archive), truncated retry, repeated-truncation clean failure;
  • to-pod: direct push over the socket, unauthenticated probe dropped without exec fallback.

Note: 6 unrelated suites (prepare-job, cleanup-job, run-*-step, e2e, k8s-utils) fail on this Windows checkout both with and without this PR's changes (k8s test-setup requires skipTLSVerify, plus a path-separator assertion). The two execCp* suites above pass.

npm run build --prefix packages/k8s passes (ncc bundle).

Deployment follow-up (not in this PR)

Merging this PR is necessary but not sufficient — the code is inert until the runtime is wired:

  1. Build/push a runner image from this commit and bump the tag (currently runner:2.338.2-v0.8.0-ascend.2) in the karc-only fed runner values.yaml.
  2. Inject HOOKS_SYNC_MODE=direct into those runner containers; add HOOKS_SYNC_LISTEN_IP only if the pod IP is not reachable by override.
  3. Confirm NetworkPolicy allows the job pod → runner pod ephemeral port, and the job container bash has /dev/tcp. Silent fallback is logged as falling back to the exec channel.
  4. After rollout, grep CI logs for direct success vs. fallback and re-measure the a2/a3 sync failures.

Follow-up hardening (b262564)

Round-2 hardening of the direct-sync failure paths, from review Minor 5 plus additional edge-case analysis:

  1. Pod-side extraction failures are no longer swallowed (execCpToPod, both channels). The tar xf - ... ; find ; sync || true chain masked a non-zero tar exit code behind sync, and tar's stderr went to /dev/null, so a mid-stream break left a torn pod-side copy that looked successful. Both the direct and the exec scripts now || exit 1 on tar; the direct attempt surfaces the failure through the exec status and falls back, and the exec path retries.
  2. Listing-verification divergence is surfaced (execCpToPod): when the 15-attempt listing comparison never converges, a warning is emitted instead of silently passing (mirrors the existing execCpFromPod behavior).
  3. Authenticated connection lost without error/end (both directions): the attempt now settles immediately with an error instead of hanging until the full attempt timeout (15 min by default). A normal close after the archive finished is unaffected.
  4. Failed publish no longer risks the last good snapshot (execCpFromPod): if the staged → target rename fails after the old target was moved to .trash, the old snapshot is restored from .trash and the error is rethrown; previously the next sync would have wiped it.
  5. Per-direction failure budgets: directSyncConsecutiveFailures split into from-pod / to-pod counters, so a failing direction no longer spends the other direction's direct attempts.
  6. IPv6 pod IPs are bracketed in the /dev/tcp handshake address.

Known accepted window (documented, not fixed): when a direct attempt fails (timeout, socket error), the pod-side bash may still be finishing for a moment while the exec fallback starts re-transferring into the same directory. Both write the same archive content; the listing verification bounds the outcome. Fully closing the window would require waiting for the pod-side exec status before falling back — left for a follow-up if it ever shows up in practice.

Verification round 2 (eefc5dc) — mount-point tar metadata handling

The test3 end-to-end run and the CI alpine job exposed a pre-existing failure that the new || exit 1 surfaced: tar xf - -C /__w tries to restore the archive's root entry — i.e. the /__w mount point itself — with utime/chmod, which fails with EPERM for the non-root runner user after a completely successful extraction. The old exec path masked this behind sync || true (status Success, stderr discarded), so every "successful" transfer was actually exiting non-zero.

Handling evolved over three commits:

  • 3198a4e: --omit-dir-times --no-same-permissions — the image's tar rejects --omit-dir-times (usage error 64, verified in-image), and the CI alpine job container runs busybox tar which rejects both new options. Red.
  • 9cf8bee: --no-overwrite-dir variant + two real fixes found while diagnosing: the exec fallback's status callback resolved regardless of status.status (a failed pod-side extraction reported success and the verification loop silently gave up after 15 tries, leaving an empty workspace downstream — observed live), and a never-converging listing verification now throws instead of passing silently. test3 green, CI still red (alpine).
  • eefc5dc (final): back to plain --no-same-owner (GNU and busybox compatible), with tar failures classified by stderr: IO/data/option errors (Cannot read, unexpected, unrecognized, No such, short read, Cannot open, EOF) are fatal; metadata-only failures on the mount point are tolerated and proven by the listing verification. The exec fallback honors the exec status (retry on non-Success), and a never-converging verification throws.

test3 verification of 2.338.2-fix-direct-sync-eefc5dc-multiarch (amd64, bad-token prober racing): prepare fallbacks 0 (32 MiB direct transfer completes), sha256 identical both sides, reverse direction 0 fallbacks with PROBE.txt round-trip intact, cleanup clean. CI fully green including the previously failing Kubernetes Hook Tests (alpine job). 9/9 test suites, tsc clean.

The pod-to-runner /__w/_temp sync streams a tar archive over the k8s exec
channel. On slow channels the peer can close the connection mid-transfer;
tar-stream then reports "Unexpected end of data" asynchronously. With no
error listener that became an uncaught exception and crashed the hook
process, so job retries never ran.

Handle the extract stream's error/entry error, stderr and exit status and
turn all of them into a rejection. Truncated transfers are retried from a
clean staging directory with 1s..30s exponential backoff (30 attempts by
default). Each attempt and the whole sync are bounded by configurable
timeouts; on expiry the exec socket is aborted and staging is removed.

Only a completely extracted staging directory may be published, so a torn
copy can never replace the previous runner-side snapshot; verified-hash
mismatches still publish with a warning as before. Also skip the transfer
when file count, total size and newest mtime already match, support
HOOKS_SYNC_EXCLUDE globs for cache directories, and log bytes/duration/
MiB/s per attempt plus a warning for syncs slower than 60s.
@opensourceways-bot

Copy link
Copy Markdown

Welcome To opensourceways Community

Hey @Longwt123 , thanks for your contribution to the community.

Bot Usage Manual

I'm the Bot here serving you. You can find the instructions on how to interact with me at Here . That means you can comment below every pull request or issue to trigger Bot Commands.

Contact Guide

If you have any questions, please contact the SIG: infratructure ,
and any of the maintainers: @GeorgeCao-hw, @TangJia025, @pkking, @zhongjun2 ,
and any of the committers: @GeorgeCao-hw, @Goalina, @Hourunze1997, @JavaPythonAIForBAT, @KadenZhang3321, @LiYanghang00, @ccijunk, @drizzlezyk, @pkking, @rosecoffe, @tfhddd, @yao-xiaobai, @zhongjun2, @zkhzkhz .

@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown

Linking Issue Notice

@Longwt123 , the pull request must be linked to at least one issue.
If an issue has already been linked, but the needs-issue label remains, you can remove the label by commenting /check-issue .

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

The exec based transfer tunnels every byte through the API server. When the
control plane runs in another site than the job pods, the stream crosses that
link twice and large /__w/_temp trees are truncated ("Unexpected end of data").

With HOOKS_SYNC_MODE=direct the job container pushes the very same tar stream
straight to the runner pod over the pod network (/dev/tcp), and the exec
channel is only used to start the sender. Any direct failure falls back to the
exec path, and two consecutive failures disable the mode for the process.

The listener binds the runner pod IP rather than 0.0.0.0, accepts a single
connection, and requires a per-attempt random token as the first line before
any byte reaches the staging directory.
@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

Fix the disable-after-N guard: the failure counter was reset on a
successful exec fallback, so direct mode was retried forever. Only a
successful direct transfer now clears the streak.

Add the reverse direction (runner -> job pod): execCpToPod now streams
the tar over a pod-network socket when HOOKS_SYNC_MODE=direct, with the
same one-time token handshake and exec fallback. This removes the
large workspace push and the per-step _temp push from the apiserver path.

Add tests for the disable guard and for the reverse direct/fallback path.
@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

@Goalina Goalina left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well-structured fix overall — error containment → bounded retry/backoff → opt-in direct mode with exec fallback and a consecutive-failure circuit breaker, plus staging + atomic rename so only complete snapshots are ever published. Verified locally: all 9 tests pass, tsc + ncc build passes, eslint passes. Below are the issues I found, in order of importance.

Needs discussion

1. Behavior change: a _temp sync failure now fails the whole step (packages/k8s/src/hooks/run-script-step.ts:113)

On main a failed copy is swallowed with core.warning and the step still succeeds. This PR rethrows, so a persistent sync failure fails every step. Probably intentional (a missing _temp means missing step outputs → garbage downstream), but it is a user-visible semantic change that the PR description does not mention. Note also that packages/k8s/src/hooks/run-container-step.ts:94 calls execCpFromPod('/__w', ...) without try/catch, so errors bubble up there too (same as main, and now they are properly typed errors, which is an improvement — but worth confirming it is intended).

2. An unauthenticated connection fails the entire direct attempt instead of being dropped (packages/k8s/src/k8s/index.ts:1358, packages/k8s/src/k8s/index.ts:1567)

In both direct directions, a connection with a bad/absent token calls settle() and fails the whole attempt → warning → exec fallback → counter ++. That means any in-cluster port prober (monitoring probes, security scanners, CNI connectivity checks) can permanently disable direct mode within two hits without ever knowing the token. There is also a first-connection race: a prober that connects first and stays silent occupies the single connection slot, the real job container's connection is then destroyed by the sockets.size > 0 guard, and the attempt burns the full 15 min timeout.

Suggestion: on handshake failure just socket.destroy(), drop it from sockets, and keep the listener waiting (bounded by the attempt timeout). Since the job pod's IP is available via readPod, also consider comparing socket.remoteAddress against it — cheap hardening against that race.

3. The isPodSyncUnchanged skip can miss a needed sync (packages/k8s/src/k8s/index.ts:998)

The signature is (file count, total bytes, max mtime in seconds). tar preserves mtimes, so after a sync both sides' signatures are naturally equal. If a step overwrites a file in place with the same size within the same second as the current max mtime, the signature still matches → the transfer is skipped → the new bytes never reach the runner. The old flow always re-transferred, so this miss path is new. Suggest at least hashing the sorted (size, name) listing (one extra pod exec + a local walk, cheap), which narrows the miss window to the same-second-same-size in-place rewrite. Second granularity is the stat -c '%Y' ceiling — acceptable, but worth documenting in the comment.

Minor

  • Prettier: packages/k8s/tests/cp-from-pod-test.ts:254-256 introduces a formatting violation — npm run format-check --prefix packages/k8s fails on this file while main passes. One-line fix.
  • The inline tokenMatches closure in transferTarFromPodDirectOnce (packages/k8s/src/k8s/index.ts:1248) duplicates the existing tokenMatchesHex helper (packages/k8s/src/k8s/index.ts:1194) — reuse the helper.
  • directSyncConsecutiveFailures (packages/k8s/src/k8s/index.ts:1176) is shared between both directions: a to-pod failure followed by a from-pod success resets the streak. Both directions use the same channel, so arguably fine — but a comment saying the sharing is intentional would help future readers.
  • The one-time token travels in the exec command string, so it is visible in apiserver audit logs / exec request params. Acceptable since it is per-attempt, one-time, and the listener port is ephemeral — but worth a sentence in the PR description's threat model.
  • The to-pod script tar xf ...; find ...; sync 2>/dev/null || true chain swallows a non-zero tar exit code and redirects its stderr to /dev/null (packages/k8s/src/k8s/index.ts:1598). This mirrors the existing exec path (not a regression), but since this is a newly written script, && chaining or capturing tar's exit code would be an easy improvement.

Review follow-up for PR #78:
- drop a socket whose handshake token is invalid / oversized / closed early
  instead of failing the whole direct attempt, so an in-cluster port prober
  cannot permanently disable direct mode with two accidental hits
- allow multiple unauthenticated peers while listening, guarding only the
  single authenticated connection that feeds the tar stream; the previous
  sockets.size guard let a silent prober evict the real job connection
- reuse the tokenMatchesHex helper instead of an inline duplicate
- update tests to assert a bad-token probe is dropped and the real
  connection still transfers over the direct channel
- fix the prettier violation in cp-from-pod-test.ts
@opensourceways-bot

Copy link
Copy Markdown

Warning

The PR code change can not be got, please check it!

@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

@Longwt123

Copy link
Copy Markdown
Collaborator Author

Thanks for the careful review — the design summary is spot on, and all the findings check out. Addressed in a056718:

Needs discussion

  1. _temp sync failure now fails the step (run-script-step.ts:113) — intentional. A missing _temp means missing step outputs, which would silently produce garbage downstream, so swallowing the error felt worse than failing loudly. Agreed this is a user-visible semantic change; it is now documented in the PR description under "Behavior change (user-visible)".

  2. Unauthenticated connections no longer kill the direct attempt (index.ts, both directions) — fixed, and this was the most valuable finding. Changes:

    • A socket whose handshake carries an invalid / oversized / early-closed token is now destroyed and removed from the socket set while the listener keeps waiting (dropUnauthenticatedSocket). Only authenticated failures (e.g. mid-stream socket errors) still settle the attempt.
    • Removed the sockets.size > 0 single-slot guard. While listening, multiple unauthenticated peers may coexist; only the single authenticated peer may feed the tar stream. A silent prober can no longer evict the real job connection.
    • On remoteAddress verification: deliberately not added. For container steps the job container runs in a separate step pod (via getStepPodName), so socket.remoteAddress would not match the runner pod IP and a whitelist would reject legitimate transfers. The one-time token remains the sole authentication boundary; the per-attempt timeout plus the drop-not-fail handling bounds the blast radius of any abuse. Happy to revisit if we later pin step pods to the runner pod.
    • Tests updated: a bad-token probe is now asserted to be dropped while the real connection still completes over the direct channel with zero exec fallbacks.
  3. isPodSyncUnchanged second-granularity mtime — documented the limitation in the PR description (same-size in-place rewrite within the same second can still be missed; the old flow always re-transferred). Keeping the current signature for now — hashing the sorted (size, name) list would narrow the window, but it also re-reads the whole tree on every sync, which trades away most of the skip's win. Can switch if you prefer accuracy over speed here.

Minor

  • Prettier violation in cp-from-pod-test.ts — fixed (format-check green).
  • Inline tokenMatches closure — now reuses tokenMatchesHex.
  • Shared failure counter — added a comment marking the cross-direction sharing as intentional (same channel, same process-wide budget).
  • Token visibility in exec command strings — documented in the PR description under "Threat model" (one-time, per-attempt, paired with an ephemeral listener port).
  • tar xf ... ; find ; sync exit code swallowing — left as-is since it mirrors the existing exec-path behavior; can be tightened in a follow-up if you want.

Note on local test runs: 6 unrelated suites (prepare-job, cleanup-job, run-*-step, e2e, k8s-utils) fail on a Windows checkout both with and without this PR (k8s test-setup requires skipTLSVerify, plus one path-separator assertion); CI is green. The two execCp* suites covering this PR pass locally (9/9).

@Goalina Goalina left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified a056718 locally: 9/9 tests pass, format-check green, eslint clean, tsc + ncc build passes.

The drop-not-fail rework is exactly right — invalid/oversized/early-closed tokens and pre-auth socket errors now destroy only the offending connection while the listener keeps waiting, the authenticatedSocket guard replaces the single-slot rule so a silent prober can no longer evict the real job connection, and the tests now assert zero exec fallback on a bad-token probe (with failDirect covering the direct-failure → fallback path and the disable-guard test). Thanks also for the PR-description sections and the remaining minor cleanups.

One correction for the record, not a request to change anything: the remoteAddress suggestion was to compare against the exec'd pod's IP (readPod(podName) — the pod whose bash opens the /dev/tcp connection, i.e. exactly the connecting peer), not the runner pod IP, so a whitelist would not reject legitimate transfers. The token-plus-timeout boundary you kept is a defensible choice — just noting the stated reason so it doesn't mislead a future reader into ruling out the option.

The consciously-accepted tradeoffs (second-granularity skip window, tar exit-code swallowing in the to-pod script) are fine as documented. Approving.

- cpToPod: pod-side tar failure is no longer masked by the trailing
  'sync || true' (exec + direct scripts exit non-zero), and a persistent
  listing-verification mismatch is surfaced with a warning instead of
  silently passing
- both directions: an authenticated connection that closes without
  'error'/'end' now settles the attempt instead of hanging until the
  full attempt timeout
- cpFromPod: a failed publish rename restores the previous snapshot
  from the trash directory instead of leaving it to be wiped by the
  next sync
- split the direct-sync failure budget per direction so one failing
  direction no longer disables the other
- bracket IPv6 pod IPs in the /dev/tcp handshake address
@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

tar xf - into the job container tries to restore the archive's root
directory entry ('.') — i.e. the /__w mount point itself — with utime
and chmod. For the non-root runner user both fail with EPERM, tar exits
2 AFTER a complete extraction, and with the new '|| exit 1' that
surfaces as a failed direct attempt followed by an unnecessary exec
fallback. The old exec path masked the same failure behind 'sync || true'.

--omit-dir-times --no-same-permissions keeps tar off the mount point's
metadata; the existing find/chmod steps still fix up file and directory
permissions for the workflow. Genuine extraction failures (truncated
stream, connection reset) still exit non-zero.
@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

…ec status

Two follow-ups from the test3 verification round:

1. The image's tar does not support --omit-dir-times (usage error 64).
   --no-overwrite-dir achieves the same goal for the mount-point case:
   tar leaves the metadata of already-existing directories (i.e. the
   /__w mount point) untouched, so the EPERM utime/chmod failure that
   aborted an otherwise complete extraction is gone.

2. The exec fallback's exec status callback resolved regardless of
   status.status, so a failed pod-side extraction reported success and
   the listing-verification loop then silently gave up after 15 tries,
   leaving an empty workspace downstream. Non-Success status now
   rejects (retry loop re-transfers), and a verification that never
   converges throws instead of passing silently.
@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

…action

The image's tar turned out to be busybox in the CI alpine job
(prepare-job-test uses alpine:latest), which rejects
--no-same-permissions/--no-overwrite-dir: every extraction attempt
failed, cpToPod burned all 30 retries and the test suite went red.

Go back to plain --no-same-owner (works on GNU and busybox tar) and
classify tar failures by stderr instead: IO/data/option errors
(Cannot read / unexpected / unrecognized / No such / short read /
Cannot open / EOF) are fatal, metadata-only failures on the /__w
mount point (utime/chmod EPERM after a complete extraction) are
tolerated and covered by the listing verification. Verified on test3
that the GNU-tar metadata-EPERM path produces exactly those messages.
@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

@Goalina Goalina left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review covers the four commits pushed after 6579aba (b262564, 3198a4e, 9cf8bee, eefc5dc) — my earlier approval was on 6579aba and does not cover these 122 lines. First: the direction is right, and it's appreciated that two of my earlier deferred findings (the swallowed tar exit code, the silent verification pass-through in execCpToPod) got fixed here, along with the per-direction circuit-breaker counters, the close-before-archive-finished settling, and the restore-from-trash on publish failure. Verified on eefc5dc: 9/9 tests pass, format-check green, eslint clean, tsc + ncc build passes.

Two substantive points before this can be re-approved:

1. The new behavior has zero test coverage

All 122 changed lines are in src/k8s/index.ts; tests/ is untouched. Untested new paths include: the per-direction failure counters, the authenticated-connection-closed-early settling, the restore-from-trash publish recovery, the exec-status rejection in execCpToPod, the verification-non-convergence throw, and both the fatal and tolerated branches of the stderr blocklist. The existing suites pass incidentally — the mocks match commands via includes('tar xf -') and always call back with status: 'Success', so the new failure branches never execute. At minimum I'd want tests for (a) a non-Success exec status on the to-pod push → rejection + retry, (b) verification never converging → the new throw, and (c) the publish-rename failing → previous snapshot restored. The blocklist's fatal-vs-tolerated split is exactly the kind of string-matching logic that regresses silently without a test.

2. /tmp/.hooks-tar.err is a compatibility regression for read-only rootfs job containers (index.ts, exec path and direct to-pod script)

The old 2>/dev/null needed no writable path; the new fixed-path redirection requires /tmp to be writable in the job container. A job container configured with readOnlyRootFilesystem: true (possible via the extension template merge) previously worked and now hard-fails: the sh redirection error lands in the exec errStream → rejection → 30 retries → throw. Loud, not silent — but it breaks a class of workflows that worked before. Suggestion: fall back to 2>/dev/null when the temp file cannot be created (tolerating all non-zero exits and letting the new verification-throw be the safety net), or write the file under the target directory instead.

Nits

  • The blocklist grep -qE is case-sensitive: GNU tar's Unexpected EOF in archive is only fatal because EOF happens to collide, and This does not look like a tar archive (a corrupt archive) is not matched at all → tolerated as a "metadata failure" and caught only by the 15-round verification (slow fail, ~15s+). Adding -i and the missing patterns would tighten the fast path; correctness is at least backstopped by the new verification throw. Also, on the fatal path /tmp/.hooks-tar.err is rm'd before its content can be surfaced — the thrown error carries no tar stderr, which will hurt debugging. cat it into the failure path before removing.
  • The same blocklist script is inlined in both the exec fallback and the direct to-pod script. Two copies of a subtle regex embedded in shell strings will drift; extracting a small builder function would keep them in sync.

Happy to re-approve once the new failure paths have tests and the /tmp write has a fallback (or a conscious decision documented in the PR description).

…ver the new failure paths

Review follow-up on the round-2 hardening commits:

1. The tar extraction script was inlined twice (exec fallback + direct
   to-pod) with a subtle stderr regex; it is now built by one exported
   podExtractScript(containerPath, stdinRedirect) so the classification
   and the chmod/sync fixup cannot drift.
2. The stderr blocklist gains -i (GNU and busybox tar capitalize
   differently) and a missing pattern: a corrupt archive prints
   'does not look like a tar archive' (or 'unexpected EOF'), which used
   to be tolerated as a metadata failure and only caught ~15s later by
   the listing verification.
3. On the fatal path the tar stderr is now echoed to the exec error
   stream BEFORE the temp file is removed, so a failed transfer is
   debuggable instead of carrying a bare exit code.
4. The fixed /tmp/.hooks-tar.err redirection broke job containers with
   readOnlyRootFilesystem: the redirection fails before tar even runs
   and every push burned 30 retries. The script now probes /tmp
   writability in a subshell first and falls back to plain 2>/dev/null
   (all non-zero exits tolerated; the verification throw is the net).
5. Test coverage for the new failure paths, previously zero:
   - pod-extract-script-test.ts pins the generated script (blocklist
     patterns, -i, cat-before-rm, /tmp fallback, fd-3 vs stdin)
   - cp-to-pod: non-Success exec status -> rejection + retry until the
     push succeeds; a pod reporting Success without materializing files
     -> the verification throw (the empty-workspace case)
   - cp-from-pod: a failed staged -> target publish rename restores the
     previous snapshot from the trash directory
@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@Longwt123

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review — all points addressed in 3008694.

1. Test coverage for the new failure paths — added:

  • pod-extract-script-test.ts (new suite): pins the generated extraction script — the blocklist patterns and -i, the fatal branch emitting stderr before removing the temp file, the read-only-/tmp fallback branch, --no-same-owner + fixup steps, and <&3 vs stdin.
  • cp-to-pod-test.ts: a non-Success exec status on the push → rejection + retry until the push succeeds (asserts >= 3 push calls and final content lands); a pod that reports Success without materializing files → the new verification throw (this is exactly the empty-workspace case we observed live).
  • cp-from-pod-test.ts: a failed staged → target publish rename → the previous snapshot is restored from .trash (the trash directory is renamed back, nothing left for the next sync to wipe). Implementation note: recent Node makes built-in fs functions non-configurable so jest.spyOn(fs, 'renameSync') fails; the suite spreads the real fs into a mock module object to make renameSync replaceable while everything else stays real.

2. /tmp write requirement (compatibility regression) — fixed with your first suggested shape: the script now probes /tmp writability in a subshell (if (true 2>/tmp/.hooks-tar.err) 2>/dev/null; then ... else ... fi) and falls back to plain 2>/dev/null, tolerating all non-zero exits with the verification throw as the safety net. Read-only-rootfs containers are back to the old, working behavior.

Nits — all fixed:

  • Blocklist is now grep -qEi and gains does not look like a tar archive (a corrupt archive header was previously tolerated as a "metadata failure" and only caught ~15s later by the verification).
  • On the fatal path tar's stderr is now echo+cated into the exec error stream before the temp file is removed, so the failure carries the actual tar output.
  • The two inline copies are gone: both paths call one exported podExtractScript(containerPath, stdinRedirect) builder.

CI should be green shortly; happy to re-review.

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@opensourceways-bot

Copy link
Copy Markdown
检查项 状态
敏感信息扫描 ✅
漏洞扫描 ✅
开源license合规扫描 ✅
开发阶段设计文档检查 ❌
流水线链接 点击跳转查看日志

it(...) with a timeout argument was hand-wrapped in a shape prettier
does not produce; format-check (not run by the currently disabled CI)
flags both suites. Regenerated with prettier --write and raised the
never-converges test timeout to 45s after re-timing it on a loaded
machine.
@opensourceways-bot

Copy link
Copy Markdown

CLA Signature Pass

Longwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍

@Goalina Goalina left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

164eb0b verified: format-check fully green and the two suites still pass (12/12; the podExtractScript suite was already green and is untouched by the formatting commit).

Everything from my previous review round is now resolved — the three failure-path tests (non-Success status retry, verification non-convergence throw, publish-rename restore), the read-only-rootfs fallback for the stderr temp file, grep -qEi with the corrupt-archive pattern plus stderr surfacing on the fatal branch, and the shared podExtractScript builder. Approving.

@Goalina
Goalina merged commit 9953bfe into main Nov 28, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants