Repository navigation
fix(k8s): harden execCpFromPod against truncated tar streams - #78
Conversation
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.
Welcome To opensourceways CommunityHey @Longwt123 , thanks for your contribution to the community. Bot Usage ManualI'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 GuideIf you have any questions, please contact the SIG: infratructure , |
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
Linking Issue Notice@Longwt123 , the pull request must be linked to at least one issue. |
|
|||||||||||||
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
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.
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
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.
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
Goalina
left a comment
There was a problem hiding this comment.
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-256introduces a formatting violation —npm run format-check --prefix packages/k8sfails on this file whilemainpasses. One-line fix. - The inline
tokenMatchesclosure intransferTarFromPodDirectOnce(packages/k8s/src/k8s/index.ts:1248) duplicates the existingtokenMatchesHexhelper (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 || truechain 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
WarningThe PR code change can not be got, please check it! |
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
|
Thanks for the careful review — the design summary is spot on, and all the findings check out. Addressed in a056718: Needs discussion
Minor
Note on local test runs: 6 unrelated suites ( |
Goalina
left a comment
There was a problem hiding this comment.
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
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
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.
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
…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.
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
…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.
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
Goalina
left a comment
There was a problem hiding this comment.
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 -qEis case-sensitive: GNU tar'sUnexpected EOF in archiveis only fatal becauseEOFhappens to collide, andThis 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-iand 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.errisrm'd before its content can be surfaced — the thrown error carries no tar stderr, which will hurt debugging.catit 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
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
Thanks for the thorough review — all points addressed in 3008694. 1. Test coverage for the new failure paths — added:
2. Nits — all fixed:
CI should be green shortly; happy to re-review. |
|
|||||||||||||
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
|
|||||||||||||
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.
CLA Signature PassLongwt123, thanks for your pull request. All authors of the commits have signed the CLA. 👍 |
Goalina
left a comment
There was a problem hiding this comment.
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.
Summary
execCpFromPodstreams a tar archive of the job pod's/__w/_tempover 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 asUnexpected end of data; with no listener it became an uncaught exception that killed the hook process, so job retries never ran.HOOKS_SYNC_MODE=directmoves 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
errorlisteners to the tar extract stream and to every entry stream; turn stderr / non-Successexec status into rejections. No transfer failure can escape as an uncaught exception.execCpFromPod): opt-in viaHOOKS_SYNC_MODE=direct. Runner listens onHOOKS_SYNC_LISTEN_IP(defaults to its own pod IP); the job container pushes tar via/dev/tcpafter a one-time token handshake. Falls back to exec on any direct failure; afterHOOKS_SYNC_DIRECT_MAX_FAILURESconsecutive failures the mode is disabled for the process.execCpToPod): the reverse direction, so the largeprepare-jobworkspace push and the per-step_temppush also bypass the apiserver. Same token handshake and exec fallback.tokenMatchesHexhelper instead of an inline duplicate.Both
tarandnc-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_tempcopy was swallowed withcore.warningand the step still succeeded. This PR rethrows the error inrun-script-step.ts:113, so a persistently failing sync now fails the step (a missing_tempmeans missing step outputs, which would otherwise produce garbage downstream).run-container-step.ts:94callsexecCpFromPod('/__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
HOOKS_SYNC_MAX_ATTEMPTS5HOOKS_SYNC_BACKOFF_BASE_MS/HOOKS_SYNC_BACKOFF_MAX_MS1000/30000HOOKS_SYNC_ATTEMPT_TIMEOUT_MS900000(15 min)HOOKS_SYNC_DEADLINE_MS7200000(2 h)HOOKS_SYNC_SLOW_WARN_MS60000HOOKS_SYNC_EXCLUDEHOOKS_SYNC_MODEexec(setdirectto opt in)HOOKS_SYNC_LISTEN_IPHOOKS_SYNC_DIRECT_MAX_FAILURES2HOOKS_SYNC_DIRECT_TIMEOUT_MS900000(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.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 requiresskipTLSVerify, plus a path-separator assertion). The twoexecCp*suites above pass.npm run build --prefix packages/k8spasses (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:
runner:2.338.2-v0.8.0-ascend.2) in the karc-only fed runnervalues.yaml.HOOKS_SYNC_MODE=directinto those runner containers; addHOOKS_SYNC_LISTEN_IPonly if the pod IP is not reachable by override./dev/tcp. Silent fallback is logged asfalling back to the exec channel.Follow-up hardening (b262564)
Round-2 hardening of the direct-sync failure paths, from review Minor 5 plus additional edge-case analysis:
execCpToPod, both channels). Thetar xf - ... ; find ; sync || truechain masked a non-zero tar exit code behindsync, 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 1on tar; the direct attempt surfaces the failure through the exec status and falls back, and the exec path retries.execCpToPod): when the 15-attempt listing comparison never converges, a warning is emitted instead of silently passing (mirrors the existingexecCpFromPodbehavior).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.execCpFromPod): if the staged → target rename fails after the old target was moved to.trash, the old snapshot is restored from.trashand the error is rethrown; previously the next sync would have wiped it.directSyncConsecutiveFailuressplit into from-pod / to-pod counters, so a failing direction no longer spends the other direction's direct attempts./dev/tcphandshake 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 1surfaced:tar xf - -C /__wtries to restore the archive's root entry — i.e. the/__wmount 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 behindsync || true(status Success, stderr discarded), so every "successful" transfer was actually exiting non-zero.Handling evolved over three commits:
--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.--no-overwrite-dirvariant + two real fixes found while diagnosing: the exec fallback's status callback resolved regardless ofstatus.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).--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 withPROBE.txtround-trip intact, cleanup clean. CI fully green including the previously failing Kubernetes Hook Tests (alpine job). 9/9 test suites,tscclean.