ModIValidazioneSintattica.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.protocol.modipa.validator;


  21. import java.util.ArrayList;
  22. import java.util.HashMap;
  23. import java.util.List;
  24. import java.util.Map;

  25. import javax.xml.soap.SOAPEnvelope;

  26. import org.apache.commons.lang.StringUtils;
  27. import org.openspcoop2.core.config.ServizioApplicativo;
  28. import org.openspcoop2.core.constants.Costanti;
  29. import org.openspcoop2.core.constants.TipoPdD;
  30. import org.openspcoop2.core.id.IDAccordo;
  31. import org.openspcoop2.core.id.IDServizio;
  32. import org.openspcoop2.core.id.IDServizioApplicativo;
  33. import org.openspcoop2.core.id.IDSoggetto;
  34. import org.openspcoop2.core.registry.AccordoServizioParteComune;
  35. import org.openspcoop2.core.registry.AccordoServizioParteSpecifica;
  36. import org.openspcoop2.core.registry.ProtocolProperty;
  37. import org.openspcoop2.core.registry.Resource;
  38. import org.openspcoop2.core.registry.driver.IDAccordoFactory;
  39. import org.openspcoop2.core.registry.driver.IDServizioFactory;
  40. import org.openspcoop2.message.OpenSPCoop2Message;
  41. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  42. import org.openspcoop2.pdd.core.CostantiPdD;
  43. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  44. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  45. import org.openspcoop2.protocol.basic.validator.ValidazioneSintattica;
  46. import org.openspcoop2.protocol.engine.utils.NamingUtils;
  47. import org.openspcoop2.protocol.modipa.AbstractModISecurityToken;
  48. import org.openspcoop2.protocol.modipa.ModIBustaRawContent;
  49. import org.openspcoop2.protocol.modipa.config.ModIProperties;
  50. import org.openspcoop2.protocol.modipa.constants.ModICostanti;
  51. import org.openspcoop2.protocol.modipa.constants.ModIHeaderType;
  52. import org.openspcoop2.protocol.modipa.utils.ModIPropertiesUtils;
  53. import org.openspcoop2.protocol.modipa.utils.ModISecurityConfig;
  54. import org.openspcoop2.protocol.modipa.utils.ModITruststoreConfig;
  55. import org.openspcoop2.protocol.modipa.utils.ModIUtilities;
  56. import org.openspcoop2.protocol.sdk.Busta;
  57. import org.openspcoop2.protocol.sdk.Eccezione;
  58. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  59. import org.openspcoop2.protocol.sdk.ProtocolException;
  60. import org.openspcoop2.protocol.sdk.SecurityToken;
  61. import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
  62. import org.openspcoop2.protocol.sdk.constants.ErroreCooperazione;
  63. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  64. import org.openspcoop2.protocol.sdk.properties.ProtocolPropertiesUtils;
  65. import org.openspcoop2.protocol.sdk.registry.IConfigIntegrationReader;
  66. import org.openspcoop2.protocol.sdk.registry.IRegistryReader;
  67. import org.openspcoop2.protocol.sdk.state.IState;
  68. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  69. import org.openspcoop2.protocol.sdk.validator.ProprietaValidazioneErrori;
  70. import org.openspcoop2.protocol.sdk.validator.ValidazioneSintatticaResult;
  71. import org.openspcoop2.protocol.sdk.validator.ValidazioneUtils;
  72. import org.openspcoop2.utils.transport.http.HttpConstants;

  73. /**
  74.  * Classe che implementa, in base al protocollo ModI, l'interfaccia {@link org.openspcoop2.protocol.sdk.validator.IValidazioneSintattica}
  75.  *
  76.  * @author Poli Andrea (apoli@link.it)
  77.  * @author Lorenzo Nardi (nardi@link.it)
  78.  * @author $Author$
  79.  * @version $Rev$, $Date$
  80.  */
  81. public class ModIValidazioneSintattica extends ValidazioneSintattica<AbstractModISecurityToken<?>>{

  82.     /** ValidazioneUtils */
  83.     protected ValidazioneUtils validazioneUtils;
  84.     private ModIProperties modiProperties;
  85.    
  86.     public ModIValidazioneSintattica(IProtocolFactory<AbstractModISecurityToken<?>> factory, IState state) throws ProtocolException {
  87.         super(factory, state);
  88.         this.validazioneUtils = new ValidazioneUtils(factory);
  89.         this.modiProperties = ModIProperties.getInstance();
  90.     }
  91.    
  92.     private static final String DIAGNOSTIC_VALIDATE_TOKEN_ID_AUTH = "validateTokenIdAuth";
  93.     private static final String DIAGNOSTIC_VALIDATE_TOKEN_INTEGRITY = "validateTokenIntegrity";
  94.     private static final String DIAGNOSTIC_IN_CORSO = "inCorso";
  95.     private static final String DIAGNOSTIC_COMPLETATA = "completata";
  96.     private static final String DIAGNOSTIC_FALLITA = "fallita";

  97.    
  98.     @Override
  99.     public ValidazioneSintatticaResult<AbstractModISecurityToken<?>> validaRichiesta(OpenSPCoop2Message msg,
  100.             Busta datiBustaLettiURLMappingProperties, ProprietaValidazioneErrori proprietaValidazioneErrori)
  101.             throws ProtocolException {
  102.        
  103.         ValidazioneSintatticaResult<AbstractModISecurityToken<?>> basicResult = super.validaRichiesta(msg, datiBustaLettiURLMappingProperties, proprietaValidazioneErrori);
  104.         return this.validate(basicResult, true, msg, datiBustaLettiURLMappingProperties);

  105.     }
  106.    
  107.     @Override
  108.     public ValidazioneSintatticaResult<AbstractModISecurityToken<?>> validaRisposta(OpenSPCoop2Message msg,
  109.             Busta bustaRichiesta, ProprietaValidazioneErrori proprietaValidazioneErrori) throws ProtocolException {
  110.        
  111.         ValidazioneSintatticaResult<AbstractModISecurityToken<?>> basicResult = super.validaRisposta(msg, bustaRichiesta, proprietaValidazioneErrori);
  112.         return this.validate(basicResult, false, msg, bustaRichiesta);
  113.        
  114.     }
  115.    
  116.     private ValidazioneSintatticaResult<AbstractModISecurityToken<?>> validate(ValidazioneSintatticaResult<AbstractModISecurityToken<?>> basicResult,
  117.             boolean request, OpenSPCoop2Message msg, Busta datiRichiesta) {
  118.         List<Eccezione> erroriValidazione = new ArrayList<>();
  119.         List<Eccezione> erroriProcessamento = new ArrayList<>();
  120.        
  121.         ModIBustaRawContent rawContent = null;
  122.        
  123.         Busta bustaRitornata = basicResult.getBusta();
  124.        
  125.         String erroreProcessamentoInternalMessage = null;
  126.         try {
  127.                    
  128.             IDServizio idServizio = null;
  129.             if(datiRichiesta!=null &&
  130.                     datiRichiesta.getTipoDestinatario()!=null && datiRichiesta.getDestinatario()!=null &&
  131.                     datiRichiesta.getTipoServizio()!=null && datiRichiesta.getServizio()!=null &&
  132.                     datiRichiesta.getVersioneServizio()!=null) {
  133.                 idServizio = IDServizioFactory.getInstance().getIDServizioFromValues(datiRichiesta.getTipoServizio(), datiRichiesta.getServizio(),
  134.                         datiRichiesta.getTipoDestinatario(), datiRichiesta.getDestinatario(),
  135.                         datiRichiesta.getVersioneServizio());
  136.                
  137.                 RequestInfo requestInfo = null;
  138.                 if(this.context!=null && this.context.containsKey(org.openspcoop2.core.constants.Costanti.REQUEST_INFO)) {
  139.                     requestInfo = (RequestInfo) this.context.getObject(org.openspcoop2.core.constants.Costanti.REQUEST_INFO);
  140.                 }
  141.                
  142.                 IRegistryReader registryReader = this.getProtocolFactory().getCachedRegistryReader(this.state, requestInfo);
  143.                 IConfigIntegrationReader configIntegrationReader = this.getProtocolFactory().getCachedConfigIntegrationReader(this.state, requestInfo);
  144.                
  145.                 AccordoServizioParteSpecifica asps = registryReader.getAccordoServizioParteSpecifica(idServizio);
  146.                
  147.                 IDAccordo idAccordo = IDAccordoFactory.getInstance().getIDAccordoFromUri(asps.getAccordoServizioParteComune());
  148.                 AccordoServizioParteComune aspc = registryReader.getAccordoServizioParteComune(idAccordo);
  149.                 boolean rest = org.openspcoop2.core.registry.constants.ServiceBinding.REST.equals(aspc.getServiceBinding());
  150.                
  151.                 String nomePortType = asps.getPortType();
  152.                 String azione = datiRichiesta.getAzione();
  153.                
  154.                 IDSoggetto idSoggettoMittente = null;
  155.                 if(!request &&  datiRichiesta.getTipoMittente()!=null &&
  156.                         datiRichiesta.getMittente()!=null) {
  157.                    
  158.                     idSoggettoMittente = new IDSoggetto(datiRichiesta.getTipoMittente(),datiRichiesta.getMittente());
  159.                    
  160.                 }
  161.                
  162.                 IDServizioApplicativo idSA = null;
  163.                 ServizioApplicativo sa = null;
  164.                 if(!request && datiRichiesta.getServizioApplicativoFruitore()!=null &&
  165.                         !CostantiPdD.SERVIZIO_APPLICATIVO_ANONIMO.equals(datiRichiesta.getServizioApplicativoFruitore()) &&
  166.                         idSoggettoMittente!=null) {
  167.                    
  168.                     idSA = new IDServizioApplicativo();
  169.                     idSA.setIdSoggettoProprietario(idSoggettoMittente);
  170.                     idSA.setNome(datiRichiesta.getServizioApplicativoFruitore());
  171.                    
  172.                     sa = configIntegrationReader.getServizioApplicativo(idSA);
  173.                 }
  174.                 if(!request && sa==null) {
  175.                     // provo a vedere se autenticato tramite autenticazione token
  176.                     IDServizioApplicativo idServizioApplicativoToken = null;
  177.                     if(this.context!=null && this.context.containsKey(org.openspcoop2.core.constants.Costanti.ID_APPLICATIVO_TOKEN)) {
  178.                         idServizioApplicativoToken = (IDServizioApplicativo) this.context.getObject(org.openspcoop2.core.constants.Costanti.ID_APPLICATIVO_TOKEN);
  179.                     }
  180.                     if(idServizioApplicativoToken!=null) {
  181.                         idSA = idServizioApplicativoToken;
  182.                         sa = configIntegrationReader.getServizioApplicativo(idSA);
  183.                     }
  184.                 }
  185.                
  186.                 ModIValidazioneSintatticaRest validatoreSintatticoRest = null;
  187.                 ModIValidazioneSintatticaSoap validatoreSintatticoSoap = null;
  188.                 if(rest) {
  189.                     validatoreSintatticoRest = new ModIValidazioneSintatticaRest(this.log, this.state, this.context, this.protocolFactory, requestInfo, this.modiProperties, this.validazioneUtils);
  190.                 }
  191.                 else {
  192.                     validatoreSintatticoSoap = new ModIValidazioneSintatticaSoap(this.log, this.state, this.context, this.protocolFactory, requestInfo, this.modiProperties, this.validazioneUtils);
  193.                 }
  194.                
  195.                
  196.                 // check Fault
  197.                 boolean isFault = false;
  198.                 if(rest) {
  199.                     isFault = msg.isFault() || msg.castAsRest().isProblemDetailsForHttpApis_RFC7807();  
  200.                 }
  201.                 else {
  202.                     isFault = msg.isFault() || msg.castAsSoap().hasSOAPFault();
  203.                 }
  204.                
  205.                
  206.                
  207.                 // Lettura profili
  208.                
  209.                
  210.                 /* *** PROFILO INTERAZIONE *** */
  211.                
  212.                 String interactionProfile = ModIPropertiesUtils.readPropertyInteractionProfile(aspc, nomePortType, azione);
  213.                 bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE, interactionProfile);
  214.                
  215.                 if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_VALUE_BLOCCANTE.equals(interactionProfile)) {
  216.                    
  217.                     if(!isFault &&
  218.                         rest) {
  219.                         validatoreSintatticoRest.validateSyncInteractionProfile(msg, request, erroriValidazione);
  220.                     }
  221.                    
  222.                 }
  223.                 else if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_VALUE_NON_BLOCCANTE.equals(interactionProfile)) {
  224.                    
  225.                     String asyncInteractionType = ModIPropertiesUtils.readPropertyAsyncInteractionProfile(aspc, nomePortType, azione);
  226.                     bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_TIPO, asyncInteractionType);
  227.                    
  228.                     String asyncInteractionRole = ModIPropertiesUtils.readPropertyAsyncInteractionRole(aspc, nomePortType, azione);
  229.                     bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_RUOLO, asyncInteractionRole);
  230.                    
  231.                     AccordoServizioParteComune apiContenenteRisorsa = null;
  232.                     if(!ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA.equals(asyncInteractionRole)) {
  233.                        
  234.                         if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_VALUE_PUSH.equals(asyncInteractionType)) {
  235.                             String asyncInteractionRequestApi = ModIPropertiesUtils.readPropertyAsyncInteractionRequestApi(aspc, nomePortType, azione);
  236.                             IDAccordo idApiCorrelata = IDAccordoFactory.getInstance().getIDAccordoFromUri(asyncInteractionRequestApi);
  237.                             String labelApi = NamingUtils.getLabelAccordoServizioParteComune(idApiCorrelata);
  238.                             bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_API_RICHIESTA_CORRELATA, labelApi);
  239.                             apiContenenteRisorsa = registryReader.getAccordoServizioParteComune(idApiCorrelata, false, false);
  240.                         }
  241.                         else {
  242.                             apiContenenteRisorsa = aspc;
  243.                         }
  244.                        
  245.                         if(rest) {
  246.                            
  247.                             String asyncInteractionRequestResource = ModIPropertiesUtils.readPropertyAsyncInteractionRequestAction(aspc, nomePortType, azione);
  248.                            
  249.                             String labelResourceCorrelata = asyncInteractionRequestResource;
  250.                             for (Resource r : apiContenenteRisorsa.getResourceList()) {
  251.                                 if(r.getNome().equals(asyncInteractionRequestResource)) {
  252.                                     labelResourceCorrelata = NamingUtils.getLabelResource(r);
  253.                                     break;
  254.                                 }
  255.                             }
  256.                            
  257.                             bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_RISORSA_RICHIESTA_CORRELATA, labelResourceCorrelata);
  258.                            
  259.                         }
  260.                         else {
  261.                            
  262.                             String asyncInteractionRequestService = ModIPropertiesUtils.readPropertyAsyncInteractionRequestService(aspc, nomePortType, azione);
  263.                             bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_SERVIZIO_RICHIESTA_CORRELATA, asyncInteractionRequestService);
  264.                            
  265.                             String asyncInteractionRequestAction = ModIPropertiesUtils.readPropertyAsyncInteractionRequestAction(aspc, nomePortType, azione);
  266.                             bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_AZIONE_RICHIESTA_CORRELATA, asyncInteractionRequestAction);
  267.                            
  268.                         }
  269.                        
  270.                     }
  271.                     else {
  272.                         apiContenenteRisorsa = aspc;
  273.                     }
  274.                    
  275.                     String replyTo = null;
  276.                     if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA.equals(asyncInteractionRole) &&
  277.                         request &&  ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_VALUE_PUSH.equals(asyncInteractionType)) {
  278.                         // devo cercare l'url di invocazione del servizio fruito correlato.
  279.                        
  280.                         try {
  281.                             replyTo = ModIUtilities.getReplyToFruizione(idServizio.getSoggettoErogatore(), idSoggettoMittente, aspc, nomePortType, azione,
  282.                                     registryReader, configIntegrationReader, this.protocolFactory, this.state, requestInfo);
  283.                         }catch(Exception e) {
  284.                             throw new ProtocolException("Configurazione presente nel registro non corretta: "+e.getMessage(),e);
  285.                         }
  286.                     }
  287.                    
  288.                     if(!isFault) {
  289.                         if(rest) {
  290.                             validatoreSintatticoRest.validateAsyncInteractionProfile(msg, request, asyncInteractionType, asyncInteractionRole,
  291.                                     apiContenenteRisorsa, azione,
  292.                                     bustaRitornata, erroriValidazione,
  293.                                     replyTo);
  294.                         }
  295.                         else {
  296.                             validatoreSintatticoSoap.validateAsyncInteractionProfile(msg, request, asyncInteractionType, asyncInteractionRole,
  297.                                     bustaRitornata, erroriValidazione,
  298.                                     replyTo);
  299.                         }
  300.                     }
  301.                 }
  302.                
  303.                 /* *** SIGNAL HUB *** */
  304.                 List<ProtocolProperty> protoProps = asps.getProtocolProperty();
  305.                 if (!protoProps.isEmpty() && ProtocolPropertiesUtils.getBooleanValuePropertyRegistry(protoProps, ModICostanti.MODIPA_API_IMPL_INFO_SIGNAL_HUB_ID, false)) {
  306.                     String operation = ProtocolPropertiesUtils.getRequiredStringValuePropertyRegistry(protoProps, ModICostanti.MODIPA_API_IMPL_INFO_SIGNAL_HUB_OPERATION_ID);
  307.                    
  308.                     if (azione.equals(operation)) {
  309.                         this.context.addObject(ModICostanti.MODIPA_KEY_INFO_SIGNAL_HUB_PROPERTIES, protoProps);
  310.                         this.context.addObject(CostantiPdD.KEY_OVERRIDE_CONNETTORE, ModICostanti.MODIPA_CONNETTORE_SIGNAL_HUB_PSEUDONYMIZATION);
  311.                     }
  312.                 }
  313.                
  314.                 /* *** SICUREZZA CANALE *** */
  315.                
  316.                 String securityChannelProfile = ModIPropertiesUtils.readPropertySecurityChannelProfile(aspc, asps);
  317.                 bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_CANALE, securityChannelProfile);
  318.                
  319.                 if(request && this.context!=null) {
  320.                    
  321.                     @SuppressWarnings("unused")
  322.                     SecurityToken securityTokenForContext = ModIUtilities.newSecurityToken(this.context); // creo per averlo a disposizione anche se non e' presente la sicurezza messaggio
  323.                    
  324.                 }
  325.                
  326.                
  327.                 /* *** SICUREZZA MESSAGGIO *** */
  328.                
  329.                 boolean filterPDND = true;
  330.                 String securityMessageProfileNonFiltratoPDND = ModIPropertiesUtils.readPropertySecurityMessageProfile(aspc, nomePortType, azione, !filterPDND);
  331.                
  332.                 boolean existsSecurityFlusso =  false;
  333.                 if(securityMessageProfileNonFiltratoPDND!=null && !ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_UNDEFINED.equals(securityMessageProfileNonFiltratoPDND)) {
  334.                     existsSecurityFlusso = ModIPropertiesUtils.processSecurity(this.log,aspc, nomePortType, azione, request,
  335.                                 msg, rest, this.modiProperties);
  336.                 }
  337.                    
  338.                 if(existsSecurityFlusso) {
  339.                     bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO,
  340.                             ModIPropertiesUtils.convertProfiloSicurezzaToSDKValue(securityMessageProfileNonFiltratoPDND, rest));
  341.                    
  342.                     String sorgenteToken = ModIPropertiesUtils.readPropertySecurityMessageSorgenteToken(aspc, nomePortType, azione, true);
  343.                     bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SORGENTE_TOKEN,
  344.                             ModIPropertiesUtils.convertProfiloSicurezzaSorgenteTokenToSDKValue(sorgenteToken));
  345.                     boolean sorgenteLocale = true;
  346.                     if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_SORGENTE_TOKEN_IDAUTH_VALUE_PDND.equals(sorgenteToken) ||
  347.                             ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_SORGENTE_TOKEN_IDAUTH_VALUE_OAUTH.equals(sorgenteToken)) {
  348.                         sorgenteLocale = false;
  349.                     }
  350.                    
  351.                     String securityMessageProfile = ModIPropertiesUtils.readPropertySecurityMessageProfile(aspc, nomePortType, azione, filterPDND);
  352.                                        
  353.                     MsgDiagnostico msgDiag = null;
  354.                     TipoPdD tipoPdD = request ? TipoPdD.APPLICATIVA : TipoPdD.DELEGATA;
  355.                     IDSoggetto idSoggetto = TipoPdD.DELEGATA.equals(tipoPdD) ? idSoggettoMittente : idServizio.getSoggettoErogatore();
  356.                     if(idSoggetto==null || idSoggetto.getTipo()==null || idSoggetto.getNome()==null) {
  357.                         idSoggetto = OpenSPCoop2Properties.getInstance().getIdentitaPortaDefault(this.protocolFactory.getProtocol(), requestInfo);
  358.                     }
  359.                     else {
  360.                         idSoggetto.setCodicePorta(registryReader.getDominio(idSoggetto));
  361.                     }
  362.                     msgDiag = MsgDiagnostico.newInstance(TipoPdD.DELEGATA,
  363.                             idSoggetto,
  364.                             "ModI", requestInfo!=null && requestInfo.getProtocolContext()!=null ? requestInfo.getProtocolContext().getInterfaceName() : null,
  365.                             requestInfo,
  366.                             this.state);
  367.                     if(TipoPdD.DELEGATA.equals(tipoPdD)){
  368.                         msgDiag.setPrefixMsgPersonalizzati(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_CONTENUTI_APPLICATIVI);
  369.                     }
  370.                     else {
  371.                         msgDiag.setPrefixMsgPersonalizzati(MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE);
  372.                     }
  373.                     msgDiag.setPddContext(this.context, this.protocolFactory);
  374.                     String tipoDiagnostico = request ? ".richiesta." : ".risposta.";
  375.                    
  376.                     boolean processSecurity = false;
  377.                     boolean securityMessageProfilePrevedeTokenLocale = securityMessageProfile!=null && !ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_UNDEFINED.equals(securityMessageProfile);
  378.                     if(securityMessageProfilePrevedeTokenLocale) {
  379.                         processSecurity = existsSecurityFlusso;
  380.                     }
  381.                    
  382.                     boolean corniceSicurezza = ModIPropertiesUtils.isPropertySecurityMessageConCorniceSicurezza(aspc, nomePortType, azione);
  383.                     String patternCorniceSicurezza = null;
  384.                     String schemaCorniceSicurezza = null;
  385.                     boolean corniceSicurezzaOpzionale = false;
  386.                     if(corniceSicurezza) {
  387.                         patternCorniceSicurezza = ModIPropertiesUtils.readPropertySecurityMessageCorniceSicurezzaPattern(aspc, nomePortType, azione);
  388.                         if(patternCorniceSicurezza==null) {
  389.                             // backward compatibility
  390.                             patternCorniceSicurezza = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_PATTERN_VALUE_OLD;
  391.                         }
  392.                         if(!ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_PATTERN_VALUE_OLD.equals(patternCorniceSicurezza)) {
  393.                             schemaCorniceSicurezza = ModIPropertiesUtils.readPropertySecurityMessageCorniceSicurezzaSchema(aspc, nomePortType, azione);
  394.                             corniceSicurezzaOpzionale = ModIPropertiesUtils.isPropertySecurityMessageCorniceSicurezzaOpzionale(aspc, nomePortType, azione);
  395.                         }
  396.                     }
  397.                    
  398.                     boolean fruizione = !request;
  399.                    
  400.                     boolean processAudit = !fruizione && corniceSicurezza &&
  401.                             patternCorniceSicurezza!=null && !ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_PATTERN_VALUE_OLD.equals(patternCorniceSicurezza);
  402.                                                
  403.                     boolean keystoreKidMode = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile)
  404.                             ||
  405.                             ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0402.equals(securityMessageProfile)
  406.                             ||
  407.                             !sorgenteLocale;
  408.                    
  409.                     Map<String, Object> dynamicMap = null;
  410.                    
  411.                     ModISecurityConfig securityConfig = null;
  412.                     ModISecurityConfig securityConfigAudit = null;                  
  413.                     ModITruststoreConfig trustStoreCertificati = null;
  414.                     ModITruststoreConfig trustStoreSsl = null;
  415.                    
  416.                     String headerTokenRest = null;
  417.                     String headerTokenRestIntegrity = null; // nel caso di Authorization insieme a Agid-JWT-Signature
  418.                     boolean integritaCustom = false;
  419.                    
  420.                     boolean buildSecurityTokenInRequest = true;
  421.                                        
  422.                     if(processSecurity || processAudit) {
  423.                        
  424.                         // dynamicMap
  425.                         // FIX: va inizializzato dentro il metodo 'validateSecurityProfile' dopo aver identificato l'applicativo
  426. /**                     boolean bufferMessage_readOnly = this.modiProperties.isReadByPathBufferEnabled();
  427. //                      Map<String, Object> dynamicMap = null;
  428. //                      Map<String, Object> dynamicMapRequest = null;
  429. //                      if(!request) {
  430. //                          dynamicMapRequest = ModIUtilities.removeDynamicMapRequest(this.context);
  431. //                      }
  432. //                      if(dynamicMapRequest!=null) {
  433. //                          dynamicMap = DynamicUtils.buildDynamicMapResponse(msg, this.context, null, this.log, bufferMessage_readOnly, dynamicMapRequest);
  434. //                      }
  435. //                      else {
  436. //                          dynamicMap = DynamicUtils.buildDynamicMap(msg, this.context, datiRichiesta, this.log, bufferMessage_readOnly);
  437. //                          ModIUtilities.saveDynamicMapRequest(this.context, dynamicMap);
  438. //                      }*/
  439.                         dynamicMap = new HashMap<>();
  440.                        
  441.                         // header
  442.                         Boolean multipleHeaderAuthorizationConfig = null;
  443.                         if(rest) {
  444.                             headerTokenRest = ModIPropertiesUtils.readPropertySecurityMessageHeader(aspc, nomePortType, azione, request, filterPDND);
  445.                             if(headerTokenRest.contains(" ")) {
  446.                                 String [] tmp = headerTokenRest.split(" ");
  447.                                 if(tmp!=null && tmp.length==2 && tmp[0]!=null && tmp[1]!=null) {
  448.                                     headerTokenRest=tmp[0];
  449.                                     headerTokenRestIntegrity=tmp[1];
  450.                                     multipleHeaderAuthorizationConfig = true;
  451.                                 }
  452.                             }
  453.                             integritaCustom = ModIPropertiesUtils.isPropertySecurityMessageHeaderCustom(aspc, nomePortType, azione, request);
  454.                             /**
  455.                              * Lo registro nella busta solamente se lo aggiungo davvero dentro il metodo ModIValidazioneSintatticaRest
  456.                              *
  457.                              * if(integritaCustom) {
  458.                                 String hdrCustom = headerTokenRest;
  459.                                 if(multipleHeaderAuthorizationConfig!=null && multipleHeaderAuthorizationConfig && headerTokenRestIntegrity!=null) {
  460.                                     hdrCustom = headerTokenRestIntegrity;
  461.                                 }
  462.                                 bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CUSTOM_HEADER,hdrCustom);
  463.                             }*/
  464.                         }
  465.                        
  466.                         // security config
  467.                        
  468.                         if(processAudit) {
  469.                             securityConfigAudit = new ModISecurityConfig(msg, this.context, this.protocolFactory, this.state, requestInfo, idSoggettoMittente,
  470.                                     aspc, asps, sa, rest, fruizione, request,
  471.                                     multipleHeaderAuthorizationConfig,
  472.                                     keystoreKidMode,
  473.                                     patternCorniceSicurezza, schemaCorniceSicurezza);
  474.                         }
  475.                        
  476.                         boolean keystoreKidModeSecurityToken = keystoreKidMode;
  477.                         if(rest && headerTokenRestIntegrity==null) {
  478.                             // un solo header
  479.                             if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0301.equals(securityMessageProfile)
  480.                                     ||
  481.                                     ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0302.equals(securityMessageProfile)) {
  482.                                 keystoreKidModeSecurityToken = false;
  483.                             }
  484.                         }
  485.                        
  486.                         securityConfig = new ModISecurityConfig(msg, this.context, this.protocolFactory, this.state, requestInfo, idSoggettoMittente,
  487.                                 aspc, asps, sa, rest, fruizione, request,
  488.                                 multipleHeaderAuthorizationConfig,
  489.                                 keystoreKidModeSecurityToken,
  490.                                 patternCorniceSicurezza, schemaCorniceSicurezza);
  491.                        
  492.                         // truststore
  493.                         trustStoreCertificati = new ModITruststoreConfig(fruizione, idSoggettoMittente, asps, false);
  494.                         if(securityConfig.isX5u()) {
  495.                             trustStoreSsl = new ModITruststoreConfig(fruizione, idSoggettoMittente, asps, true);
  496.                         }
  497.                        
  498.                         // securityToken
  499.                         if(!request) {
  500.                             String securityMessageRequest = null;
  501.                             if(datiRichiesta!=null) {
  502.                                 securityMessageRequest = datiRichiesta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO);
  503.                             }
  504.                             if(securityMessageRequest==null) {
  505.                                 buildSecurityTokenInRequest = false;
  506.                             }
  507.                             msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_BUILD_SECURITY_REQUEST_TOKEN, buildSecurityTokenInRequest);
  508.                         }
  509.                         else {
  510.                             if(this.context!=null) {
  511.                                 this.context.addObject(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_BUILD_SECURITY_REQUEST_TOKEN, processSecurity);
  512.                             }
  513.                         }
  514.                     }
  515.                    
  516.                     // security (ID_AUTH e INTEGRITY)
  517.                     boolean errorOccurs = false;
  518.                     if(processSecurity) {
  519.                                                                                        
  520.                         boolean includiRequestDigest = ModIPropertiesUtils.isPropertySecurityMessageIncludiRequestDigest(aspc, nomePortType, azione);
  521.                        
  522.                         boolean signAttachments = false;
  523.                         if(!rest) {
  524.                             signAttachments = ModIPropertiesUtils.isAttachmentsSignature(aspc, nomePortType, azione, request, msg);
  525.                         }
  526.                            
  527.                         boolean integritaX509 = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0301.equals(securityMessageProfile) ||
  528.                                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0302.equals(securityMessageProfile);
  529.                         boolean integritaKid = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile) ||
  530.                                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0402.equals(securityMessageProfile);
  531.                         boolean integrita = integritaX509 || integritaKid;
  532.                                                
  533.                         if(rest) {
  534.                             boolean securityHeaderObbligatorio = true;

  535.                             if(headerTokenRestIntegrity==null) {
  536.                                
  537.                                 String token = null;
  538.                                 String prefixMsgDiag = null;
  539.                                 if(HttpConstants.AUTHORIZATION.equalsIgnoreCase(headerTokenRest)) {
  540.                                     prefixMsgDiag = DIAGNOSTIC_VALIDATE_TOKEN_ID_AUTH;
  541.                                 }
  542.                                 else {
  543.                                     prefixMsgDiag = DIAGNOSTIC_VALIDATE_TOKEN_INTEGRITY;
  544.                                 }
  545.                                 try {
  546.                                     msgDiag.logPersonalizzato(prefixMsgDiag+tipoDiagnostico+DIAGNOSTIC_IN_CORSO);
  547.                                    
  548.                                     // Nel caso di 1 solo header da generare localmente, l'integrity, e l'authorization prodotto tramite token policy,
  549.                                     //    l'integrity è obbligatorio solo se c'è un payload o se atteso per un integrity cystom.
  550.                                     //    Nel caso non sia atteso se presente viene validato, altrimenti non da errore.
  551.                                     if(!sorgenteLocale) {
  552.                                         securityHeaderObbligatorio = msg.castAsRest().hasContent() ||
  553.                                                 (integritaCustom && ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_HEADER_CUSTOM_MODE_VALUE_ALWAYS.equals(ModIPropertiesUtils.getPropertySecurityMessageHeaderCustomMode(aspc, nomePortType, azione, request)));
  554.                                     }
  555.                                     token = validatoreSintatticoRest.validateSecurityProfile(msg, request, securityMessageProfile, false, headerTokenRest,
  556.                                             corniceSicurezza, patternCorniceSicurezza,
  557.                                             null, // devo fornirlo solo durante la validazione dell'Audit Token
  558.                                             includiRequestDigest, bustaRitornata,
  559.                                             erroriValidazione, trustStoreCertificati, trustStoreSsl, securityConfig,
  560.                                             buildSecurityTokenInRequest, ModIHeaderType.SINGLE, integritaCustom, securityHeaderObbligatorio,
  561.                                             dynamicMap, datiRichiesta,
  562.                                             idSoggetto, msgDiag);
  563.                                    
  564.                                     if(token==null && !sorgenteLocale) {
  565.                                         // non c'era un token di integrita nonostante ne sia stato configurato (es. per GET) e sia stato indicato di utilizzarlo come identificativo messaggio.
  566.                                         // per questo motivo in ricezione buste il metodo 'ModIUtils.replaceBustaIdWithJtiTokenId' non è stato invocato
  567.                                         // Utilizzo come identificativo del messaggio quello presente nel voucher.
  568.                                         /** verra' gestito nella validazione semantica, in questa fase il token non e' ancora stato validato
  569.                                          * String jtiClaimReceived = ModIUtils.readJtiFromInformazioniToken(this.context);
  570.                                         if(jtiClaimReceived!=null && StringUtils.isNotEmpty(jtiClaimReceived) &&
  571.                                                 !jtiClaimReceived.equals(bustaRitornata.getID())) {
  572.                                             bustaRitornata.removeProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUTHORIZATION_ID);
  573.                                             bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_ID, jtiClaimReceived);
  574.                                             if(jtiClaimReceived.length()<=255) {
  575.                                                 bustaRitornata.setID(jtiClaimReceived);
  576.                                             }
  577.                                         }*/
  578.                                     }
  579.                                    
  580.                                     if(erroriValidazione.isEmpty()) {
  581.                                         msgDiag.logPersonalizzato(prefixMsgDiag+tipoDiagnostico+DIAGNOSTIC_COMPLETATA);
  582.                                     }
  583.                                     else {
  584.                                         String errore = buildErrore(erroriValidazione, this.protocolFactory);
  585.                                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, errore);
  586.                                         msgDiag.logPersonalizzato(prefixMsgDiag+tipoDiagnostico+DIAGNOSTIC_FALLITA);
  587.                                         errorOccurs = true;
  588.                                     }
  589.                                 }
  590.                                 catch(ProtocolException pe) {
  591.                                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, pe.getMessage());
  592.                                     msgDiag.logPersonalizzato(prefixMsgDiag+tipoDiagnostico+DIAGNOSTIC_FALLITA);
  593.                                     throw pe;
  594.                                 }
  595.                                    
  596.                                    
  597.                                 if(token!=null) {
  598.                                    
  599.                                     if(securityConfig.getAudience()!=null &&
  600.                                         (request || (securityConfig.isCheckAudience()))
  601.                                     ){
  602.                                         String audience = securityConfig.getAudience();
  603.                                         if(fruizione && !request) {
  604.                                             try {
  605.                                                 audience = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUDIENCE,
  606.                                                         audience, dynamicMap, this.context);
  607.                                             }catch(Exception e) {
  608.                                                 this.logError(e.getMessage(),e);
  609.                                                 throw e;
  610.                                             }
  611.                                         }
  612.                                         msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_AUDIENCE_CHECK, audience);
  613.                                     }
  614.                                    
  615.                                     if(!request && securityConfig.isCheckAudience() && integritaKid && securityConfig.getTokenClientId()!=null) {
  616.                                         String audienceClientId = null;
  617.                                         try {
  618.                                             audienceClientId = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUDIENCE+"-OAuth",
  619.                                                     securityConfig.getTokenClientId(), dynamicMap, this.context);
  620.                                         }catch(Exception e) {
  621.                                             this.logError(e.getMessage(),e);
  622.                                             throw e;
  623.                                         }
  624.                                         if(audienceClientId!=null) {
  625.                                             msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_AUDIENCE_CHECK_OAUTH, audienceClientId);
  626.                                         }
  627.                                     }
  628.                                    
  629.                                     rawContent = new ModIBustaRawContent(headerTokenRest, token);
  630.                                 }
  631.                             }
  632.                             else {
  633.                                
  634.                                 boolean useKIDforIdAUTH = false; // normalmente il token authorization sarà PDND, se cmq è locale lo genero uguale per il kid
  635.                                 if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile)
  636.                                         ||
  637.                                         ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0402.equals(securityMessageProfile)) {
  638.                                     useKIDforIdAUTH = true;
  639.                                 }
  640.                                
  641.                                 // Authorization
  642.                                 String tokenAuthorization = null;
  643.                                 try {
  644.                                     msgDiag.logPersonalizzato(DIAGNOSTIC_VALIDATE_TOKEN_ID_AUTH+tipoDiagnostico+DIAGNOSTIC_IN_CORSO);
  645.                                    
  646.                                     String securityMessageProfileAuthorization = null;
  647.                                     if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0301.equals(securityMessageProfile) ||
  648.                                             ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile)) {
  649.                                         securityMessageProfileAuthorization = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM01;
  650.                                     }
  651.                                     else {
  652.                                         securityMessageProfileAuthorization = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM02;
  653.                                     }
  654.                                     tokenAuthorization = validatoreSintatticoRest.validateSecurityProfile(msg, request, securityMessageProfileAuthorization, useKIDforIdAUTH, headerTokenRest,
  655.                                             corniceSicurezza, patternCorniceSicurezza,
  656.                                             null, // devo fornirlo solo durante la validazione dell'Audit Token  
  657.                                             includiRequestDigest, bustaRitornata,
  658.                                             erroriValidazione, trustStoreCertificati, trustStoreSsl, securityConfig,
  659.                                             buildSecurityTokenInRequest, ModIHeaderType.BOTH_AUTH, integritaCustom, securityHeaderObbligatorio,
  660.                                             dynamicMap, datiRichiesta,
  661.                                             idSoggetto, msgDiag);
  662.                                    
  663.                                     String audAuthorization = null;
  664.                                     if(tokenAuthorization!=null &&
  665.                                         securityConfig.getAudience()!=null &&
  666.                                         (request || (securityConfig.isCheckAudience()))
  667.                                         ){
  668.                                         audAuthorization = securityConfig.getAudience();
  669.                                         if(fruizione && !request) {
  670.                                             try {
  671.                                                 audAuthorization = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUDIENCE,
  672.                                                         audAuthorization, dynamicMap, this.context);
  673.                                             }catch(Exception e) {
  674.                                                 this.logError(e.getMessage(),e);
  675.                                                 throw e;
  676.                                             }
  677.                                         }
  678.                                         msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_AUDIENCE_CHECK, audAuthorization);              
  679.                                     }
  680.                                    
  681.                                     if(erroriValidazione.isEmpty()) {
  682.                                         msgDiag.logPersonalizzato(DIAGNOSTIC_VALIDATE_TOKEN_ID_AUTH+tipoDiagnostico+DIAGNOSTIC_COMPLETATA);
  683.                                     }
  684.                                     else {
  685.                                         String errore = buildErrore(erroriValidazione, this.protocolFactory);
  686.                                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, errore);
  687.                                         msgDiag.logPersonalizzato(DIAGNOSTIC_VALIDATE_TOKEN_ID_AUTH+tipoDiagnostico+DIAGNOSTIC_FALLITA);
  688.                                         errorOccurs = true;
  689.                                     }
  690.                                 }
  691.                                 catch(ProtocolException pe) {
  692.                                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, pe.getMessage());
  693.                                     msgDiag.logPersonalizzato(DIAGNOSTIC_VALIDATE_TOKEN_ID_AUTH+tipoDiagnostico+DIAGNOSTIC_FALLITA);
  694.                                     throw pe;
  695.                                 }
  696.                                
  697.                                 // Integrity
  698.                                 String tokenIntegrity = null;
  699.                                 ModISecurityConfig securityConfigIntegrity = null;
  700.                                 try {
  701.                                     msgDiag.logPersonalizzato(DIAGNOSTIC_VALIDATE_TOKEN_INTEGRITY+tipoDiagnostico+DIAGNOSTIC_IN_CORSO);
  702.                                    
  703.                                     // !! Nel caso di 2 header, quello integrity è obbligatorio solo se c'è un payload o se atteso per un integrity cystom.
  704.                                     //                          Nel caso non sia atteso se presente viene validato, altrimenti non da errore.
  705.                                     boolean securityHeaderIntegrityObbligatorio = msg.castAsRest().hasContent() ||
  706.                                             (integritaCustom && ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_HEADER_CUSTOM_MODE_VALUE_ALWAYS.equals(ModIPropertiesUtils.getPropertySecurityMessageHeaderCustomMode(aspc, nomePortType, azione, request)));
  707.                                            
  708.                                     boolean keystoreKidModeIntegrity = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile)
  709.                                             ||
  710.                                             ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0402.equals(securityMessageProfile);
  711.                                     securityConfigIntegrity = new ModISecurityConfig(msg, this.context, this.protocolFactory, this.state, requestInfo, idSoggettoMittente,
  712.                                             aspc, asps, sa, rest, fruizione, request,
  713.                                             false,
  714.                                             keystoreKidModeIntegrity,
  715.                                             patternCorniceSicurezza, schemaCorniceSicurezza);
  716.                                     tokenIntegrity = validatoreSintatticoRest.validateSecurityProfile(msg, request, securityMessageProfile, useKIDforIdAUTH, headerTokenRestIntegrity,
  717.                                             corniceSicurezza, patternCorniceSicurezza,
  718.                                             null, // devo fornirlo solo durante la validazione dell'Audit Token
  719.                                             includiRequestDigest, bustaRitornata,
  720.                                             erroriValidazione, trustStoreCertificati, trustStoreSsl, securityConfigIntegrity,
  721.                                             buildSecurityTokenInRequest, ModIHeaderType.BOTH_INTEGRITY, integritaCustom, securityHeaderIntegrityObbligatorio,
  722.                                             null, null,
  723.                                             idSoggetto, msgDiag); // gia' inizializzato sopra
  724.                                                
  725.                                     if(tokenIntegrity==null) {
  726.                                         // non c'era un token di integrita nonostante ne sia stato configurato (es. per GET) e sia stato indicato di utilizzarlo come identificativo messaggio.
  727.                                         // Utilizzo come identificativo del messaggio quello presente nell'authorization.
  728.                                         String idAuth = bustaRitornata.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUTHORIZATION_ID);
  729.                                         String id = bustaRitornata.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_ID);
  730.                                         if( (id ==null || StringUtils.isEmpty(id))
  731.                                                 &&  
  732.                                                 idAuth!=null && StringUtils.isNotEmpty(idAuth) &&
  733.                                                 !idAuth.equals(bustaRitornata.getID())) {
  734.                                             bustaRitornata.removeProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUTHORIZATION_ID);
  735.                                             bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_ID, idAuth);
  736.                                             if(idAuth.length()<=255) {
  737.                                                 bustaRitornata.setID(idAuth);
  738.                                             }
  739.                                         }
  740.                                     }
  741.                                    
  742.                                     if(erroriValidazione.isEmpty()) {
  743.                                         msgDiag.logPersonalizzato(DIAGNOSTIC_VALIDATE_TOKEN_INTEGRITY+tipoDiagnostico+DIAGNOSTIC_COMPLETATA);
  744.                                     }
  745.                                     else {
  746.                                         String errore = buildErrore(erroriValidazione, this.protocolFactory);
  747.                                         msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, errore);
  748.                                         msgDiag.logPersonalizzato(DIAGNOSTIC_VALIDATE_TOKEN_INTEGRITY+tipoDiagnostico+DIAGNOSTIC_FALLITA);
  749.                                         errorOccurs = true;
  750.                                     }
  751.                                 }
  752.                                 catch(ProtocolException pe) {
  753.                                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, pe.getMessage());
  754.                                     msgDiag.logPersonalizzato(DIAGNOSTIC_VALIDATE_TOKEN_INTEGRITY+tipoDiagnostico+DIAGNOSTIC_FALLITA);
  755.                                     throw pe;
  756.                                 }
  757.                                                                
  758.                                 if(tokenIntegrity!=null &&
  759.                                     securityConfigIntegrity.getAudience()!=null &&
  760.                                     (request || (securityConfigIntegrity.isCheckAudience()))
  761.                                     ){
  762.                                     String audIntegrity = securityConfigIntegrity.getAudience();
  763.                                     if(fruizione && !request) {
  764.                                         try {
  765.                                             audIntegrity = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUDIENCE,
  766.                                                     audIntegrity, dynamicMap, this.context);
  767.                                         }catch(Exception e) {
  768.                                             this.logError(e.getMessage(),e);
  769.                                             throw e;
  770.                                         }
  771.                                     }
  772.                                     msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_AUDIENCE_INTEGRITY_CHECK, audIntegrity);
  773.                                    
  774.                                     if(!request && securityConfig.isCheckAudience() && integritaKid && securityConfig.getTokenClientId()!=null) {
  775.                                         String audienceClientId = null;
  776.                                         try {
  777.                                             audienceClientId = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUDIENCE+"-OAuth",
  778.                                                     securityConfig.getTokenClientId(), dynamicMap, this.context);
  779.                                         }catch(Exception e) {
  780.                                             this.logError(e.getMessage(),e);
  781.                                             throw e;
  782.                                         }
  783.                                         if(audienceClientId!=null) {
  784.                                             msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_AUDIENCE_INTEGRITY_CHECK_OAUTH, audienceClientId);
  785.                                         }
  786.                                     }
  787.                                 }
  788.                                
  789.                                 // Finalizzo
  790.                                
  791.                                 if(tokenAuthorization!=null && tokenIntegrity!=null) {
  792.                                     rawContent = new ModIBustaRawContent(tokenAuthorization, headerTokenRestIntegrity, tokenIntegrity);
  793.                                 }
  794.                                 else if(tokenAuthorization!=null) {
  795.                                     rawContent = new ModIBustaRawContent(headerTokenRest, tokenAuthorization);
  796.                                 }
  797.                                 else if(tokenIntegrity!=null) {
  798.                                     rawContent = new ModIBustaRawContent(headerTokenRestIntegrity, tokenIntegrity);
  799.                                 }
  800.                                
  801.                             }
  802.                            
  803.                         }
  804.                         else {

  805.                             // soap
  806.                            
  807.                             String prefixMsgDiag = null;
  808.                             if(integrita) {
  809.                                 prefixMsgDiag = DIAGNOSTIC_VALIDATE_TOKEN_INTEGRITY;
  810.                             }
  811.                             else {
  812.                                 prefixMsgDiag = DIAGNOSTIC_VALIDATE_TOKEN_ID_AUTH;
  813.                             }
  814.                             try {
  815.                                 msgDiag.logPersonalizzato(prefixMsgDiag+tipoDiagnostico+DIAGNOSTIC_IN_CORSO);
  816.                            
  817.                                 boolean corniceSicurezzaLegacySoap = corniceSicurezza && !processAudit;
  818.                                
  819.                                 SOAPEnvelope token = validatoreSintatticoSoap.validateSecurityProfile(msg, request, securityMessageProfile, corniceSicurezzaLegacySoap, includiRequestDigest, signAttachments, bustaRitornata,
  820.                                         erroriValidazione, trustStoreCertificati, securityConfig,
  821.                                         buildSecurityTokenInRequest,
  822.                                         dynamicMap, datiRichiesta, requestInfo, msgDiag );
  823.                                
  824.                                 if(token!=null) {
  825.                                    
  826.                                     if(securityConfig.getAudience()!=null &&
  827.                                         (request || (securityConfig.isCheckAudience()))
  828.                                         ){
  829.                                         String audience = securityConfig.getAudience();
  830.                                         if(fruizione && !request) {
  831.                                             try {
  832.                                                 audience = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SOAP_WSA_TO,
  833.                                                         audience, dynamicMap, this.context);
  834.                                             }catch(Exception e) {
  835.                                                 this.logError(e.getMessage(),e);
  836.                                                 throw e;
  837.                                             }
  838.                                         }
  839.                                         msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_AUDIENCE_CHECK, audience);
  840.                                     }
  841.                                    
  842.                                     rawContent = new ModIBustaRawContent(token);
  843.                                 }

  844.                                 if(erroriValidazione.isEmpty()) {
  845.                                     msgDiag.logPersonalizzato(prefixMsgDiag+tipoDiagnostico+DIAGNOSTIC_COMPLETATA);
  846.                                 }
  847.                                 else {
  848.                                     String errore = buildErrore(erroriValidazione, this.protocolFactory);
  849.                                     msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, errore);
  850.                                     msgDiag.logPersonalizzato(prefixMsgDiag+tipoDiagnostico+DIAGNOSTIC_FALLITA);
  851.                                     errorOccurs = true;
  852.                                 }
  853.                             }
  854.                             catch(ProtocolException pe) {
  855.                                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, pe.getMessage());
  856.                                 msgDiag.logPersonalizzato(prefixMsgDiag+tipoDiagnostico+DIAGNOSTIC_FALLITA);
  857.                                 throw pe;
  858.                             }
  859.                            
  860.                         }
  861.                    
  862.                     }
  863.                    
  864.                     // audit (ID_AUDIT)
  865.                     if(!errorOccurs && processAudit) {
  866.                        
  867.                         bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_PATTERN,
  868.                                 ModIPropertiesUtils.convertProfiloAuditToSDKValue(patternCorniceSicurezza));
  869.                         bustaRitornata.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_SCHEMA,
  870.                                 ModIPropertiesUtils.convertSchemaAuditToSDKValue(schemaCorniceSicurezza, this.modiProperties));
  871.                        
  872.                         if(validatoreSintatticoRest==null) {
  873.                             // audit su api soap
  874.                             validatoreSintatticoRest = new ModIValidazioneSintatticaRest(this.log, this.state, this.context, this.protocolFactory, requestInfo, this.modiProperties, this.validazioneUtils);
  875.                         }
  876.                        
  877.                         String securityMessageProfileAudit = null;
  878.                         if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0301.equals(securityMessageProfile)
  879.                                 ||
  880.                                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile)) {
  881.                             securityMessageProfileAudit = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM01;
  882.                         }
  883.                         else {
  884.                             securityMessageProfileAudit = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM02;
  885.                         }
  886.                                                
  887.                         boolean useKIDforAudit = false;
  888.                         if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile)
  889.                                 ||
  890.                                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0402.equals(securityMessageProfile)
  891.                                 ||
  892.                                 !sorgenteLocale) {
  893.                             useKIDforAudit = true;
  894.                         }
  895.                        
  896.                         String headerTokenAudit = this.modiProperties.getSecurityTokenHeaderModIAudit();
  897.                        
  898.                         try {
  899.                             msgDiag.logPersonalizzato("validateTokenAudit.richiesta.inCorso");
  900.                        
  901.                             boolean securityHeaderObbligatorio = !corniceSicurezzaOpzionale;
  902.                            
  903.                             String tokenAudit = validatoreSintatticoRest.validateSecurityProfile(msg, request, securityMessageProfileAudit, useKIDforAudit, headerTokenAudit,
  904.                                     corniceSicurezza, patternCorniceSicurezza, schemaCorniceSicurezza,
  905.                                     false, bustaRitornata,
  906.                                     erroriValidazione, trustStoreCertificati, trustStoreSsl, securityConfigAudit,
  907.                                     buildSecurityTokenInRequest, ModIHeaderType.SINGLE, integritaCustom, securityHeaderObbligatorio,
  908.                                     dynamicMap, datiRichiesta,
  909.                                     idSoggetto, msgDiag);
  910.                            
  911.                             if(tokenAudit!=null){
  912.                                 String audExpected = securityConfig.getCorniceSicurezzaAudience();
  913.                                 try {
  914.                                     audExpected = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_AUDIENCE,
  915.                                             audExpected, dynamicMap, this.context);
  916.                                 }catch(Exception e) {
  917.                                     this.logError(e.getMessage(),e);
  918.                                     throw e;
  919.                                 }
  920.                                 msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_AUDIENCE_AUDIT_CHECK, audExpected);              
  921.                             }
  922.                            
  923.                             if(rawContent!=null) {
  924.                                 rawContent.getElement().setTokenAudit(headerTokenAudit, tokenAudit);
  925.                             }
  926.                            
  927.                             if(erroriValidazione.isEmpty()) {
  928.                                 msgDiag.logPersonalizzato("validateTokenAudit.richiesta.completata");
  929.                             }
  930.                             else {
  931.                                 String errore = buildErrore(erroriValidazione, this.protocolFactory);
  932.                                 msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, errore);
  933.                                 msgDiag.logPersonalizzato("validateTokenAudit.richiesta.fallita");
  934.                             }
  935.                         }
  936.                         catch(ProtocolException pe) {
  937.                             msgDiag.addKeyword(CostantiPdD.KEY_ERRORE_PROCESSAMENTO, pe.getMessage());
  938.                             msgDiag.logPersonalizzato("validateTokenAudit.richiesta.fallita");
  939.                             throw pe;
  940.                         }
  941.                        
  942.                     }
  943.                    
  944.                    
  945.                     // jit as filtro duplicato
  946.                     if(request && !sorgenteLocale) {
  947.                         if(processSecurity) {
  948.                             String idPropertyMultipleHeaderUseJtiAuthorizationAsIdMessaggio = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_RICHIESTA_REST_DOPPI_HEADER_FILTRO_DUPLICATI;
  949.                             List<ProtocolProperty> listProtocolPropertiesInternal = ModIPropertiesUtils.getProtocolProperties(fruizione, idSoggettoMittente, asps);
  950.                             if(listProtocolPropertiesInternal!=null && !listProtocolPropertiesInternal.isEmpty()) {
  951.                                 String multipleHeaderUseJtiAuthorizationAsIdMessaggioPropRegistry = ProtocolPropertiesUtils.getOptionalStringValuePropertyRegistry(listProtocolPropertiesInternal, idPropertyMultipleHeaderUseJtiAuthorizationAsIdMessaggio);
  952.                                 if(multipleHeaderUseJtiAuthorizationAsIdMessaggioPropRegistry!=null) {
  953.                                     boolean multipleHeaderUseJtiAuthorizationAsIdMessaggio = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_REST_DOPPI_HEADER_FILTRO_DUPLICATI_VALUE_AUTHORIZATION.equals(multipleHeaderUseJtiAuthorizationAsIdMessaggioPropRegistry);
  954.                                     msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_USE_JTI_AUTHORIZATION, multipleHeaderUseJtiAuthorizationAsIdMessaggio);
  955.                                 }
  956.                             }
  957.                         }
  958.                         else {
  959.                             msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_USE_JTI_AUTHORIZATION, true);
  960.                         }
  961.                     }
  962.                 }

  963.             }
  964.                        
  965.         }catch(Exception e) {
  966.             erroreProcessamentoInternalMessage = e.getMessage();
  967.             String msgErrore =  "[ErroreInterno]: "+e.getMessage();
  968.             this.logError(msgErrore,e);
  969.             if(request) {
  970.                 ValidazioneSintatticaResult<AbstractModISecurityToken<?>> errorResult = new ValidazioneSintatticaResult<>(null, null, null,
  971.                         bustaRitornata, new ErroreCooperazione(msgErrore, CodiceErroreCooperazione.ERRORE_GENERICO_PROCESSAMENTO_MESSAGGIO), null, null, false);
  972.                 errorResult.setErrore_integrationFunctionError(IntegrationFunctionError.INTERNAL_REQUEST_ERROR);
  973.                 return errorResult;
  974.             }
  975.             else {
  976.                 try {
  977.                     erroriProcessamento.add(this.validazioneUtils.newEccezioneProcessamento(CodiceErroreCooperazione.ERRORE_GENERICO_PROCESSAMENTO_MESSAGGIO));
  978.                 }catch(Exception eInternal) {
  979.                     ValidazioneSintatticaResult<AbstractModISecurityToken<?>> errorResult = new ValidazioneSintatticaResult<>(null, null, null,
  980.                             bustaRitornata, new ErroreCooperazione(msgErrore, CodiceErroreCooperazione.ERRORE_GENERICO_PROCESSAMENTO_MESSAGGIO), null, null, false);
  981.                     errorResult.setErrore_integrationFunctionError(IntegrationFunctionError.INTERNAL_RESPONSE_ERROR);
  982.                     return errorResult;
  983.                 }
  984.             }
  985.         }
  986.        
  987.         if(!erroriValidazione.isEmpty() || !erroriProcessamento.isEmpty()) {
  988.             ValidazioneSintatticaResult<AbstractModISecurityToken<?>> resultError = new ValidazioneSintatticaResult<>(erroriValidazione, erroriProcessamento, null,
  989.                     bustaRitornata, null, null, rawContent, true);
  990.             resultError.setErroreProcessamento_internalMessage(erroreProcessamentoInternalMessage);
  991.            
  992.             if(!erroriValidazione.isEmpty() &&
  993.                 this.context!=null) {
  994.                 this.context.addObject(Costanti.ERRORE_VALIDAZIONE_PROTOCOLLO, Costanti.ERRORE_TRUE);
  995.             }
  996.            
  997.             return resultError;
  998.         }
  999.        
  1000.         basicResult.setBustaRaw(rawContent);
  1001.         return basicResult;
  1002.     }
  1003.    
  1004.     static String buildErrore(List<Eccezione> list, IProtocolFactory<?> protocolFactory) throws ProtocolException {
  1005.         return buildErrore(list, 0, protocolFactory);
  1006.     }
  1007.     static String buildErrore(List<Eccezione> list, int offset, IProtocolFactory<?> protocolFactory) throws ProtocolException {
  1008.         StringBuilder sb = new StringBuilder();
  1009.         if(list!=null && !list.isEmpty()) {
  1010.             if(list.size()==1) {
  1011.                 if(offset>0) {
  1012.                     throw new ProtocolException("Offset > 0 con lista di dimensione '"+list.size()+"'");
  1013.                 }
  1014.                 Eccezione eccezione = list.get(0);
  1015.                 sb.append("[");
  1016.                 sb.append(eccezione.getCodiceEccezioneValue(protocolFactory));
  1017.                 sb.append("] ");
  1018.                 sb.append(eccezione.getDescrizione(protocolFactory));
  1019.             }
  1020.             else {
  1021.                 if(offset>list.size()) {
  1022.                     throw new ProtocolException("Offset maggiore della dimensione della lista di errori '"+list.size()+"'");
  1023.                 }
  1024.                 int size = list.size() - offset;
  1025.                 sb.append("Riscontrate "+size+" eccezioni.");
  1026.                 int index = 0;
  1027.                 for (Eccezione eccezione : list) {
  1028.                     if(index>=offset) {
  1029.                         sb.append("\n[");
  1030.                         sb.append(eccezione.getCodiceEccezioneValue(protocolFactory));
  1031.                         sb.append("] ");
  1032.                         sb.append(eccezione.getDescrizione(protocolFactory));
  1033.                     }
  1034.                     index++;
  1035.                 }
  1036.             }
  1037.         }
  1038.         return sb.toString();
  1039.     }
  1040. }