GestoreTokenAttributeAuthorityUtilities.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.pdd.core.token;

  21. import java.io.ByteArrayOutputStream;
  22. import java.net.URI;
  23. import java.security.cert.Certificate;
  24. import java.security.cert.X509Certificate;
  25. import java.text.SimpleDateFormat;
  26. import java.util.ArrayList;
  27. import java.util.Date;
  28. import java.util.Enumeration;
  29. import java.util.HashMap;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Properties;

  33. import javax.servlet.http.HttpServletRequest;

  34. import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys;
  35. import org.openspcoop2.core.commons.DBUtils;
  36. import org.openspcoop2.core.config.AttributeAuthority;
  37. import org.openspcoop2.core.config.InvocazioneCredenziali;
  38. import org.openspcoop2.core.config.PortaApplicativa;
  39. import org.openspcoop2.core.config.PortaDelegata;
  40. import org.openspcoop2.core.config.Proprieta;
  41. import org.openspcoop2.core.config.ResponseCachingConfigurazione;
  42. import org.openspcoop2.core.config.constants.CostantiConfigurazione;
  43. import org.openspcoop2.core.config.constants.StatoFunzionalita;
  44. import org.openspcoop2.core.constants.CostantiConnettori;
  45. import org.openspcoop2.core.constants.TipiConnettore;
  46. import org.openspcoop2.core.constants.TransferLengthModes;
  47. import org.openspcoop2.core.id.IDGenericProperties;
  48. import org.openspcoop2.core.id.IDServizio;
  49. import org.openspcoop2.core.id.IDSoggetto;
  50. import org.openspcoop2.core.mvc.properties.provider.ProviderException;
  51. import org.openspcoop2.core.mvc.properties.provider.ProviderValidationException;
  52. import org.openspcoop2.message.OpenSPCoop2Message;
  53. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  54. import org.openspcoop2.message.OpenSPCoop2MessageParseResult;
  55. import org.openspcoop2.message.constants.MessageType;
  56. import org.openspcoop2.message.constants.ServiceBinding;
  57. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  58. import org.openspcoop2.pdd.config.CostantiProprieta;
  59. import org.openspcoop2.pdd.config.ForwardProxy;
  60. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  61. import org.openspcoop2.pdd.core.PdDContext;
  62. import org.openspcoop2.pdd.core.connettori.ConnettoreBaseHTTP;
  63. import org.openspcoop2.pdd.core.connettori.ConnettoreHTTP;
  64. import org.openspcoop2.pdd.core.connettori.ConnettoreHTTPS;
  65. import org.openspcoop2.pdd.core.connettori.ConnettoreMsg;
  66. import org.openspcoop2.pdd.core.controllo_traffico.PolicyTimeoutConfig;
  67. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  68. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  69. import org.openspcoop2.pdd.core.dynamic.ErrorHandler;
  70. import org.openspcoop2.pdd.core.dynamic.MessageContent;
  71. import org.openspcoop2.pdd.core.dynamic.Template;
  72. import org.openspcoop2.pdd.core.token.attribute_authority.AttributeAuthorityDynamicParameters;
  73. import org.openspcoop2.pdd.core.token.attribute_authority.BasicRetrieveAttributeAuthorityResponseParser;
  74. import org.openspcoop2.pdd.core.token.attribute_authority.EsitoRecuperoAttributi;
  75. import org.openspcoop2.pdd.core.token.attribute_authority.IRetrieveAttributeAuthorityResponseParser;
  76. import org.openspcoop2.pdd.core.token.attribute_authority.InformazioniAttributi;
  77. import org.openspcoop2.pdd.core.token.attribute_authority.PolicyAttributeAuthority;
  78. import org.openspcoop2.pdd.core.token.attribute_authority.RequiredAttributes;
  79. import org.openspcoop2.pdd.core.token.attribute_authority.pa.EsitoRecuperoAttributiPortaApplicativa;
  80. import org.openspcoop2.pdd.core.token.attribute_authority.pd.EsitoRecuperoAttributiPortaDelegata;
  81. import org.openspcoop2.pdd.core.token.parser.Claims;
  82. import org.openspcoop2.pdd.services.connector.FormUrlEncodedHttpServletRequest;
  83. import org.openspcoop2.protocol.sdk.Busta;
  84. import org.openspcoop2.protocol.sdk.Context;
  85. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  86. import org.openspcoop2.protocol.sdk.state.IState;
  87. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  88. import org.openspcoop2.security.SecurityException;
  89. import org.openspcoop2.security.keystore.CRLCertstore;
  90. import org.openspcoop2.security.keystore.JWKSetStore;
  91. import org.openspcoop2.security.keystore.KeyPairStore;
  92. import org.openspcoop2.security.keystore.MerlinKeystore;
  93. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  94. import org.openspcoop2.security.keystore.cache.GestoreOCSPResource;
  95. import org.openspcoop2.security.keystore.cache.GestoreOCSPValidator;
  96. import org.openspcoop2.security.message.constants.SecurityConstants;
  97. import org.openspcoop2.utils.LoggerBuffer;
  98. import org.openspcoop2.utils.UtilsException;
  99. import org.openspcoop2.utils.certificate.JWKSet;
  100. import org.openspcoop2.utils.certificate.KeyStore;
  101. import org.openspcoop2.utils.certificate.KeystoreType;
  102. import org.openspcoop2.utils.certificate.byok.BYOKProvider;
  103. import org.openspcoop2.utils.certificate.byok.BYOKRequestParams;
  104. import org.openspcoop2.utils.date.DateManager;
  105. import org.openspcoop2.utils.date.DateUtils;
  106. import org.openspcoop2.utils.id.UniqueIdentifierManager;
  107. import org.openspcoop2.utils.io.Base64Utilities;
  108. import org.openspcoop2.utils.json.JSONUtils;
  109. import org.openspcoop2.utils.properties.PropertiesUtilities;
  110. import org.openspcoop2.utils.security.CertificateValidityCheck;
  111. import org.openspcoop2.utils.security.JOSESerialization;
  112. import org.openspcoop2.utils.security.JWSOptions;
  113. import org.openspcoop2.utils.security.JWTOptions;
  114. import org.openspcoop2.utils.security.JsonSignature;
  115. import org.openspcoop2.utils.security.JsonVerifySignature;
  116. import org.openspcoop2.utils.security.JwtHeaders;
  117. import org.openspcoop2.utils.transport.TransportRequestContext;
  118. import org.openspcoop2.utils.transport.TransportUtils;
  119. import org.openspcoop2.utils.transport.http.HttpConstants;
  120. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  121. import org.openspcoop2.utils.transport.http.HttpResponse;
  122. import org.openspcoop2.utils.transport.http.HttpServletTransportRequestContext;
  123. import org.openspcoop2.utils.transport.http.IOCSPValidator;
  124. import org.slf4j.Logger;

  125. import com.fasterxml.jackson.databind.JsonNode;
  126. import com.fasterxml.jackson.databind.node.ObjectNode;

  127. /**    
  128.  * GestoreTokenAttributeAuthorityUtilities
  129.  *
  130.  * @author Poli Andrea (poli@link.it)
  131.  * @author $Author$
  132.  * @version $Rev$, $Date$
  133.  */
  134. public class GestoreTokenAttributeAuthorityUtilities {

  135.     private GestoreTokenAttributeAuthorityUtilities(){}
  136.        
  137.     static EsitoRecuperoAttributi readAttributes(Logger log, PolicyAttributeAuthority policyAttributeAuthority,
  138.             IProtocolFactory<?> protocolFactory,
  139.             AttributeAuthorityDynamicParameters dynamicParameters,
  140.             String request, boolean portaDelegata, Context context,
  141.             Busta busta, String idModulo, PortaApplicativa pa, PortaDelegata pd,
  142.             IState state,
  143.             IDSoggetto idDominio, IDServizio idServizio,
  144.             RequestInfo requestInfo) {
  145.         EsitoRecuperoAttributi esitoRecuperoAttributi = null;
  146.         if(portaDelegata) {
  147.             esitoRecuperoAttributi = new EsitoRecuperoAttributiPortaDelegata();
  148.         }
  149.         else {
  150.             esitoRecuperoAttributi = new EsitoRecuperoAttributiPortaApplicativa();
  151.         }
  152.        
  153.         esitoRecuperoAttributi.setTokenInternalError();
  154.        
  155.         try{            
  156.             String detailsError = null;
  157.             InformazioniAttributi informazioniAttributi = null;
  158.             Exception eProcess = null;
  159.            
  160.             IRetrieveAttributeAuthorityResponseParser tokenParser = policyAttributeAuthority.getRetrieveAttributeAuthorityResponseParser(log);
  161.            
  162.             HttpResponse httpResponse = null;
  163.             Integer httpResponseCode = null;
  164.             byte[] risposta = null;
  165.             try {
  166.                 httpResponse = http(log, policyAttributeAuthority,
  167.                         protocolFactory,
  168.                         dynamicParameters,
  169.                         request,
  170.                         state, portaDelegata, idModulo, pa, pd,
  171.                         idDominio, idServizio,
  172.                         busta, requestInfo);
  173.                 risposta = httpResponse.getContent();
  174.                 httpResponseCode = httpResponse.getResultHTTPOperation();
  175.             }catch(Exception e) {
  176.                 detailsError = "(Errore di Connessione) "+ e.getMessage();
  177.                 eProcess = e;
  178.             }
  179.            
  180.             if(detailsError==null) {
  181.                
  182.                 String decodedPayload = null;
  183.                 byte[] decodedPayloadAsBytes = null;
  184.                 if(policyAttributeAuthority.isResponseJws()) {
  185.                     // JWS Compact              
  186.                     JsonVerifySignature jsonCompactVerify = null;
  187.                     try {
  188.                         JWTOptions options = new JWTOptions(JOSESerialization.COMPACT);
  189.                         Properties p = policyAttributeAuthority.getProperties().get(org.openspcoop2.pdd.core.token.attribute_authority.Costanti.POLICY_VALIDAZIONE_JWS_VERIFICA_PROP_REF_ID);
  190.                         TokenUtilities.injectJOSEConfig(p, policyAttributeAuthority, null,  
  191.                                 busta, idDominio, idServizio,
  192.                                 context, log,
  193.                                 requestInfo, state, portaDelegata);
  194.                        
  195.                         // serve per leggere il keystore dalla cache
  196.                         TokenKeystoreInjectUtilities inject = new TokenKeystoreInjectUtilities(log, requestInfo ,
  197.                                 protocolFactory,
  198.                                 context, state, busta);
  199.                         inject.initAttributeAuthorityValidazioneRispostaJwt(policyAttributeAuthority.getName(), portaDelegata, pd, pa, p);
  200.                         inject.inject(p);
  201.                        
  202.                         String aliasMode = p.getProperty(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS+".mode");
  203.                         if(aliasMode!=null &&
  204.                                 (
  205.                                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C)
  206.                                         ||
  207.                                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5T256)
  208.                                         ||
  209.                                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C_X5T256)
  210.                                         ||
  211.                                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_KID)
  212.                                         ||
  213.                                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5U)
  214.                                 )
  215.                             ) {
  216.                            
  217.                             options.setPermitUseHeaderX5C(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C) || aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C_X5T256));
  218.                             // se lo si vuole usare utilizzare la vecchia modalità alias special case
  219.                             /** options.setPermitUseHeaderX5T(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5T256) || aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C_X5T256)); */
  220.                             options.setPermitUseHeaderX5T_256(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5T256) || aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C_X5T256));
  221.                             options.setPermitUseHeaderKID(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_KID));
  222.                             options.setPermitUseHeaderX5U(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5U));
  223.                                                        
  224.                             if(p.containsKey(SecurityConstants.JOSE_KEYSTORE)) {
  225.                                 Object oKeystore = p.get(SecurityConstants.JOSE_KEYSTORE);
  226.                                 if(oKeystore instanceof java.security.KeyStore) {
  227.                                     java.security.KeyStore keystore = (java.security.KeyStore) oKeystore;
  228.                                     jsonCompactVerify = new JsonVerifySignature(keystore, options);
  229.                                    
  230.                                     CertificateValidityCheck validityCheck = OpenSPCoop2Properties.getInstance().getGestioneAttributeAuthorityValidityCheck();
  231.                                     List<Proprieta> proprieta = null;
  232.                                     if(pa!=null) {
  233.                                         proprieta = pa.getProprietaList();
  234.                                     }
  235.                                     else if(pd!=null) {
  236.                                         proprieta = pd.getProprietaList();
  237.                                     }
  238.                                     validityCheck = CostantiProprieta.getAttributeAuthorityCertificateValidityCheck(proprieta, validityCheck);
  239.                                     jsonCompactVerify.setValidityCheck(validityCheck);
  240.                                    
  241.                                     String signatureOCSP = policyAttributeAuthority.getResponseJwsOcspPolicy();
  242.                                     String signatureCRL = policyAttributeAuthority.getResponseJwsCrl();
  243.                                    
  244.                                     boolean crlByOcsp = false;
  245.                                     if(keystore!=null && signatureOCSP!=null && !"".equals(signatureOCSP)) {
  246.                                         LoggerBuffer lb = new LoggerBuffer();
  247.                                         lb.setLogDebug(log);
  248.                                         lb.setLogError(log);
  249.                                         GestoreOCSPResource ocspResourceReader = new GestoreOCSPResource(requestInfo);
  250.                                         IOCSPValidator ocspValidator = null;
  251.                                         try {
  252.                                             org.openspcoop2.utils.certificate.KeyStore trustStore = new org.openspcoop2.utils.certificate.KeyStore(keystore);
  253.                                             ocspValidator = new GestoreOCSPValidator(requestInfo, lb,
  254.                                                     trustStore,
  255.                                                     signatureCRL,
  256.                                                     signatureOCSP,
  257.                                                     ocspResourceReader);
  258.                                         }catch(Exception e){
  259.                                             throw new TokenException("ocsp initialization (policy:'"+signatureOCSP+"') failed: "+e.getMessage(),e);
  260.                                         }
  261.                                         if(ocspValidator!=null) {
  262.                                             jsonCompactVerify.setOcspValidatorX509(ocspValidator);
  263.                                             GestoreOCSPValidator gOcspValidator = (GestoreOCSPValidator) ocspValidator;
  264.                                             if(gOcspValidator.getOcspConfig()!=null) {
  265.                                                 crlByOcsp = gOcspValidator.getOcspConfig().isCrl();
  266.                                             }
  267.                                         }
  268.                                     }
  269.                                    
  270.                                     if(signatureCRL!=null && !"".equals(signatureCRL) && !crlByOcsp) {
  271.                                         CRLCertstore crlCertstore = GestoreKeystoreCache.getCRLCertstore(requestInfo, signatureCRL);
  272.                                         if(crlCertstore==null) {
  273.                                             throw new TokenException("Process CRL '"+signatureCRL+"' failed");
  274.                                         }
  275.                                         jsonCompactVerify.setCrlX509(crlCertstore.getCertStore());
  276.                                     }

  277.                                 }
  278.                             }
  279.                             else if(p.containsKey(SecurityConstants.JOSE_KEYSTORE_JWKSET)) {
  280.                                 Object oKeystore = p.get(SecurityConstants.JOSE_KEYSTORE_JWKSET);
  281.                                 if(oKeystore instanceof String) {
  282.                                     String keystore = (String) oKeystore;
  283.                                     JsonWebKeys jwksKeystore = new JWKSet(keystore).getJsonWebKeys();
  284.                                     jsonCompactVerify = new JsonVerifySignature(jwksKeystore, options);
  285.                                 }
  286.                             }
  287.                         }
  288.                                            
  289.                         if(jsonCompactVerify==null) {
  290.                             jsonCompactVerify = new JsonVerifySignature(p, options);
  291.                         }
  292.                        
  293.                         jsonCompactVerify.setJksPasswordRequired(DBUtils.isTruststoreJksPasswordRequired());
  294.                         jsonCompactVerify.setPkcs12PasswordRequired(DBUtils.isTruststorePkcs12PasswordRequired());
  295.                        
  296.                         if(jsonCompactVerify.verify(new String(risposta))) {
  297.                             if(tokenParser instanceof BasicRetrieveAttributeAuthorityResponseParser) {
  298.                                 decodedPayload = jsonCompactVerify.getDecodedPayload();
  299.                             }
  300.                             else {
  301.                                 decodedPayloadAsBytes = jsonCompactVerify.getDecodedPayloadAsByte();
  302.                             }
  303.                         }
  304.                         else {
  305.                             detailsError = "Risposta non valida";
  306.                         }
  307.                     }catch(Exception e) {
  308.                         detailsError = "Risposta non valida: "+e.getMessage();
  309.                         eProcess = e;
  310.                     }
  311.                 }
  312.                
  313.                 if(detailsError==null) {
  314.                     try {
  315.                         if(tokenParser instanceof BasicRetrieveAttributeAuthorityResponseParser) {
  316.                             informazioniAttributi = new InformazioniAttributi(httpResponseCode, policyAttributeAuthority.getName(),
  317.                                     decodedPayload!=null ? decodedPayload : new String(risposta),
  318.                                     tokenParser);      
  319.                         }
  320.                         else {
  321.                             informazioniAttributi = new InformazioniAttributi(httpResponseCode, policyAttributeAuthority.getName(),
  322.                                     decodedPayloadAsBytes!=null ? decodedPayloadAsBytes : risposta,
  323.                                     tokenParser);      
  324.                         }
  325.                     }catch(Exception e) {
  326.                         detailsError = "Risposta del servizio di negoziazione token non valida: "+e.getMessage();
  327.                         eProcess = e;
  328.                     }
  329.                 }
  330.             }
  331.                    
  332.             if(informazioniAttributi!=null && informazioniAttributi.isValid()) {
  333.                 esitoRecuperoAttributi.setTokenValido();
  334.                 esitoRecuperoAttributi.setInformazioniAttributi(informazioniAttributi);
  335.                 esitoRecuperoAttributi.setNoCache(false);
  336.             }
  337.             else {
  338.                 esitoRecuperoAttributi.setTokenValidazioneFallita();
  339.                 esitoRecuperoAttributi.setNoCache(!policyAttributeAuthority.isSaveErrorInCache());
  340.                 esitoRecuperoAttributi.setEccezioneProcessamento(eProcess);
  341.                 if(detailsError!=null) {
  342.                     esitoRecuperoAttributi.setDetails(detailsError);    
  343.                 }
  344.                 else {
  345.                     esitoRecuperoAttributi.setDetails("Attributi non recuperabili");    
  346.                 }  
  347.             }
  348.            
  349.         }catch(Exception e){
  350.             esitoRecuperoAttributi.setTokenInternalError();
  351.             esitoRecuperoAttributi.setDetails(e.getMessage());
  352.             esitoRecuperoAttributi.setEccezioneProcessamento(e);
  353.         }
  354.        
  355.         return esitoRecuperoAttributi;
  356.     }
  357.    
  358.     static String buildCacheKeyRecuperoAttributiPrefix(String nomePolicy, String funzione) {
  359.         StringBuilder bf = new StringBuilder("AttributeAuthority_"+funzione);
  360.         bf.append("_");
  361.         bf.append(nomePolicy);
  362.         bf.append("_");
  363.         return bf.toString();
  364.     }
  365.     static String buildCacheKeyRecuperoAttributi(String nomePolicy, String funzione, boolean portaDelegata,
  366.             AttributeAuthorityDynamicParameters dynamicParameters, String request) {
  367.         StringBuilder bf = new StringBuilder();
  368.         bf.append(buildCacheKeyRecuperoAttributiPrefix(nomePolicy, funzione));
  369.         if(portaDelegata){ // serve per non aver classcast exception nei risultati
  370.             bf.append("PD");
  371.         }
  372.         else {
  373.             bf.append("PA");
  374.         }
  375.         bf.append("_");
  376.        
  377.         String dynamicParametersKeyCache = dynamicParameters.toString("_", true);
  378.         bf.append(dynamicParametersKeyCache);
  379.         bf.append("_");
  380.        
  381.         bf.append(Base64Utilities.encodeAsString(request.getBytes())); // codifico in base64 la richiesta
  382.         return bf.toString();
  383.     }
  384.    
  385.    
  386.     static Map<String, Object> buildDynamicAAMap(OpenSPCoop2Message message, Busta busta,
  387.             RequestInfo requestInfo, PdDContext pddContext, Logger log,
  388.             String nomeAttributeAuthority,
  389.             org.openspcoop2.pdd.core.token.attribute_authority.AbstractDatiInvocazione datiInvocazione) throws TokenException {
  390.    
  391.         Map<String, Object> dynamicMap = new HashMap<>();
  392.        
  393.         Map<String, List<String>> pTrasporto = null;
  394.         String urlInvocazione = null;
  395.         Map<String, List<String>> pQuery = null;
  396.         Map<String, List<String>> pForm = null;
  397.         if(requestInfo!=null && requestInfo.getProtocolContext()!=null) {
  398.             pTrasporto = requestInfo.getProtocolContext().getHeaders();
  399.             urlInvocazione = requestInfo.getProtocolContext().getUrlInvocazione_formBased();
  400.             pQuery = requestInfo.getProtocolContext().getParameters();
  401.             if(requestInfo.getProtocolContext() instanceof HttpServletTransportRequestContext) {
  402.                 HttpServletTransportRequestContext httpServletContext = requestInfo.getProtocolContext();
  403.                 HttpServletRequest httpServletRequest = httpServletContext.getHttpServletRequest();
  404.                 if(httpServletRequest instanceof FormUrlEncodedHttpServletRequest) {
  405.                     FormUrlEncodedHttpServletRequest formServlet = (FormUrlEncodedHttpServletRequest) httpServletRequest;
  406.                     if(formServlet.getFormUrlEncodedParametersValues()!=null &&
  407.                             !formServlet.getFormUrlEncodedParametersValues().isEmpty()) {
  408.                         pForm = formServlet.getFormUrlEncodedParametersValues();
  409.                     }
  410.                 }
  411.             }
  412.         }
  413.        
  414.         MessageContent messageContent = null;
  415.         try {
  416.             boolean bufferMessageReadOnly =  OpenSPCoop2Properties.getInstance().isReadByPathBufferEnabled();
  417.             if(ServiceBinding.SOAP.equals(message.getServiceBinding())){
  418.                 messageContent = new MessageContent(message.castAsSoap(), bufferMessageReadOnly, pddContext);
  419.             }
  420.             else{
  421.                 if(MessageType.XML.equals(message.getMessageType())){
  422.                     messageContent = new MessageContent(message.castAsRestXml(), bufferMessageReadOnly, pddContext);
  423.                 }
  424.                 else if(MessageType.JSON.equals(message.getMessageType())){
  425.                     messageContent = new MessageContent(message.castAsRestJson(), bufferMessageReadOnly, pddContext);
  426.                 }
  427.             }
  428.         }catch(Exception e) {
  429.             throw new TokenException(e.getMessage(),e);
  430.         }
  431.        
  432.         ErrorHandler errorHandler = new ErrorHandler();
  433.         DynamicUtils.fillDynamicMapRequest(log, dynamicMap, pddContext, urlInvocazione,
  434.                 message,
  435.                 messageContent,
  436.                 busta,
  437.                 pTrasporto,
  438.                 pQuery,
  439.                 pForm,
  440.                 errorHandler);
  441.        
  442.         List<String> listAttributi = null;
  443.         if(datiInvocazione instanceof org.openspcoop2.pdd.core.token.attribute_authority.pa.DatiInvocazionePortaApplicativa) {
  444.             org.openspcoop2.pdd.core.token.attribute_authority.pa.DatiInvocazionePortaApplicativa datiPA =
  445.                     (org.openspcoop2.pdd.core.token.attribute_authority.pa.DatiInvocazionePortaApplicativa) datiInvocazione;
  446.             if(datiPA.getPa()!=null && datiPA.getPa().sizeAttributeAuthorityList()>0) {
  447.                 for (AttributeAuthority aa : datiPA.getPa().getAttributeAuthorityList()) {
  448.                     if(nomeAttributeAuthority.equals(aa.getNome())) {
  449.                         listAttributi = aa.getAttributoList();
  450.                         break;
  451.                     }
  452.                 }
  453.             }
  454.             else if(datiPA.getPd()!=null && datiPA.getPd().sizeAttributeAuthorityList()>0) {
  455.                 for (AttributeAuthority aa : datiPA.getPd().getAttributeAuthorityList()) {
  456.                     if(nomeAttributeAuthority.equals(aa.getNome())) {
  457.                         listAttributi = aa.getAttributoList();
  458.                         break;
  459.                     }
  460.                 }
  461.             }
  462.         }
  463.         else if(datiInvocazione instanceof org.openspcoop2.pdd.core.token.attribute_authority.pd.DatiInvocazionePortaDelegata) {
  464.             org.openspcoop2.pdd.core.token.attribute_authority.pd.DatiInvocazionePortaDelegata datiPD =
  465.                     (org.openspcoop2.pdd.core.token.attribute_authority.pd.DatiInvocazionePortaDelegata) datiInvocazione;
  466.             if(datiPD.getPd()!=null && datiPD.getPd().sizeAttributeAuthorityList()>0) {
  467.                 for (AttributeAuthority aa : datiPD.getPd().getAttributeAuthorityList()) {
  468.                     if(nomeAttributeAuthority.equals(aa.getNome())) {
  469.                         listAttributi = aa.getAttributoList();
  470.                         break;
  471.                     }
  472.                 }
  473.             }
  474.         }
  475.        
  476.         // Viene messo sempre per facilitare la scrittura delle regole
  477.         if(listAttributi==null) {
  478.             listAttributi = new ArrayList<>();
  479.         }
  480.         /**if(listAttributi!=null && listAttributi.size()>0) {*/
  481.         RequiredAttributes reqAttrs = new RequiredAttributes(listAttributi);
  482.         dynamicMap.put(org.openspcoop2.pdd.core.dynamic.Costanti.MAP_REQUIRED_ATTRIBUTES, reqAttrs);
  483.         dynamicMap.put(org.openspcoop2.pdd.core.dynamic.Costanti.MAP_REQUIRED_ATTRIBUTES.toLowerCase(), reqAttrs);
  484.        
  485.         return dynamicMap;
  486.     }
  487.    
  488.     static String buildDynamicAARequest(ConfigurazionePdDManager configurazionePdDManager,
  489.             IProtocolFactory<?> protocolFactory, RequestInfo requestInfo,
  490.             PolicyAttributeAuthority policyAttributeAuthority,
  491.             AttributeAuthorityDynamicParameters dynamicParameters,
  492.             boolean addIdAndDate) throws TokenException, UtilsException {
  493.            
  494.         String dynamicContent = policyAttributeAuthority.getRequestDynamicPayload();
  495.         String request = null;
  496.        
  497.         if(policyAttributeAuthority.isRequestDynamicPayloadTemplate() || policyAttributeAuthority.isRequestDynamicPayloadJwt()) {
  498.             if(policyAttributeAuthority.isRequestDynamicPayloadTemplate()) {
  499.                 request = dynamicParameters.getRequestDynamicPayloadTemplate();
  500.             }
  501.             else {
  502.                 request = buildAAJwt(policyAttributeAuthority, dynamicParameters,
  503.                         protocolFactory, requestInfo,
  504.                         addIdAndDate);
  505.             }
  506.         }
  507.         else if(policyAttributeAuthority.isRequestDynamicPayloadFreemarkerTemplate()) {
  508.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  509.             try {
  510.                 Template template = configurazionePdDManager.getTemplateAttributeAuthorityRequest(policyAttributeAuthority.getName(), dynamicContent.getBytes(), requestInfo);
  511.                 DynamicUtils.convertFreeMarkerTemplate(template, dynamicParameters.getDynamicMap(), bout);
  512.                 bout.flush();
  513.                 bout.close();
  514.             }catch(Exception e) {
  515.                 throw new TokenException(e.getMessage(),e);
  516.             }
  517.             request = bout.toString();
  518.            
  519.             if(policyAttributeAuthority.isRequestJws()) {
  520.                 request = normalizeJwtPayload(request);
  521.             }
  522.         }
  523.         else if(policyAttributeAuthority.isRequestDynamicPayloadVelocityTemplate()) {
  524.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  525.             try {
  526.                 Template template = configurazionePdDManager.getTemplateAttributeAuthorityRequest(policyAttributeAuthority.getName(), dynamicContent.getBytes(), requestInfo);
  527.                 DynamicUtils.convertVelocityTemplate(template, dynamicParameters.getDynamicMap(), bout);
  528.                 bout.flush();
  529.                 bout.close();
  530.             }catch(Exception e) {
  531.                 throw new TokenException(e.getMessage(),e);
  532.             }
  533.             request = bout.toString();
  534.            
  535.             if(policyAttributeAuthority.isRequestJws()) {
  536.                 request = normalizeJwtPayload(request);
  537.             }
  538.         }
  539.         if(request==null || "".equals(request)) {
  540.             throw new TokenException("Request undefined");
  541.         }
  542.        
  543.         return request;
  544.     }
  545.    
  546.     private static String normalizeJwtPayload(String payload) throws UtilsException {
  547.         JSONUtils jsonUtils = JSONUtils.getInstance(false);
  548.         JsonNode jwtPayload = jsonUtils.getAsNode(payload);
  549.         return jsonUtils.toString(jwtPayload);
  550.     }
  551.    
  552.     private static String buildAAJwt(PolicyAttributeAuthority policyAttributeAuthority,
  553.             AttributeAuthorityDynamicParameters dynamicParameters,
  554.             IProtocolFactory<?> protocolFactory, RequestInfo requestInfo,
  555.             boolean addIdAndDate) throws TokenException, UtilsException {
  556.        
  557.         // https://datatracker.ietf.org/doc/html/rfc7523
  558.        
  559.         OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  560.         JSONUtils jsonUtils = JSONUtils.getInstance(false);
  561.        
  562.         ObjectNode jwtPayload = jsonUtils.newObjectNode();

  563.         // add iat, nbf, exp
  564.         long nowMs = DateManager.getTimeMillis();
  565.         long nowSeconds = nowMs/1000;
  566.        
  567.         String issuer = dynamicParameters.getIssuer();
  568.         if(issuer==null || "".equals(issuer)) {
  569.             issuer = op2Properties.getIdentitaPortaDefault(protocolFactory!=null ? protocolFactory.getProtocol() : null, requestInfo).getNome();
  570.         }
  571.         jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUER, issuer);
  572.        
  573.         String subject = dynamicParameters.getSubject();
  574.         if(subject==null) {
  575.             throw new TokenException("JWT-Subject undefined");
  576.         }
  577.         jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_SUBJECT, subject);
  578.        
  579.         // The JWT MUST contain an "aud" (audience) claim containing a value that identifies the authorization server as an intended audience.
  580.         String audience = dynamicParameters.getAudience();
  581.         if(audience==null) {
  582.             throw new TokenException("JWT-Audience undefined");
  583.         }
  584.         jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_AUDIENCE, audience);
  585.        
  586.         // claims
  587.         String claims = dynamicParameters.getClaims();
  588.         if(claims!=null && !"".equals(claims)) {
  589.             Properties convertTextToProperties = PropertiesUtilities.convertTextToProperties(claims);
  590.             if(convertTextToProperties!=null && !convertTextToProperties.isEmpty()) {
  591.                 Enumeration<Object> keys = convertTextToProperties.keys();
  592.                 while (keys.hasMoreElements()) {
  593.                     String nome = (String) keys.nextElement();
  594.                     if(nome!=null && !"".equals(nome)) {
  595.                         String valore = convertTextToProperties.getProperty(nome);
  596.                         if(valore!=null) {
  597.                             jsonUtils.putValue(jwtPayload, nome, valore);
  598.                         }
  599.                     }
  600.                 }
  601.             }
  602.         }
  603.        
  604.         if(addIdAndDate) {
  605.        
  606.             // The JWT MAY contain an "iat" (issued at) claim that identifies the time at which the JWT was issued.
  607.             jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUED_AT, nowSeconds);
  608.            
  609.             // The JWT MAY contain an "nbf" (not before) claim that identifies the time before which the token MUST NOT be accepted for processing.
  610.             jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_NOT_TO_BE_USED_BEFORE, nowSeconds);
  611.            
  612.             // The JWT MUST contain an "exp" (expiration time) claim that limits the time window during which the JWT can be used.
  613.             int ttl = -1;
  614.             try {
  615.                 ttl = policyAttributeAuthority.getJwtTtlSeconds();
  616.             }catch(Exception e) {
  617.                 throw new TokenException("Invalid JWT-TimeToLive value: "+e.getMessage(),e);
  618.             }
  619.             long expired = nowSeconds+ttl;
  620.             jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_EXPIRED, expired);
  621.            
  622.             // The JWT MAY contain a "jti" (JWT ID) claim that provides a unique identifier for the token.
  623.             String uuid = null;
  624.             try {
  625.                 uuid = UniqueIdentifierManager.newUniqueIdentifier().toString();
  626.             }catch(Exception e) {
  627.                 throw new TokenException("Invalid JWT-TimeToLive value: "+e.getMessage(),e);
  628.             }
  629.             jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID, uuid);
  630.            
  631.         }
  632.        
  633.         return jsonUtils.toString(jwtPayload);
  634.     }
  635.    
  636.     static void validazioneInformazioniAttributiRecuperati(EsitoRecuperoAttributi esitoRecuperoAttributi, PolicyAttributeAuthority policyAttributeAuthority, boolean saveErrorInCache,
  637.             AttributeAuthorityDynamicParameters dynamicParameters) throws TokenException, ProviderException, ProviderValidationException {
  638.        
  639.         Date now = DateManager.getDate();
  640.        
  641.         if(esitoRecuperoAttributi.isValido()) {
  642.             esitoRecuperoAttributi.setDateValide(true); // tanto le ricontrollo adesso
  643.         }
  644.        
  645.         if(esitoRecuperoAttributi.isValido() &&    
  646.             esitoRecuperoAttributi.getInformazioniAttributi().getExp()!=null &&            
  647.             !now.before(esitoRecuperoAttributi.getInformazioniAttributi().getExp())){
  648.             /*
  649.              *  The lifetime in seconds of the access token.  For example, the value "3600" denotes that the access token will
  650.              * expire in one hour from the time the response was generated.
  651.              * If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value.
  652.              **/
  653.             esitoRecuperoAttributi.setTokenScaduto();
  654.             esitoRecuperoAttributi.setDateValide(false);
  655.             esitoRecuperoAttributi.setDetails("Response attributes expired");
  656.         }
  657.            
  658.         if(esitoRecuperoAttributi.isValido() &&
  659.             esitoRecuperoAttributi.getInformazioniAttributi().getNbf()!=null &&    
  660.             !esitoRecuperoAttributi.getInformazioniAttributi().getNbf().before(now)){
  661.             /*
  662.              *   The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing.  
  663.              **/
  664.             esitoRecuperoAttributi.setTokenNotUsableBefore();
  665.             esitoRecuperoAttributi.setDateValide(false);
  666.             SimpleDateFormat sdf = DateUtils.getDefaultDateTimeFormatter(GestoreToken.DATE_FORMAT);
  667.             esitoRecuperoAttributi.setDetails("Response attributes not usable before "+sdf.format(esitoRecuperoAttributi.getInformazioniAttributi().getNbf()));
  668.         }
  669.        
  670.         if(esitoRecuperoAttributi.isValido() &&
  671.             esitoRecuperoAttributi.getInformazioniAttributi().getIat()!=null) {            
  672.             /*
  673.              *   The "iat" (issued at) claim identifies the time at which the JWT was issued.  This claim can be used to determine the age of the JWT.
  674.              *   The iat Claim can be used to reject tokens that were issued too far away from the current time,
  675.              *   limiting the amount of time that nonces need to be stored to prevent attacks. The acceptable range is Client specific.
  676.              **/
  677.             Long old = null;
  678.             try {
  679.                 old = OpenSPCoop2Properties.getInstance().getGestioneTokenIatTimeCheckMilliseconds();
  680.             }catch(Exception e) {
  681.                 throw new TokenException(e.getMessage(),e);
  682.             }
  683.             if(old!=null) {
  684.                 Date oldMax = new Date((DateManager.getTimeMillis() - old.longValue()));
  685.                 if(esitoRecuperoAttributi.getInformazioniAttributi().getIat().before(oldMax)) {
  686.                     esitoRecuperoAttributi.setTokenScaduto();
  687.                     esitoRecuperoAttributi.setDateValide(false);
  688.                     SimpleDateFormat sdf = DateUtils.getDefaultDateTimeFormatter(GestoreToken.DATE_FORMAT);
  689.                     esitoRecuperoAttributi.setDetails("Response attributes expired; iat time '"+sdf.format(esitoRecuperoAttributi.getInformazioniAttributi().getIat())+"' too old");
  690.                 }
  691.             }
  692.             Long future = null;
  693.             try {
  694.                 future = OpenSPCoop2Properties.getInstance().getGestioneTokenIatTimeCheckFutureToleranceMilliseconds();
  695.             }catch(Exception e) {
  696.                 throw new TokenException(e.getMessage(),e);
  697.             }
  698.             if(future!=null) {
  699.                 Date futureMax = new Date((DateManager.getTimeMillis() + future.longValue()));
  700.                 if(esitoRecuperoAttributi.getInformazioniAttributi().getIat().after(futureMax)) {
  701.                     esitoRecuperoAttributi.setTokenInTheFuture();
  702.                     esitoRecuperoAttributi.setDateValide(false);
  703.                     SimpleDateFormat sdf = DateUtils.getDefaultDateTimeFormatter(GestoreToken.DATE_FORMAT);
  704.                     esitoRecuperoAttributi.setDetails("Response attributes valid in the future; iat time '"+sdf.format(esitoRecuperoAttributi.getInformazioniAttributi().getIat())+"' is in the future");
  705.                 }
  706.             }
  707.         }
  708.        
  709.         if(esitoRecuperoAttributi.isValido()) {    
  710.             String audience = dynamicParameters.getResponseAudience();
  711.             if(audience!=null && !"".equals(audience) &&
  712.                 ( esitoRecuperoAttributi.getInformazioniAttributi().getAud()==null || !esitoRecuperoAttributi.getInformazioniAttributi().getAud().contains(audience) )
  713.                 ){              
  714.                 esitoRecuperoAttributi.setTokenValidazioneFallita();
  715.                 esitoRecuperoAttributi.setNoCache(!policyAttributeAuthority.isSaveErrorInCache());
  716.                 esitoRecuperoAttributi.setDetails("Invalid audience");  
  717.             }
  718.         }
  719.        
  720.         if(
  721.             esitoRecuperoAttributi.isValido() &&
  722.             (esitoRecuperoAttributi.getInformazioniAttributi().getAttributes()==null || esitoRecuperoAttributi.getInformazioniAttributi().getAttributes().isEmpty())
  723.             ) {
  724.             esitoRecuperoAttributi.setNoCache(!policyAttributeAuthority.isSaveErrorInCache());
  725.             esitoRecuperoAttributi.setDetails("No attributes retrieved");
  726.         }
  727.        
  728.         if(!esitoRecuperoAttributi.isValido()) {
  729.             esitoRecuperoAttributi.setNoCache(!saveErrorInCache);
  730.         }
  731.     }
  732.    
  733.     private static HttpResponse http(Logger log, PolicyAttributeAuthority policyAttributeAuthority,
  734.             IProtocolFactory<?> protocolFactory,
  735.             AttributeAuthorityDynamicParameters dynamicParameters,
  736.             String request,
  737.             IState state, boolean delegata, String idModulo, PortaApplicativa pa, PortaDelegata pd,
  738.             IDSoggetto idDominio, IDServizio idServizio,
  739.             Busta busta, RequestInfo requestInfo) throws Exception {
  740.        
  741.         // *** Raccola Parametri ***
  742.        
  743.         String endpoint = dynamicParameters.getEndpoint();
  744.         HttpRequestMethod httpMethod = policyAttributeAuthority.getRequestHttpMethod();
  745.        
  746.        
  747.         // Nell'endpoint config ci finisce i timeout e la configurazione proxy
  748.         Properties endpointConfig = policyAttributeAuthority.getProperties().get(Costanti.POLICY_ENDPOINT_CONFIG);
  749.        
  750.         boolean https = policyAttributeAuthority.isEndpointHttps();
  751.         boolean httpsClient = false;
  752.         Properties sslConfig = null;
  753.         Properties sslClientConfig = null;
  754.         if(https) {
  755.             sslConfig = policyAttributeAuthority.getProperties().get(Costanti.POLICY_ENDPOINT_SSL_CONFIG);
  756.             httpsClient = policyAttributeAuthority.isHttpsAuthentication();
  757.             if(httpsClient) {
  758.                 sslClientConfig = policyAttributeAuthority.getProperties().get(Costanti.POLICY_ENDPOINT_SSL_CLIENT_CONFIG);
  759.                 TokenUtilities.injectSameKeystoreForHttpsClient(sslConfig, sslClientConfig);
  760.             }
  761.         }
  762.        
  763.         boolean basic = policyAttributeAuthority.isBasicAuthentication();
  764.         String username = null;
  765.         String password = null;
  766.         if(basic) {
  767.             username = dynamicParameters.getBasicUsername();
  768.             password = dynamicParameters.getBasicPassword();
  769.         }
  770.        
  771.         boolean bearer = policyAttributeAuthority.isBearerAuthentication();
  772.         String bearerToken = null;
  773.         if(bearer) {
  774.             bearerToken = dynamicParameters.getBearerToken();
  775.         }
  776.        
  777.        
  778.        
  779.         // *** Definizione Endpoint ***
  780.        
  781.         ConnettoreMsg connettoreMsg = new ConnettoreMsg();
  782.         ConnettoreBaseHTTP connettore = null;
  783.         if(https) {
  784.             connettoreMsg.setTipoConnettore(TipiConnettore.HTTPS.getNome());
  785.             connettore = new ConnettoreHTTPS();
  786.         }
  787.         else {
  788.             connettoreMsg.setTipoConnettore(TipiConnettore.HTTP.getNome());
  789.             connettore = new ConnettoreHTTP();
  790.         }
  791.         connettoreMsg.setIdModulo(idModulo);
  792.         connettoreMsg.setState(state);
  793.         PolicyTimeoutConfig policyConfig = new PolicyTimeoutConfig();
  794.         policyConfig.setAttributeAuthority(policyAttributeAuthority.getName());
  795.         connettoreMsg.setPolicyTimeoutConfig(policyConfig);
  796.        
  797.         ForwardProxy forwardProxy = null;
  798.         ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(state);
  799.         if(configurazionePdDManager.isForwardProxyEnabled(requestInfo)) {
  800.             try {
  801.                 IDGenericProperties policy = new IDGenericProperties();
  802.                 policy.setTipologia(CostantiConfigurazione.GENERIC_PROPERTIES_ATTRIBUTE_AUTHORITY);
  803.                 policy.setNome(policyAttributeAuthority.getName());
  804.                 if(delegata) {
  805.                     forwardProxy = configurazionePdDManager.getForwardProxyConfigFruizione(idDominio, idServizio, policy, requestInfo);
  806.                 }
  807.                 else {
  808.                     forwardProxy = configurazionePdDManager.getForwardProxyConfigErogazione(idDominio, idServizio, policy, requestInfo);
  809.                 }
  810.             }catch(Exception e) {
  811.                 throw new TokenException(GestoreToken.getMessageErroreGovWayProxy(e),e);
  812.             }
  813.         }
  814.         if(forwardProxy!=null && forwardProxy.isEnabled() && forwardProxy.getConfigToken()!=null && forwardProxy.getConfigToken().isAttributeAuthorityEnabled()) {
  815.             connettoreMsg.setForwardProxy(forwardProxy);
  816.         }
  817.        
  818.         connettore.setForceDisable_proxyPassReverse(true);
  819.         connettore.init(dynamicParameters.getPddContext(), protocolFactory);
  820.         connettore.setRegisterSendIntoContext(false);
  821.        
  822.         if(basic){
  823.             InvocazioneCredenziali credenziali = new InvocazioneCredenziali();
  824.             credenziali.setUser(username);
  825.             credenziali.setPassword(password);
  826.             connettoreMsg.setCredenziali(credenziali);
  827.         }
  828.        
  829.         connettoreMsg.setConnectorProperties(new java.util.HashMap<>());
  830.         connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_LOCATION, endpoint);
  831.         OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  832.         boolean debug = properties.isGestioneAttributeAuthorityDebug();
  833.         if(debug) {
  834.             connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_DEBUG, true+"");
  835.         }
  836.         connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_HTTP_DATA_TRANSFER_MODE, TransferLengthModes.CONTENT_LENGTH.getNome());
  837.         GestoreToken.addProperties(connettoreMsg, endpointConfig);
  838.         if(https) {
  839.             GestoreToken.addProperties(connettoreMsg, sslConfig);
  840.             if(httpsClient) {
  841.                 GestoreToken.addProperties(connettoreMsg, sslClientConfig);
  842.             }
  843.         }
  844.        
  845.         byte[] content = null;
  846.        
  847.         TransportRequestContext transportRequestContext = new TransportRequestContext(log);
  848.         transportRequestContext.setRequestType(httpMethod.name());
  849.         transportRequestContext.setHeaders(new HashMap<>());
  850.         if(bearer) {
  851.             String authorizationHeader = HttpConstants.AUTHORIZATION_PREFIX_BEARER+bearerToken;
  852.             TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.AUTHORIZATION, authorizationHeader);
  853.         }
  854.        
  855.        
  856.         // *** request ***
  857.         String contentType = policyAttributeAuthority.getRequestContentType();
  858.         if(contentType!=null && !"".equals(contentType)) {
  859.             transportRequestContext.removeHeader(HttpConstants.CONTENT_TYPE);
  860.             TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.CONTENT_TYPE, contentType);
  861.         }
  862.        
  863.         String requestPayload = request;
  864.         if(policyAttributeAuthority.isRequestJws()) {
  865.             requestPayload = signAAJwt(policyAttributeAuthority, request, contentType,
  866.                     dynamicParameters,
  867.                     busta, requestInfo, log);
  868.         }
  869.         if(policyAttributeAuthority.isRequestPositionBearer()) {
  870.             if(transportRequestContext.getHeaders()==null) {
  871.                 transportRequestContext.setHeaders(new HashMap<>());
  872.             }
  873.             String authorizationHeader = HttpConstants.AUTHORIZATION_PREFIX_BEARER+requestPayload;
  874.             TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.AUTHORIZATION, authorizationHeader);
  875.         }
  876.         else if(policyAttributeAuthority.isRequestPositionHeader()) {
  877.             if(transportRequestContext.getHeaders()==null) {
  878.                 transportRequestContext.setHeaders(new HashMap<>());
  879.             }
  880.             String headerName = policyAttributeAuthority.getRequestPositionHeaderName();
  881.             TransportUtils.setHeader(transportRequestContext.getHeaders(),headerName, requestPayload);
  882.         }
  883.         else if(policyAttributeAuthority.isRequestPositionQuery()) {
  884.             if(transportRequestContext.getParameters()==null) {
  885.                 transportRequestContext.setParameters(new HashMap<>());
  886.             }
  887.             String queryParameterName = policyAttributeAuthority.getRequestPositionQueryParameterName();
  888.             TransportUtils.setParameter(transportRequestContext.getParameters(), queryParameterName, requestPayload);
  889.         }
  890.         else if(policyAttributeAuthority.isRequestPositionPayload()) {
  891.             content = requestPayload.getBytes();
  892.         }
  893.        
  894.            
  895.         OpenSPCoop2MessageParseResult pr = OpenSPCoop2MessageFactory.getDefaultMessageFactory().createMessage(MessageType.BINARY, transportRequestContext, content);
  896.         OpenSPCoop2Message msg = pr.getMessage_throwParseException();
  897.         connettoreMsg.setRequestMessage(msg);
  898.         connettoreMsg.setGenerateErrorWithConnectorPrefix(false);
  899.         connettore.setHttpMethod(msg);
  900.         connettore.setPa(pa);
  901.         connettore.setPd(pd);
  902.        
  903.         ResponseCachingConfigurazione responseCachingConfigurazione = new ResponseCachingConfigurazione();
  904.         responseCachingConfigurazione.setStato(StatoFunzionalita.DISABILITATO);
  905.         String prefixConnettore = "[EndpointAttributeAuthority: "+endpoint+"] ";
  906.         if(endpointConfig.containsKey(CostantiConnettori.CONNETTORE_HTTP_PROXY_HOSTNAME)) {
  907.             String hostProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_HOSTNAME);
  908.             String portProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_PORT);
  909.             prefixConnettore = prefixConnettore+GestoreToken.getMessageViaProxy(hostProxy, portProxy);
  910.         }
  911.         boolean send = connettore.send(responseCachingConfigurazione, connettoreMsg);
  912.         if(!send) {
  913.             if(connettore.getEccezioneProcessamento()!=null) {
  914.                 throw new TokenException(prefixConnettore+connettore.getErrore(), connettore.getEccezioneProcessamento());
  915.             }
  916.             else {
  917.                 throw new TokenException(prefixConnettore+connettore.getErrore());
  918.             }
  919.         }
  920.        
  921.         OpenSPCoop2Message msgResponse = connettore.getResponse();
  922.         ByteArrayOutputStream bout = null;
  923.         if(msgResponse!=null) {
  924.             bout = new ByteArrayOutputStream();
  925.             if(msgResponse!=null) {
  926.                 msgResponse.writeTo(bout, true);
  927.             }
  928.             bout.flush();
  929.             bout.close();
  930.         }
  931.        
  932.         HttpResponse httpResponse = new HttpResponse();
  933.         httpResponse.setResultHTTPOperation(connettore.getCodiceTrasporto());
  934.        
  935.         if(connettore.getCodiceTrasporto() >= 200 &&  connettore.getCodiceTrasporto() < 299) {
  936.             String msgSuccess = prefixConnettore+GestoreToken.getMessageConnettoreConnessioneSuccesso(connettore);
  937.             if(bout!=null && bout.size()>0) {
  938.                 log.debug(msgSuccess);
  939.                 httpResponse.setContent(bout.toByteArray());
  940.                 return httpResponse;
  941.             }
  942.             else {
  943.                 throw new TokenException(msgSuccess+GestoreToken.CONNETTORE_RISPOSTA_NON_PERVENUTA);
  944.             }
  945.         }
  946.         else {
  947.             String msgError = prefixConnettore+GestoreToken.getMessageConnettoreConnessioneErrore(connettore);
  948.             if(bout!=null && bout.size()>0) {
  949.                 String e = msgError+": "+bout.toString();
  950.                 log.debug(e);
  951.                 httpResponse.setContent(bout.toByteArray());
  952.                 return httpResponse;
  953.             }
  954.             else {
  955.                 log.error(msgError);
  956.                 throw new TokenException(msgError);
  957.             }
  958.         }
  959.        
  960.        
  961.     }
  962.    
  963.     private static String signAAJwt(PolicyAttributeAuthority policyAttributeAuthority, String payload, String contentType,
  964.             AttributeAuthorityDynamicParameters dynamicParameters,
  965.             Busta busta, RequestInfo requestInfo, Logger log) throws TokenException, SecurityException, UtilsException {
  966.        
  967.         String signAlgo = policyAttributeAuthority.getRequestJwtSignAlgorithm();
  968.         if(signAlgo==null) {
  969.             throw new TokenException("SignAlgorithm undefined");
  970.         }
  971.        
  972.         JWSOptions options = new JWSOptions(JOSESerialization.COMPACT);
  973.        
  974.         String keystoreType = policyAttributeAuthority.getRequestJwtSignKeystoreType();
  975.         if(keystoreType==null) {
  976.             throw new TokenException("JWT Signature keystore type undefined");
  977.         }
  978.        
  979.         String keystoreFile = null;
  980.         String keystoreFilePublicKey = null;
  981.         String keyPairAlgorithm = null;
  982.         if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  983.             keystoreFile = policyAttributeAuthority.getRequestJwtSignKeystoreFile();
  984.             if(keystoreFile==null) {
  985.                 throw new TokenException("JWT Signature private key file undefined");
  986.             }
  987.             keystoreFilePublicKey = policyAttributeAuthority.getRequestJwtSignKeystoreFilePublicKey();
  988.             if(keystoreFilePublicKey==null) {
  989.                 throw new TokenException("JWT Signature public key file undefined");
  990.             }
  991.             keyPairAlgorithm = policyAttributeAuthority.getRequestJwtSignKeystoreFileAlgorithm();
  992.             if(keyPairAlgorithm==null) {
  993.                 throw new TokenException("JWT Signature key pair algorithm undefined");
  994.             }
  995.         }
  996.         else {
  997.             keystoreFile = policyAttributeAuthority.getRequestJwtSignKeystoreFile();
  998.             if(keystoreFile==null) {
  999.                 throw new TokenException("JWT Signature keystore file undefined");
  1000.             }
  1001.         }
  1002.        
  1003.        
  1004.        

  1005.         String keystorePassword = policyAttributeAuthority.getRequestJwtSignKeystorePassword();
  1006.         if(keystorePassword==null &&
  1007.                 !SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType) &&
  1008.                 !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  1009.             boolean required = true;
  1010.             if(KeystoreType.JKS.isType(keystoreType)) {
  1011.                 required = DBUtils.isKeystoreJksPasswordRequired();
  1012.             }
  1013.             else if(KeystoreType.PKCS12.isType(keystoreType)) {
  1014.                 required = DBUtils.isKeystorePkcs12PasswordRequired();
  1015.             }
  1016.             if(required) {
  1017.                 throw new TokenException("JWT Signature keystore password undefined");
  1018.             }
  1019.         }
  1020.        
  1021.         String keyAlias = policyAttributeAuthority.getRequestJwtSignKeyAlias();
  1022.         if(keyAlias==null &&
  1023.                 !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  1024.             throw new TokenException(GestoreToken.KEY_ALIAS_UNDEFINED);
  1025.         }
  1026.        
  1027.         String keyPassword = policyAttributeAuthority.getRequestJwtSignKeyPassword();
  1028.         if(keyPassword==null &&
  1029.                 !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  1030.                 !SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType)) {
  1031.             boolean required = true;
  1032.             if(KeystoreType.JKS.isType(keystoreType)) {
  1033.                 required = DBUtils.isKeystoreJksKeyPasswordRequired();
  1034.             }
  1035.             else if(KeystoreType.PKCS12.isType(keystoreType)) {
  1036.                 required = DBUtils.isKeystorePkcs12KeyPasswordRequired();
  1037.             }
  1038.             if(required) {
  1039.                 throw new TokenException(GestoreToken.KEY_PASSWORD_UNDEFINED);
  1040.             }
  1041.         }
  1042.        
  1043.         String keystoreByokPolicy = policyAttributeAuthority.getRequestJwtSignKeystoreByokPolicy();
  1044.         BYOKRequestParams byokParams = null;
  1045.         if(BYOKProvider.isPolicyDefined(keystoreByokPolicy)) {
  1046.             Map<String, Object> dynamicMap = DynamicMapBuilderUtils.buildDynamicMap(busta,
  1047.                     requestInfo, dynamicParameters.getPddContext(), log);
  1048.             byokParams = BYOKProvider.getBYOKRequestParamsByUnwrapBYOKPolicy(keystoreByokPolicy,
  1049.                     dynamicMap );
  1050.         }
  1051.        
  1052.         KeyStore ks = null;
  1053.         KeyPairStore keyPairStore = null;
  1054.         JWKSetStore jwtStore = null;
  1055.         if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  1056.             keyPairStore = GestoreKeystoreCache.getKeyPairStore(requestInfo, keystoreFile, keystoreFilePublicKey, keyPassword, keyPairAlgorithm, byokParams);
  1057.         }
  1058.         else if(SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType)) {
  1059.             jwtStore = GestoreKeystoreCache.getJwkSetStore(requestInfo, keystoreFile, byokParams);
  1060.         }
  1061.         else {
  1062.             MerlinKeystore merlinKs = GestoreKeystoreCache.getMerlinKeystore(requestInfo, keystoreFile, keystoreType, keystorePassword, byokParams);
  1063.             if(merlinKs==null) {
  1064.                 throw new TokenException("Accesso al keystore '"+keystoreFile+"' non riuscito");
  1065.             }
  1066.             ks = merlinKs.getKeyStore();
  1067.         }
  1068.        
  1069.         JwtHeaders jwtHeaders = new JwtHeaders();
  1070.         if(policyAttributeAuthority.isRequestJwtSignIncludeKeyIdWithKeyAlias()) {
  1071.             jwtHeaders.setKid(keyAlias);
  1072.         }
  1073.         else if(policyAttributeAuthority.isRequestJwtSignIncludeKeyIdCustom()) {
  1074.             jwtHeaders.setKid(policyAttributeAuthority.getRequestJwtSignIncludeKeyIdCustom());
  1075.         }
  1076.         if(policyAttributeAuthority.isRequestJwtSignIncludeX509Cert()) {
  1077.             jwtHeaders.setAddX5C(true);
  1078.         }
  1079.         String url = policyAttributeAuthority.getRequestJwtSignIncludeX509URL();
  1080.         if(url!=null && !"".equals(url)) {
  1081.             try {
  1082.                 jwtHeaders.setX509Url(new URI(url));
  1083.             }catch(Exception e) {
  1084.                 throw new TokenException(e.getMessage(),e);
  1085.             }
  1086.         }
  1087.         if(policyAttributeAuthority.isRequestJwtSignIncludeX509CertSha1()) {
  1088.             jwtHeaders.setX509IncludeCertSha1(true);
  1089.         }
  1090.         if(policyAttributeAuthority.isRequestJwtSignIncludeX509CertSha256()) {
  1091.             jwtHeaders.setX509IncludeCertSha256(true);
  1092.         }
  1093.         if(policyAttributeAuthority.isRequestJwtSignJoseContentType() &&
  1094.             contentType!=null && !"".equals(contentType)) {
  1095.             jwtHeaders.setContentType(contentType);
  1096.         }
  1097.         String type = policyAttributeAuthority.getRequestJwtSignJoseType();
  1098.         if(type!=null && !"".equals(type) && !Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(type)) { // funzionalita' undefined undocumented
  1099.             jwtHeaders.setType(type);
  1100.         }
  1101.         if(ks!=null) {
  1102.             Certificate cert = ks.getCertificate(keyAlias);
  1103.             if(cert instanceof X509Certificate) {
  1104.                 jwtHeaders.addX509cert((X509Certificate)cert);
  1105.             }
  1106.         }
  1107.        
  1108.         JsonSignature jsonSignature = null;
  1109.         if(keyPairStore!=null || jwtStore!=null) {
  1110.             JsonWebKeys jwk = null;
  1111.             if(keyPairStore!=null) {
  1112.                 jwk = keyPairStore.getJwkSet().getJsonWebKeys();
  1113.                 keyAlias = keyPairStore.getJwkSetKid();
  1114.             }
  1115.             else {
  1116.                 jwk = jwtStore.getJwkSet().getJsonWebKeys();
  1117.             }
  1118.             jsonSignature = new JsonSignature(jwk, false, keyAlias, signAlgo, jwtHeaders, options);
  1119.         }
  1120.         else {
  1121.             jsonSignature = new JsonSignature(ks, false, keyAlias,  keyPassword, signAlgo, jwtHeaders, options);
  1122.         }
  1123.        
  1124.         return jsonSignature.sign(payload);
  1125.        
  1126.     }
  1127.    
  1128. }