Skip to content

Commit

Permalink
move config to a struct
Browse files Browse the repository at this point in the history
Signed-off-by: Nicola Murino <[email protected]>
  • Loading branch information
drakkan committed Aug 27, 2024
1 parent 4232161 commit 1ccc7f2
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 49 deletions.
61 changes: 38 additions & 23 deletions authenticator/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,45 +32,60 @@ var (
sdk.WebClientPasswordResetDisabled}
)

func NewAuthenticator(dialURLs []string, baseDN, username, password string, startTLS int, skipTLSVerify bool,
baseDir string, cacheTime int, searchQuery string, groupAttributes, caCertificates []string,
primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix string, requiresGroup bool,
sftpgoUserRequirements int,
) (*LDAPAuthenticator, error) {
rootCAs, err := loadCACerts(caCertificates)
type Config struct {
DialURLs []string `json:"dial_urls"`
BaseDN string `json:"base_dn"`
Username string `json:"username"`
Password string `json:"password"`
StartTLS int `json:"start_tls"`
SkipTLSVerify bool `json:"skip_tls_verify"`
CACertificates []string `json:"ca_certificates"`
SearchQuery string `json:"search_query"`
GroupAttributes []string `json:"group_attributes"`
PrimaryGroupPrefix string `json:"primary_group_prefix"`
SecondaryGroupPrefix string `json:"secondary_group_prefix"`
MembershipGroupPrefix string `json:"membership_group_prefix"`
RequireGroups bool `json:"require_groups"`
SFTPGoUserRequirements int `json:"sftpgo_user_requirements"`
BaseDir string `json:"base_dir"`
CacheTime int `json:"cache_time"`
}

func NewAuthenticator(config *Config) (*LDAPAuthenticator, error) {
rootCAs, err := loadCACerts(config.CACertificates)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
RootCAs: rootCAs,
InsecureSkipVerify: skipTLSVerify,
InsecureSkipVerify: config.SkipTLSVerify,
}
auth := &LDAPAuthenticator{
DialURLs: dialURLs,
BaseDN: baseDN,
Username: username,
Password: password,
StartTLS: startTLS,
SearchQuery: searchQuery,
GroupAttributes: groupAttributes,
BaseDir: baseDir,
PrimaryGroupPrefix: strings.ToLower(primaryGroupPrefix),
SecondaryGroupPrefix: strings.ToLower(secondaryGroupPrefix),
MembershipGroupPrefix: strings.ToLower(membershipGroupPrefix),
RequireGroups: requiresGroup,
SFTPGoUserRequirements: sftpgoUserRequirements,
DialURLs: config.DialURLs,
BaseDN: config.BaseDN,
Username: config.Username,
Password: config.Password,
StartTLS: config.StartTLS,
SearchQuery: config.SearchQuery,
GroupAttributes: config.GroupAttributes,
BaseDir: config.BaseDir,
PrimaryGroupPrefix: strings.ToLower(config.PrimaryGroupPrefix),
SecondaryGroupPrefix: strings.ToLower(config.SecondaryGroupPrefix),
MembershipGroupPrefix: strings.ToLower(config.MembershipGroupPrefix),
RequireGroups: config.RequireGroups,
SFTPGoUserRequirements: config.SFTPGoUserRequirements,
tlsConfig: tlsConfig,
}
if err := auth.validate(); err != nil {
return nil, err
}
if cacheTime > 0 {
if config.CacheTime > 0 {
if auth.hasGroups() {
logger.AppLogger.Warn("user caching cannot be enabled when groups are defined, continuing without caching")
} else {
logger.AppLogger.Info("enable users caching", "cache time (sec)", cacheTime)
logger.AppLogger.Info("enable users caching", "cache time (sec)", config.CacheTime)
cache = &authCache{
cacheTime: cacheTime,
cacheTime: config.CacheTime,
cache: make(map[string]cachedUser),
}
startCleanupTicker(10 * time.Minute)
Expand Down
69 changes: 47 additions & 22 deletions authenticator/ldap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ var (

func TestLDAPAuthenticator(t *testing.T) {
baseDir := filepath.Clean(os.TempDir())
auth, err := NewAuthenticator(ldapURL, baseDN, username, password, 0, false, baseDir, 2, searchQuery,
auth, err := NewAuthenticator(getConfig(ldapURL, baseDN, username, password, 0, false, baseDir, 2, searchQuery,
[]string{groupAttribute}, nil, primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix,
true, 0)
true, 0))
require.NoError(t, err)
require.Nil(t, auth.tlsConfig.RootCAs)

Expand Down Expand Up @@ -169,8 +169,8 @@ func TestLDAPAuthenticator(t *testing.T) {

func TestAuthFromCache(t *testing.T) {
baseDir := filepath.Clean(os.TempDir())
auth, err := NewAuthenticator(ldapURL, baseDN, username, password, 0, false, baseDir, 2, searchQuery,
nil, nil, "", "", "", false, 0)
auth, err := NewAuthenticator(getConfig(ldapURL, baseDN, username, password, 0, false, baseDir, 2, searchQuery,
nil, nil, "", "", "", false, 0))
require.NoError(t, err)
require.Nil(t, auth.tlsConfig.RootCAs)

Expand Down Expand Up @@ -233,9 +233,9 @@ func TestAuthFromCache(t *testing.T) {
}

func TestPreserveUserChanges(t *testing.T) {
auth, err := NewAuthenticator(ldapURL, baseDN, username, password, 0, false, "", 0, searchQuery,
auth, err := NewAuthenticator(getConfig(ldapURL, baseDN, username, password, 0, false, "", 0, searchQuery,
[]string{groupAttribute}, nil, primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix,
false, 0)
false, 0))
require.NoError(t, err)
userJSON, err := auth.CheckUserAndPass(user1, password, "", "", []byte(`{"username":"user1"}`))
require.NoError(t, err)
Expand All @@ -260,9 +260,9 @@ func TestPreserveUserChanges(t *testing.T) {
}

func TestLDAPS(t *testing.T) {
auth, err := NewAuthenticator(ldapsURL, baseDN, username, password, 0, true, "", 0, searchQuery,
auth, err := NewAuthenticator(getConfig(ldapsURL, baseDN, username, password, 0, true, "", 0, searchQuery,
[]string{groupAttribute}, nil, primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix,
false, 0)
false, 0))
require.NoError(t, err)
l, err := auth.connect()
require.NoError(t, err)
Expand All @@ -271,9 +271,9 @@ func TestLDAPS(t *testing.T) {
}

func TestLDAPConnectionErrors(t *testing.T) {
auth, err := NewAuthenticator([]string{"ldap://localhost:3892"}, baseDN, username, password, 0, true, "", 0, searchQuery,
auth, err := NewAuthenticator(getConfig([]string{"ldap://localhost:3892"}, baseDN, username, password, 0, true, "", 0, searchQuery,
[]string{groupAttribute}, nil, primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix,
false, 0)
false, 0))
require.NoError(t, err)
_, err = auth.CheckUserAndPass(user1, password, "", "", nil)
require.Error(t, err)
Expand All @@ -285,9 +285,9 @@ func TestLDAPConnectionErrors(t *testing.T) {

func TestStartTLS(t *testing.T) {
// glauth does not support STARTTLS
auth, err := NewAuthenticator(ldapURL, baseDN, username, password, 1, true, "", 0, searchQuery,
auth, err := NewAuthenticator(getConfig(ldapURL, baseDN, username, password, 1, true, "", 0, searchQuery,
[]string{groupAttribute}, nil, primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix,
false, 0)
false, 0))
require.NoError(t, err)
_, err = auth.connect()
require.Error(t, err)
Expand All @@ -297,10 +297,10 @@ func TestStartTLS(t *testing.T) {
}

func TestValidation(t *testing.T) {
_, err := NewAuthenticator(nil, "", "", "", 0, false, "", 0, "", nil, nil, "", "", "", false, 0)
_, err := NewAuthenticator(getConfig(nil, "", "", "", 0, false, "", 0, "", nil, nil, "", "", "", false, 0))
require.Error(t, err)
assert.Contains(t, err.Error(), "dial URL is required")
_, err = NewAuthenticator([]string{"", ""}, "", "", "", 0, false, "", 0, "", nil, nil, "", "", "", false, 0)
_, err = NewAuthenticator(getConfig([]string{"", ""}, "", "", "", 0, false, "", 0, "", nil, nil, "", "", "", false, 0))
require.Error(t, err)
assert.Contains(t, err.Error(), "dial URL is required")
a := LDAPAuthenticator{
Expand Down Expand Up @@ -432,28 +432,28 @@ func TestGetCNFromDN(t *testing.T) {

func TestLoadCACerts(t *testing.T) {
caCrtPath := "testcacrt"
_, err := NewAuthenticator(ldapURL, baseDN, username, password, 0, true, "", 0,
searchQuery, nil, []string{caCrtPath}, "", "", "", false, 0)
_, err := NewAuthenticator(getConfig(ldapURL, baseDN, username, password, 0, true, "", 0,
searchQuery, nil, []string{caCrtPath}, "", "", "", false, 0))
require.Error(t, err)
assert.Contains(t, err.Error(), "is not an absolute path")
caCrtPath = filepath.Join(os.TempDir(), caCrtPath)
_, err = NewAuthenticator(ldapURL, baseDN, username, password, 0, true, "", 0,
searchQuery, nil, []string{caCrtPath}, "", "", "", false, 0)
_, err = NewAuthenticator(getConfig(ldapURL, baseDN, username, password, 0, true, "", 0,
searchQuery, nil, []string{caCrtPath}, "", "", "", false, 0))
require.ErrorIs(t, err, fs.ErrNotExist)
err = os.WriteFile(caCrtPath, []byte(caCRT), 0600)
require.NoError(t, err)
auth, err := NewAuthenticator(ldapURL, baseDN, username, password, 0, true, "", 0,
searchQuery, nil, []string{caCrtPath}, "", "", "", false, 0)
auth, err := NewAuthenticator(getConfig(ldapURL, baseDN, username, password, 0, true, "", 0,
searchQuery, nil, []string{caCrtPath}, "", "", "", false, 0))
require.NoError(t, err)
require.NotNil(t, auth.tlsConfig.RootCAs)
err = os.Remove(caCrtPath)
require.NoError(t, err)
}

func TestLDAPMonitor(t *testing.T) {
auth, err := NewAuthenticator(multipleLDAPURLs, baseDN, username, password, 0, false, "", 2, searchQuery,
auth, err := NewAuthenticator(getConfig(multipleLDAPURLs, baseDN, username, password, 0, false, "", 2, searchQuery,
[]string{groupAttribute}, nil, primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix,
true, 0)
true, 0))
require.NoError(t, err)
defer auth.Cleanup()

Expand Down Expand Up @@ -489,3 +489,28 @@ func TestRetryableErrors(t *testing.T) {
require.False(t, a.isRetryableError(err))
require.False(t, a.isRetryableError(fs.ErrPermission))
}

func getConfig(dialURLs []string, baseDN, username, password string, startTLS int, skipTLSVerify bool,
baseDir string, cacheTime int, searchQuery string, groupAttributes, caCertificates []string,
primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix string, requiresGroup bool,
sftpgoUserRequirements int,
) *Config {
return &Config{
DialURLs: dialURLs,
BaseDN: baseDN,
Username: username,
Password: password,
StartTLS: startTLS,
SkipTLSVerify: skipTLSVerify,
BaseDir: baseDir,
CacheTime: cacheTime,
SearchQuery: searchQuery,
GroupAttributes: groupAttributes,
CACertificates: caCertificates,
PrimaryGroupPrefix: primaryGroupPrefix,
SecondaryGroupPrefix: secondaryGroupPrefix,
MembershipGroupPrefix: membershipGroupPrefix,
RequireGroups: requiresGroup,
SFTPGoUserRequirements: sftpgoUserRequirements,
}
}
23 changes: 19 additions & 4 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,25 @@ var (
},
},
Action: func(ctx *cli.Context) error {
a, err := authenticator.NewAuthenticator(ldapURL.Value(), ldapBaseDN, ldapUsername, ldapPassword, startTLS,
skipTLSVerify == 1, usersBaseDir, cacheTime, ldapSearchQuery, ldapGroupAttributes.Value(),
caCertificates.Value(), primaryGroupPrefix, secondaryGroupPrefix, membershipGroupPrefix,
requireGroupMembership, sftpgoUserRequirements)
config := &authenticator.Config{
DialURLs: ldapURL.Value(),
BaseDN: ldapBaseDN,
Username: ldapUsername,
Password: ldapPassword,
StartTLS: startTLS,
SkipTLSVerify: skipTLSVerify == 1,
CACertificates: caCertificates.Value(),
BaseDir: usersBaseDir,
CacheTime: cacheTime,
SearchQuery: ldapSearchQuery,
GroupAttributes: ldapGroupAttributes.Value(),
PrimaryGroupPrefix: primaryGroupPrefix,
SecondaryGroupPrefix: secondaryGroupPrefix,
MembershipGroupPrefix: membershipGroupPrefix,
RequireGroups: requireGroupMembership,
SFTPGoUserRequirements: sftpgoUserRequirements,
}
a, err := authenticator.NewAuthenticator(config)
if err != nil {
logger.AppLogger.Error("unable to create the authenticator", "err", err)
return err
Expand Down

0 comments on commit 1ccc7f2

Please sign in to comment.