2017-05-15 15:34:14 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
2022-11-02 21:05:45 +00:00
|
|
|
"strings"
|
2017-05-15 15:34:14 +00:00
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2020-08-24 11:18:39 +00:00
|
|
|
"github.com/distribution/distribution/v3/registry/auth"
|
2017-05-15 15:34:14 +00:00
|
|
|
"github.com/docker/libtrust"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestCreateJWTSuccessWithEmptyACL(t *testing.T) {
|
|
|
|
key, err := rsa.GenerateKey(rand.Reader, 1024)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
pk, err := libtrust.FromCryptoPrivateKey(key)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
tokenIssuer := TokenIssuer{
|
|
|
|
Expiration: time.Duration(100),
|
|
|
|
Issuer: "localhost",
|
|
|
|
SigningKey: pk,
|
|
|
|
}
|
|
|
|
|
2020-02-23 01:27:55 +00:00
|
|
|
grantedAccessList := make([]auth.Access, 0)
|
2017-05-15 15:34:14 +00:00
|
|
|
token, err := tokenIssuer.CreateJWT("test", "test", grantedAccessList)
|
2020-02-23 01:27:55 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
2017-05-15 15:34:14 +00:00
|
|
|
|
|
|
|
tokens := strings.Split(token, ".")
|
|
|
|
|
|
|
|
if len(token) == 0 {
|
|
|
|
t.Fatal("token not generated.")
|
|
|
|
}
|
|
|
|
|
|
|
|
json, err := decodeJWT(tokens[1])
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !strings.Contains(json, "test") {
|
|
|
|
t.Fatal("Valid token was not generated.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func decodeJWT(rawToken string) (string, error) {
|
|
|
|
data, err := joseBase64Decode(rawToken)
|
|
|
|
if err != nil {
|
|
|
|
return "", errors.New("Error in Decoding base64 String")
|
|
|
|
}
|
|
|
|
return data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func joseBase64Decode(s string) (string, error) {
|
|
|
|
switch len(s) % 4 {
|
|
|
|
case 0:
|
|
|
|
case 2:
|
|
|
|
s += "=="
|
|
|
|
case 3:
|
|
|
|
s += "="
|
|
|
|
default:
|
|
|
|
{
|
|
|
|
return "", errors.New("Invalid base64 String")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
data, err := base64.StdEncoding.DecodeString(s)
|
|
|
|
if err != nil {
|
2022-11-02 21:05:45 +00:00
|
|
|
return "", err // errors.New("Error in Decoding base64 String")
|
2017-05-15 15:34:14 +00:00
|
|
|
}
|
|
|
|
return string(data), nil
|
|
|
|
}
|