diff options
author | Antoine Vinot <antoine.vinot@sonarsource.com> | 2022-11-16 10:34:14 +0100 |
---|---|---|
committer | sonartech <sonartech@sonarsource.com> | 2022-11-16 20:03:06 +0000 |
commit | 8f7051db6a094c0f6618bb0c711a64679894c88f (patch) | |
tree | cc65d56d81db1c94fb159c8d7befff4187b548b0 /server/sonar-auth-ldap | |
parent | db89e162e9390f4a647944d1a74e7e5d686c0e60 (diff) | |
download | sonarqube-8f7051db6a094c0f6618bb0c711a64679894c88f.tar.gz sonarqube-8f7051db6a094c0f6618bb0c711a64679894c88f.zip |
SONAR-12497 Drop deprecated Ldap autodiscovery feature
Diffstat (limited to 'server/sonar-auth-ldap')
16 files changed, 171 insertions, 557 deletions
diff --git a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapAutodiscovery.java b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapAutodiscovery.java deleted file mode 100644 index 345b5ee45e1..00000000000 --- a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapAutodiscovery.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.auth.ldap; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; -import org.apache.commons.lang.math.NumberUtils; -import org.sonar.api.server.ServerSide; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; - -/** - * @author Evgeny Mandrikov - */ -@ServerSide -public class LdapAutodiscovery { - - private static final Logger LOG = Loggers.get(LdapAutodiscovery.class); - - /** - * Get the DNS domain name (eg: example.org). - * - * @return DNS domain - * @throws java.net.UnknownHostException if unable to determine DNS domain - */ - public static String getDnsDomainName() throws UnknownHostException { - return getDnsDomainName(InetAddress.getLocalHost().getCanonicalHostName()); - } - - /** - * Extracts DNS domain name from Fully Qualified Domain Name. - * - * @param fqdn Fully Qualified Domain Name - * @return DNS domain name or null, if can't be extracted - */ - public static String getDnsDomainName(String fqdn) { - if (fqdn.indexOf('.') == -1) { - return null; - } - return fqdn.substring(fqdn.indexOf('.') + 1); - } - - /** - * Get the DNS DN domain (eg: dc=example,dc=org). - * - * @param domain DNS domain - * @return DNS DN domain - */ - public static String getDnsDomainDn(String domain) { - StringBuilder result = new StringBuilder(); - String[] domainPart = domain.split("[.]"); - for (int i = 0; i < domainPart.length; i++) { - result.append(i > 0 ? "," : "").append("dc=").append(domainPart[i]); - } - return result.toString(); - } - - /** - * Get LDAP server(s) from DNS. - * - * @param domain DNS domain - * @return LDAP server(s) or empty if unable to determine - */ - public List<LdapSrvRecord> getLdapServers(String domain) { - try { - return getLdapServers(new InitialDirContext(), domain); - } catch (NamingException e) { - LOG.error("Unable to determine LDAP server(s) from DNS", e); - return Collections.emptyList(); - } - } - - List<LdapSrvRecord> getLdapServers(DirContext context, String domain) throws NamingException { - Attributes lSrvAttrs = context.getAttributes("dns:/_ldap._tcp." + domain, new String[] {"srv"}); - Attribute serversAttribute = lSrvAttrs.get("srv"); - NamingEnumeration<?> lEnum = serversAttribute.getAll(); - SortedSet<LdapSrvRecord> result = new TreeSet<>(); - while (lEnum.hasMore()) { - String srvRecord = (String) lEnum.next(); - // priority weight port target - String[] srvData = srvRecord.split(" "); - - int priority = NumberUtils.toInt(srvData[0]); - int weight = NumberUtils.toInt(srvData[1]); - String port = srvData[2]; - String target = srvData[3]; - - if (target.endsWith(".")) { - target = target.substring(0, target.length() - 1); - } - String server = "ldap://" + target + ":" + port; - result.add(new LdapSrvRecord(server, priority, weight)); - } - return new ArrayList<>(result); - } - - public static class LdapSrvRecord implements Comparable<LdapSrvRecord> { - private final String serverUrl; - private final int priority; - private final int weight; - - public LdapSrvRecord(String serverUrl, int priority, int weight) { - this.serverUrl = serverUrl; - this.priority = priority; - this.weight = weight; - } - - @Override - public int compareTo(LdapSrvRecord o) { - if (this.priority == o.priority) { - return Integer.compare(o.weight, this.weight); - } - return Integer.compare(this.priority, o.priority); - } - - String getServerUrl() { - return serverUrl; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - return this.serverUrl.equals(((LdapSrvRecord) obj).serverUrl); - } - - @Override - public int hashCode() { - return this.serverUrl.hashCode(); - } - } - -} diff --git a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapModule.java b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapModule.java index 24893b6f333..410ee5252d8 100644 --- a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapModule.java +++ b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapModule.java @@ -27,8 +27,7 @@ public class LdapModule extends Module { protected void configureModule() { add( LdapRealm.class, - LdapSettingsManager.class, - LdapAutodiscovery.class); + LdapSettingsManager.class); } } diff --git a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapSettingsManager.java b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapSettingsManager.java index db14f7bfee6..b2965d99d14 100644 --- a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapSettingsManager.java +++ b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapSettingsManager.java @@ -20,7 +20,6 @@ package org.sonar.auth.ldap; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.Configuration; @@ -28,8 +27,6 @@ import org.sonar.api.server.ServerSide; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; -import static org.sonar.auth.ldap.LdapAutodiscovery.LdapSrvRecord; - /** * The LdapSettingsManager will parse the settings. * This class is also responsible to cope with multiple ldap servers. @@ -42,8 +39,8 @@ public class LdapSettingsManager { private static final String LDAP_SERVERS_PROPERTY = "ldap.servers"; private static final String LDAP_PROPERTY_PREFIX = "ldap"; + protected static final String MANDATORY_LDAP_PROPERTY_ERROR = "The property '%s' property is empty while it is mandatory."; private final Configuration config; - private final LdapAutodiscovery ldapAutodiscovery; private Map<String, LdapUserMapping> userMappings = null; private Map<String, LdapGroupMapping> groupMappings = null; private Map<String, LdapContextFactory> contextFactories; @@ -53,9 +50,8 @@ public class LdapSettingsManager { * * @param config The config to use. */ - public LdapSettingsManager(Configuration config, LdapAutodiscovery ldapAutodiscovery) { + public LdapSettingsManager(Configuration config) { this.config = config; - this.ldapAutodiscovery = ldapAutodiscovery; } /** @@ -66,31 +62,41 @@ public class LdapSettingsManager { */ public Map<String, LdapUserMapping> getUserMappings() { if (userMappings == null) { - // Use linked hash map to preserve order - userMappings = new LinkedHashMap<>(); - String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); - if (serverKeys.length > 0) { - for (String serverKey : serverKeys) { - LdapUserMapping userMapping = new LdapUserMapping(config, LDAP_PROPERTY_PREFIX + "." + serverKey); - if (StringUtils.isNotBlank(userMapping.getBaseDn())) { - LOG.info("User mapping for server {}: {}", serverKey, userMapping); - userMappings.put(serverKey, userMapping); - } else { - LOG.info("Users will not be synchronized for server {}, because property 'ldap.{}.user.baseDn' is empty.", serverKey, serverKey); - } - } + createUserMappings(); + } + return userMappings; + } + + private void createUserMappings() { + userMappings = new LinkedHashMap<>(); + String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); + if (serverKeys.length > 0) { + createUserMappingsForMultipleLdapConfig(serverKeys); + } else { + createUserMappingsForSingleLdapConfig(); + } + } + + private void createUserMappingsForMultipleLdapConfig(String[] serverKeys) { + for (String serverKey : serverKeys) { + LdapUserMapping userMapping = new LdapUserMapping(config, LDAP_PROPERTY_PREFIX + "." + serverKey); + if (StringUtils.isNotBlank(userMapping.getBaseDn())) { + LOG.info("User mapping for server {}: {}", serverKey, userMapping); + userMappings.put(serverKey, userMapping); } else { - // Backward compatibility with single server configuration - LdapUserMapping userMapping = new LdapUserMapping(config, LDAP_PROPERTY_PREFIX); - if (StringUtils.isNotBlank(userMapping.getBaseDn())) { - LOG.info("User mapping: {}", userMapping); - userMappings.put(DEFAULT_LDAP_SERVER_KEY, userMapping); - } else { - LOG.info("Users will not be synchronized, because property 'ldap.user.baseDn' is empty."); - } + LOG.info("Users will not be synchronized for server {}, because property 'ldap.{}.user.baseDn' is empty.", serverKey, serverKey); } } - return userMappings; + } + + private void createUserMappingsForSingleLdapConfig() { + LdapUserMapping userMapping = new LdapUserMapping(config, LDAP_PROPERTY_PREFIX); + if (StringUtils.isNotBlank(userMapping.getBaseDn())) { + LOG.info("User mapping: {}", userMapping); + userMappings.put(DEFAULT_LDAP_SERVER_KEY, userMapping); + } else { + LOG.info("Users will not be synchronized, because property 'ldap.user.baseDn' is empty."); + } } /** @@ -101,31 +107,41 @@ public class LdapSettingsManager { */ public Map<String, LdapGroupMapping> getGroupMappings() { if (groupMappings == null) { - // Use linked hash map to preserve order - groupMappings = new LinkedHashMap<>(); - String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); - if (serverKeys.length > 0) { - for (String serverKey : serverKeys) { - LdapGroupMapping groupMapping = new LdapGroupMapping(config, LDAP_PROPERTY_PREFIX + "." + serverKey); - if (StringUtils.isNotBlank(groupMapping.getBaseDn())) { - LOG.info("Group mapping for server {}: {}", serverKey, groupMapping); - groupMappings.put(serverKey, groupMapping); - } else { - LOG.info("Groups will not be synchronized for server {}, because property 'ldap.{}.group.baseDn' is empty.", serverKey, serverKey); - } - } + createGroupMappings(); + } + return groupMappings; + } + + private void createGroupMappings() { + groupMappings = new LinkedHashMap<>(); + String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); + if (serverKeys.length > 0) { + createGroupMappingsForMultipleLdapConfig(serverKeys); + } else { + createGroupMappingsForSingleLdapConfig(); + } + } + + private void createGroupMappingsForMultipleLdapConfig(String[] serverKeys) { + for (String serverKey : serverKeys) { + LdapGroupMapping groupMapping = new LdapGroupMapping(config, LDAP_PROPERTY_PREFIX + "." + serverKey); + if (StringUtils.isNotBlank(groupMapping.getBaseDn())) { + LOG.info("Group mapping for server {}: {}", serverKey, groupMapping); + groupMappings.put(serverKey, groupMapping); } else { - // Backward compatibility with single server configuration - LdapGroupMapping groupMapping = new LdapGroupMapping(config, LDAP_PROPERTY_PREFIX); - if (StringUtils.isNotBlank(groupMapping.getBaseDn())) { - LOG.info("Group mapping: {}", groupMapping); - groupMappings.put(DEFAULT_LDAP_SERVER_KEY, groupMapping); - } else { - LOG.info("Groups will not be synchronized, because property 'ldap.group.baseDn' is empty."); - } + LOG.info("Groups will not be synchronized for server {}, because property 'ldap.{}.group.baseDn' is empty.", serverKey, serverKey); } } - return groupMappings; + } + + private void createGroupMappingsForSingleLdapConfig() { + LdapGroupMapping groupMapping = new LdapGroupMapping(config, LDAP_PROPERTY_PREFIX); + if (StringUtils.isNotBlank(groupMapping.getBaseDn())) { + LOG.info("Group mapping: {}", groupMapping); + groupMappings.put(DEFAULT_LDAP_SERVER_KEY, groupMapping); + } else { + LOG.info("Groups will not be synchronized, because property 'ldap.group.baseDn' is empty."); + } } /** @@ -136,7 +152,6 @@ public class LdapSettingsManager { */ public Map<String, LdapContextFactory> getContextFactories() { if (contextFactories == null) { - // Use linked hash map to preserve order contextFactories = new LinkedHashMap<>(); String[] serverKeys = config.getStringArray(LDAP_SERVERS_PROPERTY); if (serverKeys.length > 0) { @@ -149,31 +164,8 @@ public class LdapSettingsManager { } private void initSimpleLdapConfiguration() { - String realm = config.get(LDAP_PROPERTY_PREFIX + ".realm").orElse(null); - String ldapUrlKey = LDAP_PROPERTY_PREFIX + ".url"; - String ldapUrl = config.get(ldapUrlKey).orElse(null); - if (ldapUrl == null && realm != null) { - LOG.warn("Auto-discovery feature is deprecated, please use '{}' to specify LDAP url", ldapUrlKey); - List<LdapSrvRecord> ldapServers = ldapAutodiscovery.getLdapServers(realm); - if (ldapServers.isEmpty()) { - throw new LdapException(String.format("The property '%s' is empty and SonarQube is not able to auto-discover any LDAP server.", ldapUrlKey)); - } - int index = 1; - for (LdapSrvRecord ldapSrvRecord : ldapServers) { - if (StringUtils.isNotBlank(ldapSrvRecord.getServerUrl())) { - LOG.info("Detected server: {}", ldapSrvRecord.getServerUrl()); - LdapContextFactory contextFactory = new LdapContextFactory(config, LDAP_PROPERTY_PREFIX, ldapSrvRecord.getServerUrl()); - contextFactories.put(DEFAULT_LDAP_SERVER_KEY + index, contextFactory); - index++; - } - } - } else { - if (StringUtils.isBlank(ldapUrl)) { - throw new LdapException(String.format("The property '%s' is empty and no realm configured to try auto-discovery.", ldapUrlKey)); - } - LdapContextFactory contextFactory = new LdapContextFactory(config, LDAP_PROPERTY_PREFIX, ldapUrl); - contextFactories.put(DEFAULT_LDAP_SERVER_KEY, contextFactory); - } + LdapContextFactory contextFactory = initLdapContextFactory(LDAP_PROPERTY_PREFIX); + contextFactories.put(DEFAULT_LDAP_SERVER_KEY, contextFactory); } private void initMultiLdapConfiguration(String[] serverKeys) { @@ -182,14 +174,18 @@ public class LdapSettingsManager { + "all LDAP properties must be linked to one of those servers. Please remove properties like 'ldap.url', 'ldap.realm', ..."); } for (String serverKey : serverKeys) { - String prefix = LDAP_PROPERTY_PREFIX + "." + serverKey; - String ldapUrlKey = prefix + ".url"; - String ldapUrl = config.get(ldapUrlKey).orElse(null); - if (StringUtils.isBlank(ldapUrl)) { - throw new LdapException(String.format("The property '%s' property is empty while it is mandatory.", ldapUrlKey)); - } - LdapContextFactory contextFactory = new LdapContextFactory(config, prefix, ldapUrl); + LdapContextFactory contextFactory = initLdapContextFactory(LDAP_PROPERTY_PREFIX + "." + serverKey); contextFactories.put(serverKey, contextFactory); } } + + private LdapContextFactory initLdapContextFactory(String prefix) { + String ldapUrlKey = prefix + ".url"; + String ldapUrl = config.get(ldapUrlKey).orElse(null); + if (StringUtils.isBlank(ldapUrl)) { + throw new LdapException(String.format(MANDATORY_LDAP_PROPERTY_ERROR, ldapUrlKey)); + } + return new LdapContextFactory(config, prefix, ldapUrl); + } + } diff --git a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java index 4dfa51bbe6e..628cf187569 100644 --- a/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java +++ b/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/LdapUserMapping.java @@ -21,16 +21,14 @@ package org.sonar.auth.ldap; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.Configuration; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; + +import static org.sonar.auth.ldap.LdapSettingsManager.MANDATORY_LDAP_PROPERTY_ERROR; /** * @author Evgeny Mandrikov */ public class LdapUserMapping { - private static final Logger LOG = Loggers.get(LdapUserMapping.class); - private static final String DEFAULT_NAME_ATTRIBUTE = "cn"; private static final String DEFAULT_EMAIL_ATTRIBUTE = "mail"; private static final String DEFAULT_REQUEST = "(&(objectClass=inetOrgPerson)(uid={login}))"; @@ -44,17 +42,8 @@ public class LdapUserMapping { * Constructs mapping from Sonar settings. */ public LdapUserMapping(Configuration config, String settingsPrefix) { - String usesrBaseDnSettingKey = settingsPrefix + ".user.baseDn"; - String usersBaseDn = config.get(usesrBaseDnSettingKey).orElse(null); - if (usersBaseDn == null) { - String realm = config.get(settingsPrefix + ".realm").orElse(null); - if (realm != null) { - LOG.warn("Auto-discovery feature is deprecated, please use '{}' to specify user search dn", usesrBaseDnSettingKey); - usersBaseDn = LdapAutodiscovery.getDnsDomainDn(realm); - } - } - - this.baseDn = usersBaseDn; + String userBaseDnSettingKey = settingsPrefix + ".user.baseDn"; + this.baseDn = config.get(userBaseDnSettingKey).orElseThrow(() -> new LdapException(String.format(MANDATORY_LDAP_PROPERTY_ERROR, userBaseDnSettingKey))); this.realNameAttribute = StringUtils.defaultString(config.get(settingsPrefix + ".user.realNameAttribute").orElse(null), DEFAULT_NAME_ATTRIBUTE); this.emailAttribute = StringUtils.defaultString(config.get(settingsPrefix + ".user.emailAttribute").orElse(null), DEFAULT_EMAIL_ATTRIBUTE); diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapAuthenticatorTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapAuthenticatorTest.java index 2559d8836d9..550652c304f 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapAuthenticatorTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapAuthenticatorTest.java @@ -47,8 +47,7 @@ public class DefaultLdapAuthenticatorTest { exampleServer.disableAnonymousAccess(); try { LdapSettingsManager settingsManager = new LdapSettingsManager( - LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig(), - new LdapAutodiscovery()); + LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); boolean isAuthenticationSuccessful = authenticator.doAuthenticate(createContext("godin", "secret1")).isSuccess(); assertThat(isAuthenticationSuccessful).isTrue(); @@ -60,8 +59,7 @@ public class DefaultLdapAuthenticatorTest { @Test public void testSimple() { LdapSettingsManager settingsManager = new LdapSettingsManager( - LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig(), - new LdapAutodiscovery()); + LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapAuthenticationResult user1Success = authenticator.doAuthenticate(createContext("godin", "secret1")); @@ -85,7 +83,7 @@ public class DefaultLdapAuthenticatorTest { @Test public void testSimpleMultiLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( - LdapSettingsFactory.generateAuthenticationSettings(exampleServer, infosupportServer, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig(), new LdapAutodiscovery()); + LdapSettingsFactory.generateAuthenticationSettings(exampleServer, infosupportServer, LdapContextFactory.AUTH_METHOD_SIMPLE).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapAuthenticationResult user1Success = authenticator.doAuthenticate(createContext("godin", "secret1")); @@ -118,8 +116,7 @@ public class DefaultLdapAuthenticatorTest { @Test public void testSasl() { LdapSettingsManager settingsManager = new LdapSettingsManager( - LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_CRAM_MD5).asConfig(), - new LdapAutodiscovery()); + LdapSettingsFactory.generateAuthenticationSettings(exampleServer, null, LdapContextFactory.AUTH_METHOD_CRAM_MD5).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapAuthenticationResult user1Success = authenticator.doAuthenticate(createContext("godin", "secret1")); @@ -140,7 +137,7 @@ public class DefaultLdapAuthenticatorTest { @Test public void testSaslMultipleLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( - LdapSettingsFactory.generateAuthenticationSettings(exampleServer, infosupportServer, LdapContextFactory.AUTH_METHOD_CRAM_MD5).asConfig(), new LdapAutodiscovery()); + LdapSettingsFactory.generateAuthenticationSettings(exampleServer, infosupportServer, LdapContextFactory.AUTH_METHOD_CRAM_MD5).asConfig()); DefaultLdapAuthenticator authenticator = new DefaultLdapAuthenticator(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapAuthenticationResult user1Success = authenticator.doAuthenticate(createContext("godin", "secret1")); diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapGroupsProviderTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapGroupsProviderTest.java index 6a527e6cb0a..0e55abb96ee 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapGroupsProviderTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapGroupsProviderTest.java @@ -49,7 +49,7 @@ public class DefaultLdapGroupsProviderTest { public void doGetGroups_when_single_server_without_key() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, null); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); @@ -67,7 +67,7 @@ public class DefaultLdapGroupsProviderTest { public void doGetGroups_when_two_ldap_servers() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); @@ -91,7 +91,7 @@ public class DefaultLdapGroupsProviderTest { public void doGetGroups_when_two_ldap_servers_with_same_username_resolves_groups_from_right_server() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); @@ -106,7 +106,7 @@ public class DefaultLdapGroupsProviderTest { public void posix() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, null); settings.setProperty("ldap.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); @@ -119,7 +119,7 @@ public class DefaultLdapGroupsProviderTest { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); settings.setProperty("ldap.example.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); settings.setProperty("ldap.infosupport.group.request", "(&(objectClass=posixGroup)(memberUid={uid}))"); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); @@ -138,7 +138,7 @@ public class DefaultLdapGroupsProviderTest { public void mixed() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); settings.setProperty("ldap.example.group.request", "(&(|(objectClass=groupOfUniqueNames)(objectClass=posixGroup))(|(uniqueMember={dn})(memberUid={uid})))"); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); @@ -151,7 +151,7 @@ public class DefaultLdapGroupsProviderTest { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); settings.setProperty("ldap.example.group.request", "(&(|(objectClass=groupOfUniqueNames)(objectClass=posixGroup))(|(uniqueMember={dn})(memberUid={uid})))"); settings.setProperty("ldap.infosupport.group.request", "(&(|(objectClass=groupOfUniqueNames)(objectClass=posixGroup))(|(uniqueMember={dn})(memberUid={uid})))"); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapGroupsProvider groupsProvider = new DefaultLdapGroupsProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings(), settingsManager.getGroupMappings()); diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapUsersProviderTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapUsersProviderTest.java index cde909e415b..a5bdbc0124c 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapUsersProviderTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/DefaultLdapUsersProviderTest.java @@ -46,7 +46,7 @@ public class DefaultLdapUsersProviderTest { @Test public void test_user_from_first_server() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapUsersProvider usersProvider = new DefaultLdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapUserDetails details = usersProvider.doGetUserDetails(createContext("example", "godin")); @@ -57,7 +57,7 @@ public class DefaultLdapUsersProviderTest { @Test public void test_user_from_second_server() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapUsersProvider usersProvider = new DefaultLdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapUserDetails details = usersProvider.doGetUserDetails(createContext("infosupport", "robby")); @@ -69,7 +69,7 @@ public class DefaultLdapUsersProviderTest { @Test public void test_user_on_multiple_servers() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapUsersProvider usersProvider = new DefaultLdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapUserDetails detailsExample = usersProvider.doGetUserDetails(createContext("example", "tester")); @@ -84,7 +84,7 @@ public class DefaultLdapUsersProviderTest { @Test public void test_user_doesnt_exist() { MapSettings settings = LdapSettingsFactory.generateSimpleAnonymousAccessSettings(exampleServer, infosupportServer); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); DefaultLdapUsersProvider usersProvider = new DefaultLdapUsersProvider(settingsManager.getContextFactories(), settingsManager.getUserMappings()); LdapUserDetails details = usersProvider.doGetUserDetails(createContext("example", "notfound")); diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/KerberosTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/KerberosTest.java index b0e49f746d3..7eba029eef5 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/KerberosTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/KerberosTest.java @@ -46,7 +46,7 @@ public class KerberosTest { @Before public void before() { MapSettings settings = configure(); - ldapRealm = new LdapRealm(new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery())); + ldapRealm = new LdapRealm(new LdapSettingsManager(settings.asConfig())); ldapRealm.init(); authenticator = ldapRealm.doGetAuthenticator(); @@ -86,7 +86,7 @@ public class KerberosTest { public void wrong_bind_password() { MapSettings settings = configure() .setProperty("ldap.bindPassword", "wrong_bind_password"); - LdapRealm wrongPasswordRealm = new LdapRealm(new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery())); + LdapRealm wrongPasswordRealm = new LdapRealm(new LdapSettingsManager(settings.asConfig())); assertThatThrownBy(wrongPasswordRealm::init) .isInstanceOf(LdapException.class) diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapAutoDiscoveryWarningLogTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapAutoDiscoveryWarningLogTest.java deleted file mode 100644 index 45f8c4c389b..00000000000 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapAutoDiscoveryWarningLogTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.auth.ldap; - -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.utils.log.LogTester; -import org.sonar.api.utils.log.LoggerLevel; -import org.sonar.auth.ldap.server.ApacheDS; -import org.sonar.auth.ldap.server.LdapServer; - -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class LdapAutoDiscoveryWarningLogTest { - - @Rule - public LogTester logTester = new LogTester(); - - @ClassRule - public static LdapServer server = new LdapServer("/users.example.org.ldif"); - - @Test - public void does_not_display_log_when_not_using_auto_discovery() { - MapSettings settings = new MapSettings() - .setProperty("ldap.url", server.getUrl()); - LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery())); - realm.init(); - - assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty(); - } - - @Test - public void display_warning_log_when_using_auto_discovery_to_detect_server_url() { - LdapAutodiscovery ldapAutodiscovery = mock(LdapAutodiscovery.class); - when(ldapAutodiscovery.getLdapServers("example.org")).thenReturn(singletonList(new LdapAutodiscovery.LdapSrvRecord(server.getUrl(), 1, 1))); - // ldap.url setting is not set - LdapRealm realm = new LdapRealm(new LdapSettingsManager(new MapSettings().setProperty("ldap.realm", "example.org").asConfig(), - ldapAutodiscovery)); - realm.init(); - - assertThat(logTester.logs(LoggerLevel.WARN)).contains("Auto-discovery feature is deprecated, please use 'ldap.url' to specify LDAP url"); - } - - @Test - public void display_warning_log_when_using_auto_discovery_to_detect_user_baseDn_on_single_server() { - // ldap.user.baseDn setting is not set - MapSettings settings = new MapSettings().setProperty("ldap.url", server.getUrl()).setProperty("ldap.realm", "example.org"); - LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery())); - - realm.init(); - - assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("Auto-discovery feature is deprecated, please use 'ldap.user.baseDn' to specify user search dn"); - } - - @Test - public void display_warning_log_when_using_auto_discovery_to_detect_user_baseDn_on_multiple_servers() throws Exception { - ApacheDS server2 = ApacheDS.start("example.org", "dc=example,dc=org", "target/ldap-work2/"); - server2.importLdif(LdapAutoDiscoveryWarningLogTest.class.getResourceAsStream("/users.example.org.ldif")); - MapSettings settings = new MapSettings() - .setProperty("ldap.servers", "example,infosupport") - // ldap.XXX.user.baseDn settings are not set on both servers - .setProperty("ldap.example.url", server.getUrl()) - .setProperty("ldap.example.realm", "example.org") - .setProperty("ldap.infosupport.url", server2.getUrl()) - .setProperty("ldap.infosupport.realm", "infosupport.org"); - LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery())); - - realm.init(); - - assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly( - "Auto-discovery feature is deprecated, please use 'ldap.example.user.baseDn' to specify user search dn", - "Auto-discovery feature is deprecated, please use 'ldap.infosupport.user.baseDn' to specify user search dn"); - } - -} diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapAutodiscoveryTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapAutodiscoveryTest.java deleted file mode 100644 index 276075a8b60..00000000000 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapAutodiscoveryTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.auth.ldap; - -import java.net.UnknownHostException; -import java.util.Arrays; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import org.junit.Test; -import org.mockito.Mockito; -import org.sonar.auth.ldap.LdapAutodiscovery.LdapSrvRecord; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class LdapAutodiscoveryTest { - - @Test - public void testGetDnsDomain() { - assertThat(LdapAutodiscovery.getDnsDomainName("localhost")).isNull(); - assertThat(LdapAutodiscovery.getDnsDomainName("godin.example.org")).isEqualTo("example.org"); - assertThat(LdapAutodiscovery.getDnsDomainName("godin.usr.example.org")).isEqualTo("usr.example.org"); - } - - @Test - public void testGetDnsDomainWithoutParameter() { - try { - LdapAutodiscovery.getDnsDomainName(); - } catch (UnknownHostException e) { - fail(e.getMessage()); - } - } - - @Test - public void testGetDnsDomainDn() { - assertThat(LdapAutodiscovery.getDnsDomainDn("example.org")).isEqualTo("dc=example,dc=org"); - } - - @Test - public void testEqualsAndHashCode() { - assertThat(new LdapSrvRecord("http://foo:389", 1, 1)).isEqualTo(new LdapSrvRecord("http://foo:389", 2, 0)); - assertThat(new LdapSrvRecord("http://foo:389", 1, 1)).isNotEqualTo(new LdapSrvRecord("http://foo:388", 1, 1)); - - assertThat(new LdapSrvRecord("http://foo:389", 1, 1)).hasSameHashCodeAs(new LdapSrvRecord("http://foo:389", 1, 1).hashCode()); - } - - @Test - public void testGetLdapServer() throws NamingException { - DirContext context = mock(DirContext.class); - Attributes attributes = mock(Attributes.class); - Attribute attribute = mock(Attribute.class); - NamingEnumeration namingEnumeration = mock(NamingEnumeration.class); - - when(context.getAttributes(Mockito.anyString(), Mockito.any())).thenReturn(attributes); - when(attributes.get("srv")).thenReturn(attribute); - when(attribute.getAll()).thenReturn(namingEnumeration); - when(namingEnumeration.hasMore()).thenReturn(true, true, true, true, true, false); - when(namingEnumeration.next()) - .thenReturn("10 40 389 ldap5.example.org.") - .thenReturn("0 10 389 ldap3.example.org") - .thenReturn("0 60 389 ldap1.example.org") - .thenReturn("0 30 389 ldap2.example.org") - .thenReturn("10 60 389 ldap4.example.org"); - - assertThat(new LdapAutodiscovery().getLdapServers(context, "example.org.")).extracting("serverUrl") - .isEqualTo( - Arrays.asList("ldap://ldap1.example.org:389", "ldap://ldap2.example.org:389", "ldap://ldap3.example.org:389", "ldap://ldap4.example.org:389", - "ldap://ldap5.example.org:389")); - } - -} diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapModuleTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapModuleTest.java index 6496078dcc9..e0185d83ecc 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapModuleTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapModuleTest.java @@ -30,7 +30,7 @@ public class LdapModuleTest { public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new LdapModule().configure(container); - assertThat(container.getAddedObjects()).hasSize(3); + assertThat(container.getAddedObjects()).hasSize(2); } } diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapRealmTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapRealmTest.java index a194ace6ac3..8ebf44cdb09 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapRealmTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapRealmTest.java @@ -37,8 +37,9 @@ public class LdapRealmTest { @Test public void normal() { MapSettings settings = new MapSettings() - .setProperty("ldap.url", server.getUrl()); - LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery())); + .setProperty("ldap.url", server.getUrl()) + .setProperty("ldap.user.baseDn", "cn=users"); + LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig())); realm.init(); assertThat(realm.doGetAuthenticator()).isInstanceOf(DefaultLdapAuthenticator.class); assertThat(realm.getUsersProvider()).isInstanceOf(LdapUsersProvider.class).isInstanceOf(DefaultLdapUsersProvider.class); @@ -51,7 +52,7 @@ public class LdapRealmTest { .setProperty("ldap.url", "ldap://no-such-host") .setProperty("ldap.group.baseDn", "cn=groups,dc=example,dc=org") .setProperty("ldap.user.baseDn", "cn=users,dc=example,dc=org"); - LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery())); + LdapRealm realm = new LdapRealm(new LdapSettingsManager(settings.asConfig())); assertThatThrownBy(realm::init).isInstanceOf(LdapException.class).hasMessage("Unable to open LDAP connection"); assertThat(realm.doGetAuthenticator()).isInstanceOf(DefaultLdapAuthenticator.class); diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapReferralsTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapReferralsTest.java index 37c7d80432e..181d4bb0642 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapReferralsTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapReferralsTest.java @@ -64,6 +64,6 @@ public class LdapReferralsTest { if (propertyKey != null) { settings.setProperty(propertyKey, propertyValue); } - return new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()).getContextFactories(); + return new LdapSettingsManager(settings.asConfig()).getContextFactories(); } } diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSearchTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSearchTest.java index d584cf21476..1eb123503e6 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSearchTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSearchTest.java @@ -41,7 +41,7 @@ public class LdapSearchTest { @BeforeClass public static void init() { - contextFactories = new LdapSettingsManager(LdapSettingsFactory.generateSimpleAnonymousAccessSettings(server, null).asConfig(), new LdapAutodiscovery()).getContextFactories(); + contextFactories = new LdapSettingsManager(LdapSettingsFactory.generateSimpleAnonymousAccessSettings(server, null).asConfig()).getContextFactories(); } @Test @@ -57,7 +57,7 @@ public class LdapSearchTest { assertThat(search.getRequest()).isEqualTo("(objectClass={0})"); assertThat(search.getParameters()).isEqualTo(new String[] {"inetOrgPerson"}); assertThat(search.getReturningAttributes()).isEqualTo(new String[] {"objectClass"}); - assertThat(search.toString()).isEqualTo("LdapSearch{baseDn=dc=example,dc=org, scope=subtree, request=(objectClass={0}), parameters=[inetOrgPerson], attributes=[objectClass]}"); + assertThat(search).hasToString("LdapSearch{baseDn=dc=example,dc=org, scope=subtree, request=(objectClass={0}), parameters=[inetOrgPerson], attributes=[objectClass]}"); assertThat(enumerationToArrayList(search.find())) .extracting(SearchResult::getName) .containsExactlyInAnyOrder( @@ -70,7 +70,7 @@ public class LdapSearchTest { assertThatThrownBy(search::findUnique) .isInstanceOf(NamingException.class) - .hasMessage("Non unique result for " + search.toString()); + .hasMessage("Non unique result for " + search); } @Test @@ -88,7 +88,7 @@ public class LdapSearchTest { assertThat(search.getParameters()).isEqualTo(new String[] {"inetOrgPerson"}); assertThat(search.getReturningAttributes()).isEqualTo(new String[] {"cn"}); assertThat(search).hasToString("LdapSearch{baseDn=dc=example,dc=org, scope=onelevel, request=(objectClass={0}), parameters=[inetOrgPerson], attributes=[cn]}"); - assertThat(enumerationToArrayList(search.find()).size()).isZero(); + assertThat(enumerationToArrayList(search.find())).isEmpty(); assertThat(search.findUnique()).isNull(); } diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java index 581aece42db..3f19b726b9d 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java @@ -19,23 +19,21 @@ */ package org.sonar.auth.ldap; -import java.util.Arrays; -import java.util.Collections; +import java.util.Map; import org.junit.Test; +import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.sonar.auth.ldap.LdapAutodiscovery.LdapSrvRecord; +import static org.assertj.core.api.Assertions.entry; public class LdapSettingsManagerTest { @Test public void shouldFailWhenNoLdapUrl() { MapSettings settings = generateMultipleLdapSettingsWithUserAndGroupMapping(); settings.removeProperty("ldap.example.url"); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); assertThatThrownBy(settingsManager::getContextFactories) .isInstanceOf(LdapException.class) @@ -46,7 +44,7 @@ public class LdapSettingsManagerTest { public void shouldFailWhenMixingSingleAndMultipleConfiguration() { MapSettings settings = generateMultipleLdapSettingsWithUserAndGroupMapping(); settings.setProperty("ldap.url", "ldap://foo"); - LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); + LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig()); assertThatThrownBy(settingsManager::getContextFactories) .isInstanceOf(LdapException.class) @@ -56,7 +54,7 @@ public class LdapSettingsManagerTest { @Test public void testContextFactoriesWithSingleLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( - generateSingleLdapSettingsWithUserAndGroupMapping().asConfig(), new LdapAutodiscovery()); + generateSingleLdapSettingsWithUserAndGroupMapping().asConfig()); assertThat(settingsManager.getContextFactories()).hasSize(1); } @@ -67,73 +65,69 @@ public class LdapSettingsManagerTest { @Test public void testContextFactoriesWithMultipleLdap() { LdapSettingsManager settingsManager = new LdapSettingsManager( - generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig(), new LdapAutodiscovery()); + generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig()); assertThat(settingsManager.getContextFactories()).hasSize(2); // We do it twice to make sure the settings keep the same. assertThat(settingsManager.getContextFactories()).hasSize(2); } @Test - public void testAutodiscover() { - LdapAutodiscovery ldapAutodiscovery = mock(LdapAutodiscovery.class); - LdapSrvRecord ldap1 = new LdapSrvRecord("ldap://localhost:189", 1, 1); - LdapSrvRecord ldap2 = new LdapSrvRecord("ldap://localhost:1899", 1, 1); - when(ldapAutodiscovery.getLdapServers("example.org")).thenReturn(Arrays.asList(ldap1, ldap2)); - LdapSettingsManager settingsManager = new LdapSettingsManager( - generateAutodiscoverSettings().asConfig(), ldapAutodiscovery); - assertThat(settingsManager.getContextFactories()).hasSize(2); - } + public void getUserMappings_shouldCreateUserMappings_whenMultipleLdapConfig() { + Configuration configuration = generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig(); + LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); - @Test - public void testAutodiscoverFailed() { - LdapAutodiscovery ldapAutodiscovery = mock(LdapAutodiscovery.class); - when(ldapAutodiscovery.getLdapServers("example.org")).thenReturn(Collections.emptyList()); - LdapSettingsManager settingsManager = new LdapSettingsManager( - generateAutodiscoverSettings().asConfig(), ldapAutodiscovery); + Map<String, LdapUserMapping> result = settingsManager.getUserMappings(); - assertThatThrownBy(settingsManager::getContextFactories) - .isInstanceOf(LdapException.class) - .hasMessage("The property 'ldap.url' is empty and SonarQube is not able to auto-discover any LDAP server."); + assertThat(result).hasSize(2).containsOnlyKeys("example", "infosupport"); + assertThat(result.get("example")).usingRecursiveComparison().isEqualTo(new LdapUserMapping(configuration, "ldap.example")); + assertThat(result.get("infosupport")).usingRecursiveComparison().isEqualTo(new LdapUserMapping(configuration, "ldap.infosupport")); } - /** - * Test there are 2 @link{org.sonar.plugins.ldap.LdapUserMapping}s found. - * - */ @Test - public void testUserMappings() { - LdapSettingsManager settingsManager = new LdapSettingsManager( - generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig(), new LdapAutodiscovery()); - assertThat(settingsManager.getUserMappings()).hasSize(2); - // We do it twice to make sure the settings keep the same. - assertThat(settingsManager.getUserMappings()).hasSize(2); - } + public void getGroupMappings_shouldCreateGroupMappings_whenMultipleLdapConfig() { + Configuration configuration = generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig(); + LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); - /** - * Test there are 2 @link{org.sonar.plugins.ldap.LdapGroupMapping}s found. - * - */ - @Test - public void testGroupMappings() { - LdapSettingsManager settingsManager = new LdapSettingsManager( - generateMultipleLdapSettingsWithUserAndGroupMapping().asConfig(), new LdapAutodiscovery()); - assertThat(settingsManager.getGroupMappings()).hasSize(2); - // We do it twice to make sure the settings keep the same. - assertThat(settingsManager.getGroupMappings()).hasSize(2); + Map<String, LdapGroupMapping> result = settingsManager.getGroupMappings(); + + assertThat(result).hasSize(2).containsOnlyKeys("example", "infosupport"); + assertThat(result.get("example")).usingRecursiveComparison().isEqualTo(new LdapGroupMapping(configuration, "ldap.example")); + assertThat(result.get("infosupport")).usingRecursiveComparison().isEqualTo(new LdapGroupMapping(configuration, "ldap.infosupport")); } /** * Test what happens when no configuration is set. - * Normally there will be a contextFactory, but the autodiscovery doesn't work for the test server. */ @Test public void testEmptySettings() { LdapSettingsManager settingsManager = new LdapSettingsManager( - new MapSettings().asConfig(), new LdapAutodiscovery()); + new MapSettings().asConfig()); assertThatThrownBy(settingsManager::getContextFactories) .isInstanceOf(LdapException.class) - .hasMessage("The property 'ldap.url' is empty and no realm configured to try auto-discovery."); + .hasMessage("The property 'ldap.url' property is empty while it is mandatory."); + } + + @Test + public void getUserMappings_shouldCreateUserMappings_whenSingleLdapConfig() { + Configuration configuration = generateSingleLdapSettingsWithUserAndGroupMapping().asConfig(); + LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); + + Map<String, LdapUserMapping> result = settingsManager.getUserMappings(); + + assertThat(result).hasSize(1).containsOnlyKeys("default"); + assertThat(result.get("default")).usingRecursiveComparison().isEqualTo(new LdapUserMapping(configuration, "ldap")); + } + + @Test + public void getGroupMappings_shouldCreateGroupMappings_whenSingleLdapConfig() { + Configuration configuration = generateSingleLdapSettingsWithUserAndGroupMapping().asConfig(); + LdapSettingsManager settingsManager = new LdapSettingsManager(configuration); + + Map<String, LdapGroupMapping> result = settingsManager.getGroupMappings(); + + assertThat(result).hasSize(1).containsOnlyKeys("default"); + assertThat(result.get("default")).usingRecursiveComparison().isEqualTo(new LdapGroupMapping(configuration, "ldap")); } private MapSettings generateMultipleLdapSettingsWithUserAndGroupMapping() { @@ -170,16 +164,4 @@ public class LdapSettingsManagerTest { return settings; } - private MapSettings generateAutodiscoverSettings() { - MapSettings settings = new MapSettings(); - - settings.setProperty("ldap.realm", "example.org") - .setProperty("ldap.user.baseDn", "ou=users,dc=example,dc=org") - .setProperty("ldap.group.baseDn", "ou=groups,dc=example,dc=org") - .setProperty("ldap.group.request", - "(&(objectClass=posixGroup)(memberUid={uid}))"); - - return settings; - } - } diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapUserMappingTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapUserMappingTest.java index 10183a2747a..e4ae0ac163a 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapUserMappingTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapUserMappingTest.java @@ -20,22 +20,25 @@ package org.sonar.auth.ldap; import org.junit.Test; +import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LdapUserMappingTest { @Test public void defaults() { - LdapUserMapping userMapping = new LdapUserMapping(new MapSettings().asConfig(), "ldap"); - assertThat(userMapping.getBaseDn()).isNull(); + MapSettings mapSettings = new MapSettings().setProperty("ldap.user.baseDn", "cn=users"); + LdapUserMapping userMapping = new LdapUserMapping(mapSettings.asConfig(), "ldap"); + assertThat(userMapping.getBaseDn()).isEqualTo("cn=users"); assertThat(userMapping.getRequest()).isEqualTo("(&(objectClass=inetOrgPerson)(uid={0}))"); assertThat(userMapping.getRealNameAttribute()).isEqualTo("cn"); assertThat(userMapping.getEmailAttribute()).isEqualTo("mail"); assertThat(userMapping).hasToString("LdapUserMapping{" + - "baseDn=null," + + "baseDn=cn=users," + " request=(&(objectClass=inetOrgPerson)(uid={0}))," + " realNameAttribute=cn," + " emailAttribute=mail}"); @@ -62,14 +65,16 @@ public class LdapUserMappingTest { } @Test - public void realm() { - MapSettings settings = new MapSettings() + public void ldapUserMapping_shouldThrowException_whenUserBaseDnIsNotSet() { + Configuration config = new MapSettings() .setProperty("ldap.realm", "example.org") .setProperty("ldap.userObjectClass", "user") - .setProperty("ldap.loginAttribute", "sAMAccountName"); + .setProperty("ldap.loginAttribute", "sAMAccountName") + .asConfig(); - LdapUserMapping userMapping = new LdapUserMapping(settings.asConfig(), "ldap"); - assertThat(userMapping.getBaseDn()).isEqualTo("dc=example,dc=org"); + assertThatThrownBy(() -> new LdapUserMapping(config, "ldap")) + .isInstanceOf(LdapException.class) + .hasMessage("The property 'ldap.user.baseDn' property is empty while it is mandatory."); } } |