Refactor for session management (#193)

Previously every Handler function was receiving the session token in the
form of a jwt string, in consequence every time we want to access the
encrypted claims of the jwt we needed to run a decryption process,
additionally we were decrypting the jwt twice, first at the session
validation then inside each handler function, this was also causing a
lot of using related to the merge between m3 and mcs

What changed:

Now we validate and decrypt the jwt once in `configure_mcs.go`, this
works for both, mcs (console) and operator sessions, and then pass the
decrypted claims to all the functions that need it, so no further token
validation or decryption is need it.
This commit is contained in:
Lenin Alevski
2020-07-10 19:14:28 -07:00
committed by GitHub
parent 93e1168141
commit 697bc4cd1d
34 changed files with 618 additions and 605 deletions

View File

@@ -32,6 +32,7 @@ import (
jwtgo "github.com/dgrijalva/jwt-go"
"github.com/go-openapi/swag"
"github.com/minio/mcs/models"
xjwt "github.com/minio/mcs/pkg/auth/jwt"
"github.com/minio/minio-go/v6/pkg/credentials"
uuid "github.com/satori/go.uuid"
@@ -210,7 +211,7 @@ func GetTokenFromRequest(r *http.Request) (*string, error) {
return swag.String(reqToken), nil
}
func GetClaimsFromTokenInRequest(req *http.Request) (*DecryptedClaims, error) {
func GetClaimsFromTokenInRequest(req *http.Request) (*models.Principal, error) {
sessionID, err := GetTokenFromRequest(req)
if err != nil {
return nil, err
@@ -221,5 +222,10 @@ func GetClaimsFromTokenInRequest(req *http.Request) (*DecryptedClaims, error) {
if err != nil {
return nil, err
}
return claims, nil
return &models.Principal{
AccessKeyID: claims.AccessKeyID,
Actions: claims.Actions,
SecretAccessKey: claims.SecretAccessKey,
SessionToken: claims.SessionToken,
}, nil
}

View File

@@ -1,77 +0,0 @@
package auth
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"testing"
)
// RoundTripFunc .
type RoundTripFunc func(req *http.Request) (*http.Response, error)
// RoundTrip .
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
//NewTestClient returns *http.Client with Transport replaced to avoid making real calls
func NewTestClient(fn RoundTripFunc) *http.Client {
return &http.Client{
Transport: fn,
}
}
func Test_isServiceAccountTokenValid(t *testing.T) {
successResponse := NewTestClient(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),
Header: make(http.Header),
}, nil
})
failResponse := NewTestClient(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 500,
Body: ioutil.NopCloser(bytes.NewBufferString(`NOTOK`)),
Header: make(http.Header),
}, errors.New("something wrong")
})
type args struct {
client *http.Client
jwt string
}
tests := []struct {
name string
args args
want bool
}{
{
name: "Success authentication - correct jwt (service account token)",
args: args{
client: successResponse,
jwt: "GOODTOKEN",
},
want: true,
},
{
name: "Fail authentication - incorrect jwt (service account token)",
args: args{
client: failResponse,
jwt: "BADTOKEN",
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isServiceAccountTokenValid(tt.args.client, tt.args.jwt); got != tt.want {
t.Errorf("isServiceAccountTokenValid() = %v, want %v", got, tt.want)
}
})
}
}

View File

@@ -17,12 +17,12 @@
package auth
import (
"fmt"
"context"
"log"
"net/http"
"github.com/minio/mcs/cluster"
"github.com/minio/minio-go/v6/pkg/credentials"
operatorClientset "github.com/minio/minio-operator/pkg/client/clientset/versioned"
)
// operatorCredentialsProvider is an struct to hold the JWT (service account token)
@@ -44,16 +44,31 @@ func (s operatorCredentialsProvider) IsExpired() bool {
return false
}
// isServiceAccountTokenValid will make an authenticated request (using bearer token) against kubernetes api, if the
// OperatorClient interface with all functions to be implemented
// by mock when testing, it should include all OperatorClient respective api calls
// that are used within this project.
type OperatorClient interface {
Authenticate(context.Context) ([]byte, error)
}
// Interface implementation
//
// Define the structure of a operator client and define the functions that are actually used
// from the minio-operator.
type operatorClient struct {
client *operatorClientset.Clientset
}
// Authenticate implements the operator authenticate function via REST /api
func (c *operatorClient) Authenticate(ctx context.Context) ([]byte, error) {
return c.client.RESTClient().Verb("GET").RequestURI("/api").DoRaw(ctx)
}
// isServiceAccountTokenValid will make an authenticated request against kubernetes api, if the
// request success means the provided jwt its a valid service account token and the MCS user can use it for future
// requests until it fails
func isServiceAccountTokenValid(client *http.Client, jwt string) bool {
//# Explore the API with TOKEN
//curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure
apiURL := fmt.Sprintf("%s/api", cluster.GetK8sAPIServer())
req, _ := http.NewRequest("GET", apiURL, nil)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", jwt))
_, err := client.Do(req)
// requests until it expires
func isServiceAccountTokenValid(ctx context.Context, operatorClient OperatorClient) bool {
_, err := operatorClient.Authenticate(ctx)
if err != nil {
log.Println(err)
return false
@@ -63,8 +78,15 @@ func isServiceAccountTokenValid(client *http.Client, jwt string) bool {
// GetMcsCredentialsForOperator will validate the provided JWT (service account token) and return it in the form of credentials.Credentials
func GetMcsCredentialsForOperator(jwt string) (*credentials.Credentials, error) {
client := http.Client{}
if isServiceAccountTokenValid(&client, jwt) {
ctx := context.Background()
opClientClientSet, err := cluster.OperatorClient(jwt)
if err != nil {
return nil, err
}
opClient := &operatorClient{
client: opClientClientSet,
}
if isServiceAccountTokenValid(ctx, opClient) {
return credentials.New(operatorCredentialsProvider{serviceAccountJWT: jwt}), nil
}
return nil, errInvalidCredentials

82
pkg/auth/operator_test.go Normal file
View File

@@ -0,0 +1,82 @@
package auth
import (
"context"
"errors"
"testing"
"github.com/minio/mcs/cluster"
operatorClientset "github.com/minio/minio-operator/pkg/client/clientset/versioned"
)
type operatorClientTest struct {
client *operatorClientset.Clientset
}
var operatorAuthenticateMock func(ctx context.Context) ([]byte, error)
// MinIOInstanceDelete implements the minio instance delete action from minio-operator
func (c *operatorClientTest) Authenticate(ctx context.Context) ([]byte, error) {
return operatorAuthenticateMock(ctx)
}
func Test_isServiceAccountTokenValid(t *testing.T) {
successResponse := func() {
operatorAuthenticateMock = func(ctx context.Context) ([]byte, error) {
return nil, nil
}
}
failResponse := func() {
operatorAuthenticateMock = func(ctx context.Context) ([]byte, error) {
return nil, errors.New("something went wrong")
}
}
opClientClientSet, _ := cluster.OperatorClient("")
opClient := &operatorClientTest{
client: opClientClientSet,
}
type args struct {
ctx context.Context
operatorClient *operatorClientTest
mockFunction func()
}
tests := []struct {
name string
args args
want bool
}{
{
name: "Success authentication - correct jwt (service account token)",
args: args{
ctx: context.Background(),
operatorClient: opClient,
mockFunction: successResponse,
},
want: true,
},
{
name: "Fail authentication - incorrect jwt (service account token)",
args: args{
ctx: context.Background(),
operatorClient: opClient,
mockFunction: failResponse,
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.mockFunction != nil {
tt.args.mockFunction()
}
if got := isServiceAccountTokenValid(tt.args.ctx, tt.args.operatorClient); got != tt.want {
t.Errorf("isServiceAccountTokenValid() = %v, want %v", got, tt.want)
}
})
}
}