pkg/tarsum: handle xattrs like archive/tar does

When writing a tar file with archive/tar, extended attributes in the
deprecated (tar.Header).Xattrs map take precedence over conflicting
'SCHILY.xattr' records in the (tar.Header).PAXRecords map. Update
package tarsum to follow the same precedence rules as archive/tar.

Signed-off-by: Cory Snider <csnider@mirantis.com>
This commit is contained in:
Cory Snider 2023-10-26 19:23:10 -04:00
parent 7cabe08399
commit 63a9d72ee8
2 changed files with 43 additions and 0 deletions

View file

@ -119,9 +119,20 @@ func v1TarHeaderSelect(h *tar.Header) (orderedHeaders [][2]string) {
var xattrs [][2]string var xattrs [][2]string
for k, v := range h.PAXRecords { for k, v := range h.PAXRecords {
if xattr, ok := strings.CutPrefix(k, paxSchilyXattr); ok { if xattr, ok := strings.CutPrefix(k, paxSchilyXattr); ok {
// h.Xattrs keys take precedence over h.PAXRecords keys, like
// archive/tar does when writing.
if vv, ok := h.Xattrs[xattr]; ok { //nolint:staticcheck // field deprecated in stdlib
v = vv
}
xattrs = append(xattrs, [2]string{xattr, v}) xattrs = append(xattrs, [2]string{xattr, v})
} }
} }
// Get extended attributes which are not in PAXRecords.
for k, v := range h.Xattrs { //nolint:staticcheck // field deprecated in stdlib
if _, ok := h.PAXRecords[paxSchilyXattr+k]; !ok {
xattrs = append(xattrs, [2]string{k, v})
}
}
sort.Slice(xattrs, func(i, j int) bool { return xattrs[i][0] < xattrs[j][0] }) sort.Slice(xattrs, func(i, j int) bool { return xattrs[i][0] < xattrs[j][0] })
// Make the slice with enough capacity to hold the 11 basic headers // Make the slice with enough capacity to hold the 11 basic headers

View file

@ -1,7 +1,13 @@
package tarsum // import "github.com/docker/docker/pkg/tarsum" package tarsum // import "github.com/docker/docker/pkg/tarsum"
import ( import (
"archive/tar"
"fmt"
"strings"
"testing" "testing"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
) )
func TestVersionLabelForChecksum(t *testing.T) { func TestVersionLabelForChecksum(t *testing.T) {
@ -96,3 +102,29 @@ func containsVersion(versions []Version, version Version) bool {
} }
return false return false
} }
func TestSelectXattrsV1(t *testing.T) {
hdr := &tar.Header{
Xattrs: map[string]string{ //nolint:staticcheck
"user.xattronly": "x",
"user.foo": "xattr",
},
PAXRecords: map[string]string{
"SCHILY.xattr.user.paxonly": "p",
"SCHILY.xattr.user.foo": "paxrecord",
},
}
selected := v1TarHeaderSelect(hdr)
var s strings.Builder
for _, elem := range selected {
fmt.Fprintf(&s, "%s=%s\n", elem[0], elem[1])
}
t.Logf("Selected headers:\n%s", s.String())
assert.Check(t, is.DeepEqual(selected[len(selected)-3:], [][2]string{
{"user.foo", "xattr"},
{"user.paxonly", "p"},
{"user.xattronly", "x"},
}))
}