Repository navigation
zip: honor zipinsecurepath set by //go:debug or go.mod godebug - #1319
Conversation
internal/godebug only read $GODEBUG, so a program that enabled ErrInsecurePath with a //go:debug directive or a godebug line in go.mod got it from archive/zip but not from this package. Fall back to the DefaultGODEBUG build setting when $GODEBUG does not name the key, as the standard library does.
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
…post#1319) internal/godebug only read $GODEBUG, so a program that enabled ErrInsecurePath with a //go:debug directive or a godebug line in go.mod got it from archive/zip but not from this package. Fall back to the DefaultGODEBUG build setting when $GODEBUG does not name the key, as the standard library does.
…1297) * s2/cmd: harden CLI output creation and tar extraction Use atomic exclusive create for -safe paths, private temp files with rename for recompression, strip set-ID bits from new outputs, and root-scope _s2sx tar extraction with link validation. Fixes GHSA-rmjw-hrc6-xx62 Co-authored-by: Cursor <cursoragent@cursor.com> * Address PR review: sync and tar symlink validation Skip fsync on non-regular CLI outputs and reject tar symlinks that escape the extraction root after root.Stat. Adds regression tests. Co-authored-by: Cursor <cursoragent@cursor.com> * Address follow-up review on symlink Stat and sync Allow ErrNotExist after root.Stat for forward-reference symlinks, sync block devices, remove existing paths before tar file create, tighten tests, and fix s2 README heading and wording. Co-authored-by: Cursor <cursoragent@cursor.com> * Revalidate pending tar symlinks after each archive entry Track symlinks whose targets are not yet present and re-run root.Stat after later entries so deferred path components cannot turn an in-root link into an escape. Co-authored-by: Cursor <cursoragent@cursor.com> * Track all tar symlinks for revalidation and remove on deferred escape Append every archive symlink to the pending list, keep revalidating after each entry, and remove links that fail root.Stat during revalidation. Extend the deferred-escape test to cover links that initially resolve inside the extraction root. Co-authored-by: Cursor <cursoragent@cursor.com> * Address remaining PR review on tar links and s2c -safe Reject hard links to symlinks, treat ELOOP and ENOTDIR as pending symlink stat outcomes on Unix, reject -safe when s2c output overwrites the input file, and align s2/README extraction wording with cleanArchivePath behavior. Signed-off-by: Subhadeep Maity <322813880+deepnemesis@users.noreply.github.com> * zstd: inline the best encoder's reject path; cap concurrent-blocks job size (#1293) * zstd: inline the cheap reject path of the best encoder's improve The improve closure in bestFastEncoder.Encode is called for every candidate, and most candidates are rejected by the range check or the first 4-byte compare. The closure was too large to inline into Encode, so every candidate paid for a call. Split it into a small improve that does the range check and 4-byte compare, and improveSlow with the rest. improve now inlines at all 20 call sites. Output is unchanged. Written with Claude Code * zstd: cap the concurrent-blocks job size at 256 MiB With WithConcurrentBlocks, each job is 4x the window, so a 128 MiB window gives 512 MiB jobs and a 256 MiB window 1 GiB jobs. Inputs smaller than a few jobs then get little or no parallelism. Cap the job size at 256 MiB and the overlap at half a job. Windows up to 64 MiB are unchanged. For larger windows the overlap stays at the level's default until it reaches half a job. The window is clamped before it is multiplied, so a 512 MiB window no longer overflows the job size on 32-bit platforms. Written with Claude Code * zstd: shrink the capped job size test and document the cap TestConcurrentBlocks_CappedJobSize lowers maxJobSize to 4 MiB instead of encoding over 256 MiB, so it no longer needs about 2.3 GB and runs under -short too. maxJobSize becomes a variable for that. Note the job size cap and its CPU/ratio trade-off in the zstd README, and explain the MaxWindowSize row of TestJobAndOverlapSize, which checks the 32-bit overflow on 386. Written with Claude Code * zstd: check the capped job prefix and qualify the README note TestConcurrentBlocks_CappedJobSize now uses a window larger than a job at the best level, so the overlap is clamped to half a job as well. It checks that two jobs were dispatched and that the output is small enough that the second job must have used its prefix. A round trip alone passes without the prefix. The README states the 512 KiB minimum job size, presents the ratio loss as a benchmark result rather than a bound, and notes that windows over 256 MiB at the best level get a clamped overlap. Written with Claude Code * zstd: copy non-overlapping matches in 32-byte blocks (#1295) * zstd: copy non-overlapping matches in 32-byte blocks On data compressed at SpeedBetterCompression most matches are longer than 16 bytes, so the exit branch after the first 16-byte block of the extended match copy mispredicts on a large share of sequences; on a Neoverse N1 it accounts for over half of all decode branch mispredicts. Copy the first 32 bytes unconditionally (both loads before the stores, so any ml <= mo is correct) and loop in 32-byte steps, in decodeSync and executeSimple. compressedBlockOverAlloc grows from 16 to 32 to cover the wider overrun; every buffer sized from it (output, literals, the history ring) follows. The avo fork pin moves to a commit that pairs adjacent 16-byte vector moves into LDP/STP Q on arm64; nothing else in the zstd output changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci: describe the extended-copy overrun by its constant Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * all: generate assembly with github.com/honeycombio/avo The arm64 lowering lives in the honeycombio/avo fork, which now uses its own module path. Import it directly in the zstd, huff0 and s2 generators instead of replacing github.com/mmcloughlin/avo, and move all three to the same fork commit. That commit makes the pairing of adjacent 16-byte vector moves into LDP/STP Q opt-in. zstd opts in, which keeps its match copy as in the previous commit; s2 does not, because on Graviton 2-5 it was a wash for its encoders with up to +3% on 256-byte blocks. All generated assembly other than the zstd header line is byte-identical to the previous commit and s2 to master. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * Simplify S2 output and tar extraction hardening Signed-off-by: Subhadeep Maity <322813880+deepnemesis@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> * Update s2/cmd/_s2sx/_unpack/main_test.go Co-authored-by: Klaus Post <klauspost@gmail.com> * s2: don't read past src when converting LZ4 blocks (#1294) The LZ4 and LZ4s converters move literals of up to 8 bytes with a single 8-byte load, which reads up to 7 bytes past src when a block ends in fewer than 8 literals. The format only requires 5, so blocks from liblz4 often do. The bytes land in dst past the returned length, and the load faults if src ends at the end of a mapping. Use exact moves when fewer than 8 bytes of src remain. * zip: backport the standard library's writer-side Zip64 fixes (#1287) * zip: backport the standard library's writer-side Zip64 fixes Port golang.org/cl/725161 (Go 1.27): - The central directory Zip64 extra holds only the fields that reach 0xFFFFFFFF, those fields alone get the placeholder, and the entry's reader version is raised to 4.5. - The end record keeps the values that fit and writes placeholders only for the others. The Zip64 end record is written whenever an entry used a Zip64 extra. - CreateRaw with known sizes over 4 GiB and no data descriptor writes a Zip64 extra and both placeholders in the local file header. zip64_test.go, zip64_sparse_test.go and testdata/zip64 are copied from the standard library. * zip: look for the Zip64 end record when the directory size is 0xFFFFFFFF readDirectoryEnd compared the 32-bit directory size with 0xffff, so an end record whose only placeholder is the directory size was read without the Zip64 end record. The writer now emits such a record for a central directory of 4 GiB - 1 bytes or more with fewer than 65535 entries. From golang.org/cl/779180, which also makes TestZip64LargeDirectory read the archives back. * zip: check the local header's combined extra length writeHeader checked len(h.Extra) before adding the 20-byte Zip64 extra for CreateRaw entries over 4 GiB, so an Extra of 65516 to 65535 bytes wrapped the local header's extra length. Check the combined length. TestZip64LargeDirectory's two NewReader round trips each hold about 8 GiB, so together they peaked above 16 GiB. Run them one at a time, with a GC in between. --------- Co-authored-by: ybai08 <271969568+ybai08@users.noreply.github.com> * Update .github/workflows/go.yml Co-authored-by: Klaus Post <klauspost@gmail.com> * zstd: cap DecodeAll preallocation to what the input can decode to (#1291) DecodeAll grew dst to the frame's declared content size before decoding any block, so an 18-byte frame declaring 60 GiB allocated 60 GiB with default options. On 32-bit platforms a declared size near 2 GiB also overflowed the int capacity and make panicked. Each block takes at least 4 bytes of input and decodes to at most 128 KiB, so cap the preallocation to what the rest of the input can decode to, and skip it if it does not fit in an int. Valid frames are always under the bound and keep their exact-size buffer. * s2: fix LZ4 converter length overflow (32-bit only) (#1300) The LZ4 and LZ4s converters summed length extension bytes into an int with no bound. On 32-bit platforms about 8.4 MB of 0xFF bytes takes the literal length to math.MaxInt32; s+ll and d+ll wrap negative, pass their checks, and src[s:s+ll] panics. Match lengths and the decoded total wrap the same way, and the conversion then succeeds with a negative or wrong size. Check the literal length against the rest of src on every extension byte, and return ErrTooLarge when the match length or the decoded total overflows. Only the Go code is used on 32-bit. On 64-bit the new checks only reject input that was already rejected. * zstd: don't reuse a literal table that was not written (#1299) * zstd: don't reuse a literal table that was not written When literals compress with a new Huffman table, huff0 keeps that table for the next block to reuse. If the encoder then writes the literals raw, because compressed with their header they are no smaller, the decoder never gets the table, but the next block could reuse it and could not be decoded. A block that falls back to raw as a whole already stops reuse; do the same here. FuzzEncoding now writes dictionary streams in flushed pieces for inputs ending in 1, 2, 3, 4, which are removed first, and its seed corpora are added both with and without that suffix. * zstd: test streams that store compressed literals raw Two streams of small flushed writes at SpeedBetterCompression that could not be decoded before the previous commit. --------- Co-authored-by: trev <me@trev.xyz> * review changes Signed-off-by: Subhadeep Maity <322813880+deepnemesis@users.noreply.github.com> * Protect s2c block output from failed writes Signed-off-by: Subhadeep Maity <322813880+deepnemesis@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> * gzhttp: clear Content-Length when decoding a compressed request (#1301) With AllowCompressedRequests, the wrapper replaced r.Body with a gzip decoder but left r.ContentLength and the Content-Length header at the compressed size, so they no longer described what the handler reads. A handler that caps the declared length accepted a small gzip request and then read far more than its limit, and an httputil.ReverseProxy behind the wrapper forwarded the stale length, so the backend got a request cut off at the compressed size. Set ContentLength to -1 and delete Content-Length when the outer gzip coding is removed, as Transport does for responses it decodes. * s2: return ErrDstTooSmall for an LZ4 conversion into a nil dst (#1307) * s2: return ErrDstTooSmall for an LZ4 conversion into a nil dst ConvertBlock and ConvertBlockSnappy document that dst must have capacity for the converted block, and a dst that is too small is reported as ErrDstTooSmall. A nil dst was handed to the assembly as an empty slice and crashed with a nil pointer dereference on arm64, while the Go fallback returned ErrDstTooSmall. Check for a dst without spare capacity before calling the assembly in both LZ4 and LZ4s converters. * s2: accept an empty LZ4 block into a dst without capacity A block that is just the 0x00 token converts to nothing, so it needs no room; return the unchanged dst instead of ErrDstTooSmall. * s2: keep ErrCorrupt when Skip rejects an oversized chunk (#1303) An uncompressed chunk bigger than the configured maximum made Read report ErrCorrupt but Skip report ErrUnsupported, because the error guard was inverted. ensureBufferSize already sets ErrCorrupt; keep it. * review comments Signed-off-by: Deep <322813880+deepnemesis@users.noreply.github.com> * code reviews Signed-off-by: Deep <322813880+deepnemesis@users.noreply.github.com> * flate: count the whole window for the level 9 literal cost estimate (#1306) * flate: count the whole window for the level 9 literal cost estimate The level 9 gain estimate prices a candidate match against the cost of emitting the same bytes as literals, using a Huffman table built from the byte frequencies of the window. Since #1115 only the first maxFlateBlockTokens bytes were counted, to keep the uint16 frequencies from overflowing on single-value input. A byte value that first appears after that point therefore had no code and a literal cost of zero, every match covering it looked like a loss, and the rest of the block was emitted as literals. Data made of long runs of varying byte values compressed many times worse at level 9 than at level 8 once the input exceeded 32K. Count every byte of the window again and saturate the frequencies at MaxUint16 instead, which keeps the #1114 fix (a 64K single-value window counts to 65536) without dropping symbols. Found by comparing output sizes with compress/flate from the standard library across levels and data shapes. * flate: assert the compressed size of a zero window in TestOneMByte The round trip alone would not notice a literal-cost regression that keeps the output decodable but much larger. * flate: drop the last byte of a full window instead of a second histogram Count into the uint16 table directly and add the left-out byte back with a single saturating increment, which avoids the extra [256]int32 pass. * flate: use histogram for the level 9 literal frequencies Count the window with the split histogram and, for a full 65536-byte window, count the first MaxUint16 bytes and add the last one with a single saturating increment. The table, and so the output, is unchanged. * gzhttp: return buffered write errors from FlushError (#1310) * xpress: reject a Huffman match that runs past the declared size (#1309) AppendHDecompressed is documented to append decompressed_size bytes, but only checked the size before each symbol, so a final match longer than the remaining space was copied in full: the Huff7 test vector (70001 bytes) returned all 70001 bytes and a nil error for a declared size of 2. Return errCorrupt instead, as the end-of-data symbol already does when it would overrun, and have FuzzXpressHuffman check the output length. * flate: do not replay buffered data after a failed WriteTo (#1304) A short write returned io.ErrShortWrite without making the error sticky or discarding the buffered output; a writer returning (n > 0, err) had the same problem. In both cases a later Read handed out the bytes already given to the writer, silently duplicating output. A writer returning io.EOF was worse: f.err doubles as the end-of-stream marker, so io.ReadAll reported success on truncated output. Clear the buffer, keep the error on both destination failure paths, and store a non-EOF error when the writer reports EOF while still returning the writer's error from WriteTo. * s2: omit empty indexes and check stream bounds (#1311) * s2: write the stream header before an empty appended index * s2: omit indexes for empty streams * s2: check stream bounds before loading indexes * gzip: keep WriteTo errors distinct from end of stream (#1302) Two cases returned success without verifying the gzip trailer: * After WriteTo of a single-stream reader, z.err stayed nil. A later Read interpreted the following member's header bytes as a checksum and reported ErrChecksum instead of io.EOF. Mark the reader as ended to match Read. * A destination returning io.EOF was stored in z.err, which also serves as the end-of-stream marker. A later WriteTo returned (0, nil) and silently skipped the checksum check. Reuse the package's noEOF helper so the write failure stays sticky. Both cases are covered by table-checkable tests that assert byte counts and errors from repeated WriteTo/Read calls. * gzhttp: preserve status selected by buffered writes (#1318) * gzhttp: preserve status selected by buffered writes Track final status selection separately from forwarding buffered headers. Ignore later statuses after Write selects 200, including an empty Write, while preserving informational responses before a final status. Co-authored-by: GeneralTony007 <144252170+GeneralTony007@users.noreply.github.com> * gzhttp: cover implicit status selection and header ordering Add body-roundtrip and header-order regression cases for identity, gzip and zstd responses with empty, buffered and compressed bodies. Co-authored-by: GeneralTony007 <144252170+GeneralTony007@users.noreply.github.com> --------- Co-authored-by: GeneralTony007 <144252170+GeneralTony007@users.noreply.github.com> * zip: honor zipinsecurepath set by //go:debug or go.mod godebug (#1319) internal/godebug only read $GODEBUG, so a program that enabled ErrInsecurePath with a //go:debug directive or a godebug line in go.mod got it from archive/zip but not from this package. Fall back to the DefaultGODEBUG build setting when $GODEBUG does not name the key, as the standard library does. * gzip: report short writes of the CRC/ISIZE footer from Close (#1316) Close wrote the 8-byte trailer with a bare Write and only checked the error, so a destination that accepted fewer than 8 bytes silently produced a truncated gzip stream reported as success. Use the existing write() helper, which already reports io.ErrShortWrite, matching the header writes. Add TestWriterCloseReportsShortFooterWrite and TestWriterClosePreservesFooterError to gzip_test.go. * zstd: state that encoder output is only stable within one version (#1314) * zstd: state that encoder output is only stable within one version Say plainly that any release may change the encoder output and that hashes of compressed output must not be compared across versions. Also fixes a typo ("the may be"). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * zstd: tighten README output stability wording Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * zstd: faster and smaller small frames with dictionaries (#1280) * huff0: count the new table's header when choosing to reuse a table With ReusePolicyAllow, compress is meant to compare the previous table against the new one plus its header, as zstd does. The header size was read from s.Out before the table was written, so it was always 0 and the new table won whenever its data was smaller, even when the header made the output larger. Write the new table first so its size is known. zstd uses this policy for literals, so small blocks that start from a dictionary's table come out smaller. * zstd: don't build sequence tables that can't be chosen chooseComp normalized and built a new FSE table for each sequence field, and wrote its header, before comparing it with the predefined and previous tables. For small blocks a new table rarely wins. Compare those tables first with a lower bound for any new table: the entropy of the histogram, the shortest header writeCount can produce for it and the smallest final flush. When one of them is no larger, it is chosen as before, without building the new table. The choice is unchanged; TestFSEMinNewSize checks the bound against built tables. * huff0: discard the rejected output when reuse is preferred With ReusePolicyPrefer, when the previous table compresses too little, compress falls back to a new table but left the rejected output in s.Out. The new table and data were appended after it, so the result was always reported as incompressible. FuzzCompress now also compresses part of each input with a table from the rest, with every reuse policy, and fails if Prefer is incompressible where a new table is not. A seed reaches the fallback. * huff0: don't build a table that can't be chosen With ReusePolicyAllow, compress built and wrote a new table before comparing it with the previous one. A new table costs at least the entropy of the input plus the smallest header cTable.write can produce, so when the previous table's estimate is no larger, reuse it without building one. The choice is unchanged. The entropy is bounded in fixed point from a 257-entry log2 table, since math.Log2 per symbol cost about a quarter of compressing a small block. The header bound uses only the number of symbols and how many are present: either the 4-bit weights, or the smallest FSE header and the fewest bits FSE can spend on the weights. * zstd: don't reuse a literal table that was not written When literals compress with a new Huffman table, huff0 keeps that table for the next block to reuse. If the encoder then writes the literals raw, because compressed with their header they are no smaller, the decoder never gets the table, but the next block could reuse it and could not be decoded. A block that falls back to raw as a whole already stops reuse; do the same here. Since huff0 counts a new table's header when choosing whether to reuse one, small blocks reuse much more often, and FuzzEncoding found this once it wrote dictionary streams in flushed pieces. It now does that for inputs ending in 1, 2, 3, 4, which are removed first, and its seed corpora are added both with and without that suffix. --------- Co-authored-by: Klaus Post <klauspost@gmail.com> * review comments Signed-off-by: Deep <322813880+deepnemesis@users.noreply.github.com> * s2c: detect output aliases before opening destination Check Stat/SameFile before openOutputFile so read-only in-place recompression and FIFO aliases stage a temp file without O_WRONLY on the input. finishOutput chmods the destination before rename when replacing in place. Signed-off-by: Deep <322813880+deepnemesis@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> * s2c: fix staged replace without chmod on destination replaceOutput removes a regular destination file only when rename fails. Drop pathname chmod that could follow symlinks. FIFO alias test uses Stat without opening the fifo. Signed-off-by: Deep <322813880+deepnemesis@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> * Preserve output on staged rename failure Signed-off-by: Deep <322813880+deepnemesis@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> --------- Signed-off-by: Subhadeep Maity <322813880+deepnemesis@users.noreply.github.com> Signed-off-by: Deep <322813880+deepnemesis@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Danner Stodolsky c/o Boston Dynamics <dstodolsky@bostondynamics.com> Co-authored-by: Liz Fong-Jones <lizf@honeycomb.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Klaus Post <klauspost@gmail.com> Co-authored-by: Raghuvardhan-Reddy78 <raghuvardhan@labs.digiscrypt.com> Co-authored-by: Yang Bai <yangbai2026@gmail.com> Co-authored-by: ybai08 <271969568+ybai08@users.noreply.github.com> Co-authored-by: trev <me@trev.xyz> Co-authored-by: yash <yxshdogra@gmail.com> Co-authored-by: CJstate <142857225+CJstate@users.noreply.github.com> Co-authored-by: generaltony007 <191973953+hakarrr@users.noreply.github.com> Co-authored-by: GeneralTony007 <144252170+GeneralTony007@users.noreply.github.com>
zipinsecurepath is ignored when set with //go:debug or in go.mod
internal/godebug.Getonly reads$GODEBUG, but Go also applies the defaults a binary was built with://go:debugdirectives in package main andgodebuglines in go.mod, which the go command records as theDefaultGODEBUGbuild setting. A program that opts intoErrInsecurePatheither way gets it fromarchive/zipfor an archive holding../evil.txt, whilezip.NewReaderhere returns a nil error, so switching to this package silently drops the zip-slip check the program asked for.Getnow falls back toDefaultGODEBUGfromdebug.ReadBuildInfowhen$GODEBUGdoesn't name the key, with the environment still taking precedence as in the standard library; nothing changes for programs that don't opt in.TestGetDefaultin internal/godebug/godebug_test.go sets the default with a//go:debugline in the test file and fails before the change.Summary by CodeRabbit
GODEBUGenvironment variable when a setting is provided, while missing settings fall back to the binary’s built-in defaults.