From c829e60649ab1c3a1cadf220f30f99f5fbd368e1 Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Thu, 10 Apr 2025 13:04:46 +0200 Subject: [PATCH] manifest: handle "close()" errors in sbomWriter() This commit adds error handling for the `f.Close()` errors when we write the SBOM. Errors on close for RW fds are rare but we should handle them so we return the result of `f.Close()` now when returning in sbomWriter(). We still keep the `defer f.Close()` to ensure we do not leak file descriptors when e.g. `io.Copy()` fails. In the "happy" case f is closed without an error and then the defer f.Close() runs and will error with "ErrClosed" but we can ignore that. An alternative implementaiton might be: ```golang func sbomWriter(outputDir, filename string, content io.Reader) (err error) { ... f, err := os.Create(p) if err != nil { return err } defer func() { err = errors.Join(err, f.Close()) }() ... return nil } ``` no super strong opinion here. Thanks to Flo for finding this issues! --- cmd/image-builder/manifest.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cmd/image-builder/manifest.go b/cmd/image-builder/manifest.go index b7562ed..5c46ab3 100644 --- a/cmd/image-builder/manifest.go +++ b/cmd/image-builder/manifest.go @@ -41,11 +41,13 @@ func sbomWriter(outputDir, filename string, content io.Reader) error { if err != nil { return err } + // ensure we do not leak FDs if the function returns prematurely defer f.Close() + if _, err := io.Copy(f, content); err != nil { return err } - return nil + return f.Close() } // used in tests