<commit_before>package eu.h2020.symbiote.security.services;

import eu.h2020.symbiote.security.commons.Certificate;
import eu.h2020.symbiote.security.commons.SecurityConstants;
import eu.h2020.symbiote.security.commons.enums.IssuingAuthorityType;
import eu.h2020.symbiote.security.commons.enums.ManagementStatus;
import eu.h2020.symbiote.security.commons.enums.UserRole;
import eu.h2020.symbiote.security.commons.exceptions.SecurityException;
import eu.h2020.symbiote.security.commons.exceptions.custom.InvalidArgumentsException;
import eu.h2020.symbiote.security.commons.exceptions.custom.NotExistingUserException;
import eu.h2020.symbiote.security.commons.exceptions.custom.SecurityMisconfigurationException;
import eu.h2020.symbiote.security.commons.exceptions.custom.UserManagementException;
import eu.h2020.symbiote.security.communication.payloads.Credentials;
import eu.h2020.symbiote.security.communication.payloads.UserDetails;
import eu.h2020.symbiote.security.communication.payloads.UserManagementRequest;
import eu.h2020.symbiote.security.repositories.RevokedKeysRepository;
import eu.h2020.symbiote.security.repositories.UserRepository;
import eu.h2020.symbiote.security.repositories.entities.SubjectsRevokedKeys;
import eu.h2020.symbiote.security.repositories.entities.User;
import eu.h2020.symbiote.security.services.helpers.CertificationAuthorityHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.security.cert.CertificateException;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;

/**
 * Spring service used to manage users in the AAM repository.
 * <p>
 *
 * @author <NAME> (CNIT)
 * @author <NAME> (UNIVIE)
 * @author <NAME> (PSNC)
 * @author <NAME> (PSNC)
 */
@Service
public class UsersManagementService {
    private static Log log = LogFactory.getLog(UsersManagementService.class);
    private final UserRepository userRepository;
    private final RevokedKeysRepository revokedKeysRepository;
    private final PasswordEncoder passwordEncoder;
    private final String adminUsername;
    private final String adminPassword;
    private final IssuingAuthorityType deploymentType;

    @Autowired
    public UsersManagementService(UserRepository userRepository, RevokedKeysRepository revokedKeysRepository,
                                  CertificationAuthorityHelper certificationAuthorityHelper,
                                  PasswordEncoder passwordEncoder,
                                  @Value("${aam.deployment.owner.username}") String adminUsername,
                                  @Value("${aam.deployment.owner.password}") String adminPassword) throws
            SecurityMisconfigurationException {
        this.userRepository = userRepository;
        this.revokedKeysRepository = revokedKeysRepository;
        this.passwordEncoder = passwordEncoder;
        this.deploymentType = certificationAuthorityHelper.getDeploymentType();
        this.adminUsername = adminUsername;
        this.adminPassword = <PASSWORD>;

        if (userRepository.exists(adminUsername) || SecurityConstants.GUEST_NAME.equals(adminUsername))
            throw new SecurityMisconfigurationException("AAM owner user already registered in database... Either delete that user or choose a different administrator username");
    }

    public ManagementStatus authManage(UserManagementRequest request) throws
            SecurityException {

        // check if we received required administrator credentials for API auth
        if (request.getAdministratorCredentials() == null || request.getUserDetails().getCredentials() == null)
            throw new InvalidArgumentsException();
        // and if they match the admin credentials from properties
        if (!request.getAdministratorCredentials().getUsername().equals(adminUsername)
                || !request.getAdministratorCredentials().getPassword().equals(adminPassword))
            throw new UserManagementException(HttpStatus.UNAUTHORIZED);
        // do it
        return this.manage(request);
    }

    public UserDetails getUserDetails(Credentials credentials) throws UserManagementException {
        //  If requested user is not in database
        if (!userRepository.exists(credentials.getUsername()))
            throw new UserManagementException("User not in database", HttpStatus.BAD_REQUEST);

        User foundUser = userRepository.findOne(credentials.getUsername());
        // If requested user IS in database but wrong password was provided
        if (!credentials.getPassword().equals(foundUser.getPasswordEncrypted()) &&
                !passwordEncoder.matches(credentials.getPassword(), foundUser.getPasswordEncrypted()))
            throw new UserManagementException("Incorrect login / password", HttpStatus.UNAUTHORIZED);
        //  Everything is fine, returning requested user's details
        return new UserDetails(new Credentials(
                foundUser.getUsername(), ""),
                "",
                foundUser.getRecoveryMail(),
                foundUser.getRole(),
                foundUser.getAttributes(),
                foundUser.getClientCertificates()
        );
    }

    private ManagementStatus manage(UserManagementRequest userManagementRequest)
            throws SecurityException {
    	
    	log.info("Received a request for user management");
    	
        UserDetails userDetails = userManagementRequest.getUserDetails();

    	log.info("User details are "+userDetails);	// Might be a bit problematic. 1. There is no adequat toString method for userDetails. 2. Will such a method reveil passowrds?

        
        // Platform AAM does not support registering platform owners
        if (deploymentType == IssuingAuthorityType.PLATFORM
                && userDetails.getRole() != UserRole.USER) {
        	log.error("Platform AAM does not support registering platform owners");
            throw new InvalidArgumentsException();
        }

        User user = new User();
        User userToManage = userRepository.findOne(userManagementRequest.getUserDetails().getCredentials().getUsername());
        switch (userManagementRequest.getOperationType()) {
            case CREATE:
            	log.info("Request is a create request");
                // validate request
                String newUserUsername = userDetails.getCredentials().getUsername();
                if (!newUserUsername.matches("^(([\\w-])+)$")) {
                	log.error("Username "+newUserUsername+" contains invalid characters");
                    throw new InvalidArgumentsException("Could not create user with given Username");
                }
                if (newUserUsername.isEmpty()
                        || userDetails.getCredentials().getPassword().isEmpty()) {
                	log.error("Username or password is empty");
                    throw new InvalidArgumentsException("Missing username or password");
                }
                if (deploymentType == IssuingAuthorityType.CORE
                        && (userDetails.getRecoveryMail().isEmpty()))
                    // not used in R3
                    // || userDetails.getFederatedId().isEmpty()))
                {
                	log.error("Recovery information (email and OAuth) are both empty");
                    throw new InvalidArgumentsException("Missing recovery e-mail or OAuth identity");
                }

                // verify proper user role
                if (userDetails.getRole() == UserRole.NULL) {
                	log.error("User Role is null");
                    throw new UserManagementException(HttpStatus.BAD_REQUEST);
                }

                // check if user already in repository
                if (userRepository.exists(newUserUsername)) {
                	log.error("Username "+newUserUsername+" already exists");
                    return ManagementStatus.USERNAME_EXISTS;
                }

                // blocking guest and AAMOwner registration, and aam component
                if (adminUsername.equals(newUserUsername) || SecurityConstants.GUEST_NAME.equals(newUserUsername) || SecurityConstants.AAM_COMPONENT_NAME.equals(newUserUsername)) {
                	log.error("Username "+newUserUsername+" would override a predefined username");
                    return ManagementStatus.ERROR;
                }

                user.setRole(userDetails.getRole());
                user.setUsername(newUserUsername);
                user.setPasswordEncrypted(passwordEncoder.encode(userDetails.getCredentials().getPassword()));<commit_msg>Noop-change to verify travis is correctly triggered<commit_after>package eu.h2020.symbiote.security.services;

import eu.h2020.symbiote.security.commons.Certificate;
import eu.h2020.symbiote.security.commons.SecurityConstants;
import eu.h2020.symbiote.security.commons.enums.IssuingAuthorityType;
import eu.h2020.symbiote.security.commons.enums.ManagementStatus;
import eu.h2020.symbiote.security.commons.enums.UserRole;
import eu.h2020.symbiote.security.commons.exceptions.SecurityException;
import eu.h2020.symbiote.security.commons.exceptions.custom.InvalidArgumentsException;
import eu.h2020.symbiote.security.commons.exceptions.custom.NotExistingUserException;
import eu.h2020.symbiote.security.commons.exceptions.custom.SecurityMisconfigurationException;
import eu.h2020.symbiote.security.commons.exceptions.custom.UserManagementException;
import eu.h2020.symbiote.security.communication.payloads.Credentials;
import eu.h2020.symbiote.security.communication.payloads.UserDetails;
import eu.h2020.symbiote.security.communication.payloads.UserManagementRequest;
import eu.h2020.symbiote.security.repositories.RevokedKeysRepository;
import eu.h2020.symbiote.security.repositories.UserRepository;
import eu.h2020.symbiote.security.repositories.entities.SubjectsRevokedKeys;
import eu.h2020.symbiote.security.repositories.entities.User;
import eu.h2020.symbiote.security.services.helpers.CertificationAuthorityHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.security.cert.CertificateException;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;

/**
 * Spring service used to manage users in the AAM repository.
 * <p>
 *
 * @author <NAME> (CNIT)
 * @author <NAME> (UNIVIE)
 * @author <NAME> (PSNC)
 * @author <NAME> (PSNC)
 */
@Service
public class UsersManagementService {
    private static Log log = LogFactory.getLog(UsersManagementService.class);
    private final UserRepository userRepository;
    private final RevokedKeysRepository revokedKeysRepository;
    private final PasswordEncoder passwordEncoder;
    private final String adminUsername;
    private final String adminPassword;
    private final IssuingAuthorityType deploymentType;

    @Autowired
    public UsersManagementService(UserRepository userRepository, RevokedKeysRepository revokedKeysRepository,
                                  CertificationAuthorityHelper certificationAuthorityHelper,
                                  PasswordEncoder passwordEncoder,
                                  @Value("${aam.deployment.owner.username}") String adminUsername,
                                  @Value("${aam.deployment.owner.password}") String adminPassword) throws
            SecurityMisconfigurationException {
        this.userRepository = userRepository;
        this.revokedKeysRepository = revokedKeysRepository;
        this.passwordEncoder = passwordEncoder;
        this.deploymentType = certificationAuthorityHelper.getDeploymentType();
        this.adminUsername = adminUsername;
        this.adminPassword = <PASSWORD>;

        if (userRepository.exists(adminUsername) || SecurityConstants.GUEST_NAME.equals(adminUsername))
            throw new SecurityMisconfigurationException("AAM owner user already registered in database... Either delete that user or choose a different administrator username");
    }

    public ManagementStatus authManage(UserManagementRequest request) throws
            SecurityException {

        // check if we received required administrator credentials for API auth
        if (request.getAdministratorCredentials() == null || request.getUserDetails().getCredentials() == null)
            throw new InvalidArgumentsException();
        // and if they match the admin credentials from properties
        if (!request.getAdministratorCredentials().getUsername().equals(adminUsername)
                || !request.getAdministratorCredentials().getPassword().equals(adminPassword))
            throw new UserManagementException(HttpStatus.UNAUTHORIZED);
        // do it
        return this.manage(request);
    }

    public UserDetails getUserDetails(Credentials credentials) throws UserManagementException {
        //  If requested user is not in database
        if (!userRepository.exists(credentials.getUsername()))
            throw new UserManagementException("User not in database", HttpStatus.BAD_REQUEST);

        User foundUser = userRepository.findOne(credentials.getUsername());
        // If requested user IS in database but wrong password was provided
        if (!credentials.getPassword().equals(foundUser.getPasswordEncrypted()) &&
                !passwordEncoder.matches(credentials.getPassword(), foundUser.getPasswordEncrypted()))
            throw new UserManagementException("Incorrect login / password", HttpStatus.UNAUTHORIZED);
        //  Everything is fine, returning requested user's details
        return new UserDetails(new Credentials(
                foundUser.getUsername(), ""),
                "",
                foundUser.getRecoveryMail(),
                foundUser.getRole(),
                foundUser.getAttributes(),
                foundUser.getClientCertificates()
        );
    }

    private ManagementStatus manage(UserManagementRequest userManagementRequest)
            throws SecurityException {
    	
    	log.info("Received a request for user management");
    	
        UserDetails userDetails = userManagementRequest.getUserDetails();

    	log.info("User details are "+userDetails);	// Might be a bit problematic. 1. There is no adequat toString method for userDetails. 2. Will such a method reveil passowrds?

        
        // Platform AAM does not support registering platform owners
        if (deploymentType == IssuingAuthorityType.PLATFORM
                && userDetails.getRole() != UserRole.USER) {
        	log.error("Platform AAM does not support registering platform owners");
            throw new InvalidArgumentsException();
        }

        User user = new User();
        User userToManage = userRepository.findOne(userManagementRequest.getUserDetails().getCredentials().getUsername());
        switch (userManagementRequest.getOperationType()) {
            case CREATE:
            	log.info("Request is a create request");
                // validate request
                String newUserUsername = userDetails.getCredentials().getUsername();
                if (!newUserUsername.matches("^(([\\w-])+)$")) {
                	log.error("Username "+newUserUsername+" contains invalid characters");
                    throw new InvalidArgumentsException("Could not create user with given Username");
                }
                if (newUserUsername.isEmpty()
                        || userDetails.getCredentials().getPassword().isEmpty()) {
                	log.error("Username or password is empty");
                    throw new InvalidArgumentsException("Missing username or password");
                }
                if (deploymentType == IssuingAuthorityType.CORE
                        && (userDetails.getRecoveryMail().isEmpty()))
                    // not used in R3
                    // || userDetails.getFederatedId().isEmpty()))
                {
                	log.error("Recovery information (email and OAuth) are both empty");
                    throw new InvalidArgumentsException("Missing recovery e-mail or OAuth identity");
                }

                // verify proper user role 
                if (userDetails.getRole() == UserRole.NULL) {
                	log.error("User Role is null");
                    throw new UserManagementException(HttpStatus.BAD_REQUEST);
                }

                // check if user already in repository
                if (userRepository.exists(newUserUsername)) {
                	log.error("Username "+newUserUsername+" already exists");
                    return ManagementStatus.USERNAME_EXISTS;
                }

                // blocking guest and AAMOwner registration, and aam component
                if (adminUsername.equals(newUserUsername) || SecurityConstants.GUEST_NAME.equals(newUserUsername) || SecurityConstants.AAM_COMPONENT_NAME.equals(newUserUsername)) {
                	log.error("Username "+newUserUsername+" would override a predefined username");
                    return ManagementStatus.ERROR;
                }

                user.setRole(userDetails.getRole());
                user.setUsername(newUserUsername);
                user.setPasswordEncrypted(passwordEncoder.encode(userDetails.getCredentials().getPassword()));
{'fraction_non_alphanumeric': 0.08710566271157848, 'fraction_numerical': 0.009109823989203172, 'mean_word_length': 2.961684116729784, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2500166', 'n_tokens_mistral': 4388, 'n_tokens_neox': 4182, 'n_words': 935}