netbird/management/server/personal_access_token_test.go

47 lines
1.2 KiB
Go
Raw Permalink Normal View History

package server
import (
"crypto/sha256"
2023-03-29 15:21:53 +02:00
b64 "encoding/base64"
"hash/crc32"
"math/big"
"strings"
"testing"
"github.com/stretchr/testify/assert"
2023-05-16 12:57:56 +02:00
"github.com/netbirdio/netbird/base62"
)
func TestPAT_GenerateToken_Hashing(t *testing.T) {
2023-03-08 11:36:03 +01:00
hashedToken, plainToken, _ := generateNewToken()
2023-03-08 11:30:09 +01:00
expectedToken := sha256.Sum256([]byte(plainToken))
2023-03-29 15:21:53 +02:00
encodedExpectedToken := b64.StdEncoding.EncodeToString(expectedToken[:])
assert.Equal(t, hashedToken, encodedExpectedToken)
}
func TestPAT_GenerateToken_Prefix(t *testing.T) {
2023-03-08 11:36:03 +01:00
_, plainToken, _ := generateNewToken()
2023-03-06 13:49:07 +01:00
fourCharPrefix := plainToken[:4]
2023-03-08 11:54:10 +01:00
assert.Equal(t, PATPrefix, fourCharPrefix)
}
func TestPAT_GenerateToken_Checksum(t *testing.T) {
2023-03-08 11:36:03 +01:00
_, plainToken, _ := generateNewToken()
tokenWithoutPrefix := strings.Split(plainToken, "_")[1]
if len(tokenWithoutPrefix) != 36 {
t.Fatal("Token has wrong length")
}
2023-03-06 13:49:07 +01:00
secret := tokenWithoutPrefix[:len(tokenWithoutPrefix)-6]
tokenCheckSum := tokenWithoutPrefix[len(tokenWithoutPrefix)-6:]
var i big.Int
i.SetString(secret, 62)
2023-03-06 13:49:07 +01:00
expectedChecksum := crc32.ChecksumIEEE([]byte(secret))
2023-05-16 12:57:56 +02:00
actualChecksum, err := base62.Decode(tokenCheckSum)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, expectedChecksum, actualChecksum)
}