From 176e8d35ced48100844b67701c5b78b10c85d4b5 Mon Sep 17 00:00:00 2001 From: Changwei Ge Date: Wed, 2 Nov 2022 19:17:59 +0800 Subject: [PATCH] image/label: print more characters of label keys Like stargz and nydus remote snapshotter, some snapshots lables are introduced and passed to snapshotter from containerd automatically. The label keys' length are all longer than 10. The limitation of 10 characters makes it harder to debug what label is not appropriate. So we'd better to print more of the wrong label. Signed-off-by: Changwei Ge --- labels/validate.go | 11 +++++++---- labels/validate_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/labels/validate.go b/labels/validate.go index 1fd527adb..f83b5dde2 100644 --- a/labels/validate.go +++ b/labels/validate.go @@ -24,15 +24,18 @@ import ( const ( maxSize = 4096 + // maximum length of key portion of error message if len of key + len of value > maxSize + keyMaxLen = 64 ) // Validate a label's key and value are under 4096 bytes func Validate(k, v string) error { - if (len(k) + len(v)) > maxSize { - if len(k) > 10 { - k = k[:10] + total := len(k) + len(v) + if total > maxSize { + if len(k) > keyMaxLen { + k = k[:keyMaxLen] } - return fmt.Errorf("label key and value greater than maximum size (%d bytes), key: %s: %w", maxSize, k, errdefs.ErrInvalidArgument) + return fmt.Errorf("label key and value length (%d bytes) greater than maximum size (%d bytes), key: %s: %w", total, maxSize, k, errdefs.ErrInvalidArgument) } return nil } diff --git a/labels/validate_test.go b/labels/validate_test.go index 1368fc5b7..628f2fd7a 100644 --- a/labels/validate_test.go +++ b/labels/validate_test.go @@ -21,6 +21,7 @@ import ( "testing" "github.com/containerd/containerd/errdefs" + "github.com/stretchr/testify/assert" ) func TestValidLabels(t *testing.T) { @@ -51,3 +52,29 @@ func TestInvalidLabels(t *testing.T) { } } } + +func TestLongKey(t *testing.T) { + key := strings.Repeat("s", keyMaxLen+1) + value := strings.Repeat("v", maxSize-len(key)) + + err := Validate(key, value) + assert.Equal(t, err, nil) + + key = strings.Repeat("s", keyMaxLen+12) + value = strings.Repeat("v", maxSize-len(key)+1) + + err = Validate(key, value) + assert.ErrorIs(t, err, errdefs.ErrInvalidArgument) + + key = strings.Repeat("s", keyMaxLen-1) + value = strings.Repeat("v", maxSize-len(key)) + + err = Validate(key, value) + assert.Equal(t, err, nil) + + key = strings.Repeat("s", keyMaxLen-1) + value = strings.Repeat("v", maxSize-len(key)-1) + + err = Validate(key, value) + assert.Equal(t, err, nil) +}