sdk/ldap: update interface to use DialURL (#20200)

* sdk/ldap: update interface to use DialURL

* Fix scheme

* Fix race condition

* Add tls config dialopt
This commit is contained in:
Jason O'Donnell 2023-04-17 16:34:10 -04:00 committed by GitHub
parent 13dd4c0a99
commit 6d9180f900
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 17 deletions

View file

@ -32,11 +32,6 @@ func (c *Client) DialLDAP(cfg *ConfigEntry) (Connection, error) {
var conn Connection
urls := strings.Split(cfg.Url, ",")
// Default timeout in the pacakge is 60 seconds, which we default to on our
// end. This is useful if you want to take advantage of the URL list to increase
// availability of LDAP.
ldap.DefaultTimeout = time.Duration(cfg.ConnectionTimeout) * time.Second
for _, uut := range urls {
u, err := url.Parse(uut)
if err != nil {
@ -49,12 +44,20 @@ func (c *Client) DialLDAP(cfg *ConfigEntry) (Connection, error) {
}
var tlsConfig *tls.Config
dialer := net.Dialer{
Timeout: time.Duration(cfg.ConnectionTimeout) * time.Second,
}
switch u.Scheme {
case "ldap":
if port == "" {
port = "389"
}
conn, err = c.LDAP.Dial("tcp", net.JoinHostPort(host, port))
fullAddr := fmt.Sprintf("%s://%s", u.Scheme, net.JoinHostPort(host, port))
opt := ldap.DialWithDialer(&dialer)
conn, err = c.LDAP.DialURL(fullAddr, opt)
if err != nil {
break
}
@ -77,7 +80,15 @@ func (c *Client) DialLDAP(cfg *ConfigEntry) (Connection, error) {
if err != nil {
break
}
conn, err = c.LDAP.DialTLS("tcp", net.JoinHostPort(host, port), tlsConfig)
fullAddr := fmt.Sprintf("%s://%s", u.Scheme, net.JoinHostPort(host, port))
opt := ldap.DialWithDialer(&dialer)
tls := ldap.DialWithTLSConfig(tlsConfig)
conn, err = c.LDAP.DialURL(fullAddr, opt, tls)
if err != nil {
break
}
default:
retErr = multierror.Append(retErr, fmt.Errorf("invalid LDAP scheme in url %q", net.JoinHostPort(host, port)))
continue

View file

@ -4,8 +4,6 @@
package ldaputil
import (
"crypto/tls"
"github.com/go-ldap/ldap/v3"
)
@ -16,16 +14,11 @@ func NewLDAP() LDAP {
// LDAP provides ldap functionality, but through an interface
// rather than statically. This allows faking it for tests.
type LDAP interface {
Dial(network, addr string) (Connection, error)
DialTLS(network, addr string, config *tls.Config) (Connection, error)
DialURL(addr string, opts ...ldap.DialOpt) (Connection, error)
}
type ldapIfc struct{}
func (l *ldapIfc) Dial(network, addr string) (Connection, error) {
return ldap.Dial(network, addr)
}
func (l *ldapIfc) DialTLS(network, addr string, config *tls.Config) (Connection, error) {
return ldap.DialTLS(network, addr, config)
func (l *ldapIfc) DialURL(addr string, opts ...ldap.DialOpt) (Connection, error) {
return ldap.DialURL(addr, opts...)
}