<commit_before>/*
 * 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.jackrabbit.oak.security.authentication.ldap;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.jcr.SimpleCredentials;
import javax.security.auth.login.LoginException;

import com.google.common.collect.ImmutableMap;
import org.apache.directory.server.constants.ServerDNConstants;
import org.apache.jackrabbit.oak.security.authentication.ldap.impl.LdapIdentityProvider;
import org.apache.jackrabbit.oak.security.authentication.ldap.impl.LdapProviderConfig;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalGroup;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentity;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityRef;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalUser;
import org.apache.jackrabbit.util.Text;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Ignore;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;

import static org.junit.Assert.assertThat;

public class LdapProviderTest {

    protected static final InternalLdapServer LDAP_SERVER = new InternalLdapServer();

    //initialize LDAP server only once (fast, but might turn out to be not sufficiently flexible in the future)
    protected static final boolean USE_COMMON_LDAP_FIXTURE = false;

    private static final String TUTORIAL_LDIF = "apache-ds-tutorial.ldif";

    public static final String IDP_NAME = "ldap";

    protected LdapIdentityProvider idp;

    protected LdapProviderConfig providerConfig;

    @BeforeClass
    public static void beforeClass() throws Exception {
        if (USE_COMMON_LDAP_FIXTURE) {
            LDAP_SERVER.setUp();
            initLdapFixture(LDAP_SERVER);
        }
    }

    @AfterClass
    public static void afterClass() throws Exception {
        if (USE_COMMON_LDAP_FIXTURE) {
            LDAP_SERVER.tearDown();
        }
    }

    @Before
    public void before() throws Exception {
        if (!USE_COMMON_LDAP_FIXTURE) {
            LDAP_SERVER.setUp();
            initLdapFixture(LDAP_SERVER);
        }
        idp = createIDP();
    }

    @After
    public void after() throws Exception {
        if (!USE_COMMON_LDAP_FIXTURE) {
            LDAP_SERVER.tearDown();
        }
        idp.close();
        idp = null;
    }

    protected LdapIdentityProvider createIDP() {
        providerConfig = new LdapProviderConfig()
                .setName(IDP_NAME)
                .setHostname("127.0.0.1")
                .setPort(LDAP_SERVER.getPort())
                .setBindDN(ServerDNConstants.ADMIN_SYSTEM_DN)
                .setBindPassword(InternalLdapServer.ADMIN_PW)
                .setGroupMemberAttribute("uniquemember");

        providerConfig.getUserConfig()
                .setBaseDN(ServerDNConstants.USERS_SYSTEM_DN)
                .setObjectClasses("inetOrgPerson");
        providerConfig.getGroupConfig()
                .setBaseDN(ServerDNConstants.GROUPS_SYSTEM_DN)
                .setObjectClasses("groupOfUniqueNames");

        providerConfig.getAdminPoolConfig().setMaxActive(0);
        providerConfig.getUserPoolConfig().setMaxActive(0);
        return new LdapIdentityProvider(providerConfig);
    }

    protected static void initLdapFixture(InternalLdapServer server) throws Exception {
        InputStream tutorialLDIF = LdapProviderTest.class.getResourceAsStream(TUTORIAL_LDIF);
        server.loadLdif(tutorialLDIF);
    }

    public static final String TEST_USER0_DN = "cn=<NAME>,ou=users,ou=system";
    public static final String TEST_USER0_UID = "ratty";

    public static final String TEST_USER1_DN = "cn=Horatio Hornblower,ou=users,ou=system";
    public static final String TEST_USER1_UID = "hhornblo";
    public static final String TEST_USER1_PATH = "cn=Horatio Hornblower/ou=users/ou=system";

    public static final String TEST_USER2_DN = "cn=<NAME>,ou=users,ou=system";
    public static final String TEST_USER3_DN = "cn=<NAME>,ou=users,ou=system";
    public static final String TEST_USER4_DN = "cn=<NAME>,ou=users,ou=system";

    public static final String TEST_USER5_UID = "=007=";
    public static final String TEST_USER5_DN = "cn=Special\\, Agent [007],ou=users,ou=system";
    public static final String TEST_USER5_PATH = "cn=Special\\, Agent %5B007%5D/ou=users/ou=system";

    public static final String TEST_GROUP1_DN = "cn=HMS Lydia,ou=crews,ou=groups,ou=system";
    public static final String TEST_GROUP1_NAME = "HMS Lydia";
    public static final String[] TEST_GROUP1_MEMBERS = {
            TEST_USER0_DN, TEST_USER1_DN, TEST_USER2_DN, TEST_USER3_DN, TEST_USER4_DN
    };

    public static final String TEST_GROUP2_DN = "cn=HMS Victory,ou=crews,ou=groups,ou=system";
    public static final String TEST_GROUP2_NAME = "HMS Victory";

    public static final String TEST_GROUP3_DN = "cn=HMS Bounty,ou=crews,ou=groups,ou=system";
    public static final String TEST_GROUP3_NAME = "HMS Bounty";

    public static final String[] TEST_USER0_GROUPS = {TEST_GROUP1_DN, TEST_GROUP2_DN, TEST_GROUP3_DN};
    public static final String[] TEST_USER1_GROUPS = {TEST_GROUP1_DN};

    @Test
    public void testGetUserByRef() throws Exception {
        ExternalIdentityRef ref = new ExternalIdentityRef(TEST_USER1_DN, IDP_NAME);
        ExternalIdentity id = idp.getIdentity(ref);
        assertTrue("User instance", id instanceof ExternalUser);
        assertEquals("User ID", TEST_USER1_UID, id.getId());
    }

    @Test
    public void testGetUserByUserId() throws Exception {
        ExternalUser user = idp.getUser(TEST_USER1_UID);
        assertNotNull("User 1 must exist", user);
        assertEquals("User Ref", TEST_USER1_DN, user.getExternalId().getId());
    }

    @Test
    @Ignore("OAK-3144")
    public void testGetUserProperties() throws Exception {
        ExternalUser user = idp.getUser(TEST_USER1_UID);
        assertNotNull("User 1 must exist", user);
        List<String> multiValuePropValue = Arrays.asList(new String[] { "top", "person", "organizationalPerson", "inetOrgPerson"});
        Map<String, Object> properties = new ImmutableMap.Builder<String, Object>()
                .put("uid", "hhornblo")
                .put("mail", "<EMAIL>")
                .put("givenname", "Horatio")
                .put("description", "Capt. Horatio Hornblower, R.N")
                .put("sn", "Hornblower")
                .put("cn", "Horatio Hornblower")
                .put("objectclass", multiValuePropValue)
                .build();
        assertThat((Map<String, Object>) user.getProperties(), Matchers.<Map<String, Object>>equalTo(properties));
    }

    @Test
    public void testAuthenticate() throws Exception {
        SimpleCredentials creds = new SimpleCredentials(TEST_USER1_UID, "<PASSWORD>".toCharArray());
        ExternalUser user = idp.authenticate(creds);
        assertNotNull("User 1 must authenticate", user);
        assertEquals("User Ref", TEST_USER1_DN, user.getExternalId().getId());
    }

    @Test
    public void testAuthenticateValidateFalseFalse() throws Exception {
        providerConfig.getAdminPoolConfig()
                .setMaxActive(2)
                .setLookupOnValidate(false);
        providerConfig.getUserPoolConfig()
                .setMaxActive(2)
                .setLookupOnValidate(false);
        idp.close();
        idp = new LdapIdentityProvider(providerConfig);

        SimpleCredentials creds = new SimpleCredentials(TEST_USER1_UID, "<PASSWORD>".toCharArray());
        for (int i=0; i<8; i++) {
            ExternalUser user = idp.authenticate(creds);<commit_msg>OAK-3144: Support multivalue user properties for Ldap users<commit_after>/*
 * 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.jackrabbit.oak.security.authentication.ldap;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.jcr.SimpleCredentials;
import javax.security.auth.login.LoginException;

import com.google.common.collect.ImmutableMap;
import org.apache.directory.server.constants.ServerDNConstants;
import org.apache.jackrabbit.oak.security.authentication.ldap.impl.LdapIdentityProvider;
import org.apache.jackrabbit.oak.security.authentication.ldap.impl.LdapProviderConfig;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalGroup;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentity;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityRef;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalUser;
import org.apache.jackrabbit.util.Text;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Ignore;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;

import static org.junit.Assert.assertThat;

public class LdapProviderTest {

    protected static final InternalLdapServer LDAP_SERVER = new InternalLdapServer();

    //initialize LDAP server only once (fast, but might turn out to be not sufficiently flexible in the future)
    protected static final boolean USE_COMMON_LDAP_FIXTURE = false;

    private static final String TUTORIAL_LDIF = "apache-ds-tutorial.ldif";

    public static final String IDP_NAME = "ldap";

    protected LdapIdentityProvider idp;

    protected LdapProviderConfig providerConfig;

    @BeforeClass
    public static void beforeClass() throws Exception {
        if (USE_COMMON_LDAP_FIXTURE) {
            LDAP_SERVER.setUp();
            initLdapFixture(LDAP_SERVER);
        }
    }

    @AfterClass
    public static void afterClass() throws Exception {
        if (USE_COMMON_LDAP_FIXTURE) {
            LDAP_SERVER.tearDown();
        }
    }

    @Before
    public void before() throws Exception {
        if (!USE_COMMON_LDAP_FIXTURE) {
            LDAP_SERVER.setUp();
            initLdapFixture(LDAP_SERVER);
        }
        idp = createIDP();
    }

    @After
    public void after() throws Exception {
        if (!USE_COMMON_LDAP_FIXTURE) {
            LDAP_SERVER.tearDown();
        }
        idp.close();
        idp = null;
    }

    protected LdapIdentityProvider createIDP() {
        providerConfig = new LdapProviderConfig()
                .setName(IDP_NAME)
                .setHostname("127.0.0.1")
                .setPort(LDAP_SERVER.getPort())
                .setBindDN(ServerDNConstants.ADMIN_SYSTEM_DN)
                .setBindPassword(InternalLdapServer.ADMIN_PW)
                .setGroupMemberAttribute("uniquemember");

        providerConfig.getUserConfig()
                .setBaseDN(ServerDNConstants.USERS_SYSTEM_DN)
                .setObjectClasses("inetOrgPerson");
        providerConfig.getGroupConfig()
                .setBaseDN(ServerDNConstants.GROUPS_SYSTEM_DN)
                .setObjectClasses("groupOfUniqueNames");

        providerConfig.getAdminPoolConfig().setMaxActive(0);
        providerConfig.getUserPoolConfig().setMaxActive(0);
        return new LdapIdentityProvider(providerConfig);
    }

    protected static void initLdapFixture(InternalLdapServer server) throws Exception {
        InputStream tutorialLDIF = LdapProviderTest.class.getResourceAsStream(TUTORIAL_LDIF);
        server.loadLdif(tutorialLDIF);
    }

    public static final String TEST_USER0_DN = "cn=<NAME>,ou=users,ou=system";
    public static final String TEST_USER0_UID = "ratty";

    public static final String TEST_USER1_DN = "cn=Horatio Hornblower,ou=users,ou=system";
    public static final String TEST_USER1_UID = "hhornblo";
    public static final String TEST_USER1_PATH = "cn=Horatio Hornblower/ou=users/ou=system";

    public static final String TEST_USER2_DN = "cn=<NAME>,ou=users,ou=system";
    public static final String TEST_USER3_DN = "cn=<NAME>,ou=users,ou=system";
    public static final String TEST_USER4_DN = "cn=<NAME>,ou=users,ou=system";

    public static final String TEST_USER5_UID = "=007=";
    public static final String TEST_USER5_DN = "cn=Special\\, Agent [007],ou=users,ou=system";
    public static final String TEST_USER5_PATH = "cn=Special\\, Agent %5B007%5D/ou=users/ou=system";

    public static final String TEST_GROUP1_DN = "cn=HMS Lydia,ou=crews,ou=groups,ou=system";
    public static final String TEST_GROUP1_NAME = "HMS Lydia";
    public static final String[] TEST_GROUP1_MEMBERS = {
            TEST_USER0_DN, TEST_USER1_DN, TEST_USER2_DN, TEST_USER3_DN, TEST_USER4_DN
    };

    public static final String TEST_GROUP2_DN = "cn=HMS Victory,ou=crews,ou=groups,ou=system";
    public static final String TEST_GROUP2_NAME = "HMS Victory";

    public static final String TEST_GROUP3_DN = "cn=HMS Bounty,ou=crews,ou=groups,ou=system";
    public static final String TEST_GROUP3_NAME = "HMS Bounty";

    public static final String[] TEST_USER0_GROUPS = {TEST_GROUP1_DN, TEST_GROUP2_DN, TEST_GROUP3_DN};
    public static final String[] TEST_USER1_GROUPS = {TEST_GROUP1_DN};

    @Test
    public void testGetUserByRef() throws Exception {
        ExternalIdentityRef ref = new ExternalIdentityRef(TEST_USER1_DN, IDP_NAME);
        ExternalIdentity id = idp.getIdentity(ref);
        assertTrue("User instance", id instanceof ExternalUser);
        assertEquals("User ID", TEST_USER1_UID, id.getId());
    }

    @Test
    public void testGetUserByUserId() throws Exception {
        ExternalUser user = idp.getUser(TEST_USER1_UID);
        assertNotNull("User 1 must exist", user);
        assertEquals("User Ref", TEST_USER1_DN, user.getExternalId().getId());
    }

    @Test
    public void testGetUserProperties() throws Exception {
        ExternalUser user = idp.getUser(TEST_USER1_UID);
        assertNotNull("User 1 must exist", user);

        Map<String, ?> properties = user.getProperties();
        assertThat((Map<String, Collection<String>>) properties,
                Matchers.<String, Collection<String>>hasEntry(
                        Matchers.equalTo("objectclass"),
                        Matchers.containsInAnyOrder( "inetOrgPerson", "top", "person", "organizationalPerson")));
        assertThat(properties, Matchers.<String, Object>hasEntry("uid", "hhornblo"));
        assertThat(properties, Matchers.<String, Object>hasEntry("mail", "<EMAIL>"));
        assertThat(properties, Matchers.<String, Object>hasEntry("givenname", "Horatio"));
        assertThat(properties, Matchers.<String, Object>hasEntry("description", "Capt. <NAME>, R.N"));
        assertThat(properties, Matchers.<String, Object>hasEntry("sn", "Hornblower"));
    }

    @Test
    public void testAuthenticate() throws Exception {
        SimpleCredentials creds = new SimpleCredentials(TEST_USER1_UID, "<PASSWORD>".toCharArray());
        ExternalUser user = idp.authenticate(creds);
        assertNotNull("User 1 must authenticate", user);
        assertEquals("User Ref", TEST_USER1_DN, user.getExternalId().getId());
    }

    @Test
    public void testAuthenticateValidateFalseFalse() throws Exception {
        providerConfig.getAdminPoolConfig()
                .setMaxActive(2)
                .setLookupOnValidate(false);
        providerConfig.getUserPoolConfig()
                .setMaxActive(2)
                .setLookupOnValidate(false);
        idp.close();
        idp = new LdapIdentityProvider(providerConfig);

        SimpleCredentials creds = new SimpleCredentials(TEST_USER1_UID, "<PASSWORD>".toCharArray());
        for (int i=0; i<8; i++) {
            ExternalUser user = idp.authenticate(creds);
{'fraction_non_alphanumeric': 0.09669467787114847, 'fraction_numerical': 0.007955182072829131, 'mean_word_length': 3.5795279630579784, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 34, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '836364', 'n_tokens_mistral': 5244, 'n_tokens_neox': 5124, 'n_words': 1197}