feature (auth/ldap): add LDAP auth method along with associated accounts and managed groups (#2912)

* feature (auth): required schema changes for auth ldap method (#2669)

chore (auth/ldap): move schema changes to next avail migration number

* feature (auth/ldap): define AuthMethod and all its value objects (#2703)

* feature (auth/ldap): storage protos
* feature (auth/ldap): define AuthMethod and all its value objects

* feature (auth/ldap): add repo and reading an auth method (#2718)

* feature (auth/ldap): add Repository.CreateAuthMethod(...) and Repository.DeleteAuthMethod(...) (#2724)

* feature (auth/ldap): add Repository.UpdateAuthMethod(...) (#2739)

* feature (auth/ldap): add Account

* feature (auth/ldap): add AuthMethod.EnableGroups

* fix (auth/ldap): refactor AuthMethod.oplog to enforce proper constraints

* feature (auth/ldap): add Account repo functions

* refactor (auth/ldap): remove entry attributes from account

Realized the entry attributes could have absolutely anything in them
(including binary data) and since we absolutely don't have to have them
there's just no reason to take on the risk.

* feature (auth/ldap): add AuthMethod.UseTokenGroups

* feature (auth/ldap): add Authenticate(...)

* refactor (auth/ldap): ensure options take a context as the 1st parameter

* feature (auth/ldap): add Account attribute maps

* chore (auth/ldap): make fmt deltas

* feature (auth/ldap): add managed groups (#2760)

* tests (auth/ldap): add missing unit test to Repository.DeleteAccount(...)

Add bits to test the delete operation when you're not able to generate
oplog metadata

* feature (auth/ldap): add managed groups

fixup! feature (auth/ldap): add managed groups (#2760)

* feature (auth/ldap): service proto definition (#2761)

* feature (handlers/authmethods): add handlers for ldap auth method operations (#2794)

* feature (auth/ldap): add Account attribute maps

* chore (auth/ldap): update cap/ldap to latest version

* feature (auth/ldap): add ldap api generation definitions

* feature (authmethods): add ldap repo NewService(...)

* feature (authmethods/ldap): add proper mask_mapping to protobufs

* feature (authmethods): add support to get an ldap auth method

* refactor (auth/ldap): export TestGenerateCA(...)

* feature (authmethods): add support to create an ldap auth method

* feature (authmethods): add support to delete an ldap auth method

* feature (authmethods): add support to list ldap auth methods

* refactor (auth/ldap): make urls optional for NewAuthMethod(...)

* refactor (auth/ldap): export ldap.TestInvalidPem

* chore: make fmt changes

* fix (auth/ldap): properly handle group search config

Add constraints and tests to ensure when an ldap AuthMethod.EnableGroups
is true, and UseTokenGroups is false; that there's a GroupDn configured
for finding a user's associated groups

* feature (authmethods): add support to update an ldap auth methods

* chore (db/ldap): tmp mv migrations so there's no conflict with ongoing work

* feature (verifier): add ldap auth method to verifier bits

* fix (controller): prevent panic when controller stops when there's no listener

* feature (authmethods): add support to authenticate via ldap auth methods

* chore (migrations): fix whitespace in stmt

* chore: fmt fixup

* tests (auth/ldap): invalid err msg

* feature (cli/authmethods): add support for ldap auth-methods CRUD and authenticate (#2810)

* feature (authmethods): add CLI support for ldap auth methods CRUD

* tests (api/auth): ldap auth method classification tests

* feature (authmethods): add CLI support for ldap auth authenticate

* feature (auth/ldap): set request timeouts for ldap server connections

* feature (handlers/authmethods): handle u_anon listing properly.

* feature (account/handers): ldap account and managed group CRUDL APIs (#2852)

* feature (auth/ldap) add repository Listing of ManagedGroupMemberAccount

* feature (controller/handlers): add ldapRepoFn to accounts service

* feature (auth/ldap) register ldap managed group subtype

* feature (account/handlers): ldap account CRUDL APIs

* feature (controller/handlers): add ldapRepo to managed groups service

* feature (account/handlers): ldap managed group CRUDL APIs

* docs (domain): add LDAP accounts, auth-methods and managed groups (#2857)

* feature (ldap/cli) add ldap accounts and managed groups CRUDL commands (#2856)

* fix (handlers/authmethods): fix ldap authorized actions (#2892)

* feature (cli/ldap/authenticate): use primary auth method if none is provided (#2890)

* fix (auth/ldap): support setting the state attribute

* feature (cli/ldap/authenticate): use primary auth method if none is provided

* feature (wh/ldap) add tests for new ldap auth method and accounts (#2919)

* refactor (migrations/ldap): mv to correct directory

* chore: add copyright headers

* fix (api/authmethods/ldap): renumber new LdapAuthMethodAttributes field

* fix (auth/ldap): allow the auth method state to be updated (#2951)

* chore: update sdk and api versions for llb - this is tmp until merging

* tests (managed groups): add required errContains for new test
This commit is contained in:
Jim authored and GitHub committed 2023-03-15 11:40:40 -04:00
1 parent acda0c3892
commit 86192f75eb
121 files changed
+26652 -671

No files matched your search

+13 -2
View File
@@ -14,6 +14,7 @@ import (
"github.com/hashicorp/boundary/api/recovery"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/daemon/controller/common"
@@ -104,6 +105,7 @@ type verifier struct {
serversRepoFn common.ServersRepoFactory
passwordAuthRepoFn common.PasswordAuthRepoFactory
oidcAuthRepoFn common.OidcAuthRepoFactory
ldapAuthRepoFn common.LdapAuthRepoFactory
kms *kms.Kms
requestInfo *authpb.RequestInfo
res *perms.Resource
@@ -128,6 +130,7 @@ func NewVerifierContextWithAccounts(ctx context.Context,
serversRepoFn common.ServersRepoFactory,
passwordAuthRepoFn common.PasswordAuthRepoFactory,
oidcAuthRepoFn common.OidcAuthRepoFactory,
ldapAuthRepoFn common.LdapAuthRepoFactory,
kms *kms.Kms,
requestInfo *authpb.RequestInfo,
) context.Context {
@@ -137,6 +140,7 @@ func NewVerifierContextWithAccounts(ctx context.Context,
serversRepoFn: serversRepoFn,
passwordAuthRepoFn: passwordAuthRepoFn,
oidcAuthRepoFn: oidcAuthRepoFn,
ldapAuthRepoFn: ldapAuthRepoFn,
kms: kms,
requestInfo: requestInfo,
})
@@ -153,7 +157,7 @@ func NewVerifierContext(ctx context.Context,
kms *kms.Kms,
requestInfo *authpb.RequestInfo,
) context.Context {
return NewVerifierContextWithAccounts(ctx, iamRepoFn, authTokenRepoFn, serversRepoFn, nil, nil, kms, requestInfo)
return NewVerifierContextWithAccounts(ctx, iamRepoFn, authTokenRepoFn, serversRepoFn, nil, nil, nil, kms, requestInfo)
}
// Verify takes in a context that has expected parameters as values and runs an
@@ -547,7 +551,7 @@ func (v verifier) performAuthCheck(ctx context.Context) (
userData.User.Email = util.Pointer(u.Email)
userData.User.FullName = util.Pointer(u.FullName)
if userData.Account.Id != nil && *userData.Account.Id != "" && v.passwordAuthRepoFn != nil && v.oidcAuthRepoFn != nil {
if userData.Account.Id != nil && *userData.Account.Id != "" && v.passwordAuthRepoFn != nil && v.oidcAuthRepoFn != nil && v.ldapAuthRepoFn != nil {
const domain = "auth"
var acct auth.Account
var err error
@@ -566,6 +570,13 @@ func (v verifier) performAuthCheck(ctx context.Context) (
return
}
acct, err = repo.LookupAccount(ctx, *userData.Account.Id)
case ldap.Subtype:
repo, repoErr := v.ldapAuthRepoFn()
if repoErr != nil {
retErr = errors.Wrap(ctx, repoErr, op, errors.WithMsg("failed to get ldap auth repo"))
return
}
acct, err = repo.LookupAccount(ctx, *userData.Account.Id)
default:
retErr = errors.Wrap(ctx, err, op, errors.WithMsg("unrecognized account id type"))
return
@@ -4,6 +4,7 @@
package common
import (
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
credstatic "github.com/hashicorp/boundary/internal/credential/static"
@@ -22,6 +23,7 @@ type (
StaticCredentialRepoFactory = func() (*credstatic.Repository, error)
IamRepoFactory = iam.IamRepoFactory
OidcAuthRepoFactory = oidc.OidcRepoFactory
LdapAuthRepoFactory = ldap.RepoFactory
PasswordAuthRepoFactory func() (*password.Repository, error)
ServersRepoFactory func() (*server.Repository, error)
StaticRepoFactory func() (*static.Repository, error)
+5
View File
@@ -11,6 +11,7 @@ import (
"sync"
"sync/atomic"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
@@ -117,6 +118,7 @@ type Controller struct {
StaticCredentialRepoFn common.StaticCredentialRepoFactory
IamRepoFn common.IamRepoFactory
OidcRepoFn common.OidcAuthRepoFactory
LdapRepoFn common.LdapAuthRepoFactory
PasswordAuthRepoFn common.PasswordAuthRepoFactory
ServersRepoFn common.ServersRepoFactory
SessionRepoFn session.RepositoryFactory
@@ -362,6 +364,9 @@ func New(ctx context.Context, conf *Config) (*Controller, error) {
c.OidcRepoFn = func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, dbase, dbase, c.kms)
}
c.LdapRepoFn = func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, dbase, dbase, c.kms)
}
c.PasswordAuthRepoFn = func() (*password.Repository, error) {
return password.NewRepository(dbase, dbase, c.kms)
}
+2 -1
View File
@@ -72,6 +72,7 @@ func newGrpcServer(
serversRepoFn common.ServersRepoFactory,
passwordAuthRepoFn common.PasswordAuthRepoFactory,
oidcAuthRepoFn common.OidcAuthRepoFactory,
ldapAuthRepoFn common.LdapAuthRepoFactory,
kms *kms.Kms,
eventer *event.Eventer,
) (*grpc.Server, string, error) {
@@ -80,7 +81,7 @@ func newGrpcServer(
if err != nil {
return nil, "", errors.Wrap(ctx, err, op, errors.WithMsg("unable to generate gateway ticket"))
}
requestCtxInterceptor, err := requestCtxInterceptor(ctx, iamRepoFn, authTokenRepoFn, serversRepoFn, passwordAuthRepoFn, oidcAuthRepoFn, kms, ticket, eventer)
requestCtxInterceptor, err := requestCtxInterceptor(ctx, iamRepoFn, authTokenRepoFn, serversRepoFn, passwordAuthRepoFn, oidcAuthRepoFn, ldapAuthRepoFn, kms, ticket, eventer)
if err != nil {
return nil, "", err
}
+3 -3
View File
@@ -154,14 +154,14 @@ func (c *Controller) registerGrpcServices(s *grpc.Server) error {
services.RegisterHostServiceServer(s, hs)
}
if _, ok := currentServices[services.AccountService_ServiceDesc.ServiceName]; !ok {
accts, err := accounts.NewService(c.PasswordAuthRepoFn, c.OidcRepoFn)
accts, err := accounts.NewService(c.baseContext, c.PasswordAuthRepoFn, c.OidcRepoFn, c.LdapRepoFn)
if err != nil {
return fmt.Errorf("failed to create account handler service: %w", err)
}
services.RegisterAccountServiceServer(s, accts)
}
if _, ok := currentServices[services.AuthMethodService_ServiceDesc.ServiceName]; !ok {
authMethods, err := authmethods.NewService(c.kms, c.PasswordAuthRepoFn, c.OidcRepoFn, c.IamRepoFn, c.AuthTokenRepoFn)
authMethods, err := authmethods.NewService(c.kms, c.PasswordAuthRepoFn, c.OidcRepoFn, c.IamRepoFn, c.AuthTokenRepoFn, c.LdapRepoFn)
if err != nil {
return fmt.Errorf("failed to create auth method handler service: %w", err)
}
@@ -229,7 +229,7 @@ func (c *Controller) registerGrpcServices(s *grpc.Server) error {
services.RegisterSessionServiceServer(s, ss)
}
if _, ok := currentServices[services.ManagedGroupService_ServiceDesc.ServiceName]; !ok {
mgs, err := managed_groups.NewService(c.OidcRepoFn)
mgs, err := managed_groups.NewService(c.baseContext, c.OidcRepoFn, c.LdapRepoFn)
if err != nil {
return fmt.Errorf("failed to create managed groups handler service: %w", err)
}
@@ -12,6 +12,7 @@ import (
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
oidcstore "github.com/hashicorp/boundary/internal/auth/oidc/store"
"github.com/hashicorp/boundary/internal/auth/password"
@@ -52,6 +53,13 @@ const (
nameClaimField = "attributes.full_name"
emailClaimField = "attributes.email"
// ldap field names
loginAttrField = "attributes.login_name"
nameAttrField = "attributes.full_name"
emailAttrField = "attributes.email"
dnAttrField = "attributes.dn"
memberOfAttrField = "attributes.member_of_groups"
domain = "auth"
)
@@ -76,6 +84,12 @@ var (
action.Update,
action.Delete,
},
ldap.Subtype: {
action.NoOp,
action.Read,
action.Update,
action.Delete,
},
}
// CollectionActions contains the set of actions that can be performed on
@@ -102,20 +116,23 @@ type Service struct {
pwRepoFn common.PasswordAuthRepoFactory
oidcRepoFn common.OidcAuthRepoFactory
ldapRepoFn common.LdapAuthRepoFactory
}
var _ pbs.AccountServiceServer = (*Service)(nil)
// NewService returns a account service which handles account related requests to boundary.
func NewService(pwRepo common.PasswordAuthRepoFactory, oidcRepo common.OidcAuthRepoFactory) (Service, error) {
func NewService(ctx context.Context, pwRepo common.PasswordAuthRepoFactory, oidcRepo common.OidcAuthRepoFactory, ldapRepo common.LdapAuthRepoFactory) (Service, error) {
const op = "accounts.NewService"
if pwRepo == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing password repository")
switch {
case pwRepo == nil:
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing password repository")
case oidcRepo == nil:
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing oidc repository")
case ldapRepo == nil:
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing ldap repository")
}
if oidcRepo == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing oidc repository provided")
}
return Service{pwRepoFn: pwRepo, oidcRepoFn: oidcRepo}, nil
return Service{pwRepoFn: pwRepo, oidcRepoFn: oidcRepo, ldapRepoFn: ldapRepo}, nil
}
// ListAccounts implements the interface pbs.AccountServiceServer.
@@ -434,6 +451,29 @@ func (s Service) getFromRepo(ctx context.Context, id string) (auth.Account, []st
mgIds = append(mgIds, mg.GetManagedGroupId())
}
acct = a
case ldap.Subtype:
repo, err := s.ldapRepoFn()
if err != nil {
return nil, nil, err
}
a, err := repo.LookupAccount(ctx, id)
if err != nil {
return nil, nil, err
}
if err != nil {
if errors.IsNotFoundError(err) {
return nil, nil, handlers.NotFoundErrorf("LDAP account %q doesn't exist.", id)
}
return nil, nil, err
}
mgs, err := repo.ListManagedGroupMembershipsByMember(ctx, a.GetPublicId())
if err != nil {
return nil, nil, err
}
for _, mg := range mgs {
mgIds = append(mgIds, mg.GetManagedGroupId())
}
acct = a
default:
return nil, nil, handlers.NotFoundErrorf("Unrecognized id.")
}
@@ -515,6 +555,37 @@ func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item
return out, nil
}
func (s Service) createLdapInRepo(ctx context.Context, am auth.AuthMethod, item *pb.Account) (*ldap.Account, error) {
const op = "accounts.(Service).createLdapInRepo"
if item == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing item")
}
var opts []ldap.Option
if item.GetName() != nil {
opts = append(opts, ldap.WithName(ctx, item.GetName().GetValue()))
}
if item.GetDescription() != nil {
opts = append(opts, ldap.WithDescription(ctx, item.GetDescription().GetValue()))
}
a, err := ldap.NewAccount(ctx, am.GetScopeId(), am.GetPublicId(), item.GetLdapAccountAttributes().GetLoginName(), opts...)
if err != nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build account for creation: %v.", err)
}
repo, err := s.ldapRepoFn()
if err != nil {
return nil, err
}
out, err := repo.CreateAccount(ctx, a)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create account"))
}
if out == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.")
}
return out, nil
}
func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb.Account) (auth.Account, error) {
const op = "accounts.(Service).createInRepo"
if item == nil {
@@ -540,7 +611,17 @@ func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb.
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create account but no error returned from repository.")
}
out = am
case ldap.Subtype:
am, err := s.createLdapInRepo(ctx, am, item)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if am == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create ldap account but no error returned from repository.")
}
out = am
}
return out, nil
}
@@ -611,6 +692,63 @@ func (s Service) updateOidcInRepo(ctx context.Context, scopeId, amId, id string,
return out, nil
}
func (s Service) updateLdapInRepo(ctx context.Context, scopeId, amId, id string, mask []string, item *pb.Account) (*ldap.Account, error) {
const op = "accounts.(Service).updateLdapInRepo"
switch {
case item == nil:
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "nil account.")
case scopeId == "":
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "missing scope id")
case amId == "":
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "missing auth method id")
case id == "":
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "missing id")
case len(mask) == 0:
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "missing mask.")
}
u := ldap.AllocAccount()
u.PublicId = id
u.ScopeId = scopeId
u.AuthMethodId = amId
if item.GetName() != nil {
u.Name = item.GetName().GetValue()
}
if item.GetDescription() != nil {
u.Description = item.GetDescription().GetValue()
}
// we don't need a mask mgr, since none of the attributes fields are
// updatable. Just a simple split on commas looking for multiple paths in
// one mask string
dbMask := []string{}
for _, v := range mask {
vSplit := strings.Split(v, ",")
for _, m := range vSplit {
switch m {
case globals.NameField, globals.DescriptionField:
dbMask = append(dbMask, vSplit...)
case globals.VersionField:
// no-op
default:
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.ldapRepoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
out, rowsUpdated, err := repo.UpdateAccount(ctx, scopeId, u, item.GetVersion(), dbMask)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to update account"))
}
if rowsUpdated == 0 {
return nil, handlers.NotFoundErrorf("Account %q doesn't exist or incorrect version provided.", id)
}
return out, nil
}
func (s Service) updateInRepo(ctx context.Context, scopeId, authMethodId string, req *pbs.UpdateAccountRequest) (auth.Account, error) {
const op = "accounts.(Service).updateInRepo"
var out auth.Account
@@ -633,6 +771,15 @@ func (s Service) updateInRepo(ctx context.Context, scopeId, authMethodId string,
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update account but no error returned from repository.")
}
out = a
case ldap.Subtype:
a, err := s.updateLdapInRepo(ctx, scopeId, authMethodId, req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if a == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update account but no error returned from repository.")
}
out = a
}
return out, nil
}
@@ -654,6 +801,12 @@ func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool,
return false, iErr
}
rows, err = repo.DeleteAccount(ctx, scopeId, id)
case ldap.Subtype:
repo, iErr := s.ldapRepoFn()
if iErr != nil {
return false, iErr
}
rows, err = repo.DeleteAccount(ctx, id)
}
if err != nil {
if errors.IsNotFoundError(err) {
@@ -693,6 +846,18 @@ func (s Service) listFromRepo(ctx context.Context, authMethodId string) ([]auth.
for _, a := range oidcl {
outUl = append(outUl, a)
}
case ldap.Subtype:
ldapRepo, err := s.ldapRepoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
ldapList, err := ldapRepo.ListAccounts(ctx, authMethodId)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
for _, a := range ldapList {
outUl = append(outUl, a)
}
}
return outUl, nil
}
@@ -756,6 +921,11 @@ func (s Service) parentAndAuthResult(ctx context.Context, id string, a action.Ty
res.Error = err
return nil, res
}
ldapRepo, err := s.ldapRepoFn()
if err != nil {
res.Error = err
return nil, res
}
var parentId string
opts := []requestauth.Option{requestauth.WithType(resource.Account), requestauth.WithAction(a)}
@@ -786,6 +956,17 @@ func (s Service) parentAndAuthResult(ctx context.Context, id string, a action.Ty
return nil, res
}
parentId = acct.GetAuthMethodId()
case ldap.Subtype:
acct, err := ldapRepo.LookupAccount(ctx, id)
if err != nil {
res.Error = err
return nil, res
}
if acct == nil {
res.Error = handlers.NotFoundError()
return nil, res
}
parentId = acct.GetAuthMethodId()
}
opts = append(opts, requestauth.WithId(id))
}
@@ -814,6 +995,17 @@ func (s Service) parentAndAuthResult(ctx context.Context, id string, a action.Ty
return nil, res
}
authMeth = am
case ldap.Subtype:
am, err := ldapRepo.LookupAuthMethod(ctx, parentId)
if err != nil {
res.Error = err
return nil, res
}
if am == nil {
res.Error = handlers.NotFoundError()
return nil, res
}
authMeth = am
}
opts = append(opts, requestauth.WithScopeId(authMeth.GetScopeId()), requestauth.WithPin(parentId))
return authMeth, requestauth.Verify(ctx, opts...)
@@ -908,6 +1100,29 @@ func toProto(ctx context.Context, in auth.Account, opt ...handlers.Option) (*pb.
}
}
out.Attrs = attrs
case *ldap.Account:
if outputFields.Has(globals.TypeField) {
out.Type = ldap.Subtype.String()
}
if !outputFields.Has(globals.AttributesField) {
break
}
attrs := &pb.Account_LdapAccountAttributes{
LdapAccountAttributes: &pb.LdapAccountAttributes{
LoginName: i.GetLoginName(),
FullName: i.GetFullName(),
Email: i.GetEmail(),
Dn: i.GetDn(),
},
}
if encodedGroups := i.GetMemberOfGroups(); encodedGroups != "" {
var decodedGroups []string
if err := json.Unmarshal([]byte(encodedGroups), &decodedGroups); err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(""))
}
attrs.LdapAccountAttributes.MemberOfGroups = decodedGroups
}
out.Attrs = attrs
}
return &out, nil
}
@@ -946,7 +1161,7 @@ func validateGetRequest(req *pbs.GetAccountRequest) error {
if req == nil {
return errors.NewDeprecated(errors.InvalidParameter, op, "nil request")
}
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, globals.PasswordAccountPreviousPrefix, globals.PasswordAccountPrefix, globals.OidcAccountPrefix)
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, globals.PasswordAccountPreviousPrefix, globals.PasswordAccountPrefix, globals.OidcAccountPrefix, globals.LdapAccountPrefix)
}
func validateCreateRequest(req *pbs.CreateAccountRequest) error {
@@ -1001,6 +1216,31 @@ func validateCreateRequest(req *pbs.CreateAccountRequest) error {
badFields[emailClaimField] = "This is a read only field."
}
}
case ldap.Subtype:
if req.GetItem().GetType() != "" && req.GetItem().GetType() != ldap.Subtype.String() {
badFields[typeField] = "Doesn't match the parent resource's type."
}
attrs := req.GetItem().GetLdapAccountAttributes()
switch {
case attrs == nil:
badFields["attributes"] = "This is a required field."
default:
if attrs.GetLoginName() == "" {
badFields[loginAttrField] = "This is a required field for this type."
}
if attrs.GetFullName() != "" {
badFields[nameAttrField] = "This is a read only field."
}
if attrs.GetEmail() != "" {
badFields[emailAttrField] = "This is a read only field."
}
if attrs.GetDn() != "" {
badFields[dnAttrField] = "This is a read only field."
}
if len(attrs.GetMemberOfGroups()) > 0 {
badFields[memberOfAttrField] = "This is a read only field."
}
}
default:
badFields[authMethodIdField] = "Unknown auth method type from ID."
}
@@ -1036,9 +1276,28 @@ func validateUpdateRequest(req *pbs.UpdateAccountRequest) error {
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), nameClaimField) {
badFields[nameClaimField] = "Field is read only."
}
case ldap.Subtype:
if req.GetItem().GetType() != "" && req.GetItem().GetType() != ldap.Subtype.String() {
badFields[typeField] = "Cannot modify the resource type."
}
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), loginAttrField) {
badFields[loginAttrField] = "Field cannot be updated."
}
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), nameAttrField) {
badFields[nameAttrField] = "Field cannot be updated."
}
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), emailAttrField) {
badFields[emailAttrField] = "Field cannot be updated."
}
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), dnAttrField) {
badFields[dnAttrField] = "Field cannot be updated."
}
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), memberOfAttrField) {
badFields[memberOfAttrField] = "Field cannot be updated."
}
}
return badFields
}, globals.PasswordAccountPreviousPrefix, globals.PasswordAccountPrefix, globals.OidcAccountPrefix)
}, globals.PasswordAccountPreviousPrefix, globals.PasswordAccountPrefix, globals.OidcAccountPrefix, globals.LdapAccountPrefix)
}
func validateDeleteRequest(req *pbs.DeleteAccountRequest) error {
@@ -1046,7 +1305,7 @@ func validateDeleteRequest(req *pbs.DeleteAccountRequest) error {
if req == nil {
return errors.NewDeprecated(errors.InvalidParameter, op, "nil request")
}
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, globals.PasswordAccountPreviousPrefix, globals.PasswordAccountPrefix, globals.OidcAccountPrefix)
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, globals.PasswordAccountPreviousPrefix, globals.PasswordAccountPrefix, globals.OidcAccountPrefix, globals.LdapAccountPrefix)
}
func validateListRequest(req *pbs.ListAccountsRequest) error {
@@ -1055,7 +1314,7 @@ func validateListRequest(req *pbs.ListAccountsRequest) error {
return errors.NewDeprecated(errors.InvalidParameter, op, "nil request")
}
badFields := map[string]string{}
if !handlers.ValidId(handlers.Id(req.GetAuthMethodId()), globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix) {
if !handlers.ValidId(handlers.Id(req.GetAuthMethodId()), globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix) {
badFields[authMethodIdField] = "Invalid formatted identifier."
}
if _, err := handlers.NewFilter(req.GetFilter()); err != nil {
File diff suppressed because it is too large. Load diff
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
@@ -52,6 +53,14 @@ func TestValidateCreateRequest(t *testing.T) {
},
errContains: fieldError(typeField, "Doesn't match the parent resource's type."),
},
{
name: "mismatched pw authmethod ldap type",
item: &pb.Account{
Type: ldap.Subtype.String(),
AuthMethodId: globals.PasswordAuthMethodPrefix + "_1234567890",
},
errContains: fieldError(typeField, "Doesn't match the parent resource's type."),
},
{
name: "missing oidc attributes",
item: &pb.Account{
@@ -93,6 +102,69 @@ func TestValidateCreateRequest(t *testing.T) {
},
errContains: fieldError(emailClaimField, "This is a read only field."),
},
{
name: "missing ldap attributes",
item: &pb.Account{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
},
errContains: fieldError(attributesField, "This is a required field."),
},
{
name: "missing login name for ldap type",
item: &pb.Account{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: &pb.Account_LdapAccountAttributes{
LdapAccountAttributes: &pb.LdapAccountAttributes{},
},
},
errContains: fieldError(loginAttrField, "This is a required field for this type."),
},
{
name: "read only full name attr field",
item: &pb.Account{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: &pb.Account_LdapAccountAttributes{
LdapAccountAttributes: &pb.LdapAccountAttributes{FullName: "something"},
},
},
errContains: fieldError(nameAttrField, "This is a read only field."),
},
{
name: "read only email attr field",
item: &pb.Account{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: &pb.Account_LdapAccountAttributes{
LdapAccountAttributes: &pb.LdapAccountAttributes{Email: "something"},
},
},
errContains: fieldError(emailAttrField, "This is a read only field."),
},
{
name: "read only dn attr field",
item: &pb.Account{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: &pb.Account_LdapAccountAttributes{
LdapAccountAttributes: &pb.LdapAccountAttributes{Dn: "something"},
},
},
errContains: fieldError(dnAttrField, "This is a read only field."),
},
{
name: "read only member of attr field",
item: &pb.Account{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: &pb.Account_LdapAccountAttributes{
LdapAccountAttributes: &pb.LdapAccountAttributes{MemberOfGroups: []string{"something"}},
},
},
errContains: fieldError(memberOfAttrField, "This is a read only field."),
},
{
name: "missing password attributes",
item: &pb.Account{
@@ -134,6 +206,16 @@ func TestValidateCreateRequest(t *testing.T) {
},
},
},
{
name: "no ldap errors",
item: &pb.Account{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: &pb.Account_LdapAccountAttributes{
LdapAccountAttributes: &pb.LdapAccountAttributes{LoginName: "no oidc errors"},
},
},
},
}
for _, tc := range cases {
tc := tc
@@ -5,12 +5,14 @@ package authmethods
import (
"context"
"encoding/base64"
"fmt"
"net/url"
"strings"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
@@ -86,12 +88,13 @@ type Service struct {
oidcRepoFn common.OidcAuthRepoFactory
iamRepoFn common.IamRepoFactory
atRepoFn common.AuthTokenRepoFactory
ldapRepoFn common.LdapAuthRepoFactory
}
var _ pbs.AuthMethodServiceServer = (*Service)(nil)
// NewService returns a auth method service which handles auth method related requests to boundary.
func NewService(kms *kms.Kms, pwRepoFn common.PasswordAuthRepoFactory, oidcRepoFn common.OidcAuthRepoFactory, iamRepoFn common.IamRepoFactory, atRepoFn common.AuthTokenRepoFactory, opt ...handlers.Option) (Service, error) {
func NewService(kms *kms.Kms, pwRepoFn common.PasswordAuthRepoFactory, oidcRepoFn common.OidcAuthRepoFactory, iamRepoFn common.IamRepoFactory, atRepoFn common.AuthTokenRepoFactory, ldapRepoFn common.LdapAuthRepoFactory, opt ...handlers.Option) (Service, error) {
const op = "authmethods.NewService"
if kms == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing kms")
@@ -102,13 +105,16 @@ func NewService(kms *kms.Kms, pwRepoFn common.PasswordAuthRepoFactory, oidcRepoF
if oidcRepoFn == nil {
return Service{}, fmt.Errorf("nil oidc repository provided")
}
if ldapRepoFn == nil {
return Service{}, fmt.Errorf("nil ldap repository provided")
}
if iamRepoFn == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing iam repository")
}
if atRepoFn == nil {
return Service{}, fmt.Errorf("nil auth token repository provided")
}
s := Service{kms: kms, pwRepoFn: pwRepoFn, oidcRepoFn: oidcRepoFn, iamRepoFn: iamRepoFn, atRepoFn: atRepoFn}
s := Service{kms: kms, pwRepoFn: pwRepoFn, oidcRepoFn: oidcRepoFn, iamRepoFn: iamRepoFn, atRepoFn: atRepoFn, ldapRepoFn: ldapRepoFn}
return s, nil
}
@@ -427,6 +433,10 @@ func (s Service) Authenticate(ctx context.Context, req *pbs.AuthenticateRequest)
if err := validateAuthenticateOidcRequest(req); err != nil {
return nil, err
}
case ldap.Subtype:
if err := validateAuthenticateLdapRequest(req); err != nil {
return nil, err
}
}
authResults := s.authResult(ctx, req.GetAuthMethodId(), action.Authenticate)
@@ -440,6 +450,8 @@ func (s Service) Authenticate(ctx context.Context, req *pbs.AuthenticateRequest)
case oidc.Subtype:
return s.authenticateOidc(ctx, req, &authResults)
case ldap.Subtype:
return s.authenticateLdap(ctx, req, &authResults)
}
return nil, errors.New(ctx, errors.Internal, op, "Invalid auth method subtype not caught in validation function.")
}
@@ -462,6 +474,13 @@ func (s Service) getFromRepo(ctx context.Context, id string) (auth.AuthMethod, e
}
am, lookupErr = repo.LookupAuthMethod(ctx, id)
case ldap.Subtype:
repo, err := s.ldapRepoFn()
if err != nil {
return nil, err
}
am, lookupErr = repo.LookupAuthMethod(ctx, id)
default:
return nil, handlers.NotFoundErrorf("Unrecognized id.")
}
@@ -511,6 +530,19 @@ func (s Service) listFromRepo(ctx context.Context, scopeIds []string, authResult
for _, item := range pl {
outUl = append(outUl, item)
}
ldapRepo, err := s.ldapRepoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
ll, err := ldapRepo.ListAuthMethods(ctx, scopeIds, ldap.WithUnauthenticatedUser(ctx, reqCtx.UserId == globals.AnonymousUserId))
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
for _, item := range ll {
outUl = append(outUl, item)
}
return outUl, nil
}
@@ -536,6 +568,15 @@ func (s Service) createInRepo(ctx context.Context, scopeId string, item *pb.Auth
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
}
out = am
case ldap.Subtype:
am, err := s.createLdapInRepo(ctx, scopeId, item)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if am == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create auth method but no error returned from repository.")
}
out = am
}
return out, nil
}
@@ -567,6 +608,24 @@ func (s Service) updateInRepo(ctx context.Context, scopeId string, req *pbs.Upda
}
am = oam
dryRun = dr
case ldap.Subtype:
lam, err := s.updateLdapInRepo(ctx, scopeId, req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
if err != nil {
_, apiErr := err.(*handlers.ApiError)
switch {
case apiErr:
return nil, false, err
case errors.Match(errors.T(errors.InvalidParameter), err):
return nil, false, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, err.Error())
default:
return nil, false, errors.Wrap(ctx, err, op)
}
}
if lam == nil {
return nil, false, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update auth method but no error returned from repository.")
}
am = lam
}
return am, dryRun, nil
@@ -590,6 +649,14 @@ func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool,
return false, errors.Wrap(ctx, err, op)
}
rows, dErr = repo.DeleteAuthMethod(ctx, id)
case ldap.Subtype:
repo, err := s.ldapRepoFn()
if err != nil {
return false, errors.Wrap(ctx, err, op)
}
rows, dErr = repo.DeleteAuthMethod(ctx, id)
default:
return false, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("invalid auth method subtype: %q", subtypes.SubtypeFromId(domain, id)))
}
if dErr != nil {
@@ -697,6 +764,22 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type) reque
return res
}
authMeth = am
case ldap.Subtype:
repo, err := s.ldapRepoFn()
if err != nil {
res.Error = err
return res
}
am, err := repo.LookupAuthMethod(ctx, id)
if err != nil {
res.Error = err
return res
}
if am == nil {
res.Error = handlers.NotFoundError()
return res
}
authMeth = am
default:
res.Error = errors.New(ctx, errors.InvalidPublicId, op, "unrecognized auth method type")
return res
@@ -801,6 +884,60 @@ func toAuthMethodProto(ctx context.Context, in auth.AuthMethod, opt ...handlers.
out.Attrs = &pb.AuthMethod_OidcAuthMethodsAttributes{
OidcAuthMethodsAttributes: attrs,
}
case *ldap.AuthMethod:
if outputFields.Has(globals.TypeField) {
out.Type = ldap.Subtype.String()
}
if !outputFields.Has(globals.AttributesField) {
break
}
attrs := &pb.LdapAuthMethodAttributes{
State: i.GetOperationalState(),
StartTls: i.GetStartTls(),
InsecureTls: i.GetInsecureTls(),
DiscoverDn: i.GetDiscoverDn(),
AnonGroupSearch: i.GetAnonGroupSearch(),
Urls: i.GetUrls(),
EnableGroups: i.GetEnableGroups(),
Certificates: i.GetCertificates(),
ClientCertificateKeyHmac: base64.RawURLEncoding.EncodeToString(i.GetClientCertificateKeyHmac()),
BindPasswordHmac: base64.RawURLEncoding.EncodeToString(i.GetBindPasswordHmac()),
UseTokenGroups: i.GetUseTokenGroups(),
}
if i.GetUpnDomain() != "" {
attrs.UpnDomain = wrapperspb.String(i.GetUpnDomain())
}
if i.GetUserDn() != "" {
attrs.UserDn = wrapperspb.String(i.GetUserDn())
}
if i.GetUserAttr() != "" {
attrs.UserAttr = wrapperspb.String(i.GetUserAttr())
}
if i.GetUserFilter() != "" {
attrs.UserFilter = wrapperspb.String(i.GetUserFilter())
}
if i.GetGroupDn() != "" {
attrs.GroupDn = wrapperspb.String(i.GetGroupDn())
}
if i.GetGroupAttr() != "" {
attrs.GroupAttr = wrapperspb.String(i.GetGroupAttr())
}
if i.GetGroupFilter() != "" {
attrs.GroupFilter = wrapperspb.String(i.GetGroupFilter())
}
if i.GetClientCertificate() != "" {
attrs.ClientCertificate = wrapperspb.String(i.GetClientCertificate())
}
if i.GetBindDn() != "" {
attrs.BindDn = wrapperspb.String(i.GetBindDn())
}
if len(i.GetAccountAttributeMaps()) > 0 {
attrs.AccountAttributeMaps = i.GetAccountAttributeMaps()
}
out.Attrs = &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: attrs,
}
}
return &out, nil
}
@@ -829,7 +966,7 @@ func validateGetRequest(req *pbs.GetAuthMethodRequest) error {
if req == nil {
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix)
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix)
}
func validateCreateRequest(ctx context.Context, req *pbs.CreateAuthMethodRequest) error {
@@ -925,6 +1062,11 @@ func validateCreateRequest(ctx context.Context, req *pbs.CreateAuthMethodRequest
}
}
}
case ldap.Subtype:
if len(req.GetItem().GetLdapAuthMethodsAttributes().GetUrls()) == 0 {
badFields[urlsField] = "At least one URL is required"
}
validateLdapAttributes(ctx, req.GetItem().GetLdapAuthMethodsAttributes(), badFields)
default:
badFields[typeField] = fmt.Sprintf("This is a required field and must be %q.", password.Subtype.String())
}
@@ -1051,11 +1193,16 @@ func validateUpdateRequest(ctx context.Context, req *pbs.UpdateAuthMethodRequest
}
}
}
case ldap.Subtype:
if req.GetItem().GetType() != "" && subtypes.SubtypeFromType(domain, req.GetItem().GetType()) != ldap.Subtype {
badFields[typeField] = "Cannot modify the resource type."
}
validateLdapAttributes(ctx, req.GetItem().GetLdapAuthMethodsAttributes(), badFields)
default:
badFields["id"] = "Incorrectly formatted identifier."
}
return badFields
}, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix)
}, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix)
}
func validateDeleteRequest(req *pbs.DeleteAuthMethodRequest) error {
@@ -1063,7 +1210,7 @@ func validateDeleteRequest(req *pbs.DeleteAuthMethodRequest) error {
if req == nil {
return errors.NewDeprecated(errors.InvalidParameter, op, "Missing request")
}
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix)
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix)
}
func validateListRequest(req *pbs.ListAuthMethodsRequest) error {
@@ -1127,7 +1274,7 @@ func validateAuthenticateRequest(req *pbs.AuthenticateRequest) error {
} else {
st := subtypes.SubtypeFromId(domain, req.GetAuthMethodId())
switch st {
case password.Subtype, oidc.Subtype:
case password.Subtype, oidc.Subtype, ldap.Subtype:
default:
badFields[authMethodIdField] = "Unknown auth method type."
}
@@ -1267,6 +1414,14 @@ func transformAuthenticateRequestAttributes(msg proto.Message) error {
default:
return fmt.Errorf("%s: unknown command %q", op, authRequest.GetCommand())
}
case ldap.Subtype:
newAttrs := &pbs.LdapLoginAttributes{}
if err := handlers.StructToProto(attrs, newAttrs); err != nil {
return err
}
authRequest.Attrs = &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: newAttrs,
}
default:
return &subtypes.UnknownSubtypeIDError{
ID: authRequest.GetAuthMethodId(),
@@ -5,6 +5,10 @@ package authmethods_test
import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"regexp"
"strings"
@@ -12,6 +16,7 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
@@ -27,7 +32,9 @@ import (
"github.com/hashicorp/boundary/internal/types/scope"
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
scopepb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/scopes"
"golang.org/x/exp/slices"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
@@ -58,6 +65,13 @@ var (
action.ChangeState.String(),
action.Authenticate.String(),
}
ldapAuthorizedActions = []string{
action.NoOp.String(),
action.Read.String(),
action.Update.String(),
action.Delete.String(),
action.Authenticate.String(),
}
)
var authorizedCollectionActions = map[string]*structpb.ListValue{
@@ -87,6 +101,9 @@ func TestGet(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
}
@@ -153,6 +170,32 @@ func TestGet(t *testing.T) {
AuthorizedCollectionActions: authorizedCollectionActions,
}
ldapAm := ldap.TestAuthMethod(t, conn, databaseWrapper, o.GetPublicId(), []string{"ldaps://ldap1"}, ldap.WithAccountAttributeMap(ctx, map[string]ldap.AccountToAttribute{
"mail": ldap.ToEmailAttribute,
}))
wantLdap := &pb.AuthMethod{
Id: ldapAm.GetPublicId(),
ScopeId: ldapAm.GetScopeId(),
CreatedTime: ldapAm.CreateTime.GetTimestamp(),
UpdatedTime: ldapAm.UpdateTime.GetTimestamp(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
State: string(ldap.InactiveState),
Urls: []string{"ldaps://ldap1"},
AccountAttributeMaps: []string{"mail=email"},
},
},
Version: 1,
Scope: &scopepb.ScopeInfo{
Id: o.GetPublicId(),
Type: o.GetType(),
ParentScopeId: scope.Global.String(),
},
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
}
cases := []struct {
name string
scopeId string
@@ -173,7 +216,13 @@ func TestGet(t *testing.T) {
res: &pbs.GetAuthMethodResponse{Item: wantOidc},
},
{
name: "Get a non existant AuthMethod",
name: "Get an Existing LDAP AuthMethod",
scopeId: o.GetPublicId(),
req: &pbs.GetAuthMethodRequest{Id: ldapAm.GetPublicId()},
res: &pbs.GetAuthMethodResponse{Item: wantLdap},
},
{
name: "Get a non existent AuthMethod",
scopeId: o.GetPublicId(),
req: &pbs.GetAuthMethodRequest{Id: globals.PasswordAuthMethodPrefix + "_DoesntExis"},
res: nil,
@@ -198,7 +247,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(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
s, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(err, "Couldn't create new auth_method service.")
got, gErr := s.GetAuthMethod(requestauth.DisabledAuthTestContext(iamRepoFn, tc.scopeId), tc.req)
@@ -228,6 +277,9 @@ func TestList(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
}
@@ -293,6 +345,42 @@ func TestList(t *testing.T) {
})
}
sorterFn := func(a *pb.AuthMethod, b *pb.AuthMethod) bool {
switch {
case a.GetId() > b.GetId():
return true
default:
return false
}
}
cpSorted := func(ams []*pb.AuthMethod) []*pb.AuthMethod {
cp := make([]*pb.AuthMethod, 0, len(ams))
for _, a := range ams {
cp = append(cp, proto.Clone(a).(*pb.AuthMethod))
}
slices.SortFunc(cp, sorterFn)
return cp
}
ldapAm := ldap.TestAuthMethod(t, conn, databaseWrapper, oWithAuthMethods.GetPublicId(), []string{"ldaps://ldap1"}, ldap.WithOperationalState(ctx, ldap.ActivePublicState))
wantSomeAuthMethods = append(wantSomeAuthMethods, &pb.AuthMethod{
Id: ldapAm.GetPublicId(),
ScopeId: oWithAuthMethods.GetPublicId(),
CreatedTime: ldapAm.GetCreateTime().GetTimestamp(),
UpdatedTime: ldapAm.GetUpdateTime().GetTimestamp(),
Scope: &scopepb.ScopeInfo{Id: oWithAuthMethods.GetPublicId(), Type: scope.Org.String(), ParentScopeId: scope.Global.String()},
Version: 1,
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
State: string(ldap.ActivePublicState),
Urls: []string{"ldaps://ldap1"},
},
},
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
})
var wantOtherAuthMethods []*pb.AuthMethod
for _, aa := range password.TestAuthMethods(t, conn, oWithOtherAuthMethods.GetPublicId(), 3) {
wantOtherAuthMethods = append(wantOtherAuthMethods, &pb.AuthMethod{
@@ -323,12 +411,12 @@ func TestList(t *testing.T) {
{
name: "List Some Auth Methods",
req: &pbs.ListAuthMethodsRequest{ScopeId: oWithAuthMethods.GetPublicId()},
res: &pbs.ListAuthMethodsResponse{Items: wantSomeAuthMethods},
res: &pbs.ListAuthMethodsResponse{Items: cpSorted(wantSomeAuthMethods)},
},
{
name: "List Other Auth Methods",
req: &pbs.ListAuthMethodsRequest{ScopeId: oWithOtherAuthMethods.GetPublicId()},
res: &pbs.ListAuthMethodsResponse{Items: wantOtherAuthMethods},
res: &pbs.ListAuthMethodsResponse{Items: cpSorted(wantOtherAuthMethods)},
},
{
name: "List No Auth Methods",
@@ -344,7 +432,9 @@ func TestList(t *testing.T) {
name: "List All Auth Methods Recursively",
req: &pbs.ListAuthMethodsRequest{ScopeId: "global", Recursive: true},
res: &pbs.ListAuthMethodsResponse{
Items: append(wantSomeAuthMethods, wantOtherAuthMethods...),
Items: func() []*pb.AuthMethod {
return cpSorted(append(wantSomeAuthMethods, wantOtherAuthMethods...))
}(),
},
},
{
@@ -353,7 +443,7 @@ func TestList(t *testing.T) {
ScopeId: "global", Recursive: true,
Filter: fmt.Sprintf(`"/item/scope/id"==%q`, oWithAuthMethods.GetPublicId()),
},
res: &pbs.ListAuthMethodsResponse{Items: wantSomeAuthMethods},
res: &pbs.ListAuthMethodsResponse{Items: cpSorted(wantSomeAuthMethods)},
},
{
name: "Filter All Auth Methods",
@@ -369,7 +459,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(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
s, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(err, "Couldn't create new auth_method service.")
// First check with non-anonymous user
@@ -385,7 +475,11 @@ func TestList(t *testing.T) {
assert.NotEqual("secret", oidcAttrs.ClientSecretHmac)
}
}
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform(), protocmp.IgnoreFields(&pb.OidcAuthMethodAttributes{}, "client_secret_hmac")),
slices.SortFunc(got.Items, sorterFn)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform(),
protocmp.IgnoreFields(&pb.OidcAuthMethodAttributes{}, "client_secret_hmac"),
protocmp.IgnoreFields(&pb.LdapAuthMethodAttributes{}, "bind_password_hmac", "client_certificate_key_hmac")),
"ListAuthMethods() for scope %q got response %q, wanted %q", tc.req.GetScopeId(), got, tc.res)
// Now check with anonymous user
@@ -414,6 +508,9 @@ func TestDelete(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
}
@@ -430,7 +527,9 @@ func TestDelete(t *testing.T) {
oidcam := oidc.TestAuthMethod(t, conn, databaseWrapper, o.GetPublicId(), oidc.InactiveState, "alice_rp", "my-dogs-name",
oidc.WithIssuer(oidc.TestConvertToUrls(t, "https://alice.com")[0]), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://api.com")[0]))
s, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
ldapAm := ldap.TestAuthMethod(t, conn, databaseWrapper, o.GetPublicId(), []string{"ldaps://ldap1"})
s, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(t, err, "Error when getting new auth_method service.")
cases := []struct {
@@ -453,6 +552,13 @@ func TestDelete(t *testing.T) {
},
res: &pbs.DeleteAuthMethodResponse{},
},
{
name: "Delete an Existing LDAP AuthMethod",
req: &pbs.DeleteAuthMethodRequest{
Id: ldapAm.GetPublicId(),
},
res: &pbs.DeleteAuthMethodResponse{},
},
{
name: "Delete bad auth_method id",
req: &pbs.DeleteAuthMethodRequest{
@@ -494,6 +600,9 @@ func TestDelete_twice(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kms)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
}
@@ -505,7 +614,7 @@ func TestDelete_twice(t *testing.T) {
o, _ := iam.TestScopes(t, iamRepo)
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
s, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
s, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(err, "Error when getting new auth_method service.")
req := &pbs.DeleteAuthMethodRequest{
@@ -523,18 +632,21 @@ func TestCreate(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
testKms := kms.TestKms(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)
return password.NewRepository(rw, rw, testKms)
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kms)
return oidc.NewRepository(ctx, rw, rw, testKms)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, testKms)
}
atRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(rw, rw, kms)
return authtoken.NewRepository(rw, rw, testKms)
}
iamRepo := iam.TestRepo(t, conn, wrapper)
@@ -542,12 +654,20 @@ func TestCreate(t *testing.T) {
defaultAm := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
defaultCreated := defaultAm.GetCreateTime().GetTimestamp()
_, testEncodedCert := ldap.TestGenerateCA(t, "localhost")
_, privKey, err := ed25519.GenerateKey(rand.Reader)
require.NoError(t, err)
derEncodedKey, err := x509.MarshalPKCS8PrivateKey(privKey)
require.NoError(t, err)
testEncodedKey := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: derEncodedKey})
cases := []struct {
name string
req *pbs.CreateAuthMethodRequest
res *pbs.CreateAuthMethodResponse
idPrefix string
err error
name string
req *pbs.CreateAuthMethodRequest
res *pbs.CreateAuthMethodResponse
idPrefix string
err error
errContains string
}{
{
name: "Create a valid Password AuthMethod",
@@ -627,6 +747,74 @@ func TestCreate(t *testing.T) {
},
},
},
{
name: "create-a-valid-ldap-auth-method",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
StartTls: true,
InsecureTls: true,
DiscoverDn: true,
AnonGroupSearch: true,
UpnDomain: wrapperspb.String("upn_domain"),
Urls: []string{"ldap://ldap1", "ldaps://ldap1"},
BindDn: wrapperspb.String("bind-dn"),
BindPassword: wrapperspb.String("bind-password"),
UserDn: wrapperspb.String("user-dn"),
UserAttr: wrapperspb.String("user-attr"),
UserFilter: wrapperspb.String("user-filter"),
EnableGroups: true,
GroupDn: wrapperspb.String("group-dn"),
GroupAttr: wrapperspb.String("group-attr"),
GroupFilter: wrapperspb.String("group-filter"),
Certificates: []string{testEncodedCert},
ClientCertificate: wrapperspb.String(testEncodedCert),
ClientCertificateKey: wrapperspb.String(string(testEncodedKey)),
UseTokenGroups: true,
AccountAttributeMaps: []string{"mail=email"},
},
},
}},
idPrefix: globals.LdapAuthMethodPrefix + "_",
res: &pbs.CreateAuthMethodResponse{
Uri: fmt.Sprintf("auth-methods/%s_", globals.LdapAuthMethodPrefix),
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
CreatedTime: defaultAm.GetCreateTime().GetTimestamp(),
UpdatedTime: defaultAm.GetUpdateTime().GetTimestamp(),
Scope: &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()},
Version: 1,
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
State: string(ldap.InactiveState),
StartTls: true,
InsecureTls: true,
DiscoverDn: true,
AnonGroupSearch: true,
UpnDomain: wrapperspb.String("upn_domain"),
Urls: []string{"ldap://ldap1", "ldaps://ldap1"},
BindDn: wrapperspb.String("bind-dn"),
UserDn: wrapperspb.String("user-dn"),
UserAttr: wrapperspb.String("user-attr"),
UserFilter: wrapperspb.String("user-filter"),
EnableGroups: true,
GroupDn: wrapperspb.String("group-dn"),
GroupAttr: wrapperspb.String("group-attr"),
GroupFilter: wrapperspb.String("group-filter"),
Certificates: []string{testEncodedCert},
ClientCertificate: wrapperspb.String(testEncodedCert),
UseTokenGroups: true,
AccountAttributeMaps: []string{"mail=email"},
},
},
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "Create a global Password AuthMethod",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
@@ -698,6 +886,42 @@ func TestCreate(t *testing.T) {
},
},
},
{
name: "create-a-global-ldap-auth-method",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: scope.Global.String(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1", "ldaps://ldap1"},
EnableGroups: true,
GroupDn: wrapperspb.String("group-dn"),
},
},
}},
idPrefix: globals.LdapAuthMethodPrefix + "_",
res: &pbs.CreateAuthMethodResponse{
Uri: fmt.Sprintf("auth-methods/%s_", globals.LdapAuthMethodPrefix),
Item: &pb.AuthMethod{
ScopeId: scope.Global.String(),
CreatedTime: defaultAm.GetCreateTime().GetTimestamp(),
UpdatedTime: defaultAm.GetUpdateTime().GetTimestamp(),
Scope: &scopepb.ScopeInfo{Id: scope.Global.String(), Type: scope.Global.String(), Name: scope.Global.String(), Description: "Global Scope"},
Version: 1,
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
State: string(ldap.InactiveState),
Urls: []string{"ldap://ldap1", "ldaps://ldap1"},
EnableGroups: true,
GroupDn: wrapperspb.String("group-dn"),
},
},
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "Can't specify Id",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
@@ -955,18 +1179,186 @@ func TestCreate(t *testing.T) {
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "ldap-auth-method-requires-urls",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "At least one URL is required",
},
{
name: "ldap-auth-method-invalid-urls",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1", "not-ldap-scheme://ldap2"},
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "is not either ldap or ldaps",
},
{
name: "ldap-auth-method-invalid-cert",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
Certificates: []string{"invalid-cert"},
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "failed to parse certificate: invalid PEM encoding",
},
{
name: "ldap-auth-method-missing-bind-dn",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
BindPassword: wrapperspb.String("pass"),
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "attributes.bind_password is missing required attributes.bind_dn field",
},
{
name: "ldap-auth-method-missing-bind-password",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
BindDn: wrapperspb.String("bind-dn"),
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "attributes.bind_dn is missing required attributes.bind_password field",
},
{
name: "ldap-auth-method-invalid-client-cert",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
ClientCertificate: wrapperspb.String("invalid-cert"),
ClientCertificateKey: wrapperspb.String(string(testEncodedKey)),
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "failed to parse certificate: invalid PEM encoding",
},
{
name: "ldap-auth-method-invalid-client-cert-key",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
ClientCertificate: wrapperspb.String(testEncodedCert),
ClientCertificateKey: wrapperspb.String("invalid-key"),
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "attributes.client_certificate_key is not encoded as a valid pem",
},
{
name: "ldap-auth-method-client-cert-key-not-a-key",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
ClientCertificate: wrapperspb.String(testEncodedCert),
ClientCertificateKey: wrapperspb.String(testEncodedCert),
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "attributes.client_certificate_key is not a valid private key",
},
{
name: "ldap-auth-method-missing-client-cert-key",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
ClientCertificate: wrapperspb.String(testEncodedCert),
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "attributes.client_certificate is missing required attributes.client_certificate_key field",
},
{
name: "ldap-auth-method-missing-client-cert",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
ClientCertificateKey: wrapperspb.String(string(testEncodedKey)),
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "attributes.client_certificate_key is missing required attributes.client_certificate field",
},
{
name: "ldap-auth-method-invalid-attribute-map",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldap://ldap1"},
AccountAttributeMaps: []string{"invalid-map"},
},
},
}},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "invalid attributes.account_attribute_maps (unable to parse)",
},
}
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, oidcRepoFn, iamRepoFn, atRepoFn)
s, err := authmethods.NewService(testKms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(err, "Error when getting new auth_method service.")
conn.Debug(true)
got, gErr := s.CreateAuthMethod(requestauth.DisabledAuthTestContext(iamRepoFn, tc.req.GetItem().GetScopeId()), tc.req)
if tc.err != nil {
require.Error(gErr)
assert.True(errors.Is(gErr, tc.err), "CreateAuthMethod(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
if tc.errContains != "" {
assert.Contains(gErr.Error(), tc.errContains)
}
return
}
require.NoError(gErr)
@@ -1003,6 +1395,14 @@ func TestCreate(t *testing.T) {
protocmp.IgnoreFields(&pb.OidcAuthMethodAttributes{}, "client_secret_hmac", "callback_url"),
)
}
if ldapAttrs := got.Item.GetLdapAuthMethodsAttributes(); ldapAttrs != nil {
assert.NotEqual(ldapAttrs.BindPassword, ldapAttrs.BindPasswordHmac)
cmpOptions = append(
cmpOptions,
protocmp.SortRepeatedFields(&pb.LdapAuthMethodAttributes{}, "account_attribute_maps", "urls", "certificates"),
protocmp.IgnoreFields(&pb.LdapAuthMethodAttributes{}, "bind_password_hmac", "client_certificate_key_hmac"),
)
}
}
assert.Empty(cmp.Diff(got, tc.res, cmpOptions...), "CreateAuthMethod(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
@@ -51,6 +51,29 @@ func TestTransformAuthenticateRequestAttributes(t *testing.T) {
},
},
},
{
name: "ldap-attributes",
input: &pbs.AuthenticateRequest{
AuthMethodId: "amldap_test",
Attrs: &pbs.AuthenticateRequest_Attributes{
Attributes: &structpb.Struct{
Fields: map[string]*structpb.Value{
"login_name": structpb.NewStringValue("login-name"),
"password": structpb.NewStringValue("password"),
},
},
},
},
expected: &pbs.AuthenticateRequest{
AuthMethodId: "amldap_test",
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: "login-name",
Password: "password",
},
},
},
},
{
name: "oidc-start-attributes",
input: &pbs.AuthenticateRequest{
@@ -218,6 +241,20 @@ func TestTransformAuthenticateRequestAttributesErrors(t *testing.T) {
},
}))
})
t.Run("invalid-ldap-attributes", func(t *testing.T) {
t.Parallel()
require.Error(t, transformAuthenticateRequestAttributes(&pbs.AuthenticateRequest{
AuthMethodId: "amldap_test",
Attrs: &pbs.AuthenticateRequest_Attributes{
Attributes: &structpb.Struct{
Fields: map[string]*structpb.Value{
"field1": structpb.NewBoolValue(true),
"field2": structpb.NewStringValue("value2"),
},
},
},
}))
})
t.Run("invalid-oidc-start-attributes", func(t *testing.T) {
t.Parallel()
require.Error(t, transformAuthenticateRequestAttributes(&pbs.AuthenticateRequest{
@@ -0,0 +1,366 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package authmethods
import (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"net/url"
"strings"
"github.com/hashicorp/boundary/internal/auth/ldap"
ldapstore "github.com/hashicorp/boundary/internal/auth/ldap/store"
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
"github.com/hashicorp/boundary/internal/errors"
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
"github.com/hashicorp/boundary/internal/types/action"
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
"google.golang.org/grpc/codes"
)
var ldapMaskManager handlers.MaskManager
func init() {
var err error
if ldapMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&ldapstore.AuthMethod{}}, handlers.MaskSource{&pb.AuthMethod{}, &pb.LdapAuthMethodAttributes{}}); err != nil {
panic(err)
}
IdActions[ldap.Subtype] = action.ActionSet{
action.NoOp,
action.Read,
action.Update,
action.Delete,
action.Authenticate,
}
}
const (
urlsField = "attributes.urls"
bindDnField = "attributes.bind_dn"
bindPasswordField = "attributes.bind_password"
clientCertificateField = "attributes.client_certificate"
clientCertificateKeyField = "attributes.client_certificate_key"
certificatesField = "attributes.certificates"
accountAttributesMapField = "attributes.account_attribute_maps"
)
func (s Service) authenticateLdap(ctx context.Context, req *pbs.AuthenticateRequest, authResults *auth.VerifyResults) (*pbs.AuthenticateResponse, error) {
const op = "authmethod_service.(Service).authenticateLdap"
if req == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
}
if authResults == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil auth results.")
}
reqAttrs := req.GetLdapLoginAttributes()
ldapRepo, err := s.ldapRepoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
ldapFn := func() (ldap.Authenticator, error) {
return ldapRepo, nil
}
iamRepo, err := s.iamRepoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
iamFn := func() (ldap.LookupUser, error) {
return iamRepo, nil
}
atRepo, err := s.atRepoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
atFn := func() (ldap.AuthTokenCreator, error) {
return atRepo, nil
}
rawTk, err := ldap.Authenticate(ctx, ldapFn, iamFn, atFn, req.GetAuthMethodId(), reqAttrs.GetLoginName(), reqAttrs.GetPassword())
if err != nil {
// let's not send back too much info about the error
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Unauthenticated, "Unable to authenticate.")
}
tk, err := s.ConvertInternalAuthTokenToApiAuthToken(
ctx,
rawTk,
)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return s.convertToAuthenticateResponse(ctx, req, authResults, tk)
}
// createLdapInRepo creates an ldap auth method in a repo and returns the result.
// This method should never return a nil AuthMethod without returning an error.
func (s Service) createLdapInRepo(ctx context.Context, scopeId string, item *pb.AuthMethod) (*ldap.AuthMethod, error) {
u, err := toStorageLdapAuthMethod(ctx, scopeId, item)
if err != nil {
return nil, err
}
repo, err := s.ldapRepoFn()
if err != nil {
return nil, err
}
out, err := repo.CreateAuthMethod(ctx, u)
if err != nil {
return nil, fmt.Errorf("unable to create auth method: %w", err)
}
return out, nil
}
func (s Service) updateLdapInRepo(ctx context.Context, scopeId, id string, mask []string, item *pb.AuthMethod) (*ldap.AuthMethod, error) {
u, err := toStorageLdapAuthMethod(ctx, scopeId, item)
if err != nil {
return nil, err
}
version := item.GetVersion()
u.PublicId = id
dbMask := ldapMaskManager.Translate(mask)
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.ldapRepoFn()
if err != nil {
return nil, err
}
out, rowsUpdated, err := repo.UpdateAuthMethod(ctx, u, version, dbMask)
if err != nil {
return nil, fmt.Errorf("unable to update auth method: %w", err)
}
if rowsUpdated == 0 {
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist or incorrect version provided or no changes were made to the existing AuthMethod.", id)
}
return out, nil
}
func toStorageLdapAuthMethod(ctx context.Context, scopeId string, in *pb.AuthMethod) (out *ldap.AuthMethod, err error) {
const op = "authmethod_service.toStorageLdapAuthMethod"
if in == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "nil auth method.")
}
attrs := in.GetLdapAuthMethodsAttributes()
var opts []ldap.Option
if in.GetName() != nil {
opts = append(opts, ldap.WithName(ctx, in.GetName().GetValue()))
}
if in.GetDescription() != nil {
opts = append(opts, ldap.WithDescription(ctx, in.GetDescription().GetValue()))
}
var urls []*url.URL
if attrs != nil {
if attrs.GetState() != "" {
opts = append(opts, ldap.WithOperationalState(ctx, ldap.AuthMethodState(attrs.GetState())))
}
if attrs.StartTls {
opts = append(opts, ldap.WithStartTLS(ctx))
}
if attrs.InsecureTls {
opts = append(opts, ldap.WithInsecureTLS(ctx))
}
if attrs.DiscoverDn {
opts = append(opts, ldap.WithDiscoverDn(ctx))
}
if attrs.AnonGroupSearch {
opts = append(opts, ldap.WithAnonGroupSearch(ctx))
}
if attrs.UpnDomain.GetValue() != "" {
opts = append(opts, ldap.WithUpnDomain(ctx, attrs.UpnDomain.GetValue()))
}
if attrs.UserDn.GetValue() != "" {
opts = append(opts, ldap.WithUserDn(ctx, attrs.UserDn.GetValue()))
}
if attrs.UserAttr.GetValue() != "" {
opts = append(opts, ldap.WithUserAttr(ctx, attrs.UserAttr.GetValue()))
}
if attrs.UserFilter.GetValue() != "" {
opts = append(opts, ldap.WithUserFilter(ctx, attrs.UserFilter.GetValue()))
}
if attrs.EnableGroups {
opts = append(opts, ldap.WithEnableGroups(ctx))
}
if attrs.GroupDn.GetValue() != "" {
opts = append(opts, ldap.WithGroupDn(ctx, attrs.GroupDn.GetValue()))
}
if attrs.GroupAttr.GetValue() != "" {
opts = append(opts, ldap.WithGroupAttr(ctx, attrs.GroupAttr.GetValue()))
}
if attrs.GroupFilter.GetValue() != "" {
opts = append(opts, ldap.WithGroupFilter(ctx, attrs.GroupFilter.GetValue()))
}
if len(attrs.Certificates) > 0 {
certs, err := ldap.ParseCertificates(ctx, attrs.Certificates...)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
opts = append(opts, ldap.WithCertificates(ctx, certs...))
}
if attrs.ClientCertificate != nil || attrs.ClientCertificateKey != nil {
keyBlk, _ := pem.Decode([]byte(attrs.ClientCertificateKey.GetValue()))
if keyBlk == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unable to parse %s PEM", clientCertificateKeyField))
}
certBlk, _ := pem.Decode([]byte(attrs.ClientCertificate.GetValue()))
if certBlk == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unable to parse %s PEM", clientCertificateField))
}
cc, err := x509.ParseCertificate(certBlk.Bytes)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to parse %s ASN.1 DER", clientCertificateField))
}
opts = append(opts, ldap.WithClientCertificate(ctx, keyBlk.Bytes, cc))
}
if attrs.BindDn.GetValue() != "" || attrs.BindPassword.GetValue() != "" {
opts = append(opts, ldap.WithBindCredential(ctx, attrs.BindDn.GetValue(), attrs.BindPassword.GetValue()))
}
if attrs.UseTokenGroups {
opts = append(opts, ldap.WithUseTokenGroups(ctx))
}
if len(attrs.AccountAttributeMaps) > 0 {
attribMaps, err := ldap.ParseAccountAttributeMaps(ctx, attrs.AccountAttributeMaps...)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to parse %s", accountAttributesMapField))
}
fromToMap := map[string]ldap.AccountToAttribute{}
for _, m := range attribMaps {
fromToMap[m.From] = ldap.AccountToAttribute(m.To)
}
opts = append(opts, ldap.WithAccountAttributeMap(ctx, fromToMap))
}
if len(attrs.GetUrls()) > 0 {
urls = make([]*url.URL, 0, len(attrs.GetUrls()))
for _, urlStr := range attrs.GetUrls() {
u, err := url.Parse(urlStr)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to parse %q into a url", urlStr))
}
urls = append(urls, u)
}
opts = append(opts, ldap.WithUrls(ctx, urls...))
}
}
u, err := ldap.NewAuthMethod(ctx, scopeId, opts...)
if err != nil {
switch {
case errors.Match(errors.T(errors.InvalidParameter), err):
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, err.Error())
default:
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build auth method: %v.", err)
}
}
return u, nil
}
// validateLdapAttributes implements a handlers.CustomValidatorFunc(...) to be
// used when validating requests with ldap attributes.
func validateLdapAttributes(ctx context.Context, attrs *pb.LdapAuthMethodAttributes, badFields map[string]string) {
if attrs == nil {
// LDAP attributes are required when creating an LDAP auth method.
// badFields[attributesField] = "Attributes are required for creating an LDAP auth method."
return
}
if len(attrs.GetUrls()) > 0 {
badUrlMsgs := []string{}
for _, rawUrl := range attrs.GetUrls() {
u, err := url.Parse(rawUrl)
if err != nil {
badUrlMsgs = append(badUrlMsgs, fmt.Sprintf("%q is not a valid url", rawUrl))
continue
}
if u.Scheme != "ldap" && u.Scheme != "ldaps" {
badUrlMsgs = append(badUrlMsgs, fmt.Sprintf("%s scheme in url %q is not either ldap or ldaps", u.Scheme, u.String()))
}
}
if len(badUrlMsgs) > 0 {
badFields[urlsField] = strings.Join(badUrlMsgs, " / ")
}
}
if len(attrs.GetCertificates()) > 0 {
if _, err := ldap.ParseCertificates(ctx, attrs.GetCertificates()...); err != nil {
badFields[certificatesField] = fmt.Sprintf("invalid %s: %s", certificatesField, err.Error())
}
}
if attrs.GetBindDn().GetValue() != "" && attrs.GetBindPassword().GetValue() == "" {
badFields[bindPasswordField] = fmt.Sprintf("%s is missing required %s field", bindDnField, bindPasswordField)
}
if attrs.GetBindPassword().GetValue() != "" && attrs.GetBindDn().GetValue() == "" {
badFields[bindDnField] = fmt.Sprintf("%s is missing required %s field", bindPasswordField, bindDnField)
}
if attrs.GetClientCertificate().GetValue() != "" && attrs.GetClientCertificateKey().GetValue() == "" {
badFields[clientCertificateKeyField] = fmt.Sprintf("%s is missing required %s field", clientCertificateField, clientCertificateKeyField)
}
if attrs.GetClientCertificateKey().GetValue() != "" && attrs.GetClientCertificate().GetValue() == "" {
badFields[clientCertificateField] = fmt.Sprintf("%s is missing required %s field", clientCertificateKeyField, clientCertificateField)
}
if attrs.GetClientCertificate().GetValue() != "" {
if _, err := ldap.ParseCertificates(ctx, attrs.GetClientCertificate().GetValue()); err != nil {
badFields[clientCertificateField] = fmt.Sprintf("invalid %s: %s", clientCertificateField, err.Error())
}
}
if attrs.GetClientCertificateKey().GetValue() != "" {
blk, _ := pem.Decode([]byte(attrs.GetClientCertificateKey().GetValue()))
if blk == nil || blk.Bytes == nil {
badFields[clientCertificateKeyField] = fmt.Sprintf("%s is not encoded as a valid pem", clientCertificateKeyField)
} else {
if _, err := x509.ParsePKCS8PrivateKey(blk.Bytes); err != nil {
badFields[clientCertificateKeyField] = fmt.Sprintf("%s is not a valid private key", clientCertificateKeyField)
}
}
}
if len(attrs.AccountAttributeMaps) > 0 {
if _, err := ldap.ParseAccountAttributeMaps(ctx, attrs.AccountAttributeMaps...); err != nil {
badFields[accountAttributesMapField] = fmt.Sprintf("invalid %s (unable to parse)", accountAttributesMapField)
}
}
}
func validateAuthenticateLdapRequest(req *pbs.AuthenticateRequest) error {
badFields := make(map[string]string)
attrs := req.GetLdapLoginAttributes()
switch {
case attrs == nil:
badFields["attributes"] = "This is a required field."
default:
if attrs.LoginName == "" {
badFields["attributes.login_name"] = "This is a required field."
}
if attrs.Password == "" {
badFields["attributes.password"] = "This is a required field."
}
if req.GetCommand() == "" {
// TODO: Eventually, require a command. For now, fall back to "login" for backwards compat.
req.Command = loginCommand
}
if req.Command != loginCommand {
badFields[commandField] = "Invalid command for this auth method type."
}
tokenType := req.GetType()
if tokenType == "" {
// Fall back to deprecated field if type is not set
tokenType = req.GetTokenType() //nolint:all
}
tType := strings.ToLower(strings.TrimSpace(tokenType))
if tType != "" && tType != "token" && tType != "cookie" {
badFields[tokenTypeField] = `The only accepted types are "token" and "cookie".`
}
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
}
return nil
}
@@ -0,0 +1,983 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package authmethods_test
import (
"context"
"fmt"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/authmethods"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
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/types/scope"
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
scopepb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/scopes"
"github.com/hashicorp/go-hclog"
"github.com/jimlambrt/gldap"
"github.com/jimlambrt/gldap/testdirectory"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/genproto/protobuf/field_mask"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func Test_UpdateLdap(t *testing.T) {
t.Parallel()
ctx := context.TODO()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
iamRepoFn := func() (*iam.Repository, error) {
return iam.TestRepo(t, conn, wrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kms)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kms)
}
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(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(t, err, "Error when getting new auth_method service.")
defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()}
defaultAttributes := &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap1"},
State: "active-private",
},
}
defaultReadAttributes := &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap1"},
State: "active-private",
},
}
freshAuthMethod := func(t *testing.T) (*pb.AuthMethod, func()) {
ctx := auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId())
am, err := tested.CreateAuthMethod(ctx, &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Name: wrapperspb.String("default"),
Description: wrapperspb.String("default"),
Type: ldap.Subtype.String(),
Attrs: defaultAttributes,
}})
require.NoError(t, err)
clean := func() {
_, err := tested.DeleteAuthMethod(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()),
&pbs.DeleteAuthMethodRequest{Id: am.GetItem().GetId()})
require.NoError(t, err)
}
return am.GetItem(), clean
}
_, testEncodedCert := ldap.TestGenerateCA(t, "localhost")
tests := []struct {
name string
req *pbs.UpdateAuthMethodRequest
res *pbs.UpdateAuthMethodResponse
err error
errContains string
wantErr bool
}{
{
name: "update-an-existing-auth-method",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"name", "description"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
Type: ldap.Subtype.String(),
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
Version: 2,
Type: ldap.Subtype.String(),
Attrs: defaultReadAttributes,
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "multi-paths-in-single-string",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"name,description,type"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
Type: ldap.Subtype.String(),
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
Type: ldap.Subtype.String(),
Attrs: defaultReadAttributes,
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "no-update-mask",
req: &pbs.UpdateAuthMethodRequest{
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated name"},
Description: &wrapperspb.StringValue{Value: "updated desc"},
},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "UpdateMask not provided but is required to update this resource",
},
{
name: "missing-paths-in-mask",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{Paths: []string{}},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated name"},
Description: &wrapperspb.StringValue{Value: "updated desc"},
},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "No valid fields included in the update mask",
},
{
name: "non-existent-paths-in-mask",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{Paths: []string{"nonexistant_field"}},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated name"},
Description: &wrapperspb.StringValue{Value: "updated desc"},
},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "No valid fields included in the update mask",
},
{
name: "cannot-change-type",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{Paths: []string{"name", "type"}},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated name"},
Type: password.Subtype.String(),
},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "Cannot modify the resource type",
},
{
name: "cannot-change-is-primary",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{Paths: []string{"is_primary"}},
Item: &pb.AuthMethod{
IsPrimary: true,
},
},
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "This field is read only",
},
{
name: "unset-name",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"name"},
},
Item: &pb.AuthMethod{
Description: &wrapperspb.StringValue{Value: "ignored"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Description: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: defaultReadAttributes,
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "unset-description",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"description"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "ignored"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: defaultReadAttributes,
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "update-only-state",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.state"},
},
Item: &pb.AuthMethod{
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
State: "active-public",
},
},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "default"},
Description: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap1"},
State: "active-public",
},
},
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "update-only-name",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"name"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated"},
Description: &wrapperspb.StringValue{Value: "ignored"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "updated"},
Description: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: defaultReadAttributes,
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "update-only-description",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"description"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "ignored"},
Description: &wrapperspb.StringValue{Value: "notignored"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "default"},
Description: &wrapperspb.StringValue{Value: "notignored"},
Type: ldap.Subtype.String(),
Attrs: defaultReadAttributes,
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "update-a-non-existent-auth-method",
req: &pbs.UpdateAuthMethodRequest{
Id: globals.LdapAuthMethodPrefix + "_DoesNotExist",
UpdateMask: &field_mask.FieldMask{
Paths: []string{"description"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
},
},
err: handlers.ApiErrorWithCode(codes.NotFound),
errContains: "Resource not found",
},
{
name: "cannot-change-id",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"id"},
},
Item: &pb.AuthMethod{
Id: globals.LdapAuthMethodPrefix + "_something",
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "new desc"},
},
},
res: nil,
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "This is a read only field and cannot be specified in an update request",
},
{
name: "cannot-specify-created-time",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"created_time"},
},
Item: &pb.AuthMethod{
CreatedTime: timestamppb.Now(),
},
},
res: nil,
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "This is a read only field and cannot be specified in an update request",
},
{
name: "cannot-specify-updated-time",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"updated_time"},
},
Item: &pb.AuthMethod{
UpdatedTime: timestamppb.Now(),
},
},
res: nil,
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "This is a read only field and cannot be specified in an update request",
},
{
name: "cannot-specify-type",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"type"},
},
Item: &pb.AuthMethod{
Type: ldap.Subtype.String(),
},
},
res: nil,
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "No valid fields included in the update mask",
},
{
name: "cannot-change-scope",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"scope"},
},
Item: &pb.AuthMethod{
ScopeId: "something-new",
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "new desc"},
},
},
res: nil,
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "No valid fields included in the update mask",
},
{
name: "invalid-certs",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.certificates"},
},
Item: &pb.AuthMethod{
ScopeId: "something-new",
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Certificates: []string{ldap.TestInvalidPem},
},
},
},
},
res: nil,
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "invalid attributes.certificates",
},
{
name: "update-certs",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.certificates"},
},
Item: &pb.AuthMethod{
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Certificates: []string{testEncodedCert},
},
},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "default"},
Description: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap1"},
State: "active-private",
Certificates: []string{testEncodedCert},
},
},
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "update-urls",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.urls"},
},
Item: &pb.AuthMethod{
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap2", "ldaps://ldap3"},
},
},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "default"},
Description: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap2", "ldaps://ldap3"},
State: "active-private",
},
},
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "update-urls-err",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.urls"},
},
Item: &pb.AuthMethod{
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{" ldaps://ldap2"}, // invalid url (space at start)
},
},
},
},
res: nil,
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
errContains: "is not a valid url",
},
{
name: "update-user-search-config",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.user_dn", "attributes.user_attr", "attributes.user_filter"},
},
Item: &pb.AuthMethod{
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
UserDn: wrapperspb.String("user-dn"),
UserAttr: wrapperspb.String("user-attr"),
UserFilter: wrapperspb.String("user-filter"),
},
},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "default"},
Description: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap1"},
State: "active-private",
UserDn: wrapperspb.String("user-dn"),
UserAttr: wrapperspb.String("user-attr"),
UserFilter: wrapperspb.String("user-filter"),
},
},
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "use-token-groups",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.use_token_groups"},
},
Item: &pb.AuthMethod{
ScopeId: "something-new",
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
UseTokenGroups: true,
},
},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "default"},
Description: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap1"},
State: "active-private",
UseTokenGroups: true,
},
},
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "enable-groups-err",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.enable_groups"},
},
Item: &pb.AuthMethod{
ScopeId: "something-new",
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
EnableGroups: true,
},
},
},
},
res: nil,
wantErr: true,
errContains: "have a configured group_dn when enable_groups = true and use_token_groups = false",
},
{
name: "update-group-search-config",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.group_dn", "attributes.group_attr", "attributes.group_filter"},
},
Item: &pb.AuthMethod{
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
GroupDn: wrapperspb.String("group-dn"),
GroupAttr: wrapperspb.String("group-attr"),
GroupFilter: wrapperspb.String("group-filter"),
},
},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
ScopeId: o.GetPublicId(),
Version: 2,
Name: &wrapperspb.StringValue{Value: "default"},
Description: &wrapperspb.StringValue{Value: "default"},
Type: ldap.Subtype.String(),
Attrs: &pb.AuthMethod_LdapAuthMethodsAttributes{
LdapAuthMethodsAttributes: &pb.LdapAuthMethodAttributes{
Urls: []string{"ldaps://ldap1"},
State: "active-private",
GroupDn: wrapperspb.String("group-dn"),
GroupAttr: wrapperspb.String("group-attr"),
GroupFilter: wrapperspb.String("group-filter"),
},
},
Scope: defaultScopeInfo,
AuthorizedActions: ldapAuthorizedActions,
AuthorizedCollectionActions: authorizedCollectionActions,
},
},
},
{
name: "no-change",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"attributes.certificates"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "default"},
},
},
err: handlers.ApiErrorWithCode(codes.NotFound),
errContains: "no changes were made to the existing AuthMethod",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
am, cleanup := freshAuthMethod(t)
defer cleanup()
tc.req.Item.Version = am.GetVersion()
if tc.req.GetId() == "" {
tc.req.Id = am.GetId()
}
if tc.res != nil && tc.res.Item != nil {
tc.res.Item.Id = am.GetId()
tc.res.Item.CreatedTime = am.GetCreatedTime()
}
got, gErr := tested.UpdateAuthMethod(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.req)
// TODO: When handlers move to domain errors remove wantErr and rely errors.Match here.
if tc.err != nil || tc.wantErr {
require.Error(gErr)
if tc.err != nil {
assert.True(errors.Is(gErr, tc.err), "UpdateAuthMethod(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
}
if tc.errContains != "" {
assert.Contains(gErr.Error(), tc.errContains)
}
return
}
require.NoError(gErr)
if tc.res == nil {
require.Nil(got)
}
cmpOptions := []cmp.Option{protocmp.Transform()}
if got != nil {
assert.NotNilf(tc.res, "Expected UpdateAuthMethod response to be nil, but was %v", got)
gotUpdateTime := got.GetItem().GetUpdatedTime().AsTime()
created := am.GetCreatedTime().AsTime()
// Verify it is a auth_method updated after it was created
assert.True(gotUpdateTime.After(created), "Updated auth_method should have been updated after it's creation. Was updated %v, which is after %v", gotUpdateTime, created)
// Ignore all values which are hard to compare against.
cmpOptions = append(
cmpOptions,
protocmp.IgnoreFields(&pb.AuthMethod{}, "updated_time"),
protocmp.SortRepeatedFields(&pb.LdapAuthMethodAttributes{}, "account_attribute_maps", "urls", "certificates"),
protocmp.IgnoreFields(&pb.LdapAuthMethodAttributes{}, "bind_password_hmac", "client_certificate_key_hmac"),
)
assert.NotEqual("bind_password", got.Item.GetLdapAuthMethodsAttributes().GetBindPasswordHmac())
assert.NotEqual("client_certificate_key", got.Item.GetLdapAuthMethodsAttributes().GetClientCertificateKeyHmac())
}
assert.Empty(cmp.Diff(got, tc.res, cmpOptions...), "UpdateAuthMethod(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
func TestAuthenticate_Ldap(t *testing.T) {
t.Parallel()
testCtx := context.Background()
testConn, _ := db.TestSetup(t, "postgres")
testRw := db.New(testConn)
testRootWrapper := db.TestWrapper(t)
testKms := kms.TestKms(t, testConn, testRootWrapper)
o, _ := iam.TestScopes(t, iam.TestRepo(t, testConn, testRootWrapper))
iamRepoFn := func() (*iam.Repository, error) {
return iam.TestRepo(t, testConn, testRootWrapper), nil
}
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(testCtx, testRw, testRw, testKms)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(testCtx, testRw, testRw, testKms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(testRw, testRw, testKms)
}
atRepoFn := func() (*authtoken.Repository, error) {
return authtoken.NewRepository(testRw, testRw, testKms)
}
orgDbWrapper, err := testKms.GetWrapper(testCtx, o.GetPublicId(), kms.KeyPurposeDatabase)
require.NoError(t, err)
logger := hclog.New(&hclog.LoggerOptions{
Name: "test-logger",
Level: hclog.Error,
})
td := testdirectory.Start(t,
testdirectory.WithDefaults(t, &testdirectory.Defaults{AllowAnonymousBind: true}),
testdirectory.WithLogger(t, logger),
)
groups := []*gldap.Entry{
testdirectory.NewGroup(t, "admin", []string{"alice"}),
testdirectory.NewGroup(t, "users", []string{"alice"}),
}
users := testdirectory.NewUsers(t, []string{"alice"}, testdirectory.WithMembersOf(t, "admin", "users"))
users2 := testdirectory.NewUsers(t, []string{"bob"})
td.SetUsers(append(users, users2...)...)
td.SetGroups(groups...)
tdCerts, err := ldap.ParseCertificates(testCtx, td.Cert())
require.NoError(t, err)
testAm := ldap.TestAuthMethod(t, testConn, orgDbWrapper, o.PublicId,
[]string{fmt.Sprintf("ldaps://127.0.0.1:%d", td.Port())},
ldap.WithCertificates(testCtx, tdCerts...),
ldap.WithDiscoverDn(testCtx),
ldap.WithEnableGroups(testCtx),
ldap.WithUserDn(testCtx, testdirectory.DefaultUserDN),
ldap.WithGroupDn(testCtx, testdirectory.DefaultGroupDN),
)
iam.TestSetPrimaryAuthMethod(t, iam.TestRepo(t, testConn, testRootWrapper), o, testAm.PublicId)
testManagedGrp := ldap.TestManagedGroup(t, testConn, testAm, []string{"cn=admin,ou=groups,dc=example,dc=org"})
const (
testLoginName = "alice"
testPassword = "password"
testLoginName2 = "bob"
)
testAcct := ldap.TestAccount(t, testConn, testAm, testLoginName)
tests := []struct {
name string
acctId string
request *pbs.AuthenticateRequest
wantType string
wantGroups []string
wantErr error
wantErrContains string
}{
{
name: "basic-with-groups",
acctId: testAcct.PublicId,
request: &pbs.AuthenticateRequest{
AuthMethodId: testAm.GetPublicId(),
TokenType: "token",
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: testLoginName,
Password: testPassword,
},
},
},
wantGroups: []string{testManagedGrp.PublicId},
wantType: "token",
},
{
name: "basic-without-groups",
request: &pbs.AuthenticateRequest{
AuthMethodId: testAm.GetPublicId(),
TokenType: "token",
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: testLoginName2,
Password: testPassword,
},
},
},
wantType: "token",
},
{
name: "cookie-type",
acctId: testAcct.PublicId,
request: &pbs.AuthenticateRequest{
AuthMethodId: testAm.GetPublicId(),
TokenType: "cookie",
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: testLoginName,
Password: testPassword,
},
},
},
wantType: "cookie",
},
{
name: "no-token-type",
acctId: testAcct.PublicId,
request: &pbs.AuthenticateRequest{
AuthMethodId: testAm.GetPublicId(),
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: testLoginName,
Password: testPassword,
},
},
},
},
{
name: "bad-token-type",
request: &pbs.AuthenticateRequest{
AuthMethodId: testAm.GetPublicId(),
TokenType: "email",
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: testLoginName,
Password: testPassword,
},
},
},
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "no-authmethod",
request: &pbs.AuthenticateRequest{
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: testLoginName,
Password: testPassword,
},
},
},
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
},
{
name: "wrong-password",
request: &pbs.AuthenticateRequest{
AuthMethodId: testAm.GetPublicId(),
TokenType: "token",
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: testLoginName,
Password: "wrong",
},
},
},
wantErr: handlers.ApiErrorWithCode(codes.Unauthenticated),
},
{
name: "wrong-login-name",
request: &pbs.AuthenticateRequest{
AuthMethodId: testAm.GetPublicId(),
TokenType: "token",
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{
LdapLoginAttributes: &pbs.LdapLoginAttributes{
LoginName: "wrong",
Password: testPassword,
},
},
},
wantErr: handlers.ApiErrorWithCode(codes.Unauthenticated),
},
{
name: "no-attributes",
request: &pbs.AuthenticateRequest{
AuthMethodId: testAm.GetPublicId(),
TokenType: "token",
Attrs: &pbs.AuthenticateRequest_LdapLoginAttributes{},
},
wantErr: handlers.ApiErrorWithCode(codes.InvalidArgument),
wantErrContains: `Details: {{name: "attributes", desc: "This is a required field."}}`,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
s, err := authmethods.NewService(testKms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(err)
resp, err := s.Authenticate(auth.DisabledAuthTestContext(iamRepoFn, 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)
if tc.wantErrContains != "" {
assert.Contains(err.Error(), tc.wantErrContains)
}
return
}
require.NoError(err)
aToken := resp.GetAuthTokenResponse()
assert.NotEmpty(aToken.GetId())
assert.NotEmpty(aToken.GetToken())
assert.True(strings.HasPrefix(aToken.GetToken(), aToken.GetId()))
assert.Equal(testAm.GetPublicId(), aToken.GetAuthMethodId())
assert.Equal(aToken.GetCreatedTime(), aToken.GetUpdatedTime())
assert.Equal(aToken.GetCreatedTime(), aToken.GetApproximateLastUsedTime())
assert.Equal(testAm.GetPublicId(), aToken.GetAuthMethodId())
assert.Equal(tc.wantType, resp.GetType())
// support testing for pre-provisioned accounts
if tc.acctId != "" {
assert.Equal(tc.acctId, aToken.GetAccountId())
}
names := ldap.TestGetAcctManagedGroups(t, testConn, aToken.GetAccountId())
if len(tc.wantGroups) > 0 {
assert.Equal(tc.wantGroups, names)
}
})
}
}
@@ -19,6 +19,7 @@ import (
"github.com/hashicorp/boundary/globals"
authpb "github.com/hashicorp/boundary/internal/gen/controller/auth"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
@@ -58,6 +59,7 @@ type setup struct {
iamRepo *iam.Repository
iamRepoFn common.IamRepoFactory
oidcRepoFn common.OidcAuthRepoFactory
ldapRepoFn common.LdapAuthRepoFactory
pwRepoFn common.PasswordAuthRepoFactory
atRepoFn common.AuthTokenRepoFactory
org *iam.Scope
@@ -92,6 +94,9 @@ func getSetup(t *testing.T) setup {
ret.oidcRepoFn = func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, ret.rw, ret.rw, ret.kmsCache)
}
ret.ldapRepoFn = func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, ret.rw, ret.rw, ret.kmsCache)
}
ret.pwRepoFn = func() (*password.Repository, error) {
return password.NewRepository(ret.rw, ret.rw, ret.kmsCache)
}
@@ -103,7 +108,7 @@ func getSetup(t *testing.T) setup {
ret.databaseWrapper, err = ret.kmsCache.GetWrapper(ret.ctx, ret.org.PublicId, kms.KeyPurposeDatabase)
require.NoError(err)
ret.authMethodService, err = authmethods.NewService(ret.kmsCache, ret.pwRepoFn, ret.oidcRepoFn, ret.iamRepoFn, ret.atRepoFn)
ret.authMethodService, err = authmethods.NewService(ret.kmsCache, ret.pwRepoFn, ret.oidcRepoFn, ret.iamRepoFn, ret.atRepoFn, ret.ldapRepoFn)
require.NoError(err)
ret.testProvider = capoidc.StartTestProvider(t)
@@ -149,6 +154,9 @@ func TestList_FilterNonPublic(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
}
@@ -185,7 +193,7 @@ func TestList_FilterNonPublic(t *testing.T) {
oidc.WithIssuer(oidc.TestConvertToUrls(t, fmt.Sprintf("https://alice%d.com", i))[0]), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://api.com")[0]))
}
s, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
s, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(t, err, "Couldn't create new auth_method service.")
req := &pbs.ListAuthMethodsRequest{
@@ -251,6 +259,9 @@ func TestUpdate_OIDC(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kms)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
}
@@ -260,7 +271,7 @@ func TestUpdate_OIDC(t *testing.T) {
iamRepo := iam.TestRepo(t, conn, wrapper)
o, _ := iam.TestScopes(t, iamRepo)
tested, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
tested, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(t, err, "Error when getting new auth_method service.")
defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()}
@@ -1059,6 +1070,9 @@ func TestUpdate_OIDCDryRun(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
}
@@ -1118,7 +1132,7 @@ func TestUpdate_OIDCDryRun(t *testing.T) {
},
}
tested, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
tested, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(t, err, "Error when getting new auth_method service.")
cases := []struct {
name string
@@ -1235,6 +1249,9 @@ func TestChangeState_OIDC(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kmsCache)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kmsCache)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kmsCache)
}
@@ -1264,7 +1281,7 @@ func TestChangeState_OIDC(t *testing.T) {
mismatchedAM := oidc.TestAuthMethod(t, conn, databaseWrapper, o.PublicId, "inactive", "different_client_id", oidc.ClientSecret(tpClientSecret),
oidc.WithIssuer(oidc.TestConvertToUrls(t, tp.Addr())[0]), oidc.WithSigningAlgs(oidc.EdDSA), oidc.WithApiUrl(oidc.TestConvertToUrls(t, "https://example.callback:58")[0]), oidc.WithCertificates(tpCert...))
s, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
s, err := authmethods.NewService(kmsCache, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(t, err, "Error when getting new auth_method service.")
wantTemplate := &pb.AuthMethod{
@@ -10,6 +10,7 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
@@ -45,6 +46,9 @@ func TestUpdate_Password(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kms)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
}
@@ -54,7 +58,7 @@ func TestUpdate_Password(t *testing.T) {
iamRepo := iam.TestRepo(t, conn, wrapper)
o, _ := iam.TestScopes(t, iamRepo)
tested, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
tested, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(t, err, "Error when getting new auth_method service.")
defaultScopeInfo := &scopepb.ScopeInfo{Id: o.GetPublicId(), Type: o.GetType(), ParentScopeId: scope.Global.String()}
@@ -482,6 +486,9 @@ func TestAuthenticate_Password(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kms)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
}
@@ -617,7 +624,7 @@ func TestAuthenticate_Password(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(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
s, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(err)
resp, err := s.Authenticate(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), tc.request)
@@ -660,6 +667,9 @@ func TestAuthenticate_AuthAccountConnectedToIamUser_Password(t *testing.T) {
oidcRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kms)
}
ldapRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kms)
}
pwRepoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, kms)
}
@@ -683,7 +693,7 @@ func TestAuthenticate_AuthAccountConnectedToIamUser_Password(t *testing.T) {
iamUser, err := iamRepo.LookupUserWithLogin(context.Background(), acct.GetPublicId())
require.NoError(err)
s, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn)
s, err := authmethods.NewService(kms, pwRepoFn, oidcRepoFn, iamRepoFn, atRepoFn, ldapRepoFn)
require.NoError(err)
resp, err := s.Authenticate(auth.DisabledAuthTestContext(iamRepoFn, o.GetPublicId()), &pbs.AuthenticateRequest{
AuthMethodId: am.GetPublicId(),
@@ -5,10 +5,13 @@ package managed_groups
import (
"context"
"encoding/json"
"fmt"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth"
"github.com/hashicorp/boundary/internal/auth/ldap"
ldapstore "github.com/hashicorp/boundary/internal/auth/ldap/store"
"github.com/hashicorp/boundary/internal/auth/oidc"
oidcstore "github.com/hashicorp/boundary/internal/auth/oidc/store"
requestauth "github.com/hashicorp/boundary/internal/daemon/controller/auth"
@@ -29,13 +32,15 @@ import (
const (
// oidc field names
attrFilterField = "attributes.filter"
attrFilterField = "attributes.filter"
attrGroupNamesField = "attributes.group_names"
domain = "auth"
)
var (
oidcMaskManager handlers.MaskManager
ldapMaskManager handlers.MaskManager
// IdActions contains the set of actions that can be performed on
// individual resources
@@ -46,6 +51,12 @@ var (
action.Update,
action.Delete,
},
ldap.Subtype: {
action.NoOp,
action.Read,
action.Update,
action.Delete,
},
}
// CollectionActions contains the set of actions that can be performed on
@@ -61,6 +72,9 @@ func init() {
if oidcMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&oidcstore.ManagedGroup{}}, handlers.MaskSource{&pb.ManagedGroup{}, &pb.OidcManagedGroupAttributes{}}); err != nil {
panic(err)
}
if ldapMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&ldapstore.ManagedGroup{}}, handlers.MaskSource{&pb.ManagedGroup{}, &pb.LdapManagedGroupAttributes{}}); err != nil {
panic(err)
}
}
// Service handles request as described by the pbs.ManagedGroupServiceServer interface.
@@ -68,17 +82,21 @@ type Service struct {
pbs.UnsafeManagedGroupServiceServer
oidcRepoFn common.OidcAuthRepoFactory
ldapRepoFn common.LdapAuthRepoFactory
}
var _ pbs.ManagedGroupServiceServer = (*Service)(nil)
// NewService returns a managed group service which handles managed group related requests to boundary.
func NewService(oidcRepo common.OidcAuthRepoFactory) (Service, error) {
func NewService(ctx context.Context, oidcRepo common.OidcAuthRepoFactory, ldapRepo common.LdapAuthRepoFactory) (Service, error) {
const op = "managed_groups.NewService"
if oidcRepo == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing oidc repository provided")
switch {
case oidcRepo == nil:
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing oidc repository provided")
case ldapRepo == nil:
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing ldap repository provided")
}
return Service{oidcRepoFn: oidcRepo}, nil
return Service{oidcRepoFn: oidcRepo, ldapRepoFn: ldapRepo}, nil
}
// ListManagedGroups implements the interface pbs.ManagedGroupsServiceServer.
@@ -307,6 +325,29 @@ func (s Service) getFromRepo(ctx context.Context, id string) (auth.ManagedGroup,
}
}
out = mg
case ldap.Subtype:
repo, err := s.ldapRepoFn()
if err != nil {
return nil, nil, err
}
mg, err := repo.LookupManagedGroup(ctx, id)
if err != nil {
if errors.IsNotFoundError(err) {
return nil, nil, handlers.NotFoundErrorf("LDAP ManagedGroup %q doesn't exist.", id)
}
return nil, nil, err
}
ids, err := repo.ListManagedGroupMembershipsByGroup(ctx, mg.GetPublicId())
if err != nil {
return nil, nil, err
}
if len(ids) > 0 {
memberIds = make([]string, len(ids))
for i, v := range ids {
memberIds[i] = v.MemberId
}
}
out = mg
default:
return nil, nil, handlers.NotFoundErrorf("Unrecognized id.")
}
@@ -328,7 +369,7 @@ func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item
attrs := item.GetOidcManagedGroupAttributes()
mg, err := oidc.NewManagedGroup(ctx, am.GetPublicId(), attrs.GetFilter(), opts...)
if err != nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build user for creation: %v.", err)
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build managed group for creation: %v.", err)
}
repo, err := s.oidcRepoFn()
if err != nil {
@@ -345,6 +386,38 @@ func (s Service) createOidcInRepo(ctx context.Context, am auth.AuthMethod, item
return out, nil
}
func (s Service) createLdapInRepo(ctx context.Context, am auth.AuthMethod, item *pb.ManagedGroup) (*ldap.ManagedGroup, error) {
const op = "managed_groups.(Service).createLdapInRepo"
if item == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing item")
}
var opts []ldap.Option
if item.GetName() != nil {
opts = append(opts, ldap.WithName(ctx, item.GetName().GetValue()))
}
if item.GetDescription() != nil {
opts = append(opts, ldap.WithDescription(ctx, item.GetDescription().GetValue()))
}
attrs := item.GetLdapManagedGroupAttributes()
mg, err := ldap.NewManagedGroup(ctx, am.GetPublicId(), attrs.GetGroupNames(), opts...)
if err != nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build managed group for creation: %v.", err)
}
repo, err := s.ldapRepoFn()
if err != nil {
return nil, err
}
out, err := repo.CreateManagedGroup(ctx, am.GetScopeId(), mg)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create managed group"))
}
if out == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create managed group but no error returned from repository.")
}
return out, nil
}
func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb.ManagedGroup) (auth.ManagedGroup, error) {
const op = "managed_groups.(Service).createInRepo"
if item == nil {
@@ -361,6 +434,15 @@ func (s Service) createInRepo(ctx context.Context, am auth.AuthMethod, item *pb.
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create managed group but no error returned from repository.")
}
out = am
case ldap.Subtype:
am, err := s.createLdapInRepo(ctx, am, item)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if am == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create ldap managed group but no error returned from repository.")
}
out = am
}
return out, nil
}
@@ -401,6 +483,46 @@ func (s Service) updateOidcInRepo(ctx context.Context, scopeId, amId, id string,
return out, nil
}
func (s Service) updateLdapInRepo(ctx context.Context, scopeId, amId, id string, mask []string, item *pb.ManagedGroup) (*ldap.ManagedGroup, error) {
const op = "managed_groups.(Service).updateLdapInRepo"
if item == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "nil managed group.")
}
mg := ldap.AllocManagedGroup()
mg.PublicId = id
if item.GetName() != nil {
mg.Name = item.GetName().GetValue()
}
if item.GetDescription() != nil {
mg.Description = item.GetDescription().GetValue()
}
// Set this regardless; it'll only take effect if the masks contain the value
encodedGroupNames, err := json.Marshal(item.GetLdapManagedGroupAttributes().GetGroupNames())
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to encode group names"))
}
mg.GroupNames = string(encodedGroupNames)
version := item.GetVersion()
dbMask := ldapMaskManager.Translate(mask)
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.ldapRepoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
out, rowsUpdated, err := repo.UpdateManagedGroup(ctx, scopeId, mg, version, dbMask)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to update managed group"))
}
if rowsUpdated == 0 {
return nil, handlers.NotFoundErrorf("Managed Group %q doesn't exist or incorrect version provided.", id)
}
return out, nil
}
func (s Service) updateInRepo(ctx context.Context, scopeId, authMethodId string, req *pbs.UpdateManagedGroupRequest) (auth.ManagedGroup, error) {
const op = "managed_groups.(Service).updateInRepo"
var out auth.ManagedGroup
@@ -414,6 +536,15 @@ func (s Service) updateInRepo(ctx context.Context, scopeId, authMethodId string,
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update managed group but no error returned from repository.")
}
out = mg
case ldap.Subtype:
mg, err := s.updateLdapInRepo(ctx, scopeId, authMethodId, req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if mg == nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to update managed group but no error returned from repository.")
}
out = mg
}
return out, nil
}
@@ -429,6 +560,12 @@ func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool,
return false, iErr
}
rows, err = repo.DeleteManagedGroup(ctx, scopeId, id)
case ldap.Subtype:
repo, iErr := s.ldapRepoFn()
if iErr != nil {
return false, iErr
}
rows, err = repo.DeleteManagedGroup(ctx, scopeId, id)
}
if err != nil {
if errors.IsNotFoundError(err) {
@@ -456,6 +593,18 @@ func (s Service) listFromRepo(ctx context.Context, authMethodId string) ([]auth.
for _, a := range oidcl {
outUl = append(outUl, a)
}
case ldap.Subtype:
ldapRepo, err := s.ldapRepoFn()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
oidcl, err := ldapRepo.ListManagedGroups(ctx, authMethodId)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
for _, a := range oidcl {
outUl = append(outUl, a)
}
}
return outUl, nil
}
@@ -468,6 +617,11 @@ func (s Service) parentAndAuthResult(ctx context.Context, id string, a action.Ty
res.Error = err
return nil, res
}
ldapRepo, err := s.ldapRepoFn()
if err != nil {
res.Error = err
return nil, res
}
var parentId string
opts := []requestauth.Option{requestauth.WithType(resource.ManagedGroup), requestauth.WithAction(a)}
@@ -477,16 +631,27 @@ func (s Service) parentAndAuthResult(ctx context.Context, id string, a action.Ty
default:
switch subtypes.SubtypeFromId(domain, id) {
case oidc.Subtype:
acct, err := oidcRepo.LookupManagedGroup(ctx, id)
grp, err := oidcRepo.LookupManagedGroup(ctx, id)
if err != nil {
res.Error = err
return nil, res
}
if acct == nil {
if grp == nil {
res.Error = handlers.NotFoundError()
return nil, res
}
parentId = acct.GetAuthMethodId()
parentId = grp.GetAuthMethodId()
case ldap.Subtype:
grp, err := ldapRepo.LookupManagedGroup(ctx, id)
if err != nil {
res.Error = err
return nil, res
}
if grp == nil {
res.Error = handlers.NotFoundError()
return nil, res
}
parentId = grp.GetAuthMethodId()
default:
res.Error = errors.New(ctx, errors.InvalidPublicId, op, "unrecognized managed group subtype")
return nil, res
@@ -508,6 +673,18 @@ func (s Service) parentAndAuthResult(ctx context.Context, id string, a action.Ty
}
authMeth = am
opts = append(opts, requestauth.WithScopeId(am.GetScopeId()))
case ldap.Subtype:
am, err := ldapRepo.LookupAuthMethod(ctx, parentId)
if err != nil {
res.Error = err
return nil, res
}
if am == nil {
res.Error = handlers.NotFoundError()
return nil, res
}
authMeth = am
opts = append(opts, requestauth.WithScopeId(am.GetScopeId()))
default:
res.Error = errors.New(ctx, errors.InvalidPublicId, op, "unrecognized auth method subtype")
return nil, res
@@ -568,6 +745,25 @@ func toProto(ctx context.Context, in auth.ManagedGroup, opt ...handlers.Option)
out.Attrs = &pb.ManagedGroup_OidcManagedGroupAttributes{
OidcManagedGroupAttributes: attrs,
}
case *ldap.ManagedGroup:
if outputFields.Has(globals.TypeField) {
out.Type = ldap.Subtype.String()
}
if !outputFields.Has(globals.AttributesField) {
break
}
var grpNames []string
if err := json.Unmarshal([]byte(i.GetGroupNames()), &grpNames); err != nil {
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "unable to unmarshal group names")
}
attrs := &pb.LdapManagedGroupAttributes{
GroupNames: grpNames,
}
out.Attrs = &pb.ManagedGroup_LdapManagedGroupAttributes{
LdapManagedGroupAttributes: attrs,
}
}
return &out, nil
}
@@ -582,7 +778,7 @@ func validateGetRequest(req *pbs.GetManagedGroupRequest) error {
if req == nil {
return errors.NewDeprecated(errors.InvalidParameter, op, "nil request")
}
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, globals.OidcManagedGroupPrefix)
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, globals.OidcManagedGroupPrefix, globals.LdapManagedGroupPrefix)
}
func validateCreateRequest(req *pbs.CreateManagedGroupRequest) error {
@@ -612,6 +808,18 @@ func validateCreateRequest(req *pbs.CreateManagedGroupRequest) error {
}
}
}
case ldap.Subtype:
if req.GetItem().GetType() != "" && req.GetItem().GetType() != ldap.Subtype.String() {
badFields[globals.TypeField] = "Doesn't match the parent resource's type."
}
attrs := req.GetItem().GetLdapManagedGroupAttributes()
if attrs == nil {
badFields[globals.AttributesField] = "Attribute fields is required."
} else {
if len(attrs.GroupNames) == 0 {
badFields[attrGroupNamesField] = "This field is required."
}
}
default:
badFields[globals.AuthMethodIdField] = "Unknown auth method type from ID."
}
@@ -646,11 +854,21 @@ func validateUpdateRequest(req *pbs.UpdateManagedGroupRequest) error {
}
}
}
case ldap.Subtype:
if req.GetItem().GetType() != "" && req.GetItem().GetType() != ldap.Subtype.String() {
badFields[globals.TypeField] = "Cannot modify the resource type."
}
attrs := req.GetItem().GetLdapManagedGroupAttributes()
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), attrGroupNamesField) {
if len(attrs.GroupNames) == 0 {
badFields[attrFilterField] = "Field cannot be empty."
}
}
default:
badFields[globals.IdField] = "Unrecognized resource type."
}
return badFields
}, globals.OidcManagedGroupPrefix)
}, globals.OidcManagedGroupPrefix, globals.LdapManagedGroupPrefix)
}
func validateDeleteRequest(req *pbs.DeleteManagedGroupRequest) error {
@@ -658,7 +876,7 @@ func validateDeleteRequest(req *pbs.DeleteManagedGroupRequest) error {
if req == nil {
return errors.NewDeprecated(errors.InvalidParameter, op, "nil request")
}
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, globals.OidcManagedGroupPrefix)
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, globals.OidcManagedGroupPrefix, globals.LdapManagedGroupPrefix)
}
func validateListRequest(req *pbs.ListManagedGroupsRequest) error {
@@ -667,7 +885,7 @@ func validateListRequest(req *pbs.ListManagedGroupsRequest) error {
return errors.NewDeprecated(errors.InvalidParameter, op, "nil request")
}
badFields := map[string]string{}
if !handlers.ValidId(handlers.Id(req.GetAuthMethodId()), globals.OidcAuthMethodPrefix) {
if !handlers.ValidId(handlers.Id(req.GetAuthMethodId()), globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix) {
badFields[globals.AuthMethodIdField] = "Invalid formatted identifier."
}
if _, err := handlers.NewFilter(req.GetFilter()); err != nil {
File diff suppressed because it is too large. Load diff
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
@@ -78,6 +79,48 @@ func TestValidateCreateRequest(t *testing.T) {
},
},
},
{
name: "mismatched ldap authmethod pw type",
item: &pb.ManagedGroup{
Type: "oidc",
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
},
errContains: fieldError(globals.TypeField, "Doesn't match the parent resource's type."),
},
{
name: "missing ldap attributes",
item: &pb.ManagedGroup{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: nil,
},
errContains: fieldError(globals.AttributesField, "Attribute fields is required."),
},
{
name: "bad ldap attributes",
item: &pb.ManagedGroup{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: &pb.ManagedGroup_LdapManagedGroupAttributes{
LdapManagedGroupAttributes: &pb.LdapManagedGroupAttributes{
GroupNames: []string{},
},
},
},
errContains: "name: \"attributes.group_names\", desc: \"This field is required.",
},
{
name: "no ldap errors",
item: &pb.ManagedGroup{
Type: ldap.Subtype.String(),
AuthMethodId: globals.LdapAuthMethodPrefix + "_1234567890",
Attrs: &pb.ManagedGroup_LdapManagedGroupAttributes{
LdapManagedGroupAttributes: &pb.LdapManagedGroupAttributes{
GroupNames: []string{"admin"},
},
},
},
},
}
for _, tc := range cases {
tc := tc // capture range variable
@@ -113,7 +156,7 @@ func TestValidateUpdateRequest(t *testing.T) {
errContains: fieldError(globals.TypeField, "Cannot modify the resource type."),
},
{
name: "no error",
name: "oidc no error",
req: &pbs.UpdateManagedGroupRequest{
Id: globals.OidcManagedGroupPrefix + "_1234567890",
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{}},
@@ -127,6 +170,31 @@ func TestValidateUpdateRequest(t *testing.T) {
},
},
},
{
name: "ldap to password change type",
req: &pbs.UpdateManagedGroupRequest{
Id: globals.LdapManagedGroupPrefix + "_1234567890",
Item: &pb.ManagedGroup{
Type: password.Subtype.String(),
},
},
errContains: fieldError(globals.TypeField, "Cannot modify the resource type."),
},
{
name: "ldap no error",
req: &pbs.UpdateManagedGroupRequest{
Id: globals.LdapManagedGroupPrefix + "_1234567890",
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{}},
Item: &pb.ManagedGroup{
Version: 1,
Attrs: &pb.ManagedGroup_LdapManagedGroupAttributes{
LdapManagedGroupAttributes: &pb.LdapManagedGroupAttributes{
GroupNames: []string{"admin"},
},
},
},
},
},
}
for _, tc := range cases {
tc := tc // capture range variable
@@ -572,7 +572,7 @@ func (s Service) updateInRepo(ctx context.Context, parentScope *pb.ScopeInfo, sc
opts = append(opts, iam.WithName(scopeName))
}
if primaryAuthMethodId := item.GetPrimaryAuthMethodId(); primaryAuthMethodId != nil {
if !handlers.ValidId(handlers.Id(primaryAuthMethodId.GetValue()), globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix) {
if !handlers.ValidId(handlers.Id(primaryAuthMethodId.GetValue()), globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix) {
return nil, handlers.InvalidArgumentErrorf("Error in provided request.", map[string]string{"primary_auth_method_id": "Improperly formatted identifier"})
}
scopePrimaryAuthMethodId = primaryAuthMethodId.GetValue()
@@ -929,7 +929,7 @@ func validateUpdateRequest(req *pbs.UpdateScopeRequest) error {
if item.GetUpdatedTime() != nil {
badFields["updated_time"] = "This is a read only field and cannot be specified in an update request."
}
if item.GetPrimaryAuthMethodId().GetValue() != "" && !handlers.ValidId(handlers.Id(item.GetPrimaryAuthMethodId().GetValue()), globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix) {
if item.GetPrimaryAuthMethodId().GetValue() != "" && !handlers.ValidId(handlers.Id(item.GetPrimaryAuthMethodId().GetValue()), globals.PasswordAuthMethodPrefix, globals.OidcAuthMethodPrefix, globals.LdapAuthMethodPrefix) {
badFields["primary_auth_method_id"] = "Improperly formatted identifier."
}
if len(badFields) > 0 {
@@ -18,6 +18,7 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/auth/ldap"
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
"github.com/hashicorp/boundary/internal/authtoken"
@@ -2438,6 +2439,9 @@ func TestAuthorizeSession(t *testing.T) {
oidcAuthRepoFn := func() (*oidc.Repository, error) {
return oidc.NewRepository(ctx, rw, rw, kms)
}
ldapAuthRepoFn := func() (*ldap.Repository, error) {
return ldap.NewRepository(ctx, rw, rw, kms)
}
plg := host.TestPlugin(t, conn, "test")
plgm := map[string]plgpb.HostPluginServiceClient{
@@ -2485,6 +2489,7 @@ func TestAuthorizeSession(t *testing.T) {
serversRepoFn,
passwordAuthRepoFn,
oidcAuthRepoFn,
ldapAuthRepoFn,
kms,
&authpb.RequestInfo{
Token: at.GetToken(),
+2 -1
View File
@@ -53,6 +53,7 @@ func requestCtxInterceptor(
serversRepoFn common.ServersRepoFactory,
passwordAuthRepoFn common.PasswordAuthRepoFactory,
oidcAuthRepoFn common.OidcAuthRepoFactory,
ldapAuthRepoFn common.LdapAuthRepoFactory,
kms *kms.Kms,
ticket string,
eventer *event.Eventer,
@@ -110,7 +111,7 @@ func requestCtxInterceptor(
return nil, errors.New(interceptorCtx, errors.Internal, op, "Invalid context (bad ticket)")
}
interceptorCtx = auth.NewVerifierContextWithAccounts(interceptorCtx, iamRepoFn, authTokenRepoFn, serversRepoFn, passwordAuthRepoFn, oidcAuthRepoFn, kms, &requestInfo)
interceptorCtx = auth.NewVerifierContextWithAccounts(interceptorCtx, iamRepoFn, authTokenRepoFn, serversRepoFn, passwordAuthRepoFn, oidcAuthRepoFn, ldapAuthRepoFn, kms, &requestInfo)
// Add general request information to the context. The information from
// the auth verifier context is pretty specifically curated to
@@ -314,7 +314,7 @@ func Test_requestCtxInterceptor(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
interceptor, err := requestCtxInterceptor(factoryCtx, tt.iamRepoFn, tt.authTokenRepoFn, tt.serversRepoFn, nil, nil, tt.kms, tt.ticket, tt.eventer)
interceptor, err := requestCtxInterceptor(factoryCtx, tt.iamRepoFn, tt.authTokenRepoFn, tt.serversRepoFn, nil, nil, nil, tt.kms, tt.ticket, tt.eventer)
if tt.wantFactoryErr {
require.Error(err)
assert.Nil(interceptor)
+1 -1
View File
@@ -46,7 +46,7 @@ func closeListener(_ context.Context, l net.Listener, _ any) error {
func (c *Controller) startListeners() error {
servers := make([]func(), 0, len(c.conf.Listeners))
grpcServer, gwTicket, err := newGrpcServer(c.baseContext, c.IamRepoFn, c.AuthTokenRepoFn, c.ServersRepoFn, c.PasswordAuthRepoFn, c.OidcRepoFn, c.kms, c.conf.Eventer)
grpcServer, gwTicket, err := newGrpcServer(c.baseContext, c.IamRepoFn, c.AuthTokenRepoFn, c.ServersRepoFn, c.PasswordAuthRepoFn, c.OidcRepoFn, c.LdapRepoFn, c.kms, c.conf.Eventer)
if err != nil {
return fmt.Errorf("failed to create new grpc server: %w", err)
}