<commit_before>/*
 * Copyright (C) 2015 Glyptodon LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.glyptodon.guacamole.auth.json.user;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import org.codehaus.jackson.map.ObjectMapper;
import org.glyptodon.guacamole.net.auth.Connection;
import org.glyptodon.guacamole.net.auth.ConnectionGroup;
import org.glyptodon.guacamole.net.auth.Credentials;
import org.glyptodon.guacamole.net.auth.Directory;
import org.glyptodon.guacamole.net.auth.User;
import org.glyptodon.guacamole.net.auth.simple.SimpleConnection;
import org.glyptodon.guacamole.net.auth.simple.SimpleConnectionGroup;
import org.glyptodon.guacamole.net.auth.simple.SimpleConnectionGroupDirectory;
import org.glyptodon.guacamole.net.auth.simple.SimpleDirectory;
import org.glyptodon.guacamole.net.auth.simple.SimpleUser;
import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Service for deriving Guacamole extension API data from UserData objects.
 *
 * @author <NAME>
 */
public class UserDataService {

    /**
     * Logger for this class.
     */
    private final Logger logger = LoggerFactory.getLogger(UserDataService.class);

    /**
     * ObjectMapper for deserializing UserData objects.
     */
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * The identifier reserved for the root connection group.
     */
    public static final String ROOT_CONNECTION_GROUP = "ROOT";

    /**
     * The name of the HTTP parameter from which base64-encoded JSON data
     * should be read.
     */
    public static final String JSON_DATA_PARAMETER = "data";

    /**
     * Derives a new UserData object from the data contained within the given
     * Credentials. If no such data is present, or the data present is invalid,
     * null is returned.
     *
     * @param credentials
     *     The Credentials from which the new UserData object should be
     *     derived.
     *
     * @return
     *     A new UserData object derived from the data contained within the
     *     given Credentials, or null if no such data is present or if the data
     *     present is invalid.
     */
    public UserData fromCredentials(Credentials credentials) {

        // Pull HTTP request, if available
        HttpServletRequest request = credentials.getRequest();
        if (request == null)
            return null;

        // Pull base64-encoded JSON data from HTTP request, if any such data is
        // present
        String base64 = request.getParameter(JSON_DATA_PARAMETER);
        if (base64 == null)
            return null;

        // Convert parameter from base64
        String json;
        try {
            json = new String(
                DatatypeConverter.parseBase64Binary(base64),
                "UTF-8"
            );
        }

        // Fail if base64 data is not valid
        catch (IllegalArgumentException e) {
            logger.warn("Submitted data is not proper base64.");
            logger.debug("Invalid base64 data.", e);
            return null;
        }

        // Handle lack of standard UTF-8 support (should never happen)
        catch (UnsupportedEncodingException e) {
            logger.error("Unexpected lack of support for UTF-8: {}", e.getMessage());
            logger.debug("Unable to decode base64 data as UTF-8.", e);
            return null;
        }

        // Deserialize UserData from submitted JSON data
        try {

            // Deserialize UserData, but reject if expired
            UserData userData = mapper.readValue(json, UserData.class);
            if (userData.isExpired())
                return null;

            return userData;

        }

        // Fail UserData creation if JSON is invalid/unreadable<commit_msg>TSOL-2: Decrypt received base64 data.<commit_after>/*
 * Copyright (C) 2015 Glyptodon LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.glyptodon.guacamole.auth.json.user;

import com.google.inject.Inject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import org.codehaus.jackson.map.ObjectMapper;
import org.glyptodon.guacamole.GuacamoleException;
import org.glyptodon.guacamole.auth.json.ConfigurationService;
import org.glyptodon.guacamole.auth.json.CryptoService;
import org.glyptodon.guacamole.net.auth.Connection;
import org.glyptodon.guacamole.net.auth.ConnectionGroup;
import org.glyptodon.guacamole.net.auth.Credentials;
import org.glyptodon.guacamole.net.auth.Directory;
import org.glyptodon.guacamole.net.auth.User;
import org.glyptodon.guacamole.net.auth.simple.SimpleConnection;
import org.glyptodon.guacamole.net.auth.simple.SimpleConnectionGroup;
import org.glyptodon.guacamole.net.auth.simple.SimpleConnectionGroupDirectory;
import org.glyptodon.guacamole.net.auth.simple.SimpleDirectory;
import org.glyptodon.guacamole.net.auth.simple.SimpleUser;
import org.glyptodon.guacamole.protocol.GuacamoleConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Service for deriving Guacamole extension API data from UserData objects.
 *
 * @author <NAME>
 */
public class UserDataService {

    /**
     * Logger for this class.
     */
    private final Logger logger = LoggerFactory.getLogger(UserDataService.class);

    /**
     * ObjectMapper for deserializing UserData objects.
     */
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * Service for retrieving configuration information regarding the
     * JSONAuthenticationProvider.
     */
    @Inject
    private ConfigurationService confService;

    /**
     * Service for handling cryptography-related operations.
     */
    @Inject
    private CryptoService cryptoService;

    /**
     * The identifier reserved for the root connection group.
     */
    public static final String ROOT_CONNECTION_GROUP = "ROOT";

    /**
     * The name of the HTTP parameter from which base64-encoded, encrypted JSON
     * data should be read.
     */
    public static final String ENCRYPTED_DATA_PARAMETER = "data";

    /**
     * Derives a new UserData object from the data contained within the given
     * Credentials. If no such data is present, or the data present is invalid,
     * null is returned.
     *
     * @param credentials
     *     The Credentials from which the new UserData object should be
     *     derived.
     *
     * @return
     *     A new UserData object derived from the data contained within the
     *     given Credentials, or null if no such data is present or if the data
     *     present is invalid.
     */
    public UserData fromCredentials(Credentials credentials) {

        // Pull HTTP request, if available
        HttpServletRequest request = credentials.getRequest();
        if (request == null)
            return null;

        // Pull base64-encoded, encrypted JSON data from HTTP request, if any
        // such data is present
        String base64 = request.getParameter(ENCRYPTED_DATA_PARAMETER);
        if (base64 == null)
            return null;

        // Decrypt base64-encoded parameter
        String json;
        try {

            // Decrypt using defined encryption key
            byte[] decrypted = cryptoService.decrypt(
                confService.getEncryptionKey(),
                DatatypeConverter.parseBase64Binary(base64)
            );

            // Convert from UTF-8
            json = new String(decrypted, "UTF-8");

        }

        // Fail if base64 data is not valid
        catch (IllegalArgumentException e) {
            logger.warn("Submitted data is not proper base64.");
            logger.debug("Invalid base64 data.", e);
            return null;
        }

        // Handle lack of standard UTF-8 support (should never happen)
        catch (UnsupportedEncodingException e) {
            logger.error("Unexpected lack of support for UTF-8: {}", e.getMessage());
            logger.debug("Unable to decode base64 data as UTF-8.", e);
            return null;
        }

        // Fail if decryption or key retrieval fails for any reason
        catch (GuacamoleException e) {
            logger.error("Decryption of received data failed: {}", e.getMessage());
            logger.debug("Unable to decrypt received data.", e);
            return null;
        }

        // Deserialize UserData from submitted JSON data
        try {

            // Deserialize UserData, but reject if expired
            UserData userData = mapper.readValue(json, UserData.class);
            if (userData.isExpired())
                return null;

            return userData;

        }

        // Fail UserData creation if JSON is invalid/unreadable
{'fraction_non_alphanumeric': 0.07739744391813388, 'fraction_numerical': 0.006077397443918134, 'mean_word_length': 2.8321917808219177, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, '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': '2278750', 'n_tokens_mistral': 3044, 'n_tokens_neox': 2908, 'n_words': 1042}