Add option to enforce strict compatibility

Some plugins check for token length. Since PushBits uses longer tokens by default for better security, these plugins are
incompatible. With this patch, users can decide if they want an application to have a short token, so that said plugins
can talk to PushBits again.
This commit is contained in:
eikendev 2021-02-08 00:34:33 +01:00
parent fb90808288
commit d7721e827b
No known key found for this signature in database
GPG key ID: A1BDB1B28C8EF694
8 changed files with 106 additions and 30 deletions

View file

@ -2,13 +2,15 @@ package authentication
import (
"crypto/rand"
"log"
"math/big"
)
var (
tokenCharacters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
randomTokenLength = 64
applicationPrefix = "A"
tokenCharacters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
standardTokenLength = 64 // This length includes the prefix (one character).
compatTokenLength = 15 // This length includes the prefix (one character).
applicationPrefix = "A"
)
func randIntn(n int) int {
@ -23,9 +25,9 @@ func randIntn(n int) int {
}
// GenerateNotExistingToken receives a token generation function and a function to check whether the token exists, returns a unique token.
func GenerateNotExistingToken(generateToken func() string, tokenExists func(token string) bool) string {
func GenerateNotExistingToken(generateToken func(bool) string, compat bool, tokenExists func(token string) bool) string {
for {
token := generateToken()
token := generateToken(compat)
if !tokenExists(token) {
return token
@ -44,11 +46,23 @@ func generateRandomString(length int) string {
return string(res)
}
func generateRandomToken(prefix string) string {
return prefix + generateRandomString(randomTokenLength)
func generateRandomToken(prefix string, compat bool) string {
tokenLength := standardTokenLength
if compat {
tokenLength = compatTokenLength
}
// Although constant at the time of writing, this check should prevent future changes from generating insecure tokens.
randomLength := tokenLength - len(prefix)
if randomLength < 14 {
log.Fatalf("Tokens should have more than %d random characters", randomLength)
}
return prefix + generateRandomString(randomLength)
}
// GenerateApplicationToken generates a token for an application.
func GenerateApplicationToken() string {
return generateRandomToken(applicationPrefix)
func GenerateApplicationToken(compat bool) string {
return generateRandomToken(applicationPrefix, compat)
}