diff --git a/v2/spiffeid/path.go b/v2/spiffeid/path.go index 7c75602c..d65dc8f0 100644 --- a/v2/spiffeid/path.go +++ b/v2/spiffeid/path.go @@ -23,7 +23,7 @@ func FormatPath(format string, args ...interface{}) (string, error) { func JoinPathSegments(segments ...string) (string, error) { var builder strings.Builder for _, segment := range segments { - if err := validatePathSegment(segment); err != nil { + if err := ValidatePathSegment(segment); err != nil { return "", err } builder.WriteByte('/') @@ -71,9 +71,15 @@ func ValidatePath(path string) error { return nil } -func validatePathSegment(segment string) error { - if segment == "" { +// ValidatePathSegment validates that a string is a conformant segment for +// inclusion in the path for a SPIFFE ID. +// See https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE-ID.md#22-path +func ValidatePathSegment(segment string) error { + switch segment { + case "": return errEmptySegment + case ".", "..": + return errDotSegment } for i := 0; i < len(segment); i++ { if !isValidPathSegmentChar(segment[i]) { diff --git a/v2/spiffeid/path_test.go b/v2/spiffeid/path_test.go new file mode 100644 index 00000000..6e61c7bd --- /dev/null +++ b/v2/spiffeid/path_test.go @@ -0,0 +1,58 @@ +package spiffeid + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestJoinPathSegments(t *testing.T) { + assertBad := func(t *testing.T, expectErr error, segments ...string) { + _, err := JoinPathSegments(segments...) + assert.ErrorIs(t, err, expectErr) + } + assertOK := func(t *testing.T, expectPath string, segments ...string) { + path, err := JoinPathSegments(segments...) + if assert.NoError(t, err) { + assert.Equal(t, expectPath, path) + } + } + + t.Run("empty", func(t *testing.T) { + assertBad(t, errEmptySegment, "") + }) + t.Run("single dot", func(t *testing.T) { + assertBad(t, errDotSegment, ".") + }) + t.Run("double dot", func(t *testing.T) { + assertBad(t, errDotSegment, "..") + }) + t.Run("invalid char", func(t *testing.T) { + assertBad(t, errBadPathSegmentChar, "/") + }) + t.Run("valid segment", func(t *testing.T) { + assertOK(t, "/a", "a") + }) + t.Run("valid segments", func(t *testing.T) { + assertOK(t, "/a/b", "a", "b") + }) +} + +func TestValidatePathSegment(t *testing.T) { + t.Run("empty", func(t *testing.T) { + require.ErrorIs(t, ValidatePathSegment(""), errEmptySegment) + }) + t.Run("single dot", func(t *testing.T) { + require.ErrorIs(t, ValidatePathSegment("."), errDotSegment) + }) + t.Run("double dot", func(t *testing.T) { + require.ErrorIs(t, ValidatePathSegment(".."), errDotSegment) + }) + t.Run("invalid char", func(t *testing.T) { + require.ErrorIs(t, ValidatePathSegment("/"), errBadPathSegmentChar) + }) + t.Run("valid segment", func(t *testing.T) { + require.NoError(t, ValidatePathSegment("a")) + }) +}