Move authenticate service into auth method service (#635)
This was always an RPC-only distinction and from that perspective it makes sense; however it causes the generated docs to treat it as an entirely separate service even though it's under the same collection path as auth methods and this is confusing.
This commit is contained in:
1 parent
0f1fbea8f7
commit
dd8973dd9f
14 files changed
+1019
-1349
No files matched your search
@@ -23,7 +23,6 @@ import (
|
||||
"github.com/hashicorp/shared-secure-libs/configutil"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/authenticate"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/authtokens"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/groups"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/host_catalogs"
|
||||
@@ -108,14 +107,7 @@ func handleGrpcGateway(c *Controller, props HandlerProperties) (http.Handler, er
|
||||
if err := services.RegisterAccountServiceHandlerServer(ctx, mux, accts); err != nil {
|
||||
return nil, fmt.Errorf("failed to register account service handler: %w", err)
|
||||
}
|
||||
auths, err := authenticate.NewService(c.kms, c.PasswordAuthRepoFn, c.IamRepoFn, c.AuthTokenRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create authentication handler service: %w", err)
|
||||
}
|
||||
if err := services.RegisterAuthenticationServiceHandlerServer(ctx, mux, auths); err != nil {
|
||||
return nil, fmt.Errorf("failed to register authenticate service handler: %w", err)
|
||||
}
|
||||
authMethods, err := authmethods.NewService(c.PasswordAuthRepoFn, c.IamRepoFn)
|
||||
authMethods, err := authmethods.NewService(c.kms, c.PasswordAuthRepoFn, c.IamRepoFn, c.AuthTokenRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create auth method handler service: %w", err)
|
||||
}
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
package authenticate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
pba "github.com/hashicorp/boundary/internal/gen/controller/api/resources/authtokens"
|
||||
"github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
const (
|
||||
loginNameKey = "login_name"
|
||||
pwKey = "password"
|
||||
)
|
||||
|
||||
var (
|
||||
reInvalidID = regexp.MustCompile("[^A-Za-z0-9]")
|
||||
)
|
||||
|
||||
// Service handles request as described by the pbs.OrgServiceServer interface.
|
||||
type Service struct {
|
||||
kms *kms.Kms
|
||||
pwRepo common.PasswordAuthRepoFactory
|
||||
iamRepo common.IamRepoFactory
|
||||
authTokenRepo common.AuthTokenRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns an org service which handles org related requests to boundary.
|
||||
func NewService(kms *kms.Kms, pwRepo common.PasswordAuthRepoFactory, iamRepo common.IamRepoFactory, atRepo common.AuthTokenRepoFactory) (Service, error) {
|
||||
if kms == nil {
|
||||
return Service{}, errors.New("nil kms provided")
|
||||
}
|
||||
if iamRepo == nil {
|
||||
return Service{}, errors.New("nil iam repository provided")
|
||||
}
|
||||
if atRepo == nil {
|
||||
return Service{}, errors.New("nil auth token repository provided")
|
||||
}
|
||||
if pwRepo == nil {
|
||||
return Service{}, errors.New("nil password repository provided")
|
||||
}
|
||||
|
||||
return Service{kms: kms, pwRepo: pwRepo, iamRepo: iamRepo, authTokenRepo: atRepo}, nil
|
||||
}
|
||||
|
||||
var _ pbs.AuthenticationServiceServer = Service{}
|
||||
|
||||
// Authenticate implements the interface pbs.AuthenticationServiceServer.
|
||||
func (s Service) Authenticate(ctx context.Context, req *pbs.AuthenticateRequest) (*pbs.AuthenticateResponse, error) {
|
||||
if err := validateAuthenticateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetAuthMethodId(), action.Authenticate)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
creds := req.GetCredentials().GetFields()
|
||||
tok, err := s.authenticateWithRepo(ctx, authResults.Scope.GetId(), req.GetAuthMethodId(), creds[loginNameKey].GetStringValue(), creds[pwKey].GetStringValue())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pbs.AuthenticateResponse{Item: tok, TokenType: req.GetTokenType()}, nil
|
||||
}
|
||||
|
||||
func (s Service) authenticateWithRepo(ctx context.Context, scopeId, authMethodId, loginName, pw string) (*pba.AuthToken, error) {
|
||||
iamRepo, err := s.iamRepo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
atRepo, err := s.authTokenRepo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pwRepo, err := s.pwRepo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
acct, err := pwRepo.Authenticate(ctx, scopeId, authMethodId, loginName, pw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if acct == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Unauthenticated, "Unable to authenticate.")
|
||||
}
|
||||
|
||||
u, err := iamRepo.LookupUserWithLogin(ctx, acct.GetPublicId(), iam.WithAutoVivify(true))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tok, err := atRepo.CreateAuthToken(ctx, u, acct.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
token, err := authtoken.EncryptToken(ctx, s.kms, scopeId, tok.GetPublicId(), tok.GetToken())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tok.Token = tok.GetPublicId() + "_" + token
|
||||
prot := toProto(tok)
|
||||
|
||||
scp, err := iamRepo.LookupScope(ctx, u.GetScopeId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if scp == nil {
|
||||
return nil, err
|
||||
}
|
||||
prot.Scope = &scopes.ScopeInfo{
|
||||
Id: scp.GetPublicId(),
|
||||
Type: scp.GetType(),
|
||||
ParentScopeId: scp.GetParentId(),
|
||||
}
|
||||
|
||||
return prot, nil
|
||||
}
|
||||
|
||||
func (s Service) authResult(ctx context.Context, id string, a action.Type) auth.VerifyResults {
|
||||
res := auth.VerifyResults{}
|
||||
|
||||
repo, err := s.pwRepo()
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
authMeth, err := repo.LookupAuthMethod(ctx, id)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
if authMeth == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return res
|
||||
}
|
||||
|
||||
authResults := auth.Verify(ctx,
|
||||
auth.WithAction(a),
|
||||
auth.WithType(resource.AuthMethod),
|
||||
auth.WithScopeId(authMeth.GetScopeId()),
|
||||
auth.WithId(id))
|
||||
return authResults
|
||||
}
|
||||
|
||||
func toProto(t *authtoken.AuthToken) *pba.AuthToken {
|
||||
return &pba.AuthToken{
|
||||
Id: t.GetPublicId(),
|
||||
Token: t.GetToken(),
|
||||
UserId: t.GetIamUserId(),
|
||||
AuthMethodId: t.GetAuthMethodId(),
|
||||
AccountId: t.GetAuthAccountId(),
|
||||
CreatedTime: t.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: t.GetUpdateTime().GetTimestamp(),
|
||||
ApproximateLastUsedTime: t.GetApproximateLastAccessTime().GetTimestamp(),
|
||||
ExpirationTime: t.GetExpirationTime().GetTimestamp(),
|
||||
}
|
||||
}
|
||||
|
||||
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
|
||||
// requirements on the structure of the request. They verify that:
|
||||
// * The path passed in is correctly formatted
|
||||
// * All required parameters are set
|
||||
// * There are no conflicting parameters provided
|
||||
func validateAuthenticateRequest(req *pbs.AuthenticateRequest) error {
|
||||
badFields := make(map[string]string)
|
||||
if strings.TrimSpace(req.GetAuthMethodId()) == "" {
|
||||
badFields["auth_method_id"] = "This is a required field."
|
||||
} else if !handlers.ValidId(password.AuthMethodPrefix, req.GetAuthMethodId()) {
|
||||
badFields["auth_method_id"] = "Invalid formatted identifier."
|
||||
}
|
||||
// TODO: Update this when we enable different auth method types.
|
||||
if req.GetCredentials() == nil {
|
||||
badFields["credentials"] = "This is a required field."
|
||||
}
|
||||
creds := req.GetCredentials().GetFields()
|
||||
if _, ok := creds[loginNameKey]; !ok {
|
||||
badFields["credentials.login_name"] = "This is a required field."
|
||||
}
|
||||
if _, ok := creds[pwKey]; !ok {
|
||||
badFields["credentials.password"] = "This is a required field."
|
||||
}
|
||||
tType := strings.ToLower(strings.TrimSpace(req.GetTokenType()))
|
||||
if tType != "" && tType != "token" && tType != "cookie" {
|
||||
badFields["token_type"] = `The only accepted types are "token" and "cookie".`
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
package authenticate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
structpb "github.com/golang/protobuf/ptypes/struct"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
const (
|
||||
testPassword = "thetestpassword"
|
||||
testLoginName = "default"
|
||||
)
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
|
||||
authTokenRepoFn := func() (*authtoken.Repository, error) { return authtoken.NewRepository(rw, rw, kms) }
|
||||
iamRepoFn := func() (*iam.Repository, error) { return iam.NewRepository(rw, rw, kms) }
|
||||
passwordRepoFn := func() (*password.Repository, error) { return password.NewRepository(rw, rw, kms) }
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
|
||||
acct, err := password.NewAccount(am.GetPublicId(), password.WithLoginName(testLoginName))
|
||||
require.NoError(t, err)
|
||||
|
||||
pwRepo, err := passwordRepoFn()
|
||||
require.NoError(t, err)
|
||||
acct, err = pwRepo.CreateAccount(context.Background(), o.GetPublicId(), acct, password.WithPassword(testPassword))
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, acct)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
request *pbs.AuthenticateRequest
|
||||
wantType string
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "basic",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantType: "token",
|
||||
},
|
||||
{
|
||||
name: "cookie-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "cookie",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantType: "cookie",
|
||||
},
|
||||
{
|
||||
name: "no-token-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bad-token-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "email",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "no-authmethod",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "wrong-password",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: "wrong"}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.Unauthenticated),
|
||||
},
|
||||
{
|
||||
name: "wrong-login-name",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: "wrong"}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.Unauthenticated),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
s, err := NewService(kms, passwordRepoFn, iamRepoFn, authTokenRepoFn)
|
||||
require.NoError(err)
|
||||
|
||||
resp, err := s.Authenticate(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), tc.request)
|
||||
if tc.wantErr != nil {
|
||||
assert.Error(err)
|
||||
assert.Truef(errors.Is(err, tc.wantErr), "Got %#v, wanted %#v", err, tc.wantErr)
|
||||
return
|
||||
}
|
||||
require.NoError(err)
|
||||
aToken := resp.GetItem()
|
||||
assert.NotEmpty(aToken.GetId())
|
||||
assert.NotEmpty(aToken.GetToken())
|
||||
assert.True(strings.HasPrefix(aToken.GetToken(), aToken.GetId()))
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(aToken.GetCreatedTime(), aToken.GetUpdatedTime())
|
||||
assert.Equal(aToken.GetCreatedTime(), aToken.GetApproximateLastUsedTime())
|
||||
assert.Equal(acct.GetPublicId(), aToken.GetAccountId())
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(tc.wantType, resp.GetTokenType())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate_AuthAccountConnectedToIamUser(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
|
||||
passwordRepoFn := func() (*password.Repository, error) { return password.NewRepository(rw, rw, kms) }
|
||||
authTokenRepoFn := func() (*authtoken.Repository, error) { return authtoken.NewRepository(rw, rw, kms) }
|
||||
iamRepoFn := func() (*iam.Repository, error) { return iam.NewRepository(rw, rw, kms) }
|
||||
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
acct, err := password.NewAccount(am.GetPublicId(), password.WithLoginName(testLoginName))
|
||||
require.NoError(err)
|
||||
|
||||
pwRepo, err := passwordRepoFn()
|
||||
require.NoError(err)
|
||||
acct, err = pwRepo.CreateAccount(context.Background(), o.GetPublicId(), acct, password.WithPassword(testPassword))
|
||||
require.NoError(err)
|
||||
|
||||
// connected to an account.
|
||||
iamRepo, err := iamRepoFn()
|
||||
require.NoError(err)
|
||||
iamUser, err := iamRepo.LookupUserWithLogin(context.Background(), acct.GetPublicId(), iam.WithAutoVivify(true))
|
||||
require.NoError(err)
|
||||
|
||||
s, err := NewService(kms, passwordRepoFn, iamRepoFn, authTokenRepoFn)
|
||||
require.NoError(err)
|
||||
resp, err := s.Authenticate(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
})
|
||||
require.NoError(err)
|
||||
|
||||
aToken := resp.GetItem()
|
||||
assert.Equal(iamUser.GetPublicId(), aToken.GetUserId())
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(acct.GetPublicId(), aToken.GetAccountId())
|
||||
|
||||
assert.NotEmpty(aToken.GetId())
|
||||
assert.NotEmpty(aToken.GetToken())
|
||||
assert.True(strings.HasPrefix(aToken.GetToken(), aToken.GetId()))
|
||||
}
|
||||
@@ -4,13 +4,19 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/auth/password/store"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/authmethods"
|
||||
pba "github.com/hashicorp/boundary/internal/gen/controller/api/resources/authtokens"
|
||||
"github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
@@ -20,6 +26,11 @@ import (
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
const (
|
||||
loginNameKey = "login_name"
|
||||
pwKey = "password"
|
||||
)
|
||||
|
||||
var (
|
||||
maskManager handlers.MaskManager
|
||||
)
|
||||
@@ -33,19 +44,24 @@ func init() {
|
||||
|
||||
// Service handles request as described by the pbs.AuthMethodServiceServer interface.
|
||||
type Service struct {
|
||||
repoFn common.PasswordAuthRepoFactory
|
||||
kms *kms.Kms
|
||||
pwRepoFn common.PasswordAuthRepoFactory
|
||||
iamRepoFn common.IamRepoFactory
|
||||
atRepoFn common.AuthTokenRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns a auth method service which handles auth method related requests to boundary.
|
||||
func NewService(repo common.PasswordAuthRepoFactory, iamRepoFn common.IamRepoFactory) (Service, error) {
|
||||
if repo == nil {
|
||||
func NewService(kms *kms.Kms, pwRepoFn common.PasswordAuthRepoFactory, iamRepoFn common.IamRepoFactory, atRepoFn common.AuthTokenRepoFactory) (Service, error) {
|
||||
if kms == nil {
|
||||
return Service{}, errors.New("nil kms provided")
|
||||
}
|
||||
if pwRepoFn == nil {
|
||||
return Service{}, fmt.Errorf("nil password repository provided")
|
||||
}
|
||||
if iamRepoFn == nil {
|
||||
return Service{}, fmt.Errorf("nil iam repository provided")
|
||||
}
|
||||
return Service{repoFn: repo, iamRepoFn: iamRepoFn}, nil
|
||||
return Service{kms: kms, pwRepoFn: pwRepoFn, iamRepoFn: iamRepoFn, atRepoFn: atRepoFn}, nil
|
||||
}
|
||||
|
||||
var _ pbs.AuthMethodServiceServer = Service{}
|
||||
@@ -136,8 +152,25 @@ func (s Service) DeleteAuthMethod(ctx context.Context, req *pbs.DeleteAuthMethod
|
||||
return &pbs.DeleteAuthMethodResponse{}, nil
|
||||
}
|
||||
|
||||
// Authenticate implements the interface pbs.AuthenticationServiceServer.
|
||||
func (s Service) Authenticate(ctx context.Context, req *pbs.AuthenticateRequest) (*pbs.AuthenticateResponse, error) {
|
||||
if err := validateAuthenticateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetAuthMethodId(), action.Authenticate)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
creds := req.GetCredentials().GetFields()
|
||||
tok, err := s.authenticateWithRepo(ctx, authResults.Scope.GetId(), req.GetAuthMethodId(), creds[loginNameKey].GetStringValue(), creds[pwKey].GetStringValue())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pbs.AuthenticateResponse{Item: tok, TokenType: req.GetTokenType()}, nil
|
||||
}
|
||||
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (*pb.AuthMethod, error) {
|
||||
repo, err := s.repoFn()
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -151,11 +184,11 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.AuthMethod, er
|
||||
if u == nil {
|
||||
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist.", id)
|
||||
}
|
||||
return toProto(u)
|
||||
return toAuthMethodProto(u)
|
||||
}
|
||||
|
||||
func (s Service) listFromRepo(ctx context.Context, scopeId string) ([]*pb.AuthMethod, error) {
|
||||
repo, err := s.repoFn()
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -165,7 +198,7 @@ func (s Service) listFromRepo(ctx context.Context, scopeId string) ([]*pb.AuthMe
|
||||
}
|
||||
var outUl []*pb.AuthMethod
|
||||
for _, u := range ul {
|
||||
ou, err := toProto(u)
|
||||
ou, err := toAuthMethodProto(u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -186,7 +219,7 @@ func (s Service) createInRepo(ctx context.Context, scopeId string, item *pb.Auth
|
||||
if err != nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build auth method for creation: %v.", err)
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -197,7 +230,7 @@ func (s Service) createInRepo(ctx context.Context, scopeId string, item *pb.Auth
|
||||
if out == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
|
||||
}
|
||||
return toProto(out)
|
||||
return toAuthMethodProto(out)
|
||||
}
|
||||
|
||||
func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []string, item *pb.AuthMethod) (*pb.AuthMethod, error) {
|
||||
@@ -231,7 +264,7 @@ func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []st
|
||||
if len(dbMask) == 0 {
|
||||
return nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid fields provided in the update mask."})
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -242,11 +275,11 @@ func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []st
|
||||
if rowsUpdated == 0 {
|
||||
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist or incorrect version provided.", id)
|
||||
}
|
||||
return toProto(out)
|
||||
return toAuthMethodProto(out)
|
||||
}
|
||||
|
||||
func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool, error) {
|
||||
repo, err := s.repoFn()
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -260,6 +293,61 @@ func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool,
|
||||
return rows > 0, nil
|
||||
}
|
||||
|
||||
func (s Service) authenticateWithRepo(ctx context.Context, scopeId, authMethodId, loginName, pw string) (*pba.AuthToken, error) {
|
||||
iamRepo, err := s.iamRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
atRepo, err := s.atRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pwRepo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
acct, err := pwRepo.Authenticate(ctx, scopeId, authMethodId, loginName, pw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if acct == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Unauthenticated, "Unable to authenticate.")
|
||||
}
|
||||
|
||||
u, err := iamRepo.LookupUserWithLogin(ctx, acct.GetPublicId(), iam.WithAutoVivify(true))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tok, err := atRepo.CreateAuthToken(ctx, u, acct.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
token, err := authtoken.EncryptToken(ctx, s.kms, scopeId, tok.GetPublicId(), tok.GetToken())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tok.Token = tok.GetPublicId() + "_" + token
|
||||
prot := toAuthTokenProto(tok)
|
||||
|
||||
scp, err := iamRepo.LookupScope(ctx, u.GetScopeId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if scp == nil {
|
||||
return nil, err
|
||||
}
|
||||
prot.Scope = &scopes.ScopeInfo{
|
||||
Id: scp.GetPublicId(),
|
||||
Type: scp.GetType(),
|
||||
ParentScopeId: scp.GetParentId(),
|
||||
}
|
||||
|
||||
return prot, nil
|
||||
}
|
||||
|
||||
func (s Service) authResult(ctx context.Context, id string, a action.Type) auth.VerifyResults {
|
||||
res := auth.VerifyResults{}
|
||||
|
||||
@@ -283,7 +371,7 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type) auth.
|
||||
return res
|
||||
}
|
||||
default:
|
||||
repo, err := s.repoFn()
|
||||
repo, err := s.pwRepoFn()
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
@@ -304,7 +392,7 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type) auth.
|
||||
return auth.Verify(ctx, opts...)
|
||||
}
|
||||
|
||||
func toProto(in *password.AuthMethod) (*pb.AuthMethod, error) {
|
||||
func toAuthMethodProto(in *password.AuthMethod) (*pb.AuthMethod, error) {
|
||||
out := pb.AuthMethod{
|
||||
Id: in.GetPublicId(),
|
||||
ScopeId: in.GetScopeId(),
|
||||
@@ -330,6 +418,20 @@ func toProto(in *password.AuthMethod) (*pb.AuthMethod, error) {
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func toAuthTokenProto(t *authtoken.AuthToken) *pba.AuthToken {
|
||||
return &pba.AuthToken{
|
||||
Id: t.GetPublicId(),
|
||||
Token: t.GetToken(),
|
||||
UserId: t.GetIamUserId(),
|
||||
AuthMethodId: t.GetAuthMethodId(),
|
||||
AccountId: t.GetAuthAccountId(),
|
||||
CreatedTime: t.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: t.GetUpdateTime().GetTimestamp(),
|
||||
ApproximateLastUsedTime: t.GetApproximateLastAccessTime().GetTimestamp(),
|
||||
ExpirationTime: t.GetExpirationTime().GetTimestamp(),
|
||||
}
|
||||
}
|
||||
|
||||
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
|
||||
// requirements on the structure of the request. They verify that:
|
||||
// * The path passed in is correctly formatted
|
||||
@@ -393,3 +495,31 @@ func validateListRequest(req *pbs.ListAuthMethodsRequest) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAuthenticateRequest(req *pbs.AuthenticateRequest) error {
|
||||
badFields := make(map[string]string)
|
||||
if strings.TrimSpace(req.GetAuthMethodId()) == "" {
|
||||
badFields["auth_method_id"] = "This is a required field."
|
||||
} else if !handlers.ValidId(password.AuthMethodPrefix, req.GetAuthMethodId()) {
|
||||
badFields["auth_method_id"] = "Invalid formatted identifier."
|
||||
}
|
||||
// TODO: Update this when we enable different auth method types.
|
||||
if req.GetCredentials() == nil {
|
||||
badFields["credentials"] = "This is a required field."
|
||||
}
|
||||
creds := req.GetCredentials().GetFields()
|
||||
if _, ok := creds[loginNameKey]; !ok {
|
||||
badFields["credentials.login_name"] = "This is a required field."
|
||||
}
|
||||
if _, ok := creds[pwKey]; !ok {
|
||||
badFields["credentials.password"] = "This is a required field."
|
||||
}
|
||||
tType := strings.ToLower(strings.TrimSpace(req.GetTokenType()))
|
||||
if tType != "" && tType != "token" && tType != "cookie" {
|
||||
badFields["token_type"] = `The only accepted types are "token" and "cookie".`
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package authmethods_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/authmethods"
|
||||
scopepb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes"
|
||||
@@ -29,6 +31,11 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
testPassword = "thetestpassword"
|
||||
testLoginName = "default"
|
||||
)
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
@@ -37,9 +44,12 @@ func TestGet(t *testing.T) {
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
repoFn := func() (*password.Repository, error) {
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
|
||||
o, _ := iam.TestScopes(t, iamRepo)
|
||||
@@ -101,7 +111,7 @@ func TestGet(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
s, err := authmethods.NewService(repoFn, iamRepoFn)
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(err, "Couldn't create new auth_method service.")
|
||||
|
||||
got, gErr := s.GetAuthMethod(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
|
||||
@@ -122,9 +132,12 @@ func TestList(t *testing.T) {
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
repoFn := func() (*password.Repository, error) {
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
|
||||
oNoAuthMethods, _ := iam.TestScopes(t, iamRepo)
|
||||
@@ -195,7 +208,7 @@ func TestList(t *testing.T) {
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
s, err := authmethods.NewService(repoFn, iamRepoFn)
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(err, "Couldn't create new auth_method service.")
|
||||
|
||||
got, gErr := s.ListAuthMethods(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), &pbs.ListAuthMethodsRequest{ScopeId: tc.scopeId})
|
||||
@@ -216,15 +229,18 @@ func TestDelete(t *testing.T) {
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
repoFn := func() (*password.Repository, error) {
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
|
||||
o, _ := iam.TestScopes(t, iamRepo)
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
|
||||
s, err := authmethods.NewService(repoFn, iamRepoFn)
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(t, err, "Error when getting new auth_method service.")
|
||||
|
||||
cases := []struct {
|
||||
@@ -277,15 +293,18 @@ func TestDelete_twice(t *testing.T) {
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
repoFn := func() (*password.Repository, error) {
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
|
||||
o, _ := iam.TestScopes(t, iamRepo)
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
|
||||
s, err := authmethods.NewService(repoFn, iamRepoFn)
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(err, "Error when getting new auth_method service.")
|
||||
|
||||
req := &pbs.DeleteAuthMethodRequest{
|
||||
@@ -306,9 +325,12 @@ func TestCreate(t *testing.T) {
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
repoFn := func() (*password.Repository, error) {
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
|
||||
o, _ := iam.TestScopes(t, iamRepo)
|
||||
@@ -445,7 +467,7 @@ func TestCreate(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
s, err := authmethods.NewService(repoFn, iamRepoFn)
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(err, "Error when getting new auth_method service.")
|
||||
|
||||
got, gErr := s.CreateAuthMethod(auth.DisabledAuthTestContext(auth.WithScopeId(tc.req.GetItem().GetScopeId())), tc.req)
|
||||
@@ -485,13 +507,16 @@ func TestUpdate(t *testing.T) {
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
repoFn := func() (*password.Repository, error) {
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
|
||||
o, _ := iam.TestScopes(t, iamRepo)
|
||||
tested, err := authmethods.NewService(repoFn, iamRepoFn)
|
||||
tested, err := authmethods.NewService(kms, pwRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(t, err, "Error when getting new auth_method service.")
|
||||
|
||||
defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType()}
|
||||
@@ -863,3 +888,223 @@ func TestUpdate(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
|
||||
acct, err := password.NewAccount(am.GetPublicId(), password.WithLoginName(testLoginName))
|
||||
require.NoError(t, err)
|
||||
|
||||
pwRepo, err := pwRepoFn()
|
||||
require.NoError(t, err)
|
||||
acct, err = pwRepo.CreateAccount(context.Background(), o.GetPublicId(), acct, password.WithPassword(testPassword))
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, acct)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
request *pbs.AuthenticateRequest
|
||||
wantType string
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "basic",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantType: "token",
|
||||
},
|
||||
{
|
||||
name: "cookie-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "cookie",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantType: "cookie",
|
||||
},
|
||||
{
|
||||
name: "no-token-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bad-token-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "email",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "no-authmethod",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "wrong-password",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: "wrong"}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.Unauthenticated),
|
||||
},
|
||||
{
|
||||
name: "wrong-login-name",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
TokenType: "token",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: "wrong"}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: handlers.ApiErrorWithCode(codes.Unauthenticated),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(err)
|
||||
|
||||
resp, err := s.Authenticate(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), tc.request)
|
||||
if tc.wantErr != nil {
|
||||
assert.Error(err)
|
||||
assert.Truef(errors.Is(err, tc.wantErr), "Got %#v, wanted %#v", err, tc.wantErr)
|
||||
return
|
||||
}
|
||||
require.NoError(err)
|
||||
aToken := resp.GetItem()
|
||||
assert.NotEmpty(aToken.GetId())
|
||||
assert.NotEmpty(aToken.GetToken())
|
||||
assert.True(strings.HasPrefix(aToken.GetToken(), aToken.GetId()))
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(aToken.GetCreatedTime(), aToken.GetUpdatedTime())
|
||||
assert.Equal(aToken.GetCreatedTime(), aToken.GetApproximateLastUsedTime())
|
||||
assert.Equal(acct.GetPublicId(), aToken.GetAccountId())
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(tc.wantType, resp.GetTokenType())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate_AuthAccountConnectedToIamUser(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
|
||||
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iam.TestRepo(t, conn, wrapper), nil
|
||||
}
|
||||
pwRepoFn := func() (*password.Repository, error) {
|
||||
return password.NewRepository(rw, rw, kms)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
|
||||
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
|
||||
acct, err := password.NewAccount(am.GetPublicId(), password.WithLoginName(testLoginName))
|
||||
require.NoError(err)
|
||||
|
||||
pwRepo, err := pwRepoFn()
|
||||
require.NoError(err)
|
||||
acct, err = pwRepo.CreateAccount(context.Background(), o.GetPublicId(), acct, password.WithPassword(testPassword))
|
||||
require.NoError(err)
|
||||
|
||||
// connected to an account.
|
||||
iamRepo, err := iamRepoFn()
|
||||
require.NoError(err)
|
||||
iamUser, err := iamRepo.LookupUserWithLogin(context.Background(), acct.GetPublicId(), iam.WithAutoVivify(true))
|
||||
require.NoError(err)
|
||||
|
||||
s, err := authmethods.NewService(kms, pwRepoFn, iamRepoFn, atRepoFn)
|
||||
require.NoError(err)
|
||||
resp, err := s.Authenticate(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), &pbs.AuthenticateRequest{
|
||||
AuthMethodId: am.GetPublicId(),
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"login_name": {Kind: &structpb.Value_StringValue{StringValue: testLoginName}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: testPassword}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
})
|
||||
require.NoError(err)
|
||||
|
||||
aToken := resp.GetItem()
|
||||
assert.Equal(iamUser.GetPublicId(), aToken.GetUserId())
|
||||
assert.Equal(am.GetPublicId(), aToken.GetAuthMethodId())
|
||||
assert.Equal(acct.GetPublicId(), aToken.GetAccountId())
|
||||
|
||||
assert.NotEmpty(aToken.GetId())
|
||||
assert.NotEmpty(aToken.GetToken())
|
||||
assert.True(strings.HasPrefix(aToken.GetToken(), aToken.GetId()))
|
||||
}
|
||||
Reference in new issue
Block a user