Key can be anything, even empty
Edmartt opened this issue · comments
Line 71 in 0d2f0d4
I think this line needs to be validated because I was making a mistake here, forgot to set env var and even like that the key string travels empty and it's assigned. I'm not sure if this is just my fault and a trivial thing but if not, It's a thing to be careful about.
i.e if you turn the secret key into bytes(array) the array will be empty
For refererences, look at this:
I realized that even when SignedString method has interface as param, if you don't send a bytes array, the returned value is an empty string
this is the response in this case:
And now look at this:
This is the response in this case:
If the type is an interface I can send a string without any problem, but that is the response when I'm not sending the data as bytes
Hi @Edmartt
There are two issues here
-
Regarding your first post: yes, we do not really check whether you pass an empty array as a key. This is somewhat in the responsibility of the caller. Because of course we could check if it is empty, but then we could argue that a key of size 1 is also not suitable, etc.
-
Yes, because of the way the API works (it was built back when we did not have generics in Go), the key can be
any
orinterface{}
. So yes you can pass in astring
. BUT, you will get an error"key is of invalid type"
(ErrInvalidKeyType
) and the token will be empty. So in your second example, yes the token is empty, but you also ignored the error value.
I think this is working as intended, so closing the issue. But feel free to continue the discussion.
Agree with the points Christian mentioned above, although checking for the error won't help here since token.SignedString([]byte(""))
is valid, unfortunately. So ensuring you have a valid key non-empty is very important.
Side note, it's a Go best practice to check for errors and avoid using return values if err != nil
, so this bit:
func X() (tokenString string, err error) {
tokenString, tokenError := token.SignedString(secretKeyBytes)
if tokenError != nil{
return
}
}
should really be returning an error instead of a named return (which will be nil
). E.g.,
func X() (string, error) {
tokenString, err := token.SignedString(secretKeyBytes)
if err != nil{
// let the caller gracefully handle the error
// https://go.dev/doc/effective_go#errors
return "", err
}
// use return value only once we checked for an error
return tokenString, nil
}