Compare commits

...
5 changed files with 238 additions and 41 deletions

No files matched your search

@@ -0,0 +1,14 @@
Bugfix: Cache LDAP instance mapper lookups
In multi-instance deployments, resolving a user's instance name/ID during
`GET /graph/v1.0/users` (and group member expansion) issued a fresh, uncached
LDAP search per instance/guest attribute value on every request. Under load
this multiplied into large numbers of redundant LDAP round-trips per page of
users, saturating the LDAP connection pool and causing request timeouts. The
LDAP identity backend now caches instance mapper lookups, including negative
(not-found) results, for a configurable TTL
(`OCIS_LDAP_INSTANCE_MAPPER_CACHE_TTL`, default 60s, set to 0 to disable) up to a
bounded number of entries (`OCIS_LDAP_INSTANCE_MAPPER_CACHE_CAPACITY`, default
10000).
https://github.com/owncloud/ocis/pull/12823
+20 -18
View File
@@ -56,14 +56,14 @@ type Spaces struct {
}
type LDAP struct {
URI string `yaml:"uri" env:"OCIS_LDAP_URI;GRAPH_LDAP_URI" desc:"URI of the LDAP Server to connect to. Supported URI schemes are 'ldaps://' and 'ldap://'" introductionVersion:"pre5.0"`
CACert string `yaml:"cacert" env:"OCIS_LDAP_CACERT;GRAPH_LDAP_CACERT" desc:"Path/File name for the root CA certificate (in PEM format) used to validate TLS server certificates of the LDAP service. If not defined, the root directory derives from $OCIS_BASE_DATA_PATH/idm." introductionVersion:"pre5.0"`
Insecure bool `yaml:"insecure" env:"OCIS_LDAP_INSECURE;GRAPH_LDAP_INSECURE" desc:"Disable TLS certificate validation for the LDAP connections. Do not set this in production environments." introductionVersion:"pre5.0"`
BindDN string `yaml:"bind_dn" env:"OCIS_LDAP_BIND_DN;GRAPH_LDAP_BIND_DN" desc:"LDAP DN to use for simple bind authentication with the target LDAP server." introductionVersion:"pre5.0"`
BindPassword string `yaml:"bind_password" env:"OCIS_LDAP_BIND_PASSWORD;GRAPH_LDAP_BIND_PASSWORD" desc:"Password to use for authenticating the 'bind_dn'." introductionVersion:"pre5.0"`
UseServerUUID bool `yaml:"use_server_uuid" env:"GRAPH_LDAP_SERVER_UUID" desc:"If set to true, rely on the LDAP Server to generate a unique ID for users and groups, like when using 'entryUUID' as the user ID attribute." introductionVersion:"pre5.0"`
UsePasswordModExOp bool `yaml:"use_password_modify_exop" env:"GRAPH_LDAP_SERVER_USE_PASSWORD_MODIFY_EXOP" desc:"Use the 'Password Modify Extended Operation' for updating user passwords." introductionVersion:"pre5.0"`
WriteEnabled bool `yaml:"write_enabled" env:"OCIS_LDAP_SERVER_WRITE_ENABLED;GRAPH_LDAP_SERVER_WRITE_ENABLED" desc:"Allow creating, modifying and deleting LDAP users via the GRAPH API. This can only be set to 'true' when keeping default settings for the LDAP user and group attribute types (the 'OCIS_LDAP_USER_SCHEMA_* and 'OCIS_LDAP_GROUP_SCHEMA_* variables)." introductionVersion:"pre5.0"`
URI string `yaml:"uri" env:"OCIS_LDAP_URI;GRAPH_LDAP_URI" desc:"URI of the LDAP Server to connect to. Supported URI schemes are 'ldaps://' and 'ldap://'" introductionVersion:"pre5.0"`
CACert string `yaml:"cacert" env:"OCIS_LDAP_CACERT;GRAPH_LDAP_CACERT" desc:"Path/File name for the root CA certificate (in PEM format) used to validate TLS server certificates of the LDAP service. If not defined, the root directory derives from $OCIS_BASE_DATA_PATH/idm." introductionVersion:"pre5.0"`
Insecure bool `yaml:"insecure" env:"OCIS_LDAP_INSECURE;GRAPH_LDAP_INSECURE" desc:"Disable TLS certificate validation for the LDAP connections. Do not set this in production environments." introductionVersion:"pre5.0"`
BindDN string `yaml:"bind_dn" env:"OCIS_LDAP_BIND_DN;GRAPH_LDAP_BIND_DN" desc:"LDAP DN to use for simple bind authentication with the target LDAP server." introductionVersion:"pre5.0"`
BindPassword string `yaml:"bind_password" env:"OCIS_LDAP_BIND_PASSWORD;GRAPH_LDAP_BIND_PASSWORD" desc:"Password to use for authenticating the 'bind_dn'." introductionVersion:"pre5.0"`
UseServerUUID bool `yaml:"use_server_uuid" env:"GRAPH_LDAP_SERVER_UUID" desc:"If set to true, rely on the LDAP Server to generate a unique ID for users and groups, like when using 'entryUUID' as the user ID attribute." introductionVersion:"pre5.0"`
UsePasswordModExOp bool `yaml:"use_password_modify_exop" env:"GRAPH_LDAP_SERVER_USE_PASSWORD_MODIFY_EXOP" desc:"Use the 'Password Modify Extended Operation' for updating user passwords." introductionVersion:"pre5.0"`
WriteEnabled bool `yaml:"write_enabled" env:"OCIS_LDAP_SERVER_WRITE_ENABLED;GRAPH_LDAP_SERVER_WRITE_ENABLED" desc:"Allow creating, modifying and deleting LDAP users via the GRAPH API. This can only be set to 'true' when keeping default settings for the LDAP user and group attribute types (the 'OCIS_LDAP_USER_SCHEMA_* and 'OCIS_LDAP_GROUP_SCHEMA_* variables)." introductionVersion:"pre5.0"`
UpdateUserLastSignInDate bool `yaml:"update_user_last_sign_in_date" env:"OCIS_LDAP_UPDATE_LAST_SIGNIN_DATE;GRAPH_LDAP_UPDATE_LAST_SIGNIN_DATE" desc:"Update the 'oCLastSignInTimestamp' LDAP attribute of a user when the user signs in. The attribute is only persisted when 'OCIS_LDAP_SERVER_WRITE_ENABLED' is also enabled. Set this to 'false' to avoid an LDAP write on every sign-in, e.g. when the last sign-in timestamp is not needed or the LDAP write load should be reduced." introductionVersion:"8.2.0"`
RetryMaxCount int `yaml:"retry_max_count" env:"OCIS_LDAP_RETRY_MAX_COUNT;GRAPH_LDAP_RETRY_MAX_COUNT" desc:"Maximum number of retries for failed LDAP operations. Reads retry on transient and network errors; writes retry only when the connection failed before the request was sent (e.g. a reused idle connection found closed), so the request provably never reached the server and cannot be double-applied. Default 1." introductionVersion:"8.2.0"`
RetryBaseDelay time.Duration `yaml:"retry_base_delay" env:"OCIS_LDAP_RETRY_BASE_DELAY;GRAPH_LDAP_RETRY_BASE_DELAY" desc:"Base delay for exponential backoff between LDAP retries (e.g. '100ms'). Set to 0 to disable backoff." introductionVersion:"8.2.0"`
@@ -105,16 +105,18 @@ type LDAP struct {
RequireExternalID bool `yaml:"require_external_id" env:"GRAPH_LDAP_REQUIRE_EXTERNAL_ID" desc:"If enabled, the 'OCIS_LDAP_USER_SCHEMA_EXTERNAL_ID' is used as primary identifier for the provisioning API." introductionVersion:"8.0.0"`
// Multi-Instance Only
UserMemberAttribute string `yaml:"user_member_attribute" env:"OCIS_LDAP_USER_MEMBER_ATTRIBUTE" desc:"LDAP Attribute to signal the user is member of an instance. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
UserGuestAttribute string `yaml:"user_guest_attribute" env:"OCIS_LDAP_USER_GUEST_ATTRIBUTE" desc:"LDAP Attribute to signal the user is guest of an instance. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
GroupAffiliationAttribute string `yaml:"group_affiliation_attribute" env:"OCIS_LDAP_GROUP_AFFILIATION_ATTRIBUTE" desc:"LDAP Attribute to signal which instance the group is belonging to. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
PreciseSearchAttribute string `yaml:"precise_search_attribute" env:"OCIS_LDAP_PRECISE_SEARCH_ATTRIBUTE" desc:"LDAP Attribute to be used for searching users on other instances. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperEnabled bool `yaml:"instance_mapper_enabled" env:"OCIS_LDAP_INSTANCE_MAPPER_ENABLED" desc:"The InstanceMapper allows mapping instance names (user readable) to instance IDs (machine readable) based on an LDAP query. See other _INSTANCE_MAPPER_ env vars. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperBaseDN string `yaml:"instance_mapper_base_dn" env:"OCIS_LDAP_INSTANCE_MAPPER_BASE_DN" desc:"BaseDN of the 'instancename to instanceid' mapper in LDAP. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperNameAttribute string `yaml:"instance_mapper_name_attribute" env:"OCIS_LDAP_INSTANCE_MAPPER_NAME_ATTRIBUTE" desc:"LDAP Attribute of the instance name. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperIDAttribute string `yaml:"instance_mapper_id_attribute" env:"OCIS_LDAP_INSTANCE_MAPPER_ID_ATTRIBUTE" desc:"LDAP Attribute of the instance ID. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
CrossInstanceReferenceTemplate string `yaml:"cross_instance_reference_template" env:"OCIS_LDAP_CROSS_INSTANCE_REFERENCE_TEMPLATE" desc:"Template for the users unique reference across oCIS instances. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceURLTemplate string `yaml:"instance_url_template" env:"OCIS_LDAP_INSTANCE_URL_TEMPLATE" desc:"Template for the instance URL. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
UserMemberAttribute string `yaml:"user_member_attribute" env:"OCIS_LDAP_USER_MEMBER_ATTRIBUTE" desc:"LDAP Attribute to signal the user is member of an instance. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
UserGuestAttribute string `yaml:"user_guest_attribute" env:"OCIS_LDAP_USER_GUEST_ATTRIBUTE" desc:"LDAP Attribute to signal the user is guest of an instance. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
GroupAffiliationAttribute string `yaml:"group_affiliation_attribute" env:"OCIS_LDAP_GROUP_AFFILIATION_ATTRIBUTE" desc:"LDAP Attribute to signal which instance the group is belonging to. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
PreciseSearchAttribute string `yaml:"precise_search_attribute" env:"OCIS_LDAP_PRECISE_SEARCH_ATTRIBUTE" desc:"LDAP Attribute to be used for searching users on other instances. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperEnabled bool `yaml:"instance_mapper_enabled" env:"OCIS_LDAP_INSTANCE_MAPPER_ENABLED" desc:"The InstanceMapper allows mapping instance names (user readable) to instance IDs (machine readable) based on an LDAP query. See other _INSTANCE_MAPPER_ env vars. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperBaseDN string `yaml:"instance_mapper_base_dn" env:"OCIS_LDAP_INSTANCE_MAPPER_BASE_DN" desc:"BaseDN of the 'instancename to instanceid' mapper in LDAP. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperNameAttribute string `yaml:"instance_mapper_name_attribute" env:"OCIS_LDAP_INSTANCE_MAPPER_NAME_ATTRIBUTE" desc:"LDAP Attribute of the instance name. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperIDAttribute string `yaml:"instance_mapper_id_attribute" env:"OCIS_LDAP_INSTANCE_MAPPER_ID_ATTRIBUTE" desc:"LDAP Attribute of the instance ID. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
CrossInstanceReferenceTemplate string `yaml:"cross_instance_reference_template" env:"OCIS_LDAP_CROSS_INSTANCE_REFERENCE_TEMPLATE" desc:"Template for the users unique reference across oCIS instances. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceURLTemplate string `yaml:"instance_url_template" env:"OCIS_LDAP_INSTANCE_URL_TEMPLATE" desc:"Template for the instance URL. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperCacheTTL time.Duration `yaml:"instance_mapper_cache_ttl" env:"OCIS_LDAP_INSTANCE_MAPPER_CACHE_TTL" desc:"TTL for the LDAP instance mapper cache (e.g. '60s'). Set to 0 to disable caching of instance mapper lookups. Requires OCIS_MULTI_INSTANCE_ENABLED. See the Environment Variable Types description for more details." introductionVersion:"8.2.0"`
InstanceMapperCacheCapacity int `yaml:"instance_mapper_cache_capacity" env:"OCIS_LDAP_INSTANCE_MAPPER_CACHE_CAPACITY" desc:"Maximum number of entries in the LDAP instance mapper cache (default 10000). The least recently used entry is evicted when the limit is reached. Part of a cache key is the requested instance name, which a client controls, so this bounds the memory a client can make the cache consume. Set to 0 for an unlimited number of entries, which is not recommended for that reason. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.2.0"`
}
// LDAPEducationConfig represents the LDAP configuration for education related resources
@@ -104,20 +104,22 @@ func DefaultConfig() *config.Config {
UserNameAttribute: "uid",
// FIXME: switch this to some more widely available attribute by default
// ideally this needs to be constant for the lifetime of a users
UserIDAttribute: "owncloudUUID",
UserTypeAttribute: "ownCloudUserType",
UserEnabledAttribute: "ownCloudUserEnabled",
ExternalIDAttribute: "owncloudExternalID",
DisableUserMechanism: "attribute",
LdapDisabledUsersGroupDN: "cn=DisabledUsersGroup,ou=groups,o=libregraph-idm",
GroupBaseDN: "ou=groups,o=libregraph-idm",
GroupSearchScope: "sub",
GroupFilter: "",
GroupObjectClass: "groupOfNames",
GroupNameAttribute: "cn",
GroupMemberAttribute: "member",
GroupIDAttribute: "owncloudUUID",
EducationResourcesEnabled: false,
UserIDAttribute: "owncloudUUID",
UserTypeAttribute: "ownCloudUserType",
UserEnabledAttribute: "ownCloudUserEnabled",
ExternalIDAttribute: "owncloudExternalID",
DisableUserMechanism: "attribute",
LdapDisabledUsersGroupDN: "cn=DisabledUsersGroup,ou=groups,o=libregraph-idm",
GroupBaseDN: "ou=groups,o=libregraph-idm",
GroupSearchScope: "sub",
GroupFilter: "",
GroupObjectClass: "groupOfNames",
GroupNameAttribute: "cn",
GroupMemberAttribute: "member",
GroupIDAttribute: "owncloudUUID",
EducationResourcesEnabled: false,
InstanceMapperCacheTTL: 60 * time.Second,
InstanceMapperCacheCapacity: 10000,
},
},
Cache: &config.Cache{
+69 -9
View File
@@ -15,6 +15,7 @@ import (
backoff "github.com/cenkalti/backoff/v5"
"github.com/go-ldap/ldap/v3"
"github.com/google/uuid"
"github.com/jellydator/ttlcache/v3"
"github.com/libregraph/idm/pkg/ldapdn"
libregraph "github.com/owncloud/libre-graph-api-go"
@@ -69,14 +70,14 @@ type LDAP struct {
disableUserMechanism DisableUserMechanismType
localUserDisableGroupDN string
groupBaseDN string
groupCreateBaseDN string
groupFilter string
groupObjectClass string
groupAdditionalObjectClasses []string
groupIDisOctetString bool
groupScope int
groupAttributeMap groupAttributeMap
groupBaseDN string
groupCreateBaseDN string
groupFilter string
groupObjectClass string
groupAdditionalObjectClasses []string
groupIDisOctetString bool
groupScope int
groupAttributeMap groupAttributeMap
educationConfig educationConfig
@@ -94,8 +95,19 @@ type LDAP struct {
instanceMapperIDAttribute string
crossInstanceReferenceTemplate *template.Template
instanceURLTemplate *template.Template
instanceCache *ttlcache.Cache[string, string]
}
// instanceCacheKeySep separates the fields of an instanceCache key. A NUL byte can't
// appear in an LDAP attribute name or search value, so it can't cause key collisions
// between different (searchAttribute, resultAttribute, searchValue) triples.
const instanceCacheKeySep = "\x00"
// instanceCacheNotFound is stored in instanceCache to negatively cache a lookup
// that resolved to ErrNotFound, so repeatedly requested stale instance references
// don't cost a fresh LDAP round-trip on every call.
const instanceCacheNotFound = instanceCacheKeySep + "not-found"
type userAttributeMap struct {
displayName string
id string
@@ -205,6 +217,27 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst
}
}
// A nil instanceCache means "don't cache", which is what a TTL <= 0 asks for.
// ttlcache treats a TTL of 0 as "never expires", so it can't express that itself.
// No janitor goroutine is started: it would outlive the backend (which has no
// shutdown hook), and Get() already skips expired items on its own. Entries that
// expire without ever being read again are reclaimed by the capacity limit.
var instanceCache *ttlcache.Cache[string, string]
if config.InstanceMapperEnabled && config.InstanceMapperCacheTTL > 0 {
// A capacity of 0 lets ttlcache grow without limit. Part of a cache key is the
// requested instance name, which a client controls via the '$search' parameter,
// so a deployment wants the bounded default from the graph config here.
var capacity uint64
if config.InstanceMapperCacheCapacity > 0 {
capacity = uint64(config.InstanceMapperCacheCapacity)
}
instanceCache = ttlcache.New(
ttlcache.WithTTL[string, string](config.InstanceMapperCacheTTL),
ttlcache.WithCapacity[string, string](capacity),
ttlcache.WithDisableTouchOnHit[string, string](),
)
}
return &LDAP{
useServerUUID: config.UseServerUUID,
usePwModifyExOp: config.UsePasswordModExOp,
@@ -241,6 +274,7 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst
instanceMapperIDAttribute: config.InstanceMapperIDAttribute,
crossInstanceReferenceTemplate: crossInstanceReferenceTemplate,
instanceURLTemplate: instanceURLTemplate,
instanceCache: instanceCache,
}, nil
}
@@ -1604,6 +1638,16 @@ func (i *LDAP) getInstance(searchValue, searchAttribute, resultAttribute string)
return searchValue, nil
}
cacheKey := searchAttribute + instanceCacheKeySep + resultAttribute + instanceCacheKeySep + searchValue
if i.instanceCache != nil {
if item := i.instanceCache.Get(cacheKey); item != nil {
if item.Value() == instanceCacheNotFound {
return "", ErrNotFound
}
return item.Value(), nil
}
}
searchRequest := ldap.NewSearchRequest(
i.instanceMapperBaseDN,
ldap.ScopeWholeSubtree,
@@ -1615,23 +1659,39 @@ func (i *LDAP) getInstance(searchValue, searchAttribute, resultAttribute string)
res, err := i.conn.Search(searchRequest)
if err != nil {
// Not cached: this is a transient LDAP failure, not a definitive answer.
i.logger.Error().Err(err).Str("backend", "ldap").Str("dn", i.instanceMapperBaseDN).Str("searchValue", searchValue).Str("searchAttribute", searchAttribute).Str("resultAttribute", resultAttribute).Msg("Search instance failed")
return "", errorcode.New(errorcode.ItemNotFound, "instanceid search failed")
}
if len(res.Entries) == 0 {
// expected behaviour - we log debug in case something is fishy. This log can be removed when the feature proves stable
i.logger.Debug().Str("backend", "ldap").Str("dn", i.instanceMapperBaseDN).Str("searchValue", searchValue).Interface("result", res).Msg("Search instance empty")
i.cacheInstance(cacheKey, instanceCacheNotFound)
return "", ErrNotFound
}
if len(res.Entries) > 1 {
// Not cached: ambiguous data, don't freeze it in.
i.logger.Error().Str("backend", "ldap").Str("dn", i.instanceMapperBaseDN).Str("searchValue", searchValue).Interface("result", res).Msg("Search instance returned multiple responses.")
return "", errorcode.New(errorcode.ItemNotFound, "instanceid search returned multiple responses")
}
if len(res.Entries[0].Attributes) == 0 || len(res.Entries[0].Attributes[0].Values) == 0 {
// Not cached: malformed data, don't freeze it in.
i.logger.Error().Str("backend", "ldap").Str("dn", i.instanceMapperBaseDN).Str("searchValue", searchValue).Interface("result", res).Msg("Search instance returned malformed response")
return "", errorcode.New(errorcode.ItemNotFound, "instanceid search response malformed")
}
return res.Entries[0].Attributes[0].Values[0], nil
value := res.Entries[0].Attributes[0].Values[0]
i.cacheInstance(cacheKey, value)
return value, nil
}
// cacheInstance stores an instance mapper lookup result, doing nothing when
// caching is disabled.
func (i *LDAP) cacheInstance(cacheKey, value string) {
if i.instanceCache == nil {
return
}
i.instanceCache.Set(cacheKey, value, ttlcache.DefaultTTL)
}
func (i *LDAP) getInstanceID(instancename string) (string, error) {
@@ -0,0 +1,119 @@
package identity
import (
"testing"
"time"
"github.com/go-ldap/ldap/v3"
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
"github.com/owncloud/ocis/v2/services/graph/pkg/identity/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
var instanceMapperConfig = config.LDAP{
UserBaseDN: "ou=people,dc=test",
UserObjectClass: "inetOrgPerson",
UserSearchScope: "sub",
UserDisplayNameAttribute: "displayname",
UserIDAttribute: "entryUUID",
UserEmailAttribute: "mail",
UserNameAttribute: "uid",
GroupBaseDN: "ou=groups,dc=test",
GroupObjectClass: "groupOfNames",
GroupSearchScope: "sub",
GroupNameAttribute: "cn",
GroupMemberAttribute: "member",
GroupIDAttribute: "entryUUID",
InstanceMapperEnabled: true,
InstanceMapperBaseDN: "ou=instances,dc=test",
InstanceMapperNameAttribute: "instanceName",
InstanceMapperIDAttribute: "instanceID",
InstanceMapperCacheTTL: time.Minute,
}
func TestGetInstanceNameIsCached(t *testing.T) {
lm := &mocks.Client{}
b, err := getMockedBackend(lm, instanceMapperConfig, &logger)
assert.Nil(t, err)
instanceEntry := ldap.NewEntry("instanceID=instance-1,ou=instances,dc=test",
map[string][]string{
"instanceName": {"Instance One"},
})
lm.On("Search", mock.Anything).
Return(&ldap.SearchResult{Entries: []*ldap.Entry{instanceEntry}}, nil)
name1, err1 := b.getInstanceName("instance-1")
assert.Nil(t, err1)
assert.Equal(t, "Instance One", name1)
name2, err2 := b.getInstanceName("instance-1")
assert.Nil(t, err2)
assert.Equal(t, "Instance One", name2)
lm.AssertNumberOfCalls(t, "Search", 1)
}
func TestGetInstanceNameCachesNotFound(t *testing.T) {
lm := &mocks.Client{}
b, err := getMockedBackend(lm, instanceMapperConfig, &logger)
assert.Nil(t, err)
lm.On("Search", mock.Anything).
Return(&ldap.SearchResult{Entries: []*ldap.Entry{}}, nil)
_, err1 := b.getInstanceName("stale-instance")
assert.ErrorIs(t, err1, ErrNotFound)
_, err2 := b.getInstanceName("stale-instance")
assert.ErrorIs(t, err2, ErrNotFound)
lm.AssertNumberOfCalls(t, "Search", 1)
}
func TestGetInstanceNameZeroTTLDisablesCache(t *testing.T) {
lm := &mocks.Client{}
cfg := instanceMapperConfig
cfg.InstanceMapperCacheTTL = 0
b, err := getMockedBackend(lm, cfg, &logger)
assert.Nil(t, err)
instanceEntry := ldap.NewEntry("instanceID=instance-1,ou=instances,dc=test",
map[string][]string{
"instanceName": {"Instance One"},
})
lm.On("Search", mock.Anything).
Return(&ldap.SearchResult{Entries: []*ldap.Entry{instanceEntry}}, nil)
for range 2 {
name, err := b.getInstanceName("instance-1")
assert.Nil(t, err)
assert.Equal(t, "Instance One", name)
}
// A TTL of 0 means "don't cache", not "cache forever".
lm.AssertNumberOfCalls(t, "Search", 2)
}
func TestGetInstanceNameCacheCapacityIsHonoured(t *testing.T) {
lm := &mocks.Client{}
cfg := instanceMapperConfig
cfg.InstanceMapperCacheCapacity = 1
b, err := getMockedBackend(lm, cfg, &logger)
assert.Nil(t, err)
lm.On("Search", mock.Anything).
Return(&ldap.SearchResult{Entries: []*ldap.Entry{}}, nil)
// Caching "a" then "b" evicts "a", because only one entry fits, so asking
// for "a" again has to hit LDAP a second time.
for _, instanceID := range []string{"a", "b", "a"} {
_, err := b.getInstanceName(instanceID)
assert.ErrorIs(t, err, ErrNotFound)
}
lm.AssertNumberOfCalls(t, "Search", 3)
}