Skip to content

Commit

Permalink
Left pad parsed auth token bytes (#5265)
Browse files Browse the repository at this point in the history
  • Loading branch information
begelundmuller authored Jul 13, 2024
1 parent f651e7c commit 212db18
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
16 changes: 15 additions & 1 deletion admin/pkg/authtoken/authtoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,10 @@ func FromString(s string) (*Token, error) {
return nil, ErrMalformed
}

if len(payload) != 40 {
if len(payload) > 40 {
return nil, ErrMalformed
} else if len(payload) < 40 {
payload = padLeft(payload, 40)
}

var id [16]byte
Expand Down Expand Up @@ -129,3 +131,15 @@ func unmarshalBase62(s string) ([]byte, bool) {
}
return i.Bytes(), true
}

// padLeft pads a byte slice with zeros on the left such that its length is n.
// If the slice is already longer than n, it is returned as is.
func padLeft(b []byte, n int) []byte {
if len(b) >= n {
return b
}

padded := make([]byte, n)
copy(padded[n-len(b):], b)
return padded
}
44 changes: 44 additions & 0 deletions admin/pkg/authtoken/authtoken_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,47 @@ func TestValidity(t *testing.T) {
require.Equal(t, ErrMalformed, err)
}
}

func TestNull(t *testing.T) {
tkn := Token{
Type: TypeUser,
ID: uuid.UUID{},
Secret: [24]byte{},
}

str := tkn.String()

parsed, err := FromString(str)
require.NoError(t, err)
require.Equal(t, tkn.Type, parsed.Type)
require.Equal(t, tkn.ID, parsed.ID)
require.Equal(t, tkn.Secret, parsed.Secret)
}

func TestPartiallyNull(t *testing.T) {
secret := [24]byte{}
secret[23] = 0x01

tkn := Token{
Type: TypeUser,
ID: uuid.MustParse("00000000-0000-0000-0000-000000000001"),
Secret: secret,
}

str := tkn.String()

parsed, err := FromString(str)
require.NoError(t, err)
require.Equal(t, tkn.Type, parsed.Type)
require.Equal(t, tkn.ID, parsed.ID)
require.Equal(t, tkn.Secret, parsed.Secret)
}

func TestMany(t *testing.T) {
for i := 0; i < 100000; i++ {
tkn := NewRandom(TypeDeployment)
str := tkn.String()
_, err := FromString(str)
require.NoError(t, err)
}
}

0 comments on commit 212db18

Please sign in to comment.