-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
333 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
package token | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
"time" | ||
|
||
"github.com/elisasre/go-common" | ||
"github.com/golang-jwt/jwt" | ||
) | ||
|
||
// Token struct. | ||
type Token struct { | ||
User *common.User | ||
} | ||
|
||
const ( | ||
OpenID = "openid" | ||
Profile = "profile" | ||
Email = "email" | ||
Groups = "groups" | ||
Internal = "internal" | ||
) | ||
|
||
var AllScopes = []string{OpenID, Profile, Email, Groups, Internal} | ||
|
||
// SignClaims contains claims that are passed to SignExpires func. | ||
type SignClaims struct { | ||
Aud string | ||
Exp int64 | ||
Iat int64 | ||
Issuer string | ||
Nonce string | ||
Scopes []string | ||
} | ||
|
||
// SignAlgo const. | ||
const SignAlgo = "RS256" | ||
|
||
// New constructs new token which is passed for application. | ||
func New(user *common.User) *Token { | ||
return &Token{User: user} | ||
} | ||
|
||
// UserJWTClaims contains struct for making and parsing jwt tokens. | ||
type UserJWTClaims struct { | ||
*common.User | ||
jwt.StandardClaims | ||
Nonce string `json:"nonce,omitempty"` | ||
} | ||
|
||
// SignExpires makes new jwt token using expiration time and secret. | ||
func (t *Token) SignExpires(key common.JWTKey, claim SignClaims) (string, error) { | ||
t.User.Email = common.String(strings.ToLower(common.StringValue(t.User.Email))) | ||
sub := t.User.MakeSub() | ||
if claim.Iat == 0 { | ||
claim.Iat = time.Now().Unix() | ||
} | ||
|
||
if !common.Contains(claim.Scopes, OpenID) { | ||
return "", fmt.Errorf("token must contain '%s' scope", OpenID) | ||
} | ||
|
||
if !common.Contains(claim.Scopes, Internal) { | ||
t.User.Internal = nil | ||
} | ||
|
||
if !common.Contains(claim.Scopes, Email) { | ||
t.User.Email = nil | ||
t.User.EmailVerified = nil | ||
} | ||
|
||
if !common.Contains(claim.Scopes, Groups) { | ||
t.User.Groups = nil | ||
} | ||
|
||
if !common.Contains(claim.Scopes, Profile) { | ||
t.User.Name = nil | ||
} | ||
|
||
claims := UserJWTClaims{ | ||
t.User, | ||
jwt.StandardClaims{ | ||
Subject: sub, | ||
Audience: claim.Aud, | ||
ExpiresAt: claim.Exp, | ||
Issuer: claim.Issuer, | ||
IssuedAt: claim.Iat, | ||
}, | ||
claim.Nonce, | ||
} | ||
method := jwt.SigningMethodRS256 | ||
token := jwt.Token{ | ||
Header: map[string]interface{}{ | ||
"typ": "JWT", | ||
"alg": method.Alg(), | ||
"kid": key.KID, | ||
}, | ||
Claims: claims, | ||
Method: method, | ||
} | ||
if key.PrivateKey == nil { | ||
return "", fmt.Errorf("privatekey is nil for key %d", key.ID) | ||
} | ||
return token.SignedString(key.PrivateKey) | ||
} | ||
|
||
func findKidFromArray(keys []common.JWTKey, kid interface{}) (common.JWTKey, error) { | ||
kidAsString, ok := kid.(string) | ||
if !ok { | ||
return common.JWTKey{}, fmt.Errorf("not str") | ||
} | ||
for _, s := range keys { | ||
if s.KID == kidAsString { | ||
return s, nil | ||
} | ||
} | ||
return common.JWTKey{}, fmt.Errorf("could not find kid '%s'", kidAsString) | ||
} | ||
|
||
// Parse will validate jwt token and return token. | ||
func Parse(raw string, keys []common.JWTKey) (*UserJWTClaims, error) { | ||
parsed, err := jwt.ParseWithClaims(raw, &UserJWTClaims{}, func(t *jwt.Token) (interface{}, error) { | ||
if t.Method.Alg() != SignAlgo { | ||
return nil, jwt.ErrSignatureInvalid | ||
} | ||
if val, ok := t.Header["kid"]; ok { | ||
key, err := findKidFromArray(keys, val) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return key.PublicKey, nil | ||
} | ||
return nil, fmt.Errorf("could not find kid from headers") | ||
}) | ||
if err != nil { | ||
return nil, err | ||
} else if !parsed.Valid { | ||
return nil, jwt.ValidationError{} | ||
} | ||
|
||
claims, ok := parsed.Claims.(*UserJWTClaims) | ||
if !ok { | ||
return nil, fmt.Errorf("could not parse struct") | ||
} | ||
return claims, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
package token | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
"testing" | ||
"time" | ||
|
||
"github.com/elisasre/go-common" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestToken(t *testing.T) { | ||
key, err := common.GenerateNewKeyPair() | ||
require.NoError(t, err) | ||
|
||
fullUser := common.User{ | ||
Name: common.String("Test User"), | ||
Email: common.String("[email protected]"), | ||
Groups: []string{"group1", "group2"}, | ||
EmailVerified: common.Bool(true), | ||
Internal: &common.Internal{ | ||
EmployeeID: "123456", | ||
MFA: common.Bool(true), | ||
}, | ||
} | ||
|
||
type testCase struct { | ||
name string | ||
scopes []string | ||
err error | ||
user *common.User | ||
} | ||
|
||
testCases := []testCase{ | ||
{ | ||
name: "all scopes", | ||
scopes: AllScopes, | ||
user: &common.User{ | ||
Name: common.String("Test User"), | ||
Email: common.String("[email protected]"), | ||
Groups: []string{"group1", "group2"}, | ||
EmailVerified: common.Bool(true), | ||
Internal: &common.Internal{ | ||
EmployeeID: "123456", | ||
MFA: common.Bool(true), | ||
}, | ||
}, | ||
}, | ||
{ | ||
name: "openid", | ||
scopes: []string{OpenID}, | ||
user: nil, | ||
}, | ||
{ | ||
name: "openid profile", | ||
scopes: []string{OpenID, Profile}, | ||
user: &common.User{Name: common.String("Test User")}, | ||
}, | ||
{ | ||
name: "openid email", | ||
scopes: []string{OpenID, Email}, | ||
user: &common.User{ | ||
Email: common.String("[email protected]"), | ||
EmailVerified: common.Bool(true), | ||
}, | ||
}, | ||
{ | ||
name: "openid groups", | ||
scopes: []string{OpenID, Groups}, | ||
user: &common.User{ | ||
Groups: []string{"group1", "group2"}, | ||
}, | ||
}, | ||
{ | ||
name: "openid internal", | ||
scopes: []string{OpenID, Internal}, | ||
user: &common.User{ | ||
Internal: &common.Internal{ | ||
EmployeeID: "123456", | ||
MFA: common.Bool(true), | ||
}, | ||
}, | ||
}, | ||
{ | ||
name: "no openid scope", | ||
scopes: []string{}, | ||
err: fmt.Errorf("token must contain '%s' scope", OpenID), | ||
}, | ||
} | ||
|
||
for _, tc := range testCases { | ||
t.Run(tc.name, func(t *testing.T) { | ||
user := tc.user | ||
newUser := fullUser | ||
testUser := New(&newUser) | ||
token, err := testUser.SignExpires(*key, SignClaims{ | ||
Aud: "internal", | ||
Exp: time.Now().Add(time.Hour).Unix(), | ||
Issuer: "http://localhost", | ||
Scopes: tc.scopes, | ||
}) | ||
if tc.err != nil { | ||
require.Equal(t, tc.err, err) | ||
} else { | ||
require.NoError(t, err) | ||
userClaims, err := Parse(token, []common.JWTKey{*key}) | ||
require.NoError(t, err) | ||
require.Equal(t, user, userClaims.User) | ||
} | ||
}) | ||
} | ||
} | ||
|
||
func TestInvalidKid(t *testing.T) { | ||
key, err := common.GenerateNewKeyPair() | ||
require.NoError(t, err) | ||
key2, err := common.GenerateNewKeyPair() | ||
require.NoError(t, err) | ||
|
||
testUser := New(&common.User{}) | ||
token, err := testUser.SignExpires(*key, SignClaims{ | ||
Aud: "internal", | ||
Exp: time.Now().Add(time.Hour).Unix(), | ||
Issuer: "http://localhost", | ||
Scopes: AllScopes, | ||
}) | ||
require.NoError(t, err) | ||
_, err = Parse(token, []common.JWTKey{*key2}) | ||
require.Equal(t, fmt.Sprintf("could not find kid '%s'", key.KID), err.Error()) | ||
} | ||
|
||
func TestExpired(t *testing.T) { | ||
key, err := common.GenerateNewKeyPair() | ||
require.NoError(t, err) | ||
|
||
testUser := New(&common.User{}) | ||
token, err := testUser.SignExpires(*key, SignClaims{ | ||
Aud: "internal", | ||
Exp: 1, | ||
Issuer: "http://localhost", | ||
Scopes: AllScopes, | ||
}) | ||
require.NoError(t, err) | ||
_, err = Parse(token, []common.JWTKey{*key}) | ||
require.True(t, strings.HasPrefix(err.Error(), "token is expired by")) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters