Files
nfpm/ipk/tar.go
93cf82dd37 fix(ipk): normalize file modes before writing tar headers (#1145)
* fix(ipk): normalize file modes before writing tar headers

The `type: tree` walk in files.PrepareForPackager stores the raw
fs.FileMode in Content.FileInfo.Mode, so a walked directory also carries
fs.ModeDir (bit 31). Writing that value straight into a tar header makes
archive/tar switch just that header to GNU format with base-256 (binary)
numeric encoding, because 0x800001ED does not fit the 7-digit octal mode
field.

Raw mode field for a walked directory, before this change:

    name='./usr/share/doc/sub/'  mode = 80 00 00 00 80 00 01 ed  (base-256)

and after:

    name='./usr/share/doc/sub/'  mode = 0000755                    (octal ASCII)

This is the ipk half of the same defect that #1113 fixed for apk. The
apk packager keeps a normalizeFileMode helper and a table test for it;
ipk never got one. deb already masks with fm & 0o7777, and rpm normalizes
in normalizeFileMode, so ipk was the last packager writing the raw value.

Two call sites are affected:

  - ipk/ipk.go, the TypeDir/TypeImplicitDir branch
  - ipk/tar.go, writeFile, which overrode tar.FileInfoHeader's Perm()
    masking with an unmasked int64(file.Mode())

Special bits are preserved from both the Go flags (fs.ModeSetuid,
fs.ModeSetgid, fs.ModeSticky) and the traditional octal positions, so
this does not regress the setuid support the writeFile comment calls out.

Tests:
  - TestIPKTreeDirectoryModeIsNotBase256 builds a tree package and reads
    the data.tar.gz headers back, asserting permission bits only and
    that the mode field is not base-256
  - TestNormalizeIPKFileMode is the conversion table test
  - TestIPKTreePreservesSpecialModeBits guards the setuid/setgid
    direction, configuring the mode explicitly since filesystems with
    nosuid drop the bit on chmod

go test ./... -count=1, go vet ./... and go test ./ipk/ -race all pass.

* test(ipk): derive expected tree modes from disk, not hardcoded 0o755

TestIPKTreeDirectoryModeIsNotBase256 hardcoded 0o755/0o644 for the walked
tree entries, but os.MkdirAll and os.WriteFile are masked by the process
umask. Under a restrictive umask (0o077) the directory lands on disk as
0o700 and the test failed on the mode assertion instead of on the
base-256 header encoding it is meant to cover:

  expected: int(493)
  actual  : int64(448)

Stat the source entries and mask by info.Umask, matching how the apk
packager asserts the same invariant. The fix under test is unaffected:
with the old call sites restored the test still fails with actual
0x80000000, which is the fs.ModeDir bit the normalization removes.

---------

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
Co-authored-by: Yunare Maia <yunaremaia@users.noreply.github.com>
Co-authored-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: cb68ab4e-96d3-4658-a1c0-c2c33e8c52a0
2026-10-12 17:35:54 +00:00

112 lines
3.1 KiB
Go

package ipk
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"os"
"time"
"github.com/goreleaser/nfpm/v2/files"
)
// newTGZ creates a new tar.gz archive with the given name and populates it
// with the given function.
//
// The function returns the bytes of the archive, its size and an error if any.
func newTGZ(name string, populate func(*tar.Writer) error) ([]byte, error) {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
tarball := tar.NewWriter(gz)
// the writers are properly closed later, this is just in case that we error out
defer gz.Close() // nolint: errcheck
defer tarball.Close() // nolint: errcheck
if err := populate(tarball); err != nil {
return nil, fmt.Errorf("cannot populate '%s': %w", name, err)
}
if err := tarball.Close(); err != nil {
return nil, fmt.Errorf("cannot close '%s': %w", name, err)
}
if err := gz.Close(); err != nil {
return nil, fmt.Errorf("cannot close '%s': %w", name, err)
}
return buf.Bytes(), nil
}
// writeFile writes a file from the filesystem to the tarball.
func writeFile(out *tar.Writer, file *files.Content) (int64, error) {
f, err := os.OpenFile(file.Source, os.O_RDONLY, 0o600) //nolint:gosec
if err != nil {
return 0, fmt.Errorf("could not open file %s to read and include in the archive: %w", file.Source, err)
}
defer f.Close() // nolint: errcheck
header, err := tar.FileInfoHeader(file, file.Source)
if err != nil {
return 0, err
}
content, err := io.ReadAll(f)
if err != nil {
return 0, err
}
size := int64(len(content))
// tar.FileInfoHeader only uses file.Mode().Perm() which masks the mode with
// 0o777 which we don't want because we want to be able to set the suid bit.
// normalizeIPKFileMode keeps the permission and special bits while dropping
// the fs.FileMode type flags, which would otherwise overflow the tar header's
// octal mode field and switch it to base-256 encoding.
header.Mode = normalizeIPKFileMode(file.Mode())
header.Format = tar.FormatGNU
header.Name = files.AsExplicitRelativePath(file.Destination)
header.Size = size
header.Uname = file.FileInfo.Owner
header.Gname = file.FileInfo.Group
if err := out.WriteHeader(header); err != nil {
return 0, fmt.Errorf("cannot write tar header for file %s to archive: %w", file.Source, err)
}
n, err := out.Write(content)
if err != nil {
return 0, fmt.Errorf("%s: failed to copy: %w", file.Source, err)
}
if int64(n) != size {
return 0, fmt.Errorf("%s: failed to copy: expected %d bytes, copied %d", file.Source, size, n)
}
return size, nil
}
// writeToFile writes a file to the tarball where the contents are an array of bytes.
func writeToFile(out *tar.Writer, filename string, content []byte, mtime time.Time) error {
header := tar.Header{
Name: files.AsExplicitRelativePath(filename),
Size: int64(len(content)),
Mode: 0o644,
ModTime: mtime,
Typeflag: tar.TypeReg,
Format: tar.FormatGNU,
}
if err := out.WriteHeader(&header); err != nil {
return fmt.Errorf("cannot write file header %s to archive: %w", header.Name, err)
}
_, err := out.Write(content)
if err != nil {
return fmt.Errorf("cannot write file %s payload: %w", header.Name, err)
}
return nil
}