Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,21 +144,7 @@ public LDAPConnectionContext(RealmConfiguration realmConfig) throws UserStoreExc
String connectionURL = null;
//if DNS enabled in AD case, this can be null
if (rawConnectionURL != null) {
String portInfo = rawConnectionURL.split(":")[2];

String port = null;

// if the port contains a template string that refers to carbon.xml
if ((portInfo.contains("${")) && (portInfo.contains("}"))) {
port = Integer.toString(CarbonUtils.getPortFromServerConfig(portInfo));
}

if (port != null) {
connectionURL = rawConnectionURL.replace(portInfo, port);
} else {
// if embedded-ldap is not enabled,
connectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
}
connectionURL = resolvePort(rawConnectionURL);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log Improvement Suggestion No: 1

Suggested change
connectionURL = resolvePort(rawConnectionURL);
connectionURL = resolvePort(rawConnectionURL);
log.debug("Resolved LDAP connection URL: {}", connectionURL);

}

String connectionName = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME);
Expand Down Expand Up @@ -1123,4 +1109,65 @@ protected long getValidatedThresholdTimeoutInMilliseconds(long retryWaitingTime)
throw new UserStoreException("Error occurred while parsing ConnectionRetryDelay property value.");
}
}

/**
* Resolves the port for the connection URL.
* The port number is optional, according to the LDAP URL spec.
* Therefore, if the port number isn't present, LDAP URL should default to port 389
* and LDAPS URL should default to port 636.
* See spec: https://ldapwiki.com/wiki/Wiki.jsp?page=LDAP+URL
*
* @param url The LDAP URL to resolve.
* @return The URL with resolved port.
*/
private static String resolvePort(String url) {

if (StringUtils.isEmpty(url)) {
return url;
}
Comment on lines +1125 to +1127
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log Improvement Suggestion No: 2

Suggested change
if (StringUtils.isEmpty(url)) {
return url;
}
if (StringUtils.isEmpty(url)) {
log.debug("LDAP URL is empty, returning as-is");
return url;
}


url = url.trim();
int schemeIndex = url.indexOf(LDAPConstants.URL_SCHEME_SEPARATOR);
if (schemeIndex == -1) {
return url;
}

String scheme = url.substring(0, schemeIndex);
String rest = url.substring(schemeIndex + LDAPConstants.URL_SCHEME_SEPARATOR.length());

String hostAndPort;
String path = "";
int pathIndex = rest.indexOf("/");
if (pathIndex != -1) {
hostAndPort = rest.substring(0, pathIndex);
path = rest.substring(pathIndex);
} else {
hostAndPort = rest;
}

// Handle IPv6: [2001:db8::1]:389
int lastColonIndex = hostAndPort.lastIndexOf(':');
int lastBracketIndex = hostAndPort.lastIndexOf(']');

if (lastColonIndex != -1 && lastColonIndex > lastBracketIndex) {
// Port is present.
String portInfo = hostAndPort.substring(lastColonIndex + 1);
// If the port contains a template string that refers to carbon.xml.
if (portInfo.contains("${") && portInfo.contains("}")) {
int resolvedPort = CarbonUtils.getPortFromServerConfig(portInfo);
if (resolvedPort != -1) {
return scheme + LDAPConstants.URL_SCHEME_SEPARATOR + hostAndPort.substring(0, lastColonIndex) +
":" + resolvedPort + path;
}
}
return url;
} else {
// Port is missing, add default port.
int defaultPort = LDAPConstants.LDAP_DEFAULT_PORT;
if (LDAPConstants.LDAPS_SCHEME.equalsIgnoreCase(scheme)) {
defaultPort = LDAPConstants.LDAPS_DEFAULT_PORT;
}
return scheme + LDAPConstants.URL_SCHEME_SEPARATOR + hostAndPort + ":" + defaultPort + path;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ public class LDAPConstants {
public static final String SHARED_TENANT_OBJECT_CLASS = "SharedTenantObjectClass";

public static final String CONNECTION_POOLING_ENABLED = "ConnectionPoolingEnabled";

public static final int LDAP_DEFAULT_PORT = 389;
public static final int LDAPS_DEFAULT_PORT = 636;
public static final String LDAPS_SCHEME = "ldaps";
public static final String URL_SCHEME_SEPARATOR = "://";
public static final String USER_CACHE_EXPIRY_MILLISECONDS = "UserCacheExpiryMilliseconds";
public static final String USER_DN_CACHE_ENABLED = "UserDNCacheEnabled";

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.wso2.carbon.user.core.ldap;

import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.wso2.carbon.utils.CarbonUtils;

import java.lang.reflect.Method;

import static org.mockito.ArgumentMatchers.anyString;

/**
* Unit tests for LDAPConnectionContext class.
*/
public class LDAPConnectionContextTest {

private String invokeResolvePort(String url) throws Exception {

Method method = LDAPConnectionContext.class.getDeclaredMethod("resolvePort", String.class);
method.setAccessible(true);
return (String) method.invoke(null, url);
}

@DataProvider(name = "urlDataProvider")
public Object[][] urlDataProvider() {

return new Object[][]{
{"ldap://localhost:389", "ldap://localhost:389"},
{"ldap://localhost", "ldap://localhost:389"},
{"ldaps://localhost", "ldaps://localhost:636"},
{"ldap://127.0.0.1:389", "ldap://127.0.0.1:389"},
{"ldap://127.0.0.1", "ldap://127.0.0.1:389"},
{"ldaps://127.0.0.1", "ldaps://127.0.0.1:636"},
{"ldap://[2001:db8::1]:389", "ldap://[2001:db8::1]:389"},
{"ldap://[2001:db8::1]", "ldap://[2001:db8::1]:389"},
{"ldap://localhost/dc=wso2,dc=org", "ldap://localhost:389/dc=wso2,dc=org"},
{" ldap://localhost ", "ldap://localhost:389"}
};
}

@Test(dataProvider = "urlDataProvider")
public void testResolvePort(String url, String expectedUrl) throws Exception {

String resolvedUrl = invokeResolvePort(url);
Assert.assertEquals(resolvedUrl, expectedUrl, "URL resolution failed for: " + url);
}

@Test
public void testResolvePortWithTemplate() throws Exception {

String template = "Ports.EmbeddedLDAP.LDAPServerPort";
int portValue = 10389;

try (MockedStatic<CarbonUtils> carbonUtilsMock = Mockito.mockStatic(CarbonUtils.class)) {
carbonUtilsMock.when(() -> CarbonUtils.getPortFromServerConfig(anyString())).thenReturn(portValue);

String url = "ldap://localhost:${" + template + "}";
String expectedUrl = "ldap://localhost:" + portValue;

String resolvedUrl = invokeResolvePort(url);
Assert.assertEquals(resolvedUrl, expectedUrl, "Template resolution failed");
}
}
}