<commit_before>/*
 * Telefónica Digital - Product Development and Innovation
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
 * All rights reserved.
 */

package es.tid.cosmos.platform.injection.server;

import java.io.File;
import java.sql.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import es.tid.cosmos.base.util.Logger;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

/**
 * FrontendPasswordTest
 *
 * @author logc
 */
public class FrontendPasswordTest extends BaseSftpTest {

    private static final org.apache.log4j.Logger LOGGER =
            Logger.get(FrontendPassword.class);
    private static final org.apache.log4j.Logger TEST_LOGGER =
            Logger.get(FrontendPasswordTest.class);

    private FrontendPassword instance;
    private String fileName;
    private String frontendDbUrl;
    private Connection connection;

    public FrontendPasswordTest() {
        super(LOGGER);
    }

    @Before
    public void setUp() throws Exception {
        this.instance = new FrontendPassword();
        this.fileName = "test.db";
        this.frontendDbUrl = "jdbc:sqlite:" + fileName;
        Class.forName("org.sqlite.JDBC").newInstance();
        this.connection = DriverManager.getConnection(this.frontendDbUrl);
        Statement stat = this.connection.createStatement();
        stat.executeUpdate("DROP TABLE IF EXISTS auth_user");
        //  As dumped from frontend temporary database on 2012-05-15 with the
        //  following commands:
        //  bin/django syncdb; sqlite3 /tmp/cosmos.db; > .schema auth_user

        //  Unused fields (e.g. first_name) were ignored
        String createStatement = "CREATE TABLE \"auth_user\" (\n" +
                "    \"username\" varchar(30) NOT NULL UNIQUE,\n" +
                "    \"password\" varchar(128) NOT NULL\n" +
                ");";
        stat.executeUpdate(createStatement);
        // as dumped from frontend temporary database on 2012-05-15 with the
        // following commands:
        // > SELECT username, password FROM auth_user;
        String usernameColContent1 = "test";
        String passwordColContent1 =
                "<PASSWORD>";
        String usernameColContent2 = "testMd5";
        String passwordColContent2 =
                "<PASSWORD>";
        String usernameColContent3 = "testSenselessContent";
        String passwordColContent3 =
                "<PASSWORD>";

        this.insertIntoTestDb(usernameColContent1, passwordColContent1);
        this.insertIntoTestDb(usernameColContent2, passwordColContent2);
        this.insertIntoTestDb(usernameColContent3, passwordColContent3);
    }

    private void insertIntoTestDb(String usernameColContent,
                String passwordColContent) throws SQLException {
        String sql = "INSERT INTO auth_user(username, password) " +
                "VALUES (?, ?)";
        PreparedStatement insertion = this.connection.prepareStatement(sql);
        insertion.setString(1, usernameColContent);
        insertion.setString(2, passwordColContent);
        insertion.execute();
    }

    @After
    public void tearDown() throws Exception {
        this.deleteDbFile();
    }

    private void deleteDbFile() {
        boolean deleted = false;
        File f = new File(this.fileName);
        if (f.exists() && f.canWrite() && !f.isDirectory()) {
            deleted = f.delete();
        }
        if (!deleted) {
            TEST_LOGGER.error("test DB at " + this.fileName + "could not be " +
                    "deleted");
        }
    }

    /**
     * The PasswordAuthenticator interface requires us to catch any exceptions
     * thrown by the underlying authentication, including SQL databases not
     * found, etc ...
     *
     * Here we show that the exception is caught and we do not allow
     * authentication if the credentials are correct but the database is missing
     *
     * @throws Exception
     */
    @Test
    public void testWithoutDb() throws Exception {
        this.instance.setFrontendCredentials(this.frontendDbUrl, "", "", "");
        this.deleteDbFile();
        assertFalse(this.instance.authenticate("who_cares", "whatever",
                null));
    }

    @Test
    public void testAuthenticate() throws Exception {
        this.instance.setFrontendCredentials(this.frontendDbUrl, "", "", "");
        assertFalse(this.instance.authenticate("test", "fake_password", null));
        assertTrue(this.instance.authenticate("test", "test", null));
        assertFalse(this.instance.authenticate("testMd5", "very_fake", null));
        assertTrue(this.instance.authenticate("testMd5", "test", null));
    }

    /**
     * Show that if the content found in the database does not make sense, we
     * do not allow authentication. Note that one user does not exist and the
     * other has 'colt45' stored as its password hashing algorithm.
     *
     * @throws Exception
     */
    @Test
    public void testDefaultAuthenticationIsFalse() throws Exception {
        this.instance.setFrontendCredentials(this.frontendDbUrl, "", "", "");
        assertFalse(this.instance.authenticate("anonymous",
                "we_are_legion", null));
        assertFalse(this.instance.authenticate("testSenselessContent",
                "whatever", null));
    }

    /**
     * Show that if the database URL is wrongly configured, we catch the
     * exception and do not allow to authenticate.
     * @throws Exception
     */
    @Test
    public void testAuthenticationWhenDbConfigWrong() throws Exception {
        this.instance.setFrontendCredentials("jdbc:superdb:cosmos.db", "", "",
                "");
        assertFalse(this.instance.authenticate("test", "test", null));
    }
}
<commit_msg>[SFTP tests] Mock frontend DB also in tempdir<commit_after>/*
 * Telefónica Digital - Product Development and Innovation
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
 * All rights reserved.
 */

package es.tid.cosmos.platform.injection.server;

import java.io.File;
import java.sql.*;

import com.google.common.io.Files;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import es.tid.cosmos.base.util.Logger;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

/**
 * FrontendPasswordTest
 *
 * @author logc
 */
public class FrontendPasswordTest extends BaseSftpTest {

    private static final org.apache.log4j.Logger LOGGER =
            Logger.get(FrontendPassword.class);
    private static final org.apache.log4j.Logger TEST_LOGGER =
            Logger.get(FrontendPasswordTest.class);

    private FrontendPassword instance;
    private String fileName;
    private String frontendDbUrl;
    private Connection connection;
    private File tempDir;

    public FrontendPasswordTest() {
        super(LOGGER);
    }

    @Before
    public void setUp() throws Exception {
        this.instance = new FrontendPassword();
        this.tempDir = Files.createTempDir();
        this.fileName = "test.db";
        this.frontendDbUrl = "jdbc:sqlite:" + this.tempDir.toString() +
                fileName;
        Class.forName("org.sqlite.JDBC").newInstance();
        this.connection = DriverManager.getConnection(this.frontendDbUrl);
        Statement stat = this.connection.createStatement();
        stat.executeUpdate("DROP TABLE IF EXISTS auth_user");
        //  As dumped from frontend temporary database on 2012-05-15 with the
        //  following commands:
        //  bin/django syncdb; sqlite3 /tmp/cosmos.db; > .schema auth_user

        //  Unused fields (e.g. first_name) were ignored
        String createStatement = "CREATE TABLE \"auth_user\" (\n" +
                "    \"username\" varchar(30) NOT NULL UNIQUE,\n" +
                "    \"password\" varchar(128) NOT NULL\n" +
                ");";
        stat.executeUpdate(createStatement);
        // as dumped from frontend temporary database on 2012-05-15 with the
        // following commands:
        // > SELECT username, password FROM auth_user;
        String usernameColContent1 = "test";
        String passwordColContent1 =
                "<PASSWORD>";
        String usernameColContent2 = "testMd5";
        String passwordColContent2 =
                "<PASSWORD>";
        String usernameColContent3 = "testSenselessContent";
        String passwordColContent3 =
                "<PASSWORD>";

        this.insertIntoTestDb(usernameColContent1, passwordColContent1);
        this.insertIntoTestDb(usernameColContent2, passwordColContent2);
        this.insertIntoTestDb(usernameColContent3, passwordColContent3);
    }

    private void insertIntoTestDb(String usernameColContent,
                String passwordColContent) throws SQLException {
        String sql = "INSERT INTO auth_user(username, password) " +
                "VALUES (?, ?)";
        PreparedStatement insertion = this.connection.prepareStatement(sql);
        insertion.setString(1, usernameColContent);
        insertion.setString(2, passwordColContent);
        insertion.execute();
    }

    @After
    public void tearDown() throws Exception {
        this.deleteDbFile();
    }

    private void deleteDbFile() {
        boolean deleted = false;
        File f = new File(this.tempDir.toString() + this.fileName);
        if (f.exists() && f.canWrite() && !f.isDirectory()) {
            deleted = f.delete();
        }
        if (!deleted) {
            TEST_LOGGER.error("test DB at " + this.tempDir.toString() +
                    this .fileName +  "could not be deleted");
        }
    }

    /**
     * The PasswordAuthenticator interface requires us to catch any exceptions
     * thrown by the underlying authentication, including SQL databases not
     * found, etc ...
     *
     * Here we show that the exception is caught and we do not allow
     * authentication if the credentials are correct but the database is missing
     *
     * @throws Exception
     */
    @Test
    public void testWithoutDb() throws Exception {
        this.instance.setFrontendCredentials(this.frontendDbUrl, "", "", "");
        this.deleteDbFile();
        assertFalse(this.instance.authenticate("who_cares", "whatever",
                null));
    }

    @Test
    public void testAuthenticate() throws Exception {
        this.instance.setFrontendCredentials(this.frontendDbUrl, "", "", "");
        assertFalse(this.instance.authenticate("test", "fake_password", null));
        assertTrue(this.instance.authenticate("test", "test", null));
        assertFalse(this.instance.authenticate("testMd5", "very_fake", null));
        assertTrue(this.instance.authenticate("testMd5", "test", null));
    }

    /**
     * Show that if the content found in the database does not make sense, we
     * do not allow authentication. Note that one user does not exist and the
     * other has 'colt45' stored as its password hashing algorithm.
     *
     * @throws Exception
     */
    @Test
    public void testDefaultAuthenticationIsFalse() throws Exception {
        this.instance.setFrontendCredentials(this.frontendDbUrl, "", "", "");
        assertFalse(this.instance.authenticate("anonymous",
                "we_are_legion", null));
        assertFalse(this.instance.authenticate("testSenselessContent",
                "whatever", null));
    }

    /**
     * Show that if the database URL is wrongly configured, we catch the
     * exception and do not allow to authenticate.
     * @throws Exception
     */
    @Test
    public void testAuthenticationWhenDbConfigWrong() throws Exception {
        this.instance.setFrontendCredentials("jdbc:superdb:cosmos.db", "", "",
                "");
        assertFalse(this.instance.authenticate("test", "test", null));
    }
}

{'fraction_non_alphanumeric': 0.1026517000162681, 'fraction_numerical': 0.006995282251504799, 'mean_word_length': 2.6899759903961584, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5634459', 'n_tokens_mistral': 3354, 'n_tokens_neox': 3253, 'n_words': 868}