Skip to content
Draft
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
@@ -0,0 +1,82 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF 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.apache.cloudstack.api.command;

import javax.inject.Inject;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.DomainResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.ldap.LdapManager;

import com.cloud.user.Account;

@APICommand(name = "ldapTestConfiguration", description = "Tests connectivity to an LDAP server without saving a configuration", responseObject = SuccessResponse.class,
since = "24.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class LdapTestConfigurationCmd extends BaseCmd {

@Inject

Check warning on line 36 in plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/api/command/LdapTestConfigurationCmd.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this field injection and use constructor injection instead.

See more on https://sonarcloud.io/project/issues?id=apache_cloudstack&issues=AaGcDtjxhoNVqYq0MzAF&open=AaGcDtjxhoNVqYq0MzAF&pullRequest=13954
private LdapManager ldapManager;

@Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname")
private String hostname;

@Parameter(name = ApiConstants.PORT, type = CommandType.INTEGER, description = "Port")
private int port;

@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "Linked Domain")
private Long domainId;

public LdapTestConfigurationCmd() {
super();
}

public LdapTestConfigurationCmd(final LdapManager ldapManager) {
super();
this.ldapManager = ldapManager;
}

public String getHostname() {
return hostname;
}

public int getPort() {
return port;
}

public Long getDomainId() {
return domainId;
}

@Override
public void execute() throws ServerApiException {
// a failing bind throws InvalidParameterValueException, which is reported to the caller as an API error
ldapManager.testConnection(this);
SuccessResponse response = new SuccessResponse(getCommandName());
response.setDisplayText("Successfully connected to the LDAP server");
setResponseObject(response);
}

@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.apache.cloudstack.api.command.LdapAddConfigurationCmd;
import org.apache.cloudstack.api.command.LdapDeleteConfigurationCmd;
import org.apache.cloudstack.api.command.LdapListConfigurationCmd;
import org.apache.cloudstack.api.command.LdapTestConfigurationCmd;
import org.apache.cloudstack.api.command.LinkAccountToLdapCmd;
import org.apache.cloudstack.api.command.LinkDomainToLdapCmd;
import org.apache.cloudstack.api.command.UnlinkDomainFromLdapCmd;
Expand All @@ -41,6 +42,8 @@ enum LinkType { GROUP, OU }

LdapConfigurationResponse addConfiguration(String hostname, int port, Long domainId) throws InvalidParameterValueException;

void testConnection(LdapTestConfigurationCmd cmd) throws InvalidParameterValueException;

boolean canAuthenticate(String principal, String password, final Long domainId);

LdapConfigurationResponse createLdapConfigurationResponse(LdapConfigurationVO configuration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.apache.cloudstack.api.command.LdapImportUsersCmd;
import org.apache.cloudstack.api.command.LdapListConfigurationCmd;
import org.apache.cloudstack.api.command.LdapListUsersCmd;
import org.apache.cloudstack.api.command.LdapTestConfigurationCmd;
import org.apache.cloudstack.api.command.LdapUserSearchCmd;
import org.apache.cloudstack.api.command.LinkAccountToLdapCmd;
import org.apache.cloudstack.api.command.LinkDomainToLdapCmd;
Expand Down Expand Up @@ -175,30 +176,47 @@ private LdapConfigurationResponse addConfigurationInternal(final String hostname
// hostname:port is unique for domain binding
LdapConfigurationVO configuration = _ldapConfigurationDao.find(hostname, port, domainId);
if (configuration == null) {
LdapContext context = null;
try {
final String providerUrl = "ldap://" + hostname + ":" + port;
context = _ldapContextFactory.createBindContext(providerUrl,domainId);
configuration = new LdapConfigurationVO(hostname, port, domainId);
_ldapConfigurationDao.persist(configuration);
logger.info("Added a new LDAP server with URL: {}{}", providerUrl, domainId == null ? "" : " for domain " + domainId);
return createLdapConfigurationResponse(configuration);
} catch (NamingException | IOException e) {
logger.debug("NamingException while doing an LDAP bind", e);
throw new InvalidParameterValueException("Unable to bind to the given LDAP server");
} catch (RuntimeException e) {
if (e.getMessage().contains("Invalid truststore")) {
throw new InvalidParameterValueException("Invalid truststore or truststore password");
}
throw e;
} finally {
closeContext(context);
}
testBind(hostname, port, domainId);
configuration = new LdapConfigurationVO(hostname, port, domainId);
_ldapConfigurationDao.persist(configuration);
logger.info("Added a new LDAP server with URL: ldap://{}:{}{}", hostname, port, domainId == null ? "" : " for domain " + domainId);
return createLdapConfigurationResponse(configuration);
} else {
throw new InvalidParameterValueException("Duplicate configuration");
}
}

@Override
public void testConnection(LdapTestConfigurationCmd cmd) throws InvalidParameterValueException {
int port = cmd.getPort();
if (port <= 0) {
port = 389;
}
testBind(cmd.getHostname(), port, cmd.getDomainId());
}

/**
* Binds to the given LDAP server without persisting a configuration, so both adding a new
* configuration and {@link #testConnection} can share the same connectivity check.
*/
private void testBind(final String hostname, final int port, final Long domainId) throws InvalidParameterValueException {
LdapContext context = null;
try {
final String providerUrl = "ldap://" + hostname + ":" + port;
context = _ldapContextFactory.createBindContext(providerUrl, domainId);
} catch (NamingException | IOException e) {
logger.debug("NamingException while doing an LDAP bind", e);
throw new InvalidParameterValueException("Unable to bind to the given LDAP server");
} catch (RuntimeException e) {
if (StringUtils.contains(e.getMessage(), "Invalid truststore")) {
throw new InvalidParameterValueException("Invalid truststore or truststore password");
}
throw e;
} finally {
closeContext(context);
}
}

/**
* TODO decide if the principal is good enough to get the domain id or we need to add it as parameter
* @param principal ldap user
Expand Down Expand Up @@ -302,6 +320,7 @@ public List<Class<?>> getCommands() {
cmdList.add(LdapUserSearchCmd.class);
cmdList.add(LdapListUsersCmd.class);
cmdList.add(LdapAddConfigurationCmd.class);
cmdList.add(LdapTestConfigurationCmd.class);
cmdList.add(LdapDeleteConfigurationCmd.class);
cmdList.add(LdapListConfigurationCmd.class);
cmdList.add(LdapCreateAccountCmd.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF 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.apache.cloudstack.api.command;

import com.cloud.exception.InvalidParameterValueException;
import com.cloud.user.Account;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.ldap.LdapManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;

/**
* Tests {@link LdapTestConfigurationCmd}: a successful bind yields a success response, a failed
* bind propagates as an error rather than a response reporting success=false.
*/
@RunWith(MockitoJUnitRunner.class)
public class LdapTestConfigurationCmdTest {

@Mock
private LdapManager ldapManager;

private LdapTestConfigurationCmd cmd;

@Before
public void setUp() {
cmd = new LdapTestConfigurationCmd(ldapManager);
ReflectionTestUtils.setField(cmd, "hostname", "ldap.example.com");
ReflectionTestUtils.setField(cmd, "port", 389);
ReflectionTestUtils.setField(cmd, "domainId", 1L);
}

@Test
public void executeReturnsSuccessResponseWhenBindSucceeds() {
cmd.execute();

verify(ldapManager).testConnection(cmd);
SuccessResponse response = (SuccessResponse) cmd.getResponseObject();
assertTrue(response.getSuccess());
assertEquals("ldaptestconfigurationresponse", response.getResponseName());
assertEquals("Successfully connected to the LDAP server", response.getDisplayText());
}

@Test
public void executePropagatesBindFailure() {
doThrow(new InvalidParameterValueException("Unable to bind to the given LDAP server")).when(ldapManager).testConnection(cmd);

InvalidParameterValueException e = assertThrows(InvalidParameterValueException.class, () -> cmd.execute());

assertEquals("Unable to bind to the given LDAP server", e.getMessage());
assertNull(cmd.getResponseObject());
}

@Test
public void gettersExposeParameters() {
assertEquals("ldap.example.com", cmd.getHostname());
assertEquals(389, cmd.getPort());
assertEquals(Long.valueOf(1L), cmd.getDomainId());
assertEquals(Account.ACCOUNT_ID_SYSTEM, cmd.getEntityOwnerId());
}
}
Loading
Loading