Skip to content

fix(util): clean up incomplete temporary ZIP archives - #401

Open
anishpentyala wants to merge 5 commits into
claudiodangelis:mainfrom
anishpentyala:fix-zip-failure-cleanup
Open

anishpentyala wants to merge 5 commits into
claudiodangelis:mainfrom
anishpentyala:fix-zip-failure-cleanup

Conversation

@anishpentyala

Copy link
Copy Markdown
Contributor

ZipFiles creates its temporary archive before checking the input paths. If a later stat, open, or archive write fails, it returns an empty filename but leaves the partial archive and its file handle behind.

Add failure cleanup that closes the ZIP writer and file before removing the archive. Track the temporary path across its rename, keep the original error, and leave completed archives available for the caller as before.

Tests cover missing first and later inputs, a failing directory entry, completed ZIP contents, and leaked descriptors on Linux. The symlink test skips when symlink creation is unavailable; descriptor inspection skips without /proc/self/fd.

Validation:

  • go test -race ./util -count=1
  • go test ./util -run TestZipFiles -count=30
  • go vet ./...
  • golint on ./util, no findings
  • go test -race ./... -skip '^TestNew$'

The unfiltered race suite hits config.TestNew's "no interfaces found" panic in this environment. The same test fails on the unchanged base. Windows was not tested.

@claudiodangelis

claudiodangelis commented Nov 27, 2026 •

Copy link
Copy Markdown
Owner

Thanks for this, the bug is real and your tests reproduce it nicely: they fail on main and pass with your change. Before merging I wonder if we could simplify things a bit, since the cleanup is being added on top of a function that's more complicated than it needs to be.

1. What about dropping the create/close/rename/reopen sequence?

As far as I can tell, that sequence exists only to give the temp file a .zip suffix, and os.CreateTemp can do that directly with a pattern. What if we used that? With only one path to keep track of, archiveName, the complete flag and the double closes would go away, and the cleanup could be a plain deferred check on a named err:

// ZipFiles and return the resulting zip's filename
func ZipFiles(files []string) (_ string, err error) {
	tmpfile, err := os.CreateTemp("", "qrcp-*.zip")
	if err != nil {
		return "", err
	}
	defer func() {
		if err != nil {
			_ = tmpfile.Close()
			_ = os.Remove(tmpfile.Name())
		}
	}()
	zip := new(archivex.ZipFile)
	if err := zip.CreateWriter(tmpfile.Name(), tmpfile); err != nil {
		return "", err
	}
	for _, filename := range files {
		if err := addToZip(zip, filename); err != nil {
			return "", err
		}
	}
	if err := zip.Writer.Close(); err != nil {
		return "", err
	}
	if err := tmpfile.Close(); err != nil {
		return "", err
	}
	return tmpfile.Name(), nil
}

I don't think the ZIP writer needs closing on the failure path, since the archive is being deleted anyway. Does that match your understanding?

2. What about moving the per-file work into a helper?

Right now defer file.Close() sits inside the loop, so every input file stays open until ZipFiles returns. This was already there before your PR, but since we're touching this code, how about a small helper like this?

func addToZip(zip *archivex.ZipFile, filename string) error {
	fileinfo, err := os.Stat(filename)
	if err != nil {
		return err
	}
	if fileinfo.IsDir() {
		return zip.AddAll(filename, true)
	}
	file, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer func() { _ = file.Close() }()
	return zip.Add(filename, file, fileinfo)
}

3. Could the tests be trimmed a little?

  • TestZipFilesClosesFailedArchive can go away: it only runs on Linux, and checking for leaked file handles doesn't add much for a command that exits right after the error. The leftover-file tests already cover the part users would notice.
  • What about putting the remaining tests in util/util_test.go instead of a new file?
  • The map[bool]string{...}[afterValid] trick for naming subtests is clever, but wouldn't a normal table of cases be easier to read? For example []struct{ name string; afterValid bool }.
  • One note for context: body/payload.go already checks every argument exists before it calls ZipFiles, so the "missing input" cases mostly cover a file that disappears in between. The broken-symlink test is the one closest to what users would actually hit. What if we also covered an unreadable file inside a directory, if it's easy to set up? Not required, though.

I'll squash on merge, so don't worry about the commit history. Thanks again!

EDIT: I can take care of this in case you don't find time

C

@anishpentyala

Copy link
Copy Markdown
Contributor Author

Thanks, the simpler temp-file path makes sense. Updated to CreateTemp with a .zip suffix and a named-error cleanup defer, moved per-file handling into a helper so each input is closed promptly, and moved the trimmed tests into util_test.go with table-based names. The optional unreadable directory-entry case also passes here. The discarded ZIP writer does not need to be finalised on failure; closing its underlying file is enough before removal.

The util race tests, 30 repeated ZIP test runs, and go vet pass. The full race suite passes excluding the previously reported config.TestNew network-interface failure. No Windows run locally; hosted checks are pending.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants