Don't log error on invalid token (#50056)

- Removed error logging
 - Tiny improvement to doc
 - Added unit test
This commit is contained in:
David Veszelovszki 2023-03-28 16:54:03 +02:00 committed by GitHub
parent 48a265d4b1
commit 45b78101b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 8 deletions

View File

@ -107,12 +107,6 @@ func AccessTokenAuthMiddleware(db database.DB, logger log.Logger, next http.Hand
subjectUserID, err := db.AccessTokens().Lookup(r.Context(), token, requiredScope)
if err != nil {
if err == database.ErrAccessTokenNotFound || errors.HasType(err, database.InvalidTokenError{}) {
logger.Error(
"invalid access token",
log.String("token", token),
log.Error(err),
)
anonymousId, anonCookieSet := cookie.AnonymousUID(r)
if !anonCookieSet {
anonymousId = fmt.Sprintf("unknown user @ %s", time.Now()) // we don't have a reliable user identifier at the time of the failure

View File

@ -443,8 +443,8 @@ func (s *accessTokenStore) delete(ctx context.Context, cond *sqlf.Query) error {
return nil
}
// tokenSHA256Hash returns the SHA-256 hash of its hex-encoded value (after stripping the "sgp_"
// token prefix, if present).
// tokenSHA256Hash returns the 32-byte long SHA-256 hash of its hex-encoded value
// (after stripping the "sgp_" token prefix, if present).
func tokenSHA256Hash(token string) ([]byte, error) {
token = strings.TrimPrefix(token, personalAccessTokenPrefix)
value, err := hex.DecodeString(token)

View File

@ -436,3 +436,29 @@ func TestAccessTokens_Lookup_deletedUser(t *testing.T) {
}
})
}
func TestAccessTokens_tokenSHA256Hash(t *testing.T) {
testCases := []struct {
name string
token string
wantError bool
}{
{name: "empty", token: ""},
{name: "short", token: "abc123"},
{name: "invalid", token: "×", wantError: true},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
hash, err := tokenSHA256Hash(tc.token)
if tc.wantError {
assert.ErrorContains(t, err, "invalid token")
} else {
assert.NoError(t, err)
if len(hash) != 32 {
t.Errorf("got %d characters, want 32", len(hash))
}
}
})
}
}