Authenticate Handler API and SDK, and much more (#183)
This commit is contained in:
1 parent
acce195dcb
commit
28dbcd84bd
89 files changed
+5296
-1943
No files matched your search
@@ -0,0 +1,164 @@
|
||||
package authenticate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base32"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/hashicorp/watchtower/internal/authtoken"
|
||||
"github.com/hashicorp/watchtower/internal/db"
|
||||
pba "github.com/hashicorp/watchtower/internal/gen/controller/api/resources/authtokens"
|
||||
pbs "github.com/hashicorp/watchtower/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/watchtower/internal/iam"
|
||||
iamStore "github.com/hashicorp/watchtower/internal/iam/store"
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/common"
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/watchtower/internal/types/scope"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const orgIdFieldName = "org_id"
|
||||
|
||||
var (
|
||||
reInvalidID = regexp.MustCompile("[^A-Za-z0-9]")
|
||||
|
||||
// TODO: Remove once auth methods are in
|
||||
OrgScope string
|
||||
RWDb = new(atomic.Value)
|
||||
)
|
||||
|
||||
func init() {
|
||||
RWDb.Store((*db.Db)(nil))
|
||||
}
|
||||
|
||||
// Service handles request as described by the pbs.OrgServiceServer interface.
|
||||
type Service struct {
|
||||
iamRepo common.IamRepoFactory
|
||||
authTokenRepo common.AuthTokenRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns an org service which handles org related requests to watchtower.
|
||||
func NewService(iamRepo common.IamRepoFactory, atRepo common.AuthTokenRepoFactory) (Service, error) {
|
||||
if iamRepo == nil {
|
||||
return Service{}, fmt.Errorf("nil iam repository provided")
|
||||
}
|
||||
if atRepo == nil {
|
||||
return Service{}, fmt.Errorf("nil auth token repository provided")
|
||||
}
|
||||
|
||||
return Service{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
|
||||
}
|
||||
tok, err := s.authenticateWithRepo(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pbs.AuthenticateResponse{Item: tok}, nil
|
||||
}
|
||||
|
||||
// Deauthenticate implements the interface pbs.AuthenticationServiceServer.
|
||||
func (s Service) Deauthenticate(ctx context.Context, req *pbs.DeauthenticateRequest) (*pbs.DeauthenticateResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "Requested method is unimplemented for Org.")
|
||||
}
|
||||
|
||||
func (s Service) authenticateWithRepo(ctx context.Context, req *pbs.AuthenticateRequest) (*pba.AuthToken, error) {
|
||||
userRepo, err := s.iamRepo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
atRepo, err := s.authTokenRepo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Place holder for making a request to authenticate
|
||||
creds := req.GetCredentials().GetFields()
|
||||
pwName, password := creds["name"], creds["password"]
|
||||
if pwName.GetStringValue() == "wrong" && password.GetStringValue() == "wrong" {
|
||||
return nil, status.Error(codes.Unauthenticated, "Unable to authenticate.")
|
||||
}
|
||||
// Get back a password.Account with a CredentialId string and a public Id
|
||||
// Create a fake auth account ID for the moment
|
||||
acctIdBytes := sha256.Sum256([]byte(pwName.GetStringValue()))
|
||||
acctId := fmt.Sprintf("aa_%s", base32.StdEncoding.EncodeToString(acctIdBytes[:])[0:10])
|
||||
|
||||
aAcct := &iam.AuthAccount{AuthAccount: &iamStore.AuthAccount{
|
||||
PublicId: acctId,
|
||||
ScopeId: OrgScope,
|
||||
AuthMethodId: req.AuthMethodId,
|
||||
}}
|
||||
RWDb.Load().(*db.Db).Create(ctx, aAcct)
|
||||
|
||||
u, err := userRepo.LookupUserWithLogin(ctx, acctId, iam.WithAutoVivify(true))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tok, err := atRepo.CreateAuthToken(ctx, u.GetPublicId(), acctId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tok.Token = tok.GetPublicId() + "_" + tok.GetToken()
|
||||
return toProto(tok), nil
|
||||
}
|
||||
|
||||
func toProto(t *authtoken.AuthToken) *pba.AuthToken {
|
||||
return &pba.AuthToken{
|
||||
Id: t.GetPublicId(),
|
||||
Token: t.GetToken(),
|
||||
UserId: t.GetIamUserId(),
|
||||
AuthMethodId: t.GetAuthMethodId(),
|
||||
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 !validId(req.GetOrgId(), scope.Org.Prefix()+"_") {
|
||||
badFields[orgIdFieldName] = "Invalid formatted identifier."
|
||||
}
|
||||
if strings.TrimSpace(req.GetAuthMethodId()) == "" {
|
||||
badFields["auth_method_id"] = "This is a required field."
|
||||
} else if validId(req.GetAuthMethodId(), "am") {
|
||||
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."
|
||||
}
|
||||
// TODO: Update this when we enable split cookie token types.
|
||||
tType := strings.ToLower(strings.TrimSpace(req.GetTokenType()))
|
||||
if tType != "" && tType != "token" {
|
||||
badFields["token_type"] = "The only accepted type is 'token'."
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validId(id, prefix string) bool {
|
||||
if !strings.HasPrefix(id, prefix) {
|
||||
return false
|
||||
}
|
||||
id = strings.TrimPrefix(id, prefix)
|
||||
return !reInvalidID.Match([]byte(id))
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package authenticate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base32"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
structpb "github.com/golang/protobuf/ptypes/struct"
|
||||
"github.com/hashicorp/watchtower/internal/authtoken"
|
||||
"github.com/hashicorp/watchtower/internal/db"
|
||||
pba "github.com/hashicorp/watchtower/internal/gen/controller/api/resources/authtokens"
|
||||
pbs "github.com/hashicorp/watchtower/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/watchtower/internal/iam"
|
||||
iamStore "github.com/hashicorp/watchtower/internal/iam/store"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func getAuthMethodAndAccountId(t *testing.T, org *iam.Scope, rw *db.Db) (string, string) {
|
||||
// TODO: Remove this when Auth Account repo is in place.
|
||||
insert := `insert into auth_method
|
||||
(public_id, scope_id)
|
||||
values
|
||||
($1, $2);`
|
||||
amId, err := db.NewPublicId("am")
|
||||
require.NoError(t, err)
|
||||
innerDb, err := rw.DB()
|
||||
require.NoError(t, err)
|
||||
_, err = innerDb.Exec(insert, amId, org.GetPublicId())
|
||||
require.NoError(t, err)
|
||||
aAcctId, err := db.NewPublicId("aa")
|
||||
require.NoError(t, err)
|
||||
|
||||
aAcct := &iam.AuthAccount{AuthAccount: &iamStore.AuthAccount{
|
||||
PublicId: aAcctId,
|
||||
ScopeId: org.GetPublicId(),
|
||||
AuthMethodId: amId,
|
||||
}}
|
||||
require.NoError(t, rw.Create(context.Background(), aAcct))
|
||||
return aAcct.GetAuthMethodId(), aAcct.GetPublicId()
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
RWDb.Store(rw)
|
||||
wrapper := db.TestWrapper(t)
|
||||
o, _ := iam.TestScopes(t, conn)
|
||||
|
||||
authTokenRepoFn := func() (*authtoken.Repository, error) { return authtoken.NewRepository(rw, rw, wrapper) }
|
||||
iamRepoFn := func() (*iam.Repository, error) { return iam.NewRepository(rw, rw, wrapper) }
|
||||
amId, _ := getAuthMethodAndAccountId(t, o, rw)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
request *pbs.AuthenticateRequest
|
||||
want *pbs.AuthenticateResponse
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "basic",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
OrgId: o.GetPublicId(),
|
||||
AuthMethodId: amId,
|
||||
TokenType: "token",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"name": {Kind: &structpb.Value_StringValue{StringValue: "admin"}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: "hunter2"}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
want: &pbs.AuthenticateResponse{Item: &pba.AuthToken{
|
||||
AuthMethodId: amId,
|
||||
}},
|
||||
},
|
||||
{
|
||||
name: "no-token-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
OrgId: o.GetPublicId(),
|
||||
AuthMethodId: amId,
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"name": {Kind: &structpb.Value_StringValue{StringValue: "admin"}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: "hunter2"}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
want: &pbs.AuthenticateResponse{Item: &pba.AuthToken{
|
||||
AuthMethodId: amId,
|
||||
}},
|
||||
},
|
||||
{
|
||||
name: "bad-token-type",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
OrgId: o.GetPublicId(),
|
||||
AuthMethodId: amId,
|
||||
TokenType: "email",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"name": {Kind: &structpb.Value_StringValue{StringValue: "admin"}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: "hunter2"}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: status.Error(codes.InvalidArgument, "invalid argument"),
|
||||
},
|
||||
{
|
||||
name: "no-authmethod",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
OrgId: o.GetPublicId(),
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"name": {Kind: &structpb.Value_StringValue{StringValue: "admin"}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: "hunter2"}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: status.Error(codes.InvalidArgument, "invalid argument"),
|
||||
},
|
||||
{
|
||||
name: "wrong-username-password",
|
||||
request: &pbs.AuthenticateRequest{
|
||||
OrgId: o.GetPublicId(),
|
||||
AuthMethodId: amId,
|
||||
TokenType: "token",
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"name": {Kind: &structpb.Value_StringValue{StringValue: "wrong"}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: "wrong"}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
},
|
||||
wantErr: status.Error(codes.Unauthenticated, "unauthenticated"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
s, err := NewService(iamRepoFn, authTokenRepoFn)
|
||||
require.NoError(err)
|
||||
|
||||
// TODO: remove when we stop faking things
|
||||
name := tc.request.Credentials.Fields["name"].GetStringValue()
|
||||
acctIdBytes := sha256.Sum256([]byte(name))
|
||||
acctId := fmt.Sprintf("aa_%s", base32.StdEncoding.EncodeToString(acctIdBytes[:])[0:10])
|
||||
|
||||
aAcct := &iam.AuthAccount{AuthAccount: &iamStore.AuthAccount{
|
||||
PublicId: acctId,
|
||||
ScopeId: o.PublicId,
|
||||
AuthMethodId: amId,
|
||||
}}
|
||||
RWDb.Load().(*db.Db).Create(context.Background(), aAcct)
|
||||
|
||||
resp, err := s.Authenticate(context.Background(), tc.request)
|
||||
if tc.wantErr != nil {
|
||||
assert.Error(err)
|
||||
assert.Equal(status.Code(tc.wantErr), status.Code(err))
|
||||
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(amId, aToken.GetAuthMethodId())
|
||||
assert.Equal(aToken.GetCreatedTime(), aToken.GetUpdatedTime())
|
||||
assert.Equal(aToken.GetCreatedTime(), aToken.GetApproximateLastUsedTime())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate_AuthAccountConnectedToIamUser(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
RWDb.Store(rw)
|
||||
wrapper := db.TestWrapper(t)
|
||||
o, _ := iam.TestScopes(t, conn)
|
||||
|
||||
authTokenRepoFn := func() (*authtoken.Repository, error) { return authtoken.NewRepository(rw, rw, wrapper) }
|
||||
iamRepoFn := func() (*iam.Repository, error) { return iam.NewRepository(rw, rw, wrapper) }
|
||||
iamRepo, err := iamRepoFn()
|
||||
require.NoError(err)
|
||||
|
||||
// connected to an account.
|
||||
amId, _ := getAuthMethodAndAccountId(t, o, rw)
|
||||
|
||||
name := "admin"
|
||||
acctIdBytes := sha256.Sum256([]byte(name))
|
||||
acctId := fmt.Sprintf("aa_%s", base32.StdEncoding.EncodeToString(acctIdBytes[:])[0:10])
|
||||
|
||||
aAcct := &iam.AuthAccount{AuthAccount: &iamStore.AuthAccount{
|
||||
PublicId: acctId,
|
||||
ScopeId: o.PublicId,
|
||||
AuthMethodId: amId,
|
||||
}}
|
||||
RWDb.Load().(*db.Db).Create(context.Background(), aAcct)
|
||||
|
||||
iamUser, err := iamRepo.LookupUserWithLogin(context.Background(), acctId, iam.WithAutoVivify(true))
|
||||
require.NoError(err)
|
||||
|
||||
s, err := NewService(iamRepoFn, authTokenRepoFn)
|
||||
require.NoError(err)
|
||||
resp, err := s.Authenticate(context.Background(), &pbs.AuthenticateRequest{
|
||||
OrgId: o.GetPublicId(),
|
||||
AuthMethodId: amId,
|
||||
Credentials: func() *structpb.Struct {
|
||||
creds := map[string]*structpb.Value{
|
||||
"name": {Kind: &structpb.Value_StringValue{StringValue: name}},
|
||||
"password": {Kind: &structpb.Value_StringValue{StringValue: "hunter2"}},
|
||||
}
|
||||
return &structpb.Struct{Fields: creds}
|
||||
}(),
|
||||
})
|
||||
require.NoError(err)
|
||||
|
||||
aToken := resp.GetItem()
|
||||
assert.Equal(iamUser.GetPublicId(), aToken.GetUserId())
|
||||
assert.Equal(amId, aToken.GetAuthMethodId())
|
||||
|
||||
assert.NotEmpty(aToken.GetId())
|
||||
assert.NotEmpty(aToken.GetToken())
|
||||
assert.True(strings.HasPrefix(aToken.GetToken(), aToken.GetId()))
|
||||
}
|
||||
Reference in new issue
Block a user