<commit_before>package org.esupportail.smsuapi.business;

import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import java.security.cert.X509Certificate;
import javax.security.cert.CertificateException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.esupportail.commons.utils.HttpUtils;
import org.esupportail.commons.services.logging.Logger;
import org.esupportail.commons.services.logging.LoggerImpl;
import org.esupportail.smsuapi.dao.DaoService;
import org.esupportail.smsuapi.dao.beans.Application;
import org.esupportail.smsuapi.exceptions.UnknownIdentifierApplicationException;
import org.springframework.beans.factory.InitializingBean;

/**
 * @author xphp8691
 *
 */
public class ClientManager implements InitializingBean {

	/**
	 * pattern as sting used to extract the client name.
	 */
	private String subjectDNRegex;
	
	/**
	 * 
	 */
	private DaoService daoService;

	private String PASSWORD_PREFIX_IN_CERTIFCATE = "PASSWORD:";
	
	/**
	 * A logger.
	 */
	private final Logger logger = new LoggerImpl(getClass());

	
	/**
	 * constructor.
	 */
	public ClientManager() {
		super();
	}


	/**
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws IllegalArgumentException {	
		compileSubjectDNRegex();
	}

	public Pattern compileSubjectDNRegex() throws IllegalArgumentException {
		try {
			return Pattern.compile(subjectDNRegex, Pattern.CASE_INSENSITIVE);
		} catch (PatternSyntaxException e) {
			throw new IllegalArgumentException("Malformed regular expression: " + subjectDNRegex);
		}
	}

	public String getNoCertificateNorBasicAuthErrorMessage() {
		return "no certificate nor basic auth received by smsuapi. Either fix smsuapi configuration: you need clientAuth=optional in server.xml (tomcat) or \"SSLVerifyClient optional\" in apache conf (if you use a frontal apache). Or use Basic Auth";
	}

	/**
	 * @return the client name, "unknown" if the name can not be found.
	 * @throws IllegalArgumentException
	 */
	public String getClientName() throws IllegalArgumentException {
		String cn = getCertificateCN();
		if (cn == null) cn = getBasicAuthUser();
		if (cn == null) { 
			logger.error(getNoCertificateNorBasicAuthErrorMessage());
			return "";
		} else {
			return cn;
		}
	}

	private String getCertificateCN() throws IllegalArgumentException {
		if (logger.isDebugEnabled()) {
			logger.debug("Client connexion. get Client Name.");
		}
		
		X509Certificate[] certs = getClientX509Certificates();
		
		if ((certs != null) && (certs.length > 0)) {
			return getCNFromCertificate(certs[0]);
		} else {
			return null;
		}
	}

	private X509Certificate[] getClientX509Certificates() {
		HttpServletRequest request = HttpUtils.getHttpServletRequest();
		return (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
	}
	
	/**
	 * 
	 * @param certificateCN
	 * @return
	 */
	public Application getApplicationByCertificateCN(final String certificateCN) {
		if (certificateCN == null) return null;

		for (Application application : daoService.getAllApplications()) {
			try {
				String cn = getCNFromApplication(application);
				if (certificateCN.equalsIgnoreCase(cn)) {					
					if (logger.isDebugEnabled())<commit_msg>smsuapi: avoid warning in log on "applications" configured for basic auth<commit_after>package org.esupportail.smsuapi.business;

import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import java.security.cert.X509Certificate;
import javax.security.cert.CertificateException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.esupportail.commons.utils.HttpUtils;
import org.esupportail.commons.services.logging.Logger;
import org.esupportail.commons.services.logging.LoggerImpl;
import org.esupportail.smsuapi.dao.DaoService;
import org.esupportail.smsuapi.dao.beans.Application;
import org.esupportail.smsuapi.exceptions.UnknownIdentifierApplicationException;
import org.springframework.beans.factory.InitializingBean;

/**
 * @author xphp8691
 *
 */
public class ClientManager implements InitializingBean {

	/**
	 * pattern as sting used to extract the client name.
	 */
	private String subjectDNRegex;
	
	/**
	 * 
	 */
	private DaoService daoService;

	private String PASSWORD_PREFIX_IN_CERTIFCATE = "PASSWORD:";
	
	/**
	 * A logger.
	 */
	private final Logger logger = new LoggerImpl(getClass());

	
	/**
	 * constructor.
	 */
	public ClientManager() {
		super();
	}


	/**
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws IllegalArgumentException {	
		compileSubjectDNRegex();
	}

	public Pattern compileSubjectDNRegex() throws IllegalArgumentException {
		try {
			return Pattern.compile(subjectDNRegex, Pattern.CASE_INSENSITIVE);
		} catch (PatternSyntaxException e) {
			throw new IllegalArgumentException("Malformed regular expression: " + subjectDNRegex);
		}
	}

	public String getNoCertificateNorBasicAuthErrorMessage() {
		return "no certificate nor basic auth received by smsuapi. Either fix smsuapi configuration: you need clientAuth=optional in server.xml (tomcat) or \"SSLVerifyClient optional\" in apache conf (if you use a frontal apache). Or use Basic Auth";
	}

	/**
	 * @return the client name, "unknown" if the name can not be found.
	 * @throws IllegalArgumentException
	 */
	public String getClientName() throws IllegalArgumentException {
		String cn = getCertificateCN();
		if (cn == null) cn = getBasicAuthUser();
		if (cn == null) { 
			logger.error(getNoCertificateNorBasicAuthErrorMessage());
			return "";
		} else {
			return cn;
		}
	}

	private String getCertificateCN() throws IllegalArgumentException {
		if (logger.isDebugEnabled()) {
			logger.debug("Client connexion. get Client Name.");
		}
		
		X509Certificate[] certs = getClientX509Certificates();
		
		if ((certs != null) && (certs.length > 0)) {
			return getCNFromCertificate(certs[0]);
		} else {
			return null;
		}
	}

	private X509Certificate[] getClientX509Certificates() {
		HttpServletRequest request = HttpUtils.getHttpServletRequest();
		return (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
	}
	
	/**
	 * 
	 * @param certificateCN
	 * @return
	 */
	public Application getApplicationByCertificateCN(final String certificateCN) {
		if (certificateCN == null) return null;

		for (Application application : daoService.getAllApplications()) {

			if (getPassword(application) != null) // skip apps configured for basic auth
				continue;

			try {
				String cn = getCNFromApplication(application);
				if (certificateCN.equalsIgnoreCase(cn)) {					
					if (logger.isDebugEnabled())
{'fraction_non_alphanumeric': 0.10502152080344333, 'fraction_numerical': 0.008321377331420373, 'mean_word_length': 4.685970636215335, 'pattern_counts': {'":': 0, '<': 3, '<?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': '1368057', 'n_tokens_mistral': 2194, 'n_tokens_neox': 1978, 'n_words': 479}