GestoreAutorizzazione.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.autorizzazione;

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

  25. import org.openspcoop2.core.config.AutorizzazioneScope;
  26. import org.openspcoop2.core.config.PortaApplicativaAutorizzazioneServizioApplicativo;
  27. import org.openspcoop2.core.config.PortaDelegata;
  28. import org.openspcoop2.core.config.PortaDelegataServizioApplicativo;
  29. import org.openspcoop2.core.config.Scope;
  30. import org.openspcoop2.core.config.ServizioApplicativo;
  31. import org.openspcoop2.core.config.constants.CostantiConfigurazione;
  32. import org.openspcoop2.core.config.constants.RuoloTipologia;
  33. import org.openspcoop2.core.config.constants.ScopeTipoMatch;
  34. import org.openspcoop2.core.config.constants.StatoFunzionalita;
  35. import org.openspcoop2.core.id.IDPortaApplicativa;
  36. import org.openspcoop2.core.id.IDPortaDelegata;
  37. import org.openspcoop2.core.id.IDServizio;
  38. import org.openspcoop2.core.id.IDServizioApplicativo;
  39. import org.openspcoop2.core.id.IDSoggetto;
  40. import org.openspcoop2.message.OpenSPCoop2Message;
  41. import org.openspcoop2.message.utils.WWWAuthenticateErrorCode;
  42. import org.openspcoop2.message.utils.WWWAuthenticateGenerator;
  43. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  44. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  45. import org.openspcoop2.pdd.config.dynamic.PddPluginLoader;
  46. import org.openspcoop2.pdd.core.AbstractCore;
  47. import org.openspcoop2.pdd.core.CostantiPdD;
  48. import org.openspcoop2.pdd.core.PdDContext;
  49. import org.openspcoop2.pdd.core.autorizzazione.pa.DatiInvocazionePortaApplicativa;
  50. import org.openspcoop2.pdd.core.autorizzazione.pa.EsitoAutorizzazionePortaApplicativa;
  51. import org.openspcoop2.pdd.core.autorizzazione.pa.IAutorizzazioneContenutoPortaApplicativa;
  52. import org.openspcoop2.pdd.core.autorizzazione.pa.IAutorizzazionePortaApplicativa;
  53. import org.openspcoop2.pdd.core.autorizzazione.pd.DatiInvocazionePortaDelegata;
  54. import org.openspcoop2.pdd.core.autorizzazione.pd.EsitoAutorizzazionePortaDelegata;
  55. import org.openspcoop2.pdd.core.autorizzazione.pd.IAutorizzazioneContenutoPortaDelegata;
  56. import org.openspcoop2.pdd.core.autorizzazione.pd.IAutorizzazionePortaDelegata;
  57. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  58. import org.openspcoop2.pdd.core.token.InformazioniToken;
  59. import org.openspcoop2.pdd.core.token.TokenUtilities;
  60. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  61. import org.openspcoop2.protocol.engine.constants.Costanti;
  62. import org.openspcoop2.protocol.registry.RegistroServiziManager;
  63. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  64. import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
  65. import org.openspcoop2.protocol.sdk.constants.ErroriCooperazione;
  66. import org.openspcoop2.protocol.sdk.constants.ErroriIntegrazione;
  67. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  68. import org.openspcoop2.protocol.sdk.constants.RuoloBusta;
  69. import org.openspcoop2.utils.SemaphoreLock;
  70. import org.openspcoop2.utils.SortedMap;
  71. import org.openspcoop2.utils.UtilsException;
  72. import org.openspcoop2.utils.cache.Cache;
  73. import org.openspcoop2.utils.cache.CacheAlgorithm;
  74. import org.openspcoop2.utils.cache.CacheResponse;
  75. import org.openspcoop2.utils.cache.CacheType;
  76. import org.openspcoop2.utils.properties.PropertiesUtilities;
  77. import org.openspcoop2.utils.regexp.RegularExpressionEngine;
  78. import org.slf4j.Logger;

  79. /**
  80.  * Classe utilizzata per la gestione del processo di autorizzazione Buste
  81.  *
  82.  * @author Poli Andrea (apoli@link.it)
  83.  * @author $Author$
  84.  * @version $Rev$, $Date$
  85.  */
  86. public class GestoreAutorizzazione {

  87.    
  88.     /** Chiave della cache per l'autorizzazione Buste  */
  89.     private static final String AUTORIZZAZIONE_CACHE_NAME = "autorizzazione";
  90.     /** Cache */
  91.     private static Cache cacheAutorizzazione = null;
  92.     //private static final Boolean semaphoreAutorizzazionePD = true;
  93.     //private static final Boolean semaphoreAutorizzazionePA = true;
  94.     //private static final Boolean semaphoreAutorizzazioneContenutiPD = true;
  95.     //private static final Boolean semaphoreAutorizzazioneContenutiPA = true;
  96.    
  97.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockAutorizzazionePD = new HashMap<>();
  98.     private static synchronized org.openspcoop2.utils.Semaphore initLockAutorizzazionePD(String tipoAutorizzazione){
  99.         org.openspcoop2.utils.Semaphore s = _lockAutorizzazionePD.get(tipoAutorizzazione);
  100.         if(s==null) {
  101.             Integer permits = OpenSPCoop2Properties.getInstance().getAutorizzazioneLockPermits(tipoAutorizzazione);
  102.             if(permits==null) {
  103.                 permits = OpenSPCoop2Properties.getInstance().getAutorizzazioneLockPermits();
  104.             }
  105.             if(permits!=null && permits.intValue()>1) {
  106.                 s = new org.openspcoop2.utils.Semaphore("GestoreAutorizzazioneFruizioni_"+tipoAutorizzazione, permits);
  107.             }
  108.             else {
  109.                 s = new org.openspcoop2.utils.Semaphore("GestoreAutorizzazioneFruizioni_"+tipoAutorizzazione);
  110.             }
  111.             _lockAutorizzazionePD.put(tipoAutorizzazione, s);
  112.         }
  113.         return s;
  114.     }
  115.     private static org.openspcoop2.utils.Semaphore getLockAutorizzazionePD(String tipoAutorizzazione){
  116.         org.openspcoop2.utils.Semaphore s = _lockAutorizzazionePD.get(tipoAutorizzazione);
  117.         if(s==null) {
  118.             s = initLockAutorizzazionePD(tipoAutorizzazione);
  119.         }
  120.         return s;
  121.     }
  122.    
  123.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockAutorizzazionePA = new HashMap<>();
  124.     private static synchronized org.openspcoop2.utils.Semaphore initLockAutorizzazionePA(String tipoAutorizzazione){
  125.         org.openspcoop2.utils.Semaphore s = _lockAutorizzazionePA.get(tipoAutorizzazione);
  126.         if(s==null) {
  127.             Integer permits = OpenSPCoop2Properties.getInstance().getAutorizzazioneLockPermits(tipoAutorizzazione);
  128.             if(permits==null) {
  129.                 permits = OpenSPCoop2Properties.getInstance().getAutorizzazioneLockPermits();
  130.             }
  131.             if(permits!=null && permits.intValue()>1) {
  132.                 s = new org.openspcoop2.utils.Semaphore("GestoreAutorizzazioneErogazioni_"+tipoAutorizzazione, permits);
  133.             }
  134.             else {
  135.                 s = new org.openspcoop2.utils.Semaphore("GestoreAutorizzazioneErogazioni_"+tipoAutorizzazione);
  136.             }
  137.             _lockAutorizzazionePA.put(tipoAutorizzazione, s);
  138.         }
  139.         return s;
  140.     }
  141.     private static org.openspcoop2.utils.Semaphore getLockAutorizzazionePA(String tipoAutorizzazione){
  142.         org.openspcoop2.utils.Semaphore s = _lockAutorizzazionePA.get(tipoAutorizzazione);
  143.         if(s==null) {
  144.             s = initLockAutorizzazionePA(tipoAutorizzazione);
  145.         }
  146.         return s;
  147.     }
  148.    
  149.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockAutorizzazioneContenutiPD = new HashMap<>();
  150.     private static synchronized org.openspcoop2.utils.Semaphore initLockAutorizzazioneContenutiPD(String tipoAutorizzazioneContenuti){
  151.         org.openspcoop2.utils.Semaphore s = _lockAutorizzazioneContenutiPD.get(tipoAutorizzazioneContenuti);
  152.         if(s==null) {
  153.             Integer permits = OpenSPCoop2Properties.getInstance().getAutorizzazioneContenutiLockPermits(tipoAutorizzazioneContenuti);
  154.             if(permits==null) {
  155.                 permits = OpenSPCoop2Properties.getInstance().getAutorizzazioneContenutiLockPermits();
  156.             }
  157.             if(permits!=null && permits.intValue()>1) {
  158.                 s = new org.openspcoop2.utils.Semaphore("GestoreAutorizzazioneContenutiFruizioni_"+tipoAutorizzazioneContenuti, permits);
  159.             }
  160.             else {
  161.                 s = new org.openspcoop2.utils.Semaphore("GestoreAutorizzazioneContenutiFruizioni_"+tipoAutorizzazioneContenuti);
  162.             }
  163.             _lockAutorizzazioneContenutiPD.put(tipoAutorizzazioneContenuti, s);
  164.         }
  165.         return s;
  166.     }
  167.     private static org.openspcoop2.utils.Semaphore getLockAutorizzazioneContenutiPD(String tipoAutorizzazioneContenuti){
  168.         org.openspcoop2.utils.Semaphore s = _lockAutorizzazioneContenutiPD.get(tipoAutorizzazioneContenuti);
  169.         if(s==null) {
  170.             s = initLockAutorizzazioneContenutiPD(tipoAutorizzazioneContenuti);
  171.         }
  172.         return s;
  173.     }
  174.    
  175.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockAutorizzazioneContenutiPA = new HashMap<>();
  176.     private static synchronized org.openspcoop2.utils.Semaphore initLockAutorizzazioneContenutiPA(String tipoAutorizzazioneContenuti){
  177.         org.openspcoop2.utils.Semaphore s = _lockAutorizzazioneContenutiPA.get(tipoAutorizzazioneContenuti);
  178.         if(s==null) {
  179.             Integer permits = OpenSPCoop2Properties.getInstance().getAutorizzazioneContenutiLockPermits(tipoAutorizzazioneContenuti);
  180.             if(permits==null) {
  181.                 permits = OpenSPCoop2Properties.getInstance().getAutorizzazioneContenutiLockPermits();
  182.             }
  183.             if(permits!=null && permits.intValue()>1) {
  184.                 s = new org.openspcoop2.utils.Semaphore("GestoreAutorizzazioneContenutiErogazioni_"+tipoAutorizzazioneContenuti, permits);
  185.             }
  186.             else {
  187.                 s = new org.openspcoop2.utils.Semaphore("GestoreAutorizzazioneContenutiErogazioni_"+tipoAutorizzazioneContenuti);
  188.             }
  189.             _lockAutorizzazioneContenutiPA.put(tipoAutorizzazioneContenuti, s);
  190.         }
  191.         return s;
  192.     }
  193.     private static org.openspcoop2.utils.Semaphore getLockAutorizzazioneContenutiPA(String tipoAutorizzazioneContenuti){
  194.         org.openspcoop2.utils.Semaphore s = _lockAutorizzazioneContenutiPA.get(tipoAutorizzazioneContenuti);
  195.         if(s==null) {
  196.             s = initLockAutorizzazioneContenutiPA(tipoAutorizzazioneContenuti);
  197.         }
  198.         return s;
  199.     }
  200.    
  201.     /** Logger log */
  202.     private static Logger logger = null;
  203.     private static Logger logConsole = OpenSPCoop2Logger.getLoggerOpenSPCoopConsole();



  204.     /* --------------- Cache --------------------*/
  205.     public static void resetCache() throws AutorizzazioneException{
  206.         if(GestoreAutorizzazione.cacheAutorizzazione!=null){
  207.             try{
  208.                 GestoreAutorizzazione.cacheAutorizzazione.clear();
  209.             }catch(Exception e){
  210.                 throw new AutorizzazioneException(e.getMessage(),e);
  211.             }
  212.         }
  213.     }
  214.     public static String printStatsCache(String separator) throws AutorizzazioneException{
  215.         try{
  216.             if(GestoreAutorizzazione.cacheAutorizzazione!=null){
  217.                 return GestoreAutorizzazione.cacheAutorizzazione.printStats(separator);
  218.             }
  219.             else{
  220.                 throw new Exception("Cache non abilitata");
  221.             }
  222.         }catch(Exception e){
  223.             throw new AutorizzazioneException("Visualizzazione Statistiche riguardante la cache delle autorizzazioni non riuscita: "+e.getMessage(),e);
  224.         }
  225.     }
  226.     public static void abilitaCache() throws AutorizzazioneException{
  227.         if(GestoreAutorizzazione.cacheAutorizzazione!=null)
  228.             throw new AutorizzazioneException("Cache gia' abilitata");
  229.         else{
  230.             _abilitaCache();
  231.         }
  232.     }
  233.     private static synchronized void _abilitaCache() throws AutorizzazioneException{
  234.         if(GestoreAutorizzazione.cacheAutorizzazione==null) {
  235.             try{
  236.                 GestoreAutorizzazione.cacheAutorizzazione = new Cache(CacheType.JCS, GestoreAutorizzazione.AUTORIZZAZIONE_CACHE_NAME); // lascio JCS come default abilitato via jmx
  237.                 GestoreAutorizzazione.cacheAutorizzazione.build();
  238.             }catch(Exception e){
  239.                 throw new AutorizzazioneException(e.getMessage(),e);
  240.             }
  241.         }
  242.     }
  243.     public static void abilitaCache(Long dimensioneCache,Boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond) throws AutorizzazioneException{
  244.         if(GestoreAutorizzazione.cacheAutorizzazione!=null)
  245.             throw new AutorizzazioneException("Cache gia' abilitata");
  246.         else{
  247.             try{
  248.                 int dimensioneCacheInt = -1;
  249.                 if(dimensioneCache!=null){
  250.                     dimensioneCacheInt = dimensioneCache.intValue();
  251.                 }
  252.                
  253.                 String algoritmoCache = null;
  254.                 if(algoritmoCacheLRU!=null){
  255.                     if(algoritmoCacheLRU)
  256.                          algoritmoCache = CostantiConfigurazione.CACHE_LRU.toString();
  257.                     else
  258.                          algoritmoCache = CostantiConfigurazione.CACHE_MRU.toString();
  259.                 }else{
  260.                     algoritmoCache = CostantiConfigurazione.CACHE_LRU.toString();
  261.                 }
  262.                
  263.                 long itemIdleTimeLong = -1;
  264.                 if(itemIdleTime!=null){
  265.                     itemIdleTimeLong = itemIdleTime;
  266.                 }
  267.                
  268.                 long itemLifeSecondLong = -1;
  269.                 if(itemLifeSecond!=null){
  270.                     itemLifeSecondLong = itemLifeSecond;
  271.                 }
  272.                
  273.                 GestoreAutorizzazione.initCacheAutorizzazione(CacheType.JCS, dimensioneCacheInt, algoritmoCache, itemIdleTimeLong, itemLifeSecondLong, null); // lascio JCS come default abilitato via jmx
  274.             }catch(Exception e){
  275.                 throw new AutorizzazioneException(e.getMessage(),e);
  276.             }
  277.         }
  278.     }
  279.     public static void disabilitaCache() throws AutorizzazioneException{
  280.         if(GestoreAutorizzazione.cacheAutorizzazione==null)
  281.             throw new AutorizzazioneException("Cache gia' disabilitata");
  282.         else{
  283.             _disabilitaCache();
  284.         }
  285.     }
  286.     private static synchronized void _disabilitaCache() throws AutorizzazioneException{
  287.         if(GestoreAutorizzazione.cacheAutorizzazione!=null) {
  288.             try{
  289.                 GestoreAutorizzazione.cacheAutorizzazione.clear();
  290.                 GestoreAutorizzazione.cacheAutorizzazione = null;
  291.             }catch(Exception e){
  292.                 throw new AutorizzazioneException(e.getMessage(),e);
  293.             }
  294.         }
  295.     }
  296.     public static boolean isCacheAbilitata(){
  297.         return GestoreAutorizzazione.cacheAutorizzazione != null;
  298.     }
  299.     public static String listKeysCache(String separator) throws AutorizzazioneException{
  300.         if(GestoreAutorizzazione.cacheAutorizzazione!=null){
  301.             try{
  302.                 return GestoreAutorizzazione.cacheAutorizzazione.printKeys(separator);
  303.             }catch(Exception e){
  304.                 throw new AutorizzazioneException(e.getMessage(),e);
  305.             }
  306.         }else{
  307.             throw new AutorizzazioneException("Cache non abilitata");
  308.         }
  309.     }
  310.     public static List<String> listKeysCache() throws AutorizzazioneException{
  311.         if(GestoreAutorizzazione.cacheAutorizzazione!=null){
  312.             try{
  313.                 return GestoreAutorizzazione.cacheAutorizzazione.keys();
  314.             }catch(Exception e){
  315.                 throw new AutorizzazioneException(e.getMessage(),e);
  316.             }
  317.         }else{
  318.             throw new AutorizzazioneException("Cache non abilitata");
  319.         }
  320.     }
  321.     public static String getObjectCache(String key) throws AutorizzazioneException{
  322.         if(GestoreAutorizzazione.cacheAutorizzazione!=null){
  323.             try{
  324.                 Object o = GestoreAutorizzazione.cacheAutorizzazione.get(key);
  325.                 if(o!=null){
  326.                     return o.toString();
  327.                 }else{
  328.                     return "oggetto con chiave ["+key+"] non presente";
  329.                 }
  330.             }catch(Exception e){
  331.                 throw new AutorizzazioneException(e.getMessage(),e);
  332.             }
  333.         }else{
  334.             throw new AutorizzazioneException("Cache non abilitata");
  335.         }
  336.     }
  337.     public static Object getRawObjectCache(String key) throws AutorizzazioneException{
  338.         if(GestoreAutorizzazione.cacheAutorizzazione!=null){
  339.             try{
  340.                 Object o = GestoreAutorizzazione.cacheAutorizzazione.get(key);
  341.                 if(o!=null){
  342.                     if(o instanceof CacheResponse) {
  343.                         CacheResponse cR = (CacheResponse) o;
  344.                         if(cR.getObject()!=null) {
  345.                             o = cR.getObject();
  346.                         }
  347.                         else if(cR.getException()!=null) {
  348.                             o = cR.getException();
  349.                         }
  350.                     }
  351.                     return o;
  352.                 }else{
  353.                     return null;
  354.                 }
  355.             }catch(Exception e){
  356.                 throw new AutorizzazioneException(e.getMessage(),e);
  357.             }
  358.         }else{
  359.             throw new AutorizzazioneException("Cache non abilitata");
  360.         }
  361.     }
  362.     public static void removeObjectCache(String key) throws AutorizzazioneException{
  363.         if(GestoreAutorizzazione.cacheAutorizzazione!=null){
  364.             try{
  365.                 GestoreAutorizzazione.cacheAutorizzazione.remove(key);
  366.             }catch(Exception e){
  367.                 throw new AutorizzazioneException(e.getMessage(),e);
  368.             }
  369.         }else{
  370.             throw new AutorizzazioneException("Cache non abilitata");
  371.         }
  372.     }
  373.    


  374.     /*----------------- INIZIALIZZAZIONE --------------------*/
  375.     public static void initialize(Logger log) throws Exception{
  376.         GestoreAutorizzazione.initialize(null, false, -1,null,-1l,-1l, log);
  377.     }
  378.     public static void initialize(CacheType cacheType, int dimensioneCache,String algoritmoCache,
  379.             long idleTime, long itemLifeSecond, Logger log) throws Exception{
  380.         GestoreAutorizzazione.initialize(cacheType, true, dimensioneCache,algoritmoCache,idleTime,itemLifeSecond, log);
  381.     }

  382.     private static void initialize(CacheType cacheType, boolean cacheAbilitata,int dimensioneCache,String algoritmoCache,
  383.             long idleTime, long itemLifeSecond, Logger log) throws Exception{

  384.         // Inizializzo log
  385.         GestoreAutorizzazione.logger = log;
  386.        
  387.         // Inizializzazione Cache
  388.         if(cacheAbilitata){
  389.             GestoreAutorizzazione.initCacheAutorizzazione(cacheType, dimensioneCache, algoritmoCache, idleTime, itemLifeSecond, log);
  390.         }

  391.     }


  392.     public static void initCacheAutorizzazione(CacheType cacheType, int dimensioneCache,String algoritmoCache,
  393.             long idleTime, long itemLifeSecond, Logger log) throws Exception {
  394.        
  395.         if(log!=null)
  396.             log.info("Inizializzazione cache Autorizzazione");

  397.         GestoreAutorizzazione.cacheAutorizzazione = new Cache(cacheType, GestoreAutorizzazione.AUTORIZZAZIONE_CACHE_NAME);

  398.         if( (dimensioneCache>0) ||
  399.                 (algoritmoCache != null) ){

  400.             if( dimensioneCache>0 ){
  401.                 try{
  402.                     String msg = "Dimensione della cache (Autorizzazione) impostata al valore: "+dimensioneCache;
  403.                     if(log!=null)
  404.                         log.info(msg);
  405.                     GestoreAutorizzazione.logConsole.info(msg);
  406.                     GestoreAutorizzazione.cacheAutorizzazione.setCacheSize(dimensioneCache);
  407.                 }catch(Exception error){
  408.                     throw new AutorizzazioneException("Parametro errato per la dimensione della cache (Gestore Messaggi): "+error.getMessage(),error);
  409.                 }
  410.             }
  411.             if(algoritmoCache != null ){
  412.                 String msg = "Algoritmo di cache (Autorizzazione) impostato al valore: "+algoritmoCache;
  413.                 if(log!=null)
  414.                     log.info(msg);
  415.                 GestoreAutorizzazione.logConsole.info(msg);
  416.                 if(CostantiConfigurazione.CACHE_MRU.toString().equalsIgnoreCase(algoritmoCache))
  417.                     GestoreAutorizzazione.cacheAutorizzazione.setCacheAlgoritm(CacheAlgorithm.MRU);
  418.                 else
  419.                     GestoreAutorizzazione.cacheAutorizzazione.setCacheAlgoritm(CacheAlgorithm.LRU);
  420.             }

  421.         }

  422.         if( idleTime > 0  ){
  423.             try{
  424.                 String msg = "Attributo 'IdleTime' (Autorizzazione) impostato al valore: "+idleTime;
  425.                 if(log!=null)
  426.                     log.info(msg);
  427.                 GestoreAutorizzazione.logConsole.info(msg);
  428.                 GestoreAutorizzazione.cacheAutorizzazione.setItemIdleTime(idleTime);
  429.             }catch(Exception error){
  430.                 throw new AutorizzazioneException("Parametro errato per l'attributo 'IdleTime' (Gestore Messaggi): "+error.getMessage(),error);
  431.             }
  432.         }
  433.         try{
  434.             String msg = "Attributo 'MaxLifeSecond' (Autorizzazione) impostato al valore: "+itemLifeSecond;
  435.             if(log!=null)
  436.                 log.info(msg);
  437.             GestoreAutorizzazione.logConsole.info(msg);
  438.             GestoreAutorizzazione.cacheAutorizzazione.setItemLifeTime(itemLifeSecond);
  439.         }catch(Exception error){
  440.             throw new AutorizzazioneException("Parametro errato per l'attributo 'MaxLifeSecond' (Gestore Messaggi): "+error.getMessage(),error);
  441.         }
  442.        
  443.         GestoreAutorizzazione.cacheAutorizzazione.build();

  444.     }
  445.    

  446.     @SuppressWarnings("deprecation")
  447.     @Deprecated
  448.     public static void disableSyncronizedGet() throws UtilsException {
  449.         if(GestoreAutorizzazione.cacheAutorizzazione==null) {
  450.             throw new UtilsException("Cache disabled");
  451.         }
  452.         GestoreAutorizzazione.cacheAutorizzazione.disableSyncronizedGet();
  453.     }
  454.     @SuppressWarnings("deprecation")
  455.     @Deprecated
  456.     public static boolean isDisableSyncronizedGet() throws UtilsException {
  457.         if(GestoreAutorizzazione.cacheAutorizzazione==null) {
  458.             throw new UtilsException("Cache disabled");
  459.         }
  460.         return GestoreAutorizzazione.cacheAutorizzazione.isDisableSyncronizedGet();
  461.     }
  462.    
  463.    
  464.    
  465.    
  466.    
  467.    
  468. /*----------------- CLEANER --------------------*/
  469.    
  470.     public static void removePortaApplicativa(IDPortaApplicativa idPA) throws Exception {
  471.         if(GestoreAutorizzazione.isCacheAbilitata()) {
  472.             List<String> keyForClean = new ArrayList<>();
  473.             List<String> keys = GestoreAutorizzazione.listKeysCache();
  474.             if(keys!=null && !keys.isEmpty()) {
  475.                 String match = IDPortaApplicativa.PORTA_APPLICATIVA_PREFIX+idPA.getNome()+IDPortaApplicativa.PORTA_APPLICATIVA_SUFFIX;
  476.                 for (String key : keys) {
  477.                     if(key!=null && key.contains(match)) {
  478.                         keyForClean.add(key);
  479.                     }
  480.                 }
  481.             }
  482.             if(keyForClean!=null && !keyForClean.isEmpty()) {
  483.                 for (String key : keyForClean) {
  484.                     removeObjectCache(key);
  485.                 }
  486.             }
  487.         }
  488.     }
  489.    
  490.     public static void removePortaDelegata(IDPortaDelegata idPD) throws Exception {
  491.         if(GestoreAutorizzazione.isCacheAbilitata()) {
  492.             List<String> keyForClean = new ArrayList<>();
  493.             List<String> keys = GestoreAutorizzazione.listKeysCache();
  494.             if(keys!=null && !keys.isEmpty()) {
  495.                 String match = IDPortaDelegata.PORTA_DELEGATA_PREFIX+idPD.getNome()+IDPortaDelegata.PORTA_DELEGATA_SUFFIX;
  496.                 for (String key : keys) {
  497.                     if(key!=null && key.contains(match)) {
  498.                         keyForClean.add(key);
  499.                     }
  500.                 }
  501.             }
  502.             if(keyForClean!=null && !keyForClean.isEmpty()) {
  503.                 for (String key : keyForClean) {
  504.                     removeObjectCache(key);
  505.                 }
  506.             }
  507.         }
  508.     }
  509.    
  510.     public static void removeSoggetto(IDSoggetto idSoggetto) throws Exception {
  511.         if(GestoreAutorizzazione.isCacheAbilitata()) {
  512.             List<String> keyForClean = new ArrayList<>();
  513.             List<String> keys = GestoreAutorizzazione.listKeysCache();
  514.             if(keys!=null && !keys.isEmpty()) {
  515.                 String matchSoggettoFruitore = DatiInvocazionePortaApplicativa.SOGGETTO_FRUITORE_PREFIX+idSoggetto.toString()+DatiInvocazionePortaApplicativa.SOGGETTO_FRUITORE_SUFFIX;
  516.                 for (String key : keys) {
  517.                     if(key!=null && key.contains(matchSoggettoFruitore)) {
  518.                         keyForClean.add(key);
  519.                     }
  520.                 }
  521.             }
  522.             if(keyForClean!=null && !keyForClean.isEmpty()) {
  523.                 for (String key : keyForClean) {
  524.                     removeObjectCache(key);
  525.                 }
  526.             }
  527.         }
  528.     }
  529.    
  530.     public static void removeApplicativo(IDServizioApplicativo idApplicativo) throws Exception {
  531.         if(GestoreAutorizzazione.isCacheAbilitata()) {
  532.             List<String> keyForClean = new ArrayList<>();
  533.             List<String> keys = GestoreAutorizzazione.listKeysCache();
  534.             if(keys!=null && !keys.isEmpty()) {
  535.                 String matchApplicativoFruitore = DatiInvocazionePortaApplicativa.APPLICATIVO_FRUITORE_PREFIX+idApplicativo.toString()+DatiInvocazionePortaApplicativa.APPLICATIVO_FRUITORE_SUFFIX;
  536.                 String matchApplicativo = DatiInvocazionePortaDelegata.APPLICATIVO_PREFIX+idApplicativo.toString()+DatiInvocazionePortaDelegata.APPLICATIVO_SUFFIX;
  537.                 for (String key : keys) {
  538.                     if(key!=null && (key.contains(matchApplicativoFruitore) || key.contains(matchApplicativo))) {
  539.                         keyForClean.add(key);
  540.                     }
  541.                 }
  542.             }
  543.             if(keyForClean!=null && !keyForClean.isEmpty()) {
  544.                 for (String key : keyForClean) {
  545.                     removeObjectCache(key);
  546.                 }
  547.             }
  548.         }
  549.     }
  550.    
  551.    
  552.    
  553.    
  554.    
  555.    
  556.    
  557.     /*----------------- AUTORIZZAZIONE --------------------*/
  558.    

  559.     public static EsitoAutorizzazionePortaDelegata verificaAutorizzazionePortaDelegata(String tipoAutorizzazione, DatiInvocazionePortaDelegata datiInvocazione,
  560.               PdDContext pddContext,IProtocolFactory<?> protocolFactory, OpenSPCoop2Message msg, Logger log) throws Exception{
  561.        
  562.         checkDatiPortaDelegata(datiInvocazione);
  563.        
  564.         EsitoAutorizzazionePortaDelegata esito = _verificaAutorizzazionePortaDelegata(tipoAutorizzazione, datiInvocazione, pddContext, protocolFactory, msg);
  565.         if(esito.isAutorizzato()==false) {
  566.             return esito;
  567.         }
  568.        
  569.         // Verifiche Richieste
  570.         boolean verificaAutorizzazioneRichiedenti = false;
  571.         boolean verificaAutorizzazioneRuoli = false;
  572.         if(datiInvocazione.getPd()!=null) {
  573.             if(datiInvocazione.getPd().getAutorizzazioneToken()!=null) {
  574.                 if(StatoFunzionalita.ABILITATO.equals(datiInvocazione.getPd().getAutorizzazioneToken().getAutorizzazioneApplicativi())){
  575.                     verificaAutorizzazioneRichiedenti=true;
  576.                 }
  577.                 if(StatoFunzionalita.ABILITATO.equals(datiInvocazione.getPd().getAutorizzazioneToken().getAutorizzazioneRuoli())){
  578.                     verificaAutorizzazioneRuoli = true;
  579.                 }
  580.             }
  581.         }
  582.        
  583.         // Verifica Token Richiedenti
  584.        
  585.         IDServizioApplicativo idSAToken = null;
  586.         if(pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_APPLICATIVO_TOKEN)) {
  587.             idSAToken = (IDServizioApplicativo) pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_APPLICATIVO_TOKEN);
  588.         }
  589.        
  590.         boolean authRichiedenti = true;
  591.         if(verificaAutorizzazioneRichiedenti){
  592.             authRichiedenti = false;
  593.             if( idSAToken!=null &&
  594.                     datiInvocazione.getPd().getAutorizzazioneToken().getServiziApplicativi()!=null &&
  595.                     datiInvocazione.getPd().getAutorizzazioneToken().getServiziApplicativi().sizeServizioApplicativoList()>0){
  596.                 for (PortaDelegataServizioApplicativo sa : datiInvocazione.getPd().getAutorizzazioneToken().getServiziApplicativi().getServizioApplicativoList()) {
  597.                     if(idSAToken.getNome().equals(sa.getNome())) {
  598.                         authRichiedenti = true;
  599.                         break;
  600.                     }
  601.                 }
  602.             }
  603.         }

  604.        
  605.         // Verifica Token Roles
  606.        
  607.         boolean authRuoli = true;
  608.         StringBuilder detailsBufferRuoli = null;
  609.         if(verificaAutorizzazioneRuoli){
  610.             boolean checkRuoloRegistro = false;
  611.             boolean checkRuoloEsterno = false;
  612.             if( datiInvocazione.getPd().getAutorizzazioneToken().getTipologiaRuoli()==null ||
  613.                 RuoloTipologia.QUALSIASI.equals(datiInvocazione.getPd().getAutorizzazioneToken().getTipologiaRuoli())){
  614.                 checkRuoloRegistro = true;
  615.                 checkRuoloEsterno = true;
  616.             }
  617.             else if( RuoloTipologia.INTERNO.equals(datiInvocazione.getPd().getAutorizzazioneToken().getTipologiaRuoli())){
  618.                 checkRuoloRegistro = true;
  619.             }
  620.             else if( RuoloTipologia.ESTERNO.equals(datiInvocazione.getPd().getAutorizzazioneToken().getTipologiaRuoli())){
  621.                 checkRuoloEsterno = true;
  622.             }
  623.             detailsBufferRuoli = new StringBuilder();
  624.             ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(datiInvocazione.getState());
  625.             ServizioApplicativo sa = null;
  626.             if(idSAToken!=null) {
  627.                 sa = configurazionePdDManager.getServizioApplicativo(idSAToken, datiInvocazione.getRequestInfo());
  628.             }
  629.             authRuoli = configurazionePdDManager.
  630.                     autorizzazioneTokenRoles(datiInvocazione.getPd(), sa,
  631.                             datiInvocazione.getInfoConnettoreIngresso(),
  632.                             pddContext, datiInvocazione.getRequestInfo(),
  633.                             checkRuoloRegistro, checkRuoloEsterno,
  634.                             detailsBufferRuoli);
  635.         }
  636.        
  637.        
  638.         // Esiti Verifiche Richieste
  639.        
  640.         if(verificaAutorizzazioneRichiedenti && verificaAutorizzazioneRuoli) {
  641.             // se una delle due autorizzazione e' andata a buon fine devo autorizzare
  642.             if(!authRichiedenti && !authRuoli) {
  643.                 // uso eccezione per ruolo che e' più completa come messaggistica
  644.                 EsitoAutorizzazionePortaDelegata esitoNew = esito;
  645.                 if(idSAToken!=null){
  646.                     esito.setErroreIntegrazione(IntegrationFunctionError.AUTHORIZATION_MISSING_ROLE, ErroriIntegrazione.ERRORE_404_AUTORIZZAZIONE_FALLITA_SA.
  647.                             getErrore404_AutorizzazioneFallitaServizioApplicativo(idSAToken.getNome()));
  648.                 }
  649.                 else{
  650.                     esito.setErroreIntegrazione(IntegrationFunctionError.AUTHORIZATION_MISSING_ROLE, ErroriIntegrazione.ERRORE_404_AUTORIZZAZIONE_FALLITA_SA_ANONIMO.
  651.                             getErrore404_AutorizzazioneFallitaServizioApplicativoAnonimo());
  652.                 }
  653.                 esito.setAutorizzato(false);
  654.                 if(detailsBufferRuoli.length()>0) {
  655.                     esito.setDetails(detailsBufferRuoli.toString());
  656.                 }
  657.                 return esitoNew;
  658.             }
  659.         }
  660.         else {
  661.             if(verificaAutorizzazioneRichiedenti && !authRichiedenti) {
  662.                 EsitoAutorizzazionePortaDelegata esitoNew = esito;
  663.                 esitoNew.setAutorizzato(false);
  664.                 esito.setErroreIntegrazione(IntegrationFunctionError.AUTHORIZATION_DENY, ErroriIntegrazione.ERRORE_404_AUTORIZZAZIONE_FALLITA_SA.
  665.                         getErrore404_AutorizzazioneFallitaServizioApplicativo(idSAToken!=null ? idSAToken.getNome() : CostantiPdD.SERVIZIO_APPLICATIVO_ANONIMO ));
  666.                 return esitoNew;
  667.             }
  668.             if(verificaAutorizzazioneRuoli && !authRuoli) {
  669.                 EsitoAutorizzazionePortaDelegata esitoNew = esito;
  670.                 if(idSAToken!=null){
  671.                     esito.setErroreIntegrazione(IntegrationFunctionError.AUTHORIZATION_MISSING_ROLE, ErroriIntegrazione.ERRORE_404_AUTORIZZAZIONE_FALLITA_SA.
  672.                             getErrore404_AutorizzazioneFallitaServizioApplicativo(idSAToken.getNome()));
  673.                 }
  674.                 else{
  675.                     esito.setErroreIntegrazione(IntegrationFunctionError.AUTHORIZATION_MISSING_ROLE, ErroriIntegrazione.ERRORE_404_AUTORIZZAZIONE_FALLITA_SA_ANONIMO.
  676.                             getErrore404_AutorizzazioneFallitaServizioApplicativoAnonimo());
  677.                 }
  678.                 esito.setAutorizzato(false);
  679.                 if(detailsBufferRuoli.length()>0) {
  680.                     esito.setDetails(detailsBufferRuoli.toString());
  681.                 }
  682.                 return esitoNew;
  683.             }
  684.         }
  685.        
  686.        
  687.         // Verifica Token Scopes
  688.        
  689.         AutorizzazioneScope authScope = null;
  690.         if(datiInvocazione.getPd()!=null) {
  691.             authScope = datiInvocazione.getPd().getScope();
  692.         }
  693.         if(authScope!=null && authScope.sizeScopeList()>0) {
  694.             EsitoAutorizzazionePortaDelegata esitoNew = (EsitoAutorizzazionePortaDelegata) autorizzazioneScope(authScope, esito, pddContext, datiInvocazione);
  695.             if(esitoNew.isAutorizzato()==false) {
  696.                 esitoNew.setErroreIntegrazione(IntegrationFunctionError.AUTHORIZATION_MISSING_SCOPE, ErroriIntegrazione.ERRORE_445_TOKEN_AUTORIZZAZIONE_FALLITA.getErroreIntegrazione());
  697.                 return esitoNew;
  698.             }
  699.         }
  700.        
  701.         // Verifica Token Options
  702.        
  703.         if(datiInvocazione.getPd()!=null && datiInvocazione.getPd().getGestioneToken()!=null
  704.                 && datiInvocazione.getPd().getGestioneToken().getOptions()!=null) {
  705.             EsitoAutorizzazionePortaDelegata esitoNew =
  706.                     (EsitoAutorizzazionePortaDelegata) autorizzazioneTokenOptions(datiInvocazione.getPd().getGestioneToken().getOptions(),
  707.                             esito, pddContext, datiInvocazione,
  708.                             log, msg);
  709.             if(esitoNew.isAutorizzato()==false) {
  710.                 esitoNew.setErroreIntegrazione(IntegrationFunctionError.AUTHORIZATION_TOKEN_DENY, ErroriIntegrazione.ERRORE_445_TOKEN_AUTORIZZAZIONE_FALLITA.getErroreIntegrazione());
  711.                 return esitoNew;
  712.             }
  713.         }
  714.        
  715.         return esito;
  716.        
  717.     }
  718.    
  719.     private static EsitoAutorizzazionePortaDelegata _verificaAutorizzazionePortaDelegata(String tipoAutorizzazione, DatiInvocazionePortaDelegata datiInvocazione,
  720.           PdDContext pddContext,IProtocolFactory<?> protocolFactory, OpenSPCoop2Message msg) throws Exception{
  721.        
  722.         IAutorizzazionePortaDelegata auth = newInstanceAuthPortaDelegata(tipoAutorizzazione, pddContext, protocolFactory);
  723.        
  724.         try {
  725.             if(GestoreAutorizzazione.cacheAutorizzazione==null || !auth.saveAuthorizationResultInCache()){
  726.                 return auth.process(datiInvocazione);
  727.             }
  728.             else{
  729.                 String keyCache = buildCacheKey(true, tipoAutorizzazione, datiInvocazione.getKeyCache(), auth.getSuffixKeyAuthorizationResultInCache(datiInvocazione) );
  730.    
  731.                 // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  732.                 org.openspcoop2.utils.cache.CacheResponse response =
  733.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreAutorizzazione.cacheAutorizzazione.get(keyCache);
  734.                 if(response != null){
  735.                     if(response.getObject()!=null){
  736.                         GestoreAutorizzazione.logger.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) in cache.");
  737.                         EsitoAutorizzazionePortaDelegata esito = (EsitoAutorizzazionePortaDelegata) response.getObject();
  738.                         esito.setEsitoPresenteInCache(true);
  739.                         return esito;
  740.                     }else if(response.getException()!=null){
  741.                         GestoreAutorizzazione.logger.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) in cache.");
  742.                         throw (Exception) response.getException();
  743.                     }else{
  744.                         GestoreAutorizzazione.logger.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  745.                     }
  746.                 }
  747.            
  748.                 String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  749.                 //synchronized (GestoreAutorizzazione.semaphoreAutorizzazionePD) {
  750.                 org.openspcoop2.utils.Semaphore lockAutorizzazionePD = getLockAutorizzazionePD(tipoAutorizzazione);
  751.                 SemaphoreLock lock = lockAutorizzazionePD.acquire("verificaAutorizzazionePortaDelegata", idTransazione);
  752.                 try {
  753.                    
  754.                     response =
  755.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreAutorizzazione.cacheAutorizzazione.get(keyCache);
  756.                     if(response != null){
  757.                         if(response.getObject()!=null){
  758.                             GestoreAutorizzazione.logger.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) in cache.");
  759.                             EsitoAutorizzazionePortaDelegata esito = (EsitoAutorizzazionePortaDelegata) response.getObject();
  760.                             esito.setEsitoPresenteInCache(true);
  761.                             return esito;
  762.                         }else if(response.getException()!=null){
  763.                             GestoreAutorizzazione.logger.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) in cache.");
  764.                             throw (Exception) response.getException();
  765.                         }else{
  766.                             GestoreAutorizzazione.logger.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  767.                         }
  768.                     }
  769.    
  770.                     // Effettuo la query
  771.                     GestoreAutorizzazione.logger.debug("oggetto con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) ricerco nella configurazione...");
  772.                     EsitoAutorizzazionePortaDelegata esito = auth.process(datiInvocazione);
  773.    
  774.                     // Aggiungo la risposta in cache (se esiste una cache)  
  775.                     // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  776.                     // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  777.                     // - impostare il noCache a true
  778.                     if(esito!=null){
  779.                         if(!esito.isNoCache()){
  780.                             GestoreAutorizzazione.logger.info("Aggiungo oggetto ["+keyCache+"] in cache");
  781.                             try{    
  782.                                 org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  783.                                 responseCache.setObject(esito);
  784.                                 GestoreAutorizzazione.cacheAutorizzazione.put(keyCache,responseCache);
  785.                             }catch(UtilsException e){
  786.                                 GestoreAutorizzazione.logger.error("Errore durante l'inserimento in cache ["+keyCache+"]: "+e.getMessage());
  787.                             }
  788.                         }
  789.                         return esito;
  790.                     }else{
  791.                         throw new AutorizzazioneException("Metodo (GestoreAutorizzazione.autorizzazionePortaDelegata.process) ha ritornato un valore di esito null");
  792.                     }
  793.                 }finally {
  794.                     lockAutorizzazionePD.release(lock, "verificaAutorizzazionePortaDelegata", idTransazione);
  795.                 }
  796.             }
  797.         }finally {
  798.             if(msg!=null) {
  799.                 auth.cleanPostAuth(msg);
  800.             }
  801.         }
  802.     }
  803.    
  804.     public static EsitoAutorizzazionePortaApplicativa verificaAutorizzazionePortaApplicativa(String tipoAutorizzazione, DatiInvocazionePortaApplicativa datiInvocazione,
  805.             PdDContext pddContext,IProtocolFactory<?> protocolFactory, OpenSPCoop2Message msg, Logger log) throws Exception{
  806.          
  807.         checkDatiPortaApplicativa(datiInvocazione);
  808.    
  809.         EsitoAutorizzazionePortaApplicativa esito = _verificaAutorizzazionePortaApplicativa(tipoAutorizzazione, datiInvocazione, pddContext, protocolFactory, msg);
  810.         if(esito.isAutorizzato()==false) {
  811.             return esito;
  812.         }
  813.        
  814.                
  815.         boolean skipProfiloModi = false;
  816.         if(protocolFactory!=null && Costanti.MODIPA_PROTOCOL_NAME.equals(protocolFactory.getProtocol())) {
  817.             skipProfiloModi=true;
  818.         }
  819.        
  820.         if(!skipProfiloModi) {
  821.        
  822.             // Verifiche Richieste
  823.            
  824.             boolean verificaAutorizzazioneRichiedenti = false;
  825.             boolean verificaAutorizzazioneRuoli = false;
  826.             if(datiInvocazione.getPa()!=null) {
  827.                 if(datiInvocazione.getPa().getAutorizzazioneToken()!=null) {
  828.                     if(StatoFunzionalita.ABILITATO.equals(datiInvocazione.getPa().getAutorizzazioneToken().getAutorizzazioneApplicativi())){
  829.                         verificaAutorizzazioneRichiedenti=true;
  830.                     }
  831.                     if(StatoFunzionalita.ABILITATO.equals(datiInvocazione.getPa().getAutorizzazioneToken().getAutorizzazioneRuoli())){
  832.                         verificaAutorizzazioneRuoli = true;
  833.                     }
  834.                 }
  835.             }
  836.             else if(datiInvocazione.getPd()!=null){
  837.                 if(datiInvocazione.getPd().getAutorizzazioneToken()!=null) {
  838.                     if(StatoFunzionalita.ABILITATO.equals(datiInvocazione.getPd().getAutorizzazioneToken().getAutorizzazioneApplicativi())){
  839.                         verificaAutorizzazioneRichiedenti=true;
  840.                     }
  841.                     if(StatoFunzionalita.ABILITATO.equals(datiInvocazione.getPd().getAutorizzazioneToken().getAutorizzazioneRuoli())){
  842.                         verificaAutorizzazioneRuoli = true;
  843.                     }
  844.                 }
  845.             }
  846.        

  847.             // Verifica Token Richiedenti
  848.        
  849.             IDServizioApplicativo idSAToken = null;
  850.             if(pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_APPLICATIVO_TOKEN)) {
  851.                 idSAToken = (IDServizioApplicativo) pddContext.getObject(org.openspcoop2.core.constants.Costanti.ID_APPLICATIVO_TOKEN);
  852.             }
  853.            
  854.             boolean authRichiedenti = true;
  855.             if(datiInvocazione.getPa()!=null) {
  856.                 if(verificaAutorizzazioneRichiedenti){
  857.                     authRichiedenti = false;
  858.                     if( idSAToken!=null &&
  859.                             datiInvocazione.getPa().getAutorizzazioneToken().getServiziApplicativi()!=null &&
  860.                             datiInvocazione.getPa().getAutorizzazioneToken().getServiziApplicativi().sizeServizioApplicativoList()>0){
  861.                         for (PortaApplicativaAutorizzazioneServizioApplicativo sa : datiInvocazione.getPa().getAutorizzazioneToken().getServiziApplicativi().getServizioApplicativoList()) {
  862.                             if(idSAToken.getNome().equals(sa.getNome()) &&
  863.                                     idSAToken.getIdSoggettoProprietario().getTipo().equals(sa.getTipoSoggettoProprietario()) &&
  864.                                     idSAToken.getIdSoggettoProprietario().getNome().equals(sa.getNomeSoggettoProprietario())) {
  865.                                 authRichiedenti = true;
  866.                                 break;
  867.                             }
  868.                         }
  869.                     }
  870.                 }
  871.             }
  872.             else if(datiInvocazione.getPd()!=null){
  873.                 if(verificaAutorizzazioneRichiedenti){
  874.                     authRichiedenti = false;
  875.                     if( idSAToken!=null &&
  876.                             datiInvocazione.getPd().getAutorizzazioneToken().getServiziApplicativi()!=null &&
  877.                             datiInvocazione.getPd().getAutorizzazioneToken().getServiziApplicativi().sizeServizioApplicativoList()>0){
  878.                         for (PortaDelegataServizioApplicativo sa : datiInvocazione.getPd().getAutorizzazioneToken().getServiziApplicativi().getServizioApplicativoList()) {
  879.                             if(idSAToken.getNome().equals(sa.getNome())) {
  880.                                 authRichiedenti = true;
  881.                                 break;
  882.                             }
  883.                         }
  884.                     }
  885.                 }
  886.             }
  887.        
  888.        
  889.             // Verifica Token Roles
  890.        
  891.             boolean authRuoli = true;
  892.             StringBuilder detailsBufferRuoli = null;
  893.             if(datiInvocazione.getPa()!=null) {
  894.                 if(verificaAutorizzazioneRuoli){
  895.                     boolean checkRuoloRegistro = false;
  896.                     boolean checkRuoloEsterno = false;
  897.                     if( datiInvocazione.getPa().getAutorizzazioneToken().getTipologiaRuoli()==null ||
  898.                         RuoloTipologia.QUALSIASI.equals(datiInvocazione.getPa().getAutorizzazioneToken().getTipologiaRuoli())){
  899.                         checkRuoloRegistro = true;
  900.                         checkRuoloEsterno = true;
  901.                     }
  902.                     else if( RuoloTipologia.INTERNO.equals(datiInvocazione.getPa().getAutorizzazioneToken().getTipologiaRuoli())){
  903.                         checkRuoloRegistro = true;
  904.                     }
  905.                     else if( RuoloTipologia.ESTERNO.equals(datiInvocazione.getPa().getAutorizzazioneToken().getTipologiaRuoli())){
  906.                         checkRuoloEsterno = true;
  907.                     }
  908.                     detailsBufferRuoli = new StringBuilder();
  909.                     ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(datiInvocazione.getState());
  910.                     ServizioApplicativo sa = null;
  911.                     if(idSAToken!=null) {
  912.                         sa = configurazionePdDManager.getServizioApplicativo(idSAToken, datiInvocazione.getRequestInfo());
  913.                     }
  914.                     authRuoli = configurazionePdDManager.
  915.                             autorizzazioneTokenRoles(datiInvocazione.getPa(), sa,
  916.                                     datiInvocazione.getInfoConnettoreIngresso(),
  917.                                     pddContext, datiInvocazione.getRequestInfo(),
  918.                                     checkRuoloRegistro, checkRuoloEsterno,
  919.                                     detailsBufferRuoli);
  920.                 }
  921.             }
  922.             else if(datiInvocazione.getPd()!=null){
  923.                 if(verificaAutorizzazioneRuoli){
  924.                     boolean checkRuoloRegistro = false;
  925.                     boolean checkRuoloEsterno = false;
  926.                     if( datiInvocazione.getPd().getAutorizzazioneToken().getTipologiaRuoli()==null ||
  927.                         RuoloTipologia.QUALSIASI.equals(datiInvocazione.getPd().getAutorizzazioneToken().getTipologiaRuoli())){
  928.                         checkRuoloRegistro = true;
  929.                         checkRuoloEsterno = true;
  930.                     }
  931.                     else if( RuoloTipologia.INTERNO.equals(datiInvocazione.getPd().getAutorizzazioneToken().getTipologiaRuoli())){
  932.                         checkRuoloRegistro = true;
  933.                     }
  934.                     else if( RuoloTipologia.ESTERNO.equals(datiInvocazione.getPd().getAutorizzazioneToken().getTipologiaRuoli())){
  935.                         checkRuoloEsterno = true;
  936.                     }
  937.                     detailsBufferRuoli = new StringBuilder();
  938.                     ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(datiInvocazione.getState());
  939.                     ServizioApplicativo sa = null;
  940.                     if(idSAToken!=null) {
  941.                         sa = configurazionePdDManager.getServizioApplicativo(idSAToken, datiInvocazione.getRequestInfo());
  942.                     }
  943.                     authRuoli = configurazionePdDManager.
  944.                             autorizzazioneTokenRoles(datiInvocazione.getPd(), sa,
  945.                                     datiInvocazione.getInfoConnettoreIngresso(),
  946.                                     pddContext, datiInvocazione.getRequestInfo(),
  947.                                     checkRuoloRegistro, checkRuoloEsterno,
  948.                                     detailsBufferRuoli);
  949.                 }
  950.             }
  951.            
  952.            
  953.             // Esiti Verifiche Richieste
  954.            
  955.             if(verificaAutorizzazioneRichiedenti && verificaAutorizzazioneRuoli) {
  956.                 // se una delle due autorizzazione e' andata a buon fine devo autorizzare
  957.                 if(!authRichiedenti && !authRuoli) {
  958.                     // uso eccezione per ruolo che e' più completa come messaggistica
  959.                     EsitoAutorizzazionePortaApplicativa esitoNew = esito;
  960.                     String errore = "";
  961.                     esitoNew.setErroreCooperazione(IntegrationFunctionError.AUTHORIZATION_MISSING_ROLE, ErroriCooperazione.AUTORIZZAZIONE_FALLITA.getErroreAutorizzazione(errore, CodiceErroreCooperazione.SICUREZZA_AUTORIZZAZIONE_FALLITA));
  962.                     esitoNew.setAutorizzato(false);
  963.                     if(detailsBufferRuoli.length()>0) {
  964.                         esitoNew.setDetails(detailsBufferRuoli.toString());
  965.                     }
  966.                     return esitoNew;
  967.                 }
  968.             }
  969.             else {
  970.                 if(verificaAutorizzazioneRichiedenti && !authRichiedenti) {
  971.                     EsitoAutorizzazionePortaApplicativa esitoNew = esito;
  972.                     esitoNew.setAutorizzato(false);
  973.                     IDServizio idServizio = datiInvocazione.getIdServizio();
  974.                     String errore = org.openspcoop2.pdd.core.autorizzazione.pa.AbstractAutorizzazioneBase.getErrorString(idSAToken, null, idServizio);
  975.                     if(esitoNew.getDetails()!=null){
  976.                         errore = errore + " ("+esitoNew.getDetails()+")";
  977.                     }
  978.                     esitoNew.setErroreCooperazione(IntegrationFunctionError.AUTHORIZATION_DENY, ErroriCooperazione.AUTORIZZAZIONE_FALLITA.getErroreAutorizzazione(errore, CodiceErroreCooperazione.SICUREZZA_AUTORIZZAZIONE_FALLITA));
  979.                     return esitoNew;
  980.                 }
  981.                 if(verificaAutorizzazioneRuoli && !authRuoli) {
  982.                     EsitoAutorizzazionePortaApplicativa esitoNew = esito;
  983.                     String errore = "";
  984.                     esitoNew.setErroreCooperazione(IntegrationFunctionError.AUTHORIZATION_MISSING_ROLE, ErroriCooperazione.AUTORIZZAZIONE_FALLITA.getErroreAutorizzazione(errore, CodiceErroreCooperazione.SICUREZZA_AUTORIZZAZIONE_FALLITA));
  985.                     esitoNew.setAutorizzato(false);
  986.                     if(detailsBufferRuoli.length()>0) {
  987.                         esitoNew.setDetails(detailsBufferRuoli.toString());
  988.                     }
  989.                     return esitoNew;
  990.                 }
  991.             }
  992.         }
  993.        
  994.         // Verifica Token Scopes
  995.        
  996.         AutorizzazioneScope authScope = null;
  997.         if(datiInvocazione.getPa()!=null) {
  998.             authScope = datiInvocazione.getPa().getScope();
  999.         }
  1000.         else if(datiInvocazione.getPd()!=null){
  1001.             authScope = datiInvocazione.getPd().getScope();
  1002.         }
  1003.         if(authScope!=null && authScope.sizeScopeList()>0) {
  1004.             EsitoAutorizzazionePortaApplicativa esitoNew = (EsitoAutorizzazionePortaApplicativa) autorizzazioneScope(authScope, esito, pddContext, datiInvocazione);
  1005.             if(!esitoNew.isAutorizzato()) {
  1006.                 esitoNew.setErroreCooperazione(IntegrationFunctionError.AUTHORIZATION_MISSING_SCOPE, ErroriCooperazione.TOKEN_AUTORIZZAZIONE_FALLITA.getErroreCooperazione());
  1007.                 return esitoNew;
  1008.             }
  1009.         }
  1010.        
  1011.        
  1012.         // Verifica Token Options
  1013.        
  1014.         String tokenOptions = null;
  1015.         if(datiInvocazione.getPa()!=null) {
  1016.             if(datiInvocazione.getPa().getGestioneToken()!=null) {
  1017.                 tokenOptions = datiInvocazione.getPa().getGestioneToken().getOptions();
  1018.             }
  1019.         }
  1020.         else if(datiInvocazione.getPd()!=null){
  1021.             if(datiInvocazione.getPd().getGestioneToken()!=null) {
  1022.                 tokenOptions = datiInvocazione.getPd().getGestioneToken().getOptions();
  1023.             }
  1024.         }
  1025.        
  1026.         if(tokenOptions!=null) {
  1027.             EsitoAutorizzazionePortaApplicativa esitoNew =
  1028.                     (EsitoAutorizzazionePortaApplicativa) autorizzazioneTokenOptions(tokenOptions,
  1029.                             esito, pddContext, datiInvocazione,
  1030.                             log, msg);
  1031.             if(!esitoNew.isAutorizzato()) {
  1032.                 esitoNew.setErroreCooperazione(IntegrationFunctionError.AUTHORIZATION_TOKEN_DENY, ErroriCooperazione.TOKEN_AUTORIZZAZIONE_FALLITA.getErroreCooperazione());
  1033.                 return esitoNew;
  1034.             }
  1035.         }
  1036.        
  1037.         return esito;
  1038.        
  1039.     }
  1040.     private static EsitoAutorizzazionePortaApplicativa _verificaAutorizzazionePortaApplicativa(String tipoAutorizzazione, DatiInvocazionePortaApplicativa datiInvocazione,
  1041.             PdDContext pddContext,IProtocolFactory<?> protocolFactory, OpenSPCoop2Message msg) throws Exception{
  1042.        
  1043.         IAutorizzazionePortaApplicativa auth = newInstanceAuthPortaApplicativa(tipoAutorizzazione, pddContext, protocolFactory);
  1044.        
  1045.         try {
  1046.             if(GestoreAutorizzazione.cacheAutorizzazione==null || !auth.saveAuthorizationResultInCache()){
  1047.                 return auth.process(datiInvocazione);
  1048.             }
  1049.             else{
  1050.                 String keyCache = buildCacheKey(false, tipoAutorizzazione, datiInvocazione.getKeyCache(), auth.getSuffixKeyAuthorizationResultInCache(datiInvocazione));
  1051.    
  1052.                 // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  1053.                 org.openspcoop2.utils.cache.CacheResponse response =
  1054.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreAutorizzazione.cacheAutorizzazione.get(keyCache);
  1055.                 if(response != null){
  1056.                     if(response.getObject()!=null){
  1057.                         GestoreAutorizzazione.logger.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) in cache.");
  1058.                         EsitoAutorizzazionePortaApplicativa esito = (EsitoAutorizzazionePortaApplicativa) response.getObject();
  1059.                         esito.setEsitoPresenteInCache(true);
  1060.                         return esito;
  1061.                     }else if(response.getException()!=null){
  1062.                         GestoreAutorizzazione.logger.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) in cache.");
  1063.                         throw (Exception) response.getException();
  1064.                     }else{
  1065.                         GestoreAutorizzazione.logger.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  1066.                     }
  1067.                 }
  1068.                
  1069.                 String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  1070.                 //synchronized (GestoreAutorizzazione.semaphoreAutorizzazionePA) {
  1071.                 org.openspcoop2.utils.Semaphore lockAutorizzazionePA = getLockAutorizzazionePA(tipoAutorizzazione);
  1072.                 SemaphoreLock lock = lockAutorizzazionePA.acquire("verificaAutorizzazionePortaApplicativa", idTransazione);
  1073.                 try {
  1074.                    
  1075.                     response =
  1076.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreAutorizzazione.cacheAutorizzazione.get(keyCache);
  1077.                     if(response != null){
  1078.                         if(response.getObject()!=null){
  1079.                             GestoreAutorizzazione.logger.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) in cache.");
  1080.                             EsitoAutorizzazionePortaApplicativa esito = (EsitoAutorizzazionePortaApplicativa) response.getObject();
  1081.                             esito.setEsitoPresenteInCache(true);
  1082.                             return esito;
  1083.                         }else if(response.getException()!=null){
  1084.                             GestoreAutorizzazione.logger.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) in cache.");
  1085.                             throw (Exception) response.getException();
  1086.                         }else{
  1087.                             GestoreAutorizzazione.logger.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  1088.                         }
  1089.                     }
  1090.    
  1091.                     // Effettuo la query
  1092.                     GestoreAutorizzazione.logger.debug("oggetto con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) ricerco nella configurazione...");
  1093.                     EsitoAutorizzazionePortaApplicativa esito = auth.process(datiInvocazione);
  1094.    
  1095.                     // Aggiungo la risposta in cache (se esiste una cache)  
  1096.                     // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  1097.                     // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  1098.                     // - impostare il noCache a true
  1099.                     if(esito!=null){
  1100.                         if(!esito.isNoCache()){
  1101.                             GestoreAutorizzazione.logger.info("Aggiungo oggetto ["+keyCache+"] in cache");
  1102.                             try{    
  1103.                                 org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1104.                                 responseCache.setObject(esito);
  1105.                                 GestoreAutorizzazione.cacheAutorizzazione.put(keyCache,responseCache);
  1106.                             }catch(UtilsException e){
  1107.                                 GestoreAutorizzazione.logger.error("Errore durante l'inserimento in cache ["+keyCache+"]: "+e.getMessage());
  1108.                             }
  1109.                         }
  1110.                         return esito;
  1111.                     }else{
  1112.                         throw new AutorizzazioneException("Metodo (GestoreAutorizzazione.autorizzazionePortaApplicativa.process) ha ritornato un valore di esito null");
  1113.                     }
  1114.                 }finally {
  1115.                     lockAutorizzazionePA.release(lock, "verificaAutorizzazionePortaApplicativa", idTransazione);
  1116.                 }
  1117.             }
  1118.         }finally {
  1119.             if(msg!=null) {
  1120.                 auth.cleanPostAuth(msg);
  1121.             }
  1122.         }
  1123.     }
  1124.    
  1125.     private static void checkDatiPortaDelegata(DatiInvocazionePortaDelegata datiInvocazione) throws AutorizzazioneException{
  1126.        
  1127.         IDServizio idServizio = datiInvocazione.getIdServizio();
  1128.         if(idServizio==null)
  1129.             throw new AutorizzazioneException("(Parametri) IDServizio non definito");
  1130.         if(idServizio.getTipo()==null || idServizio.getNome()==null || idServizio.getVersione()==null)
  1131.             throw new AutorizzazioneException("(Parametri) Servizio non definito");
  1132.         if(idServizio.getSoggettoErogatore()==null || idServizio.getSoggettoErogatore().getTipo()==null || idServizio.getSoggettoErogatore().getNome()==null)
  1133.             throw new AutorizzazioneException("(Parametri) Soggetto erogatore non definito");
  1134.        
  1135.         IDPortaDelegata idPD = datiInvocazione.getIdPD();
  1136.         if(idPD==null)
  1137.             throw new AutorizzazioneException("(Parametri) IDPortaDelegata non definito");
  1138.         if(idPD.getNome()==null)
  1139.             throw new AutorizzazioneException("(Parametri) IDPortaDelegata.nome non definito");
  1140.        
  1141.         PortaDelegata pd = datiInvocazione.getPd();
  1142.         if(pd==null)
  1143.             throw new AutorizzazioneException("(Parametri) PortaDelegata non definito");
  1144.        
  1145.         IDServizioApplicativo idSA = datiInvocazione.getIdServizioApplicativo();
  1146.         if(idSA==null)
  1147.             throw new AutorizzazioneException("(Parametri) IDServizioApplicativo non definito");
  1148.         if(idSA.getNome()==null)
  1149.             throw new AutorizzazioneException("(Parametri) IDServizioApplicativo.nome non definito");
  1150.         IDSoggetto idSoggettoProprietario = idSA.getIdSoggettoProprietario();
  1151.         if(idSoggettoProprietario==null || idSoggettoProprietario.getTipo()==null || idSoggettoProprietario.getNome()==null)
  1152.             throw new AutorizzazioneException("(Parametri) IDServizioApplicativo.Soggetto non definito");
  1153.        
  1154.     }
  1155.    
  1156.     private static void checkDatiPortaApplicativa(DatiInvocazionePortaApplicativa datiInvocazione) throws AutorizzazioneException{
  1157.        
  1158.         IDServizio idServizio = datiInvocazione.getIdServizio();
  1159.         if(idServizio==null)
  1160.             throw new AutorizzazioneException("(Parametri) IDServizio non definito");
  1161.         if(idServizio.getTipo()==null || idServizio.getNome()==null || idServizio.getVersione()==null)
  1162.             throw new AutorizzazioneException("(Parametri) Servizio non definito");
  1163.         if(idServizio.getSoggettoErogatore()==null || idServizio.getSoggettoErogatore().getTipo()==null || idServizio.getSoggettoErogatore().getNome()==null)
  1164.             throw new AutorizzazioneException("(Parametri) Soggetto erogatore non definito");

  1165.         // Dipende dal ruolo della Busta, se c'e' la porta applicativa o delegata
  1166. //      IDPortaApplicativaByNome idPA = datiInvocazione.getIdPA();
  1167. //      if(idPA==null)
  1168. //          throw new AutorizzazioneException("(Parametri) IDPortaApplicativaByNome non definito");
  1169. //      if(idPA.getNome()==null)
  1170. //          throw new AutorizzazioneException("(Parametri) IDPortaApplicativaByNome.nome non definito");
  1171. //      IDSoggetto idSoggettoProprietarioPA = idPA.getSoggetto();
  1172. //      if(idSoggettoProprietarioPA==null || idSoggettoProprietarioPA.getTipo()==null || idSoggettoProprietarioPA.getNome()==null)
  1173. //          throw new AutorizzazioneException("(Parametri) IDPortaApplicativaByNome.Soggetto non definito");
  1174. //      
  1175. //      PortaApplicativa pa = datiInvocazione.getPa();
  1176. //      if(pa==null)
  1177. //          throw new AutorizzazioneException("(Parametri) PortaApplicativa non definito");
  1178.        
  1179.         // In caso di autenticazione dei soggetti abilitata, il parametro soggetto fruitore può non essere definito
  1180. //      IDSoggetto idSoggettoFruitore = datiInvocazione.getIdSoggettoFruitore();
  1181. //      if(idSoggettoFruitore==null || idSoggettoFruitore.getTipo()==null || idSoggettoFruitore.getNome()==null)
  1182. //          throw new AutorizzazioneException("(Parametri) IDSoggettoFruitore non definito");
  1183.        
  1184.         RuoloBusta ruolo = datiInvocazione.getRuoloBusta();
  1185.         if(ruolo==null)
  1186.             throw new AutorizzazioneException("(Parametri) RuoloBusta non definito");
  1187.     }
  1188.    
  1189.     private static String buildCacheKey(boolean portaDelegata, String tipoAutorizzazione, String keyCache, String suffixKeyCache) throws AutorizzazioneException{
  1190.         StringBuilder bf = new StringBuilder();
  1191.        
  1192.         if(portaDelegata)
  1193.             bf.append("PD ");
  1194.         else
  1195.             bf.append("PA ");
  1196.        
  1197.         bf.append(" Auth:").append(tipoAutorizzazione).append(" ");
  1198.        
  1199.         bf.append(keyCache);
  1200.        
  1201.         if(suffixKeyCache!=null && !"".equals(suffixKeyCache)){
  1202.             bf.append(" ");
  1203.             bf.append(suffixKeyCache);
  1204.         }
  1205.        
  1206.         return bf.toString();
  1207.     }
  1208.    
  1209.     private static IAutorizzazionePortaDelegata newInstanceAuthPortaDelegata(String tipoAutorizzazione,PdDContext pddContext, IProtocolFactory<?> protocolFactory) throws AutorizzazioneException{
  1210.         IAutorizzazionePortaDelegata auth = null;
  1211.         try{
  1212.             PddPluginLoader pluginLoader = PddPluginLoader.getInstance();
  1213.             auth = (IAutorizzazionePortaDelegata) pluginLoader.newAutorizzazionePortaDelegata(tipoAutorizzazione);
  1214.         }catch(Exception e){
  1215.             throw new AutorizzazioneException(e.getMessage(),e); // descrizione errore già corretta
  1216.         }
  1217.         String classType = null;
  1218.         try{
  1219.             classType = auth.getClass().getName();
  1220.             AbstractCore.init(auth, pddContext, protocolFactory);
  1221.             return auth;
  1222.         }catch(Exception e){
  1223.             throw new AutorizzazioneException("Riscontrato errore durante l'inizializzazione della classe ["+classType+
  1224.                     "] che definisce l'autorizzazione della fruizione: "+e.getMessage(),e);
  1225.         }
  1226.     }
  1227.    
  1228.     private static IAutorizzazionePortaApplicativa newInstanceAuthPortaApplicativa(String tipoAutorizzazione,PdDContext pddContext, IProtocolFactory<?> protocolFactory) throws AutorizzazioneException{
  1229.         IAutorizzazionePortaApplicativa auth = null;
  1230.         try{
  1231.             PddPluginLoader pluginLoader = PddPluginLoader.getInstance();
  1232.             auth = (IAutorizzazionePortaApplicativa) pluginLoader.newAutorizzazionePortaApplicativa(tipoAutorizzazione);
  1233.         }catch(Exception e){
  1234.             throw new AutorizzazioneException(e.getMessage(),e); // descrizione errore già corretta
  1235.         }
  1236.         String classType = null;
  1237.         try{
  1238.             classType = auth.getClass().getName();
  1239.             AbstractCore.init(auth, pddContext, protocolFactory);
  1240.             return auth;
  1241.         }catch(Exception e){
  1242.             throw new AutorizzazioneException("Riscontrato errore durante l'inizializzazione della classe ["+classType+
  1243.                     "] che definisce l'autorizzazione della erogazione: "+e.getMessage(),e);
  1244.         }
  1245.     }
  1246.    
  1247.     private static EsitoAutorizzazione autorizzazioneScope(AutorizzazioneScope authScope, EsitoAutorizzazione esito,
  1248.             PdDContext pddContext, AbstractDatiInvocazione datiInvocazione) throws Exception {
  1249.         if(authScope!=null && authScope.sizeScopeList()>0) {
  1250.            
  1251.             InformazioniToken informazioniTokenNormalizzate = null;
  1252.             Object oInformazioniTokenNormalizzate = pddContext.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_INFORMAZIONI_NORMALIZZATE);
  1253.             if(oInformazioniTokenNormalizzate!=null) {
  1254.                 informazioniTokenNormalizzate = (InformazioniToken) oInformazioniTokenNormalizzate;
  1255.             }
  1256.             boolean autorizzato = true;
  1257.             String errorMessage = null;
  1258.             if(informazioniTokenNormalizzate==null || informazioniTokenNormalizzate.getScopes()==null || informazioniTokenNormalizzate.getScopes().size()<=0) {
  1259.                 errorMessage = "Token without scopes";
  1260.                 autorizzato = false;
  1261.             }
  1262.             else {
  1263.                 boolean foundAlmostOne = false;
  1264.                 for (Scope scope : authScope.getScopeList()) {
  1265.                     org.openspcoop2.core.registry.Scope scopeOp2Registry = RegistroServiziManager.getInstance(datiInvocazione.getState()).getScope(scope.getNome(),null,datiInvocazione.getRequestInfo());
  1266.                     String nomeScope = scopeOp2Registry.getNome();
  1267.                     if(scopeOp2Registry.getNomeEsterno()!=null && !"".equals(scopeOp2Registry.getNomeEsterno())) {
  1268.                         nomeScope = scopeOp2Registry.getNomeEsterno();
  1269.                     }
  1270.                     if(informazioniTokenNormalizzate.getScopes().contains(nomeScope)==false) {
  1271.                         if(ScopeTipoMatch.ALL.equals(authScope.getMatch())) {
  1272.                             autorizzato = false;
  1273.                             errorMessage = "Scope '"+nomeScope+"' not found";
  1274.                             break;
  1275.                         }
  1276.                     }
  1277.                     else {
  1278.                         foundAlmostOne = true;
  1279.                     }
  1280.                 }
  1281.                 if(!foundAlmostOne) {
  1282.                     autorizzato = false;
  1283.                     errorMessage = "Scopes not found";
  1284.                 }
  1285.             }
  1286.            
  1287.             if(!autorizzato) {
  1288.            
  1289.                 String realm = "OpenSPCoop";
  1290.                 Object oRealm = pddContext.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_REALM);
  1291.                 if(oRealm!=null) {
  1292.                     realm = (String) oRealm;
  1293.                 }
  1294.                
  1295.                 boolean emptyMessage = false;
  1296.                 Object oEmptyMessage = pddContext.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_MESSAGE_ERROR_BODY_EMPTY);
  1297.                 if(oEmptyMessage!=null) {
  1298.                     emptyMessage = (Boolean) oEmptyMessage;
  1299.                 }
  1300.                
  1301.                 boolean genericMessage = false;
  1302.                 Object oGenericMessage = pddContext.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_MESSAGE_ERROR_GENERIC_MESSAGE);
  1303.                 if(oGenericMessage!=null) {
  1304.                     genericMessage = (Boolean) oGenericMessage;
  1305.                 }
  1306.                
  1307.                 if(genericMessage) {
  1308.                     esito.setDetails(errorMessage);
  1309.                 }
  1310.                
  1311.                 String [] scopes = new String[authScope.sizeScopeList()];
  1312.                 for (int i = 0; i < authScope.sizeScopeList(); i++) {
  1313.                     org.openspcoop2.core.registry.Scope scopeOp2Registry = RegistroServiziManager.getInstance(datiInvocazione.getState()).getScope(authScope.getScope(i).getNome(),null,datiInvocazione.getRequestInfo());
  1314.                     String nomeScope = scopeOp2Registry.getNome();
  1315.                     if(scopeOp2Registry.getNomeEsterno()!=null) {
  1316.                         nomeScope = scopeOp2Registry.getNomeEsterno();
  1317.                     }
  1318.                     scopes[i] = nomeScope;
  1319.                 }
  1320.                
  1321.                 esito.setAutorizzato(false);
  1322.                 if(emptyMessage) {
  1323.                     esito.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.insufficient_scope, realm, genericMessage, errorMessage, scopes));
  1324.                 }
  1325.                 else {
  1326.                     esito.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.insufficient_scope, realm, genericMessage, errorMessage, scopes));
  1327.                 }
  1328.                
  1329.             }
  1330.            
  1331.            
  1332.         }
  1333.        
  1334.         return esito;
  1335.     }

  1336.     private static final String ATTRIBUTE_AUTHORITY_PREFIX = "aa.";
  1337.     private static final String ATTRIBUTE_PREFIX = "attribute.";
  1338.     private static EsitoAutorizzazione autorizzazioneTokenOptions(String tokenOptions, EsitoAutorizzazione esito,
  1339.             PdDContext pddContext, AbstractDatiInvocazione datiInvocazione,
  1340.             Logger log, OpenSPCoop2Message message) throws Exception {
  1341.        
  1342.         boolean autorizzato = true;
  1343.         String errorMessage = null;
  1344.         if(tokenOptions!=null) {
  1345.            
  1346.             /**Properties properties = PropertiesUtilities.convertTextToProperties(tokenOptions);*/
  1347.             // Fix per preservare l'ordine di configurazione
  1348.             SortedMap<List<String>> properties = PropertiesUtilities.convertTextToSortedListMap(tokenOptions);
  1349.             if(properties!=null && properties.size()>0) {
  1350.            
  1351.                 InformazioniToken informazioniTokenNormalizzate = null;
  1352.                 Object oInformazioniTokenNormalizzate = pddContext.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_INFORMAZIONI_NORMALIZZATE);
  1353.                 if(oInformazioniTokenNormalizzate!=null) {
  1354.                     informazioniTokenNormalizzate = (InformazioniToken) oInformazioniTokenNormalizzate;
  1355.                 }
  1356.            
  1357.                 if(informazioniTokenNormalizzate==null || informazioniTokenNormalizzate.getClaims()==null || informazioniTokenNormalizzate.getClaims().size()<=0) {
  1358.                     autorizzato = false;
  1359.                     errorMessage = "Token without claims";
  1360.                 }
  1361.                 else {
  1362.                                        
  1363.                     /* Costruisco dynamic Map */
  1364.                     boolean bufferMessageReadOnly =  OpenSPCoop2Properties.getInstance().isReadByPathBufferEnabled();
  1365.                     Map<String, Object> dynamicMap = DynamicUtils.buildDynamicMap(message, pddContext, datiInvocazione.getBusta(), log, bufferMessageReadOnly);
  1366.                                        
  1367.                     /* Analisi claims di autorizzazione */
  1368.                    
  1369.                     /**System.out.println("\n\n@ ===== AUTH TOKEN CLAIMS =====");*/
  1370.                    
  1371.                     List<String> keys = properties.keys();
  1372.                     for (String key : keys) {
  1373.                        
  1374.                         List<String> expectedValues = properties.get(key);
  1375.                         if(expectedValues!=null && !expectedValues.isEmpty()) {
  1376.                            
  1377.                             for (String expectedValue : expectedValues) {
  1378.                                
  1379.                                 /**System.out.println("check '"+key+"'='"+expectedValue+"'");*/
  1380.                                
  1381.                                 String attributeAuthorityName = null;
  1382.                                 String attributeName = null;
  1383.                                 boolean findAttribute = false;
  1384.                                 Object valueAttributeObject = null;
  1385.                                
  1386.                                 // verifica presenza claim nel token
  1387.                                 log.debug("Verifico presenza '"+key+"' nel token ...");
  1388.                                 if(!informazioniTokenNormalizzate.getClaims().containsKey(key)) {
  1389.                                    
  1390.                                     if(key.startsWith(ATTRIBUTE_AUTHORITY_PREFIX) && key.length()>ATTRIBUTE_AUTHORITY_PREFIX.length()) {
  1391.                                         String tmp = key.substring(ATTRIBUTE_AUTHORITY_PREFIX.length());
  1392.                                         //System.out.println("DEBUG ["+tmp+"]");
  1393.                                         if(tmp!=null && tmp.contains(".")) {
  1394.                                             int indexOf = tmp.indexOf(".");
  1395.                                             if(indexOf>0 && indexOf<tmp.length()) {
  1396.                                                 attributeAuthorityName = tmp.substring(0, indexOf);
  1397.                                                 tmp = tmp.substring(indexOf);
  1398.                                                 //System.out.println("DEBUG attributeAuthorityName["+attributeAuthorityName+"] tmp["+tmp+"]");
  1399.                                                 if(tmp.startsWith(("."+ATTRIBUTE_PREFIX)) && tmp.length()>("."+ATTRIBUTE_PREFIX).length()) {
  1400.                                                     indexOf = tmp.indexOf(".",1); // ho appurato che iniza con '.'
  1401.                                                     if(indexOf>0 && indexOf<tmp.length()) {
  1402.                                                         attributeName = tmp.substring(indexOf);
  1403.                                                         if(attributeName.startsWith(".") && attributeName.length()>1) {
  1404.                                                             attributeName = attributeName.substring(1);
  1405.                                                         }
  1406.                                                         //System.out.println("DEBUG attributeName["+attributeName+"]");
  1407.                                                     }
  1408.                                                 }
  1409.                                             }
  1410.                                         }
  1411.                                     }
  1412.                                     else if(key.startsWith(ATTRIBUTE_PREFIX) && key.length()>ATTRIBUTE_PREFIX.length()) {
  1413.                                         attributeName = key.substring(ATTRIBUTE_PREFIX.length());
  1414.                                     }
  1415.                                    
  1416.                                     if(attributeAuthorityName!=null && attributeName!=null) {
  1417.                                         if(informazioniTokenNormalizzate.getAa()!=null &&
  1418.                                                 informazioniTokenNormalizzate.getAa().isMultipleAttributeAuthorities()!=null &&
  1419.                                                 informazioniTokenNormalizzate.getAa().isMultipleAttributeAuthorities().getValue()!=null &&
  1420.                                                 informazioniTokenNormalizzate.getAa().isMultipleAttributeAuthorities().getValue().booleanValue() &&
  1421.                                                 informazioniTokenNormalizzate.getAa().getAttributes()!=null &&
  1422.                                                 informazioniTokenNormalizzate.getAa().getAttributes().containsKey(attributeAuthorityName)) {
  1423.                                             Object o = informazioniTokenNormalizzate.getAa().getAttributes().get(attributeAuthorityName);
  1424.                                             if(o instanceof Map) {
  1425.                                                 @SuppressWarnings("unchecked")
  1426.                                                 Map<String, Object> map = (Map<String, Object>) o;
  1427.                                                 if(map.containsKey(attributeName)) {
  1428.                                                     findAttribute = true;
  1429.                                                     valueAttributeObject = map.get(attributeName);
  1430.                                                 }
  1431.                                             }
  1432.                                         }
  1433.                                     }
  1434.                                     else if(attributeName!=null) {
  1435.                                         if(informazioniTokenNormalizzate.getAa()!=null &&
  1436.                                                 (
  1437.                                                         informazioniTokenNormalizzate.getAa().isMultipleAttributeAuthorities()==null ||
  1438.                                                         informazioniTokenNormalizzate.getAa().isMultipleAttributeAuthorities().getValue()==null ||
  1439.                                                         !informazioniTokenNormalizzate.getAa().isMultipleAttributeAuthorities().getValue()
  1440.                                                 ) &&
  1441.                                                 informazioniTokenNormalizzate.getAa().getAttributes()!=null &&
  1442.                                                 informazioniTokenNormalizzate.getAa().getAttributes().containsKey(attributeName)) {
  1443.                                             findAttribute = true;
  1444.                                             valueAttributeObject = informazioniTokenNormalizzate.getAa().getAttributes().get(attributeName);
  1445.                                         }
  1446.                                     }
  1447.                                    
  1448.                                     if(!findAttribute) {
  1449.                                         if(CostantiAutorizzazione.AUTHZ_UNDEFINED.equalsIgnoreCase(expectedValue)) {
  1450.                                             continue;
  1451.                                         }
  1452.                                         autorizzato = false;
  1453.                                         if(attributeName!=null) {
  1454.                                             errorMessage = "Token without attribute '"+key+"'";
  1455.                                         }
  1456.                                         else {
  1457.                                             errorMessage = "Token without claim '"+key+"'";
  1458.                                         }
  1459.                                         break;
  1460.                                     }
  1461.                                 }
  1462.                                
  1463.                                 List<String> lClaimValues =null;
  1464.                                 if(findAttribute && valueAttributeObject!=null) {
  1465.                                     lClaimValues = TokenUtilities.getClaimValues(valueAttributeObject);
  1466.                                 }
  1467.                                 else {
  1468.                                     Object valueClaimObject = informazioniTokenNormalizzate.getClaims().get(key);
  1469.                                     lClaimValues = TokenUtilities.getClaimValues(valueClaimObject);
  1470.                                 }
  1471.                                 String nomeClaimAttribute = (attributeName!=null) ? attributeName : key;
  1472.                                 if(lClaimValues==null || lClaimValues.isEmpty()) {
  1473.                                     if(CostantiAutorizzazione.AUTHZ_UNDEFINED.equalsIgnoreCase(expectedValue)) {
  1474.                                         continue;
  1475.                                     }
  1476.                                     autorizzato = false;
  1477.                                     if(attributeName!=null) {
  1478.                                         errorMessage = "Token with attribute '"+nomeClaimAttribute+"' without value";
  1479.                                     }
  1480.                                     else {
  1481.                                         errorMessage = "Token with claim '"+nomeClaimAttribute+"' without value";
  1482.                                     }
  1483.                                     break;
  1484.                                 }
  1485.                                
  1486.                                 // verifica valore atteso per il claim
  1487.                                 String object = (attributeName!=null) ? "Attribute" : "Claim";
  1488.                                 log.debug("Verifico valore '"+expectedValue+"' per "+object.toLowerCase()+" '"+nomeClaimAttribute+"' nel token ...");
  1489.                                 if(expectedValue==null) {
  1490.                                     throw new Exception(object+" '"+nomeClaimAttribute+"' without expected value");
  1491.                                 }
  1492.                                 expectedValue = expectedValue.trim();
  1493.                                
  1494.                                 if(CostantiAutorizzazione.AUTHZ_ANY_VALUE.equalsIgnoreCase(expectedValue)) {
  1495.                                    
  1496.                                     /** ANY VALUE */
  1497.                                    
  1498.                                     log.debug("Verifico valore "+object.toLowerCase()+" '"+nomeClaimAttribute+"' che non sia null e non sia vuoto ...");
  1499.                                    
  1500.                                     // basta che abbia un valore not null
  1501.                                     boolean ok = false;
  1502.                                     for (String v : lClaimValues) {
  1503.                                         if(v!=null && !"".equals(v)) {
  1504.                                             ok = true;
  1505.                                             break;
  1506.                                         }
  1507.                                     }
  1508.                                     if(!ok) {
  1509.                                         autorizzato = false;
  1510.                                         errorMessage = "Token "+object.toLowerCase()+" '"+nomeClaimAttribute+"' with unexpected empty value";
  1511.                                         break;
  1512.                                     }
  1513.                                 }
  1514.                                 else if(CostantiAutorizzazione.AUTHZ_UNDEFINED.equalsIgnoreCase(expectedValue)) {
  1515.                                    
  1516.                                     /** NOT PRESENT */
  1517.                                    
  1518.                                     log.debug("Verifico valore "+object.toLowerCase()+" '"+nomeClaimAttribute+"' sia null o sia vuoto ...");
  1519.                                    
  1520.                                     // basta che abbia un valore
  1521.                                     boolean ok = false;
  1522.                                     for (String v : lClaimValues) {
  1523.                                         if(v!=null && !"".equals(v)) {
  1524.                                             ok = true;
  1525.                                             break;
  1526.                                         }
  1527.                                     }
  1528.                                     if(ok) {
  1529.                                         autorizzato = false;
  1530.                                         errorMessage = "Token unexpected "+object.toLowerCase()+" '"+nomeClaimAttribute+"'";
  1531.                                         break;
  1532.                                     }
  1533.                                    
  1534.                                 }
  1535.                                 else if(
  1536.                                         (
  1537.                                                 expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_MATCH_PREFIX.toLowerCase())
  1538.                                                 ||
  1539.                                                 expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_FIND_PREFIX.toLowerCase())
  1540.                                                 ||
  1541.                                                 expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_NOT_MATCH_PREFIX.toLowerCase())
  1542.                                                 ||
  1543.                                                 expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_NOT_FIND_PREFIX.toLowerCase())
  1544.                                         )
  1545.                                         &&
  1546.                                         expectedValue.toLowerCase().endsWith(CostantiAutorizzazione.AUTHZ_REGEXP_SUFFIX.toLowerCase())) {
  1547.                                    
  1548.                                     /** REGULAR EXPRESSION MATCH/FIND */
  1549.                                    
  1550.                                     boolean match = expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_MATCH_PREFIX.toLowerCase())
  1551.                                             ||
  1552.                                             expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_NOT_MATCH_PREFIX.toLowerCase());
  1553.                                     boolean not = expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_NOT_MATCH_PREFIX.toLowerCase())
  1554.                                             ||
  1555.                                             expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_NOT_FIND_PREFIX.toLowerCase());
  1556.                                     String regexpPattern = null;
  1557.                                     if(match) {
  1558.                                         int length = -1;
  1559.                                         if(expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_MATCH_PREFIX.toLowerCase())) {
  1560.                                             length = CostantiAutorizzazione.AUTHZ_REGEXP_MATCH_PREFIX.length();
  1561.                                         }
  1562.                                         else {
  1563.                                             length = CostantiAutorizzazione.AUTHZ_REGEXP_NOT_MATCH_PREFIX.length();
  1564.                                         }
  1565.                                         if(expectedValue.length()<= (length+CostantiAutorizzazione.AUTHZ_REGEXP_SUFFIX.length()) ) {
  1566.                                             throw new Exception(object+" '"+nomeClaimAttribute+"' without expected regexp match");
  1567.                                         }
  1568.                                         regexpPattern = expectedValue.substring(length, (expectedValue.length()-CostantiAutorizzazione.AUTHZ_REGEXP_SUFFIX.length()));
  1569.                                     }
  1570.                                     else {
  1571.                                         int length = -1;
  1572.                                         if(expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_REGEXP_FIND_PREFIX.toLowerCase())) {
  1573.                                             length = CostantiAutorizzazione.AUTHZ_REGEXP_FIND_PREFIX.length();
  1574.                                         }
  1575.                                         else {
  1576.                                             length = CostantiAutorizzazione.AUTHZ_REGEXP_NOT_FIND_PREFIX.length();
  1577.                                         }
  1578.                                         if(expectedValue.length()<= (length+CostantiAutorizzazione.AUTHZ_REGEXP_SUFFIX.length()) ) {
  1579.                                             throw new Exception(object+" '"+nomeClaimAttribute+"' without expected regexp find");
  1580.                                         }
  1581.                                         regexpPattern = expectedValue.substring(length, (expectedValue.length()-CostantiAutorizzazione.AUTHZ_REGEXP_SUFFIX.length()));
  1582.                                     }
  1583.                                     regexpPattern = regexpPattern.trim();
  1584.                                     log.debug("Verifico valore del "+object.toLowerCase()+" '"+nomeClaimAttribute+"' tramite espressione regolare (match:"+match+") '"+regexpPattern+"' ...");
  1585.                                    
  1586.                                     // basta che un valore abbia match
  1587.                                     boolean ok = false;
  1588.                                     for (String v : lClaimValues) {
  1589.                                         if( match ? RegularExpressionEngine.isMatch(v, regexpPattern) : RegularExpressionEngine.isFind(v, regexpPattern)) {
  1590.                                             ok = true;
  1591.                                             break;
  1592.                                         }
  1593.                                     }
  1594.                                     if(not) {
  1595.                                         if(ok) {
  1596.                                             autorizzato = false;
  1597.                                             String tipo = match ? "match" : "find";
  1598.                                             errorMessage = "Token "+object.toLowerCase()+" '"+nomeClaimAttribute+"' with unexpected value (regExpr not "+tipo+" failed)";
  1599.                                             break;
  1600.                                         }
  1601.                                     }
  1602.                                     else {
  1603.                                         if(!ok) {
  1604.                                             autorizzato = false;
  1605.                                             String tipo = match ? "match" : "find";
  1606.                                             errorMessage = "Token "+object.toLowerCase()+" '"+nomeClaimAttribute+"' with unexpected value (regExpr "+tipo+" failed)";
  1607.                                             break;
  1608.                                         }
  1609.                                     }
  1610.                                    
  1611.                                 }
  1612.                                 else {
  1613.                                
  1614.                                     /** VALUE (con PLACEHOLDERS) */
  1615.                                    
  1616.                                     boolean not = false;
  1617.                                     if(
  1618.                                             expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_NOT_PREFIX.toLowerCase())
  1619.                                             &&
  1620.                                             expectedValue.toLowerCase().endsWith(CostantiAutorizzazione.AUTHZ_NOT_SUFFIX.toLowerCase())) {
  1621.                                         not = true;
  1622.                                         if(expectedValue.length()<= (CostantiAutorizzazione.AUTHZ_NOT_PREFIX.length()+CostantiAutorizzazione.AUTHZ_NOT_SUFFIX.length()) ) {
  1623.                                             throw new Exception(object+" '"+nomeClaimAttribute+"' without value in not condition");
  1624.                                         }
  1625.                                         expectedValue = expectedValue.substring(CostantiAutorizzazione.AUTHZ_NOT_PREFIX.length(), (expectedValue.length()-CostantiAutorizzazione.AUTHZ_NOT_SUFFIX.length()));
  1626.                                     }
  1627.                                    
  1628.                                     boolean ignoreCase = false;
  1629.                                     if(
  1630.                                             expectedValue.toLowerCase().startsWith(CostantiAutorizzazione.AUTHZ_IGNORE_CASE_PREFIX.toLowerCase())
  1631.                                             &&
  1632.                                             expectedValue.toLowerCase().endsWith(CostantiAutorizzazione.AUTHZ_IGNORE_CASE_SUFFIX.toLowerCase())) {
  1633.                                         ignoreCase = true;
  1634.                                         if(expectedValue.length()<= (CostantiAutorizzazione.AUTHZ_IGNORE_CASE_PREFIX.length()+CostantiAutorizzazione.AUTHZ_IGNORE_CASE_SUFFIX.length()) ) {
  1635.                                             throw new Exception(object+" '"+nomeClaimAttribute+"' without value in ignore case condition");
  1636.                                         }
  1637.                                         expectedValue = expectedValue.substring(CostantiAutorizzazione.AUTHZ_IGNORE_CASE_PREFIX.length(), (expectedValue.length()-CostantiAutorizzazione.AUTHZ_IGNORE_CASE_SUFFIX.length()));
  1638.                                     }
  1639.                                    
  1640.                                     try {
  1641.                                         expectedValue = DynamicUtils.convertDynamicPropertyValue(key, expectedValue, dynamicMap, pddContext);
  1642.                                     }catch(Exception e) {
  1643.                                         String msg = "Conversione valore per "+object.toLowerCase()+" '"+nomeClaimAttribute+"' non riuscita (valore: "+expectedValue+"): "+e.getMessage();
  1644.                                         //throw new Exception(msg,e);
  1645.                                         log.error(msg, e);
  1646.                                         autorizzato = false;
  1647.                                         errorMessage = "Token "+object.toLowerCase()+" '"+nomeClaimAttribute+"' not verifiable; unprocessable dynamic value '"+expectedValue+"': "+e.getMessage();
  1648.                                         break;
  1649.                                     }
  1650.                                    
  1651.                                     boolean ok = false;
  1652.                                     if(expectedValue.contains(",")) {
  1653.                                         String [] values = expectedValue.split(",");
  1654.                                         ok = false;
  1655.                                         for (int i = 0; i < values.length; i++) {
  1656.                                             String v = values[i].trim();
  1657.                                             if(ignoreCase) {
  1658.                                                 boolean find = false;
  1659.                                                 for (String claim : lClaimValues) {
  1660.                                                     if(claim.equalsIgnoreCase(v)) {
  1661.                                                         find = true;
  1662.                                                         break;
  1663.                                                     }  
  1664.                                                 }
  1665.                                                 if(find) {
  1666.                                                     ok = true;
  1667.                                                     break;
  1668.                                                 }
  1669.                                             }
  1670.                                             else {
  1671.                                                 if(lClaimValues.contains(v)) {
  1672.                                                     ok = true;
  1673.                                                     break;
  1674.                                                 }
  1675.                                             }
  1676.                                         }
  1677.                                     }
  1678.                                     else {
  1679.                                         if(ignoreCase) {
  1680.                                             boolean find = false;
  1681.                                             for (String claim : lClaimValues) {
  1682.                                                 if(claim.equalsIgnoreCase(expectedValue)) {
  1683.                                                     find = true;
  1684.                                                     break;
  1685.                                                 }  
  1686.                                             }
  1687.                                             ok = find;
  1688.                                         }
  1689.                                         else {
  1690.                                             ok = lClaimValues.contains(expectedValue);
  1691.                                         }
  1692.                                     }
  1693.                                    
  1694.                                     if(not) {
  1695.                                         if(ok) {
  1696.                                             autorizzato = false;
  1697.                                             errorMessage = "Token "+object.toLowerCase()+" '"+nomeClaimAttribute+"' with unauthorized value";
  1698.                                             break;
  1699.                                         }
  1700.                                     }
  1701.                                     else {
  1702.                                         if(!ok) {
  1703.                                             autorizzato = false;
  1704.                                             errorMessage = "Token "+object.toLowerCase()+" '"+nomeClaimAttribute+"' with unexpected value";
  1705.                                             break;
  1706.                                         }
  1707.                                     }
  1708.                                 }
  1709.                             }
  1710.                         }
  1711.                     }
  1712.                 }
  1713.             }
  1714.            
  1715.         }
  1716.        
  1717.         if(!autorizzato) {
  1718.            
  1719.             String realm = "GovWay";
  1720.             Object oRealm = pddContext.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_REALM);
  1721.             if(oRealm!=null) {
  1722.                 realm = (String) oRealm;
  1723.             }
  1724.            
  1725.             boolean emptyMessage = false;
  1726.             Object oEmptyMessage = pddContext.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_MESSAGE_ERROR_BODY_EMPTY);
  1727.             if(oEmptyMessage!=null) {
  1728.                 emptyMessage = (Boolean) oEmptyMessage;
  1729.             }
  1730.            
  1731.             boolean genericMessage = false;
  1732.             Object oGenericMessage = pddContext.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_MESSAGE_ERROR_GENERIC_MESSAGE);
  1733.             if(oGenericMessage!=null) {
  1734.                 genericMessage = (Boolean) oGenericMessage;
  1735.             }
  1736.            
  1737.             if(genericMessage) {
  1738.                 esito.setDetails(errorMessage);
  1739.             }
  1740.            
  1741.             esito.setAutorizzato(false);
  1742.             if(emptyMessage) {
  1743.                 esito.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.insufficient_scope, realm, genericMessage, errorMessage));
  1744.             }
  1745.             else {
  1746.                 esito.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.insufficient_scope, realm, genericMessage, errorMessage));
  1747.             }
  1748.         }
  1749.        
  1750.        
  1751.         return esito;
  1752.     }
  1753.    
  1754.    
  1755.    
  1756.    
  1757.    
  1758.    
  1759.    
  1760.     /*----------------- AUTORIZZAZIONE CONTENUTO --------------------*/
  1761.    

  1762.     // NOTA: le chiamate ad autorizzazione per contenuto possono essere cachate solamente se viene definito un suffix,
  1763.     //       poiche' altrimenti variano sempre i contenuti e non finiscono nella chiave di cache.
  1764.     public static EsitoAutorizzazionePortaDelegata verificaAutorizzazioneContenutoPortaDelegata(String tipoAutorizzazione, DatiInvocazionePortaDelegata datiInvocazione,
  1765.               PdDContext pddContext,IProtocolFactory<?> protocolFactory, OpenSPCoop2Message msg, Logger log) throws Exception{
  1766.        
  1767.         checkDatiPortaDelegataAuthContenuto(datiInvocazione, msg);
  1768.        
  1769.         EsitoAutorizzazionePortaDelegata esito = _verificaAutorizzazioneContenutoPortaDelegata(tipoAutorizzazione, datiInvocazione, pddContext, protocolFactory, msg);
  1770.         if(esito.isAutorizzato()==false) {
  1771.             return esito;
  1772.         }
  1773.        
  1774.         return esito;
  1775.        
  1776.     }
  1777.    
  1778.     private static EsitoAutorizzazionePortaDelegata _verificaAutorizzazioneContenutoPortaDelegata(String tipoAutorizzazione, DatiInvocazionePortaDelegata datiInvocazione,
  1779.           PdDContext pddContext,IProtocolFactory<?> protocolFactory, OpenSPCoop2Message msg) throws Exception{
  1780.        
  1781.         IAutorizzazioneContenutoPortaDelegata auth = newInstanceAuthContenutoPortaDelegata(tipoAutorizzazione, pddContext, protocolFactory);
  1782.        
  1783.         try {
  1784.             if(GestoreAutorizzazione.cacheAutorizzazione==null || !auth.saveAuthorizationResultInCache()){
  1785.                 return auth.process(datiInvocazione, msg);
  1786.             }
  1787.             else{
  1788.                 String keyCache = buildCacheKeyContenuto(true, tipoAutorizzazione, datiInvocazione.getKeyCache(), auth.getSuffixKeyAuthorizationResultInCache(datiInvocazione, msg) );
  1789.    
  1790.                 // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  1791.                 org.openspcoop2.utils.cache.CacheResponse response =
  1792.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreAutorizzazione.cacheAutorizzazione.get(keyCache);
  1793.                 if(response != null){
  1794.                     if(response.getObject()!=null){
  1795.                         GestoreAutorizzazione.logger.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) in cache.");
  1796.                         EsitoAutorizzazionePortaDelegata esito = (EsitoAutorizzazionePortaDelegata) response.getObject();
  1797.                         esito.setEsitoPresenteInCache(true);
  1798.                         return esito;
  1799.                     }else if(response.getException()!=null){
  1800.                         GestoreAutorizzazione.logger.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) in cache.");
  1801.                         throw (Exception) response.getException();
  1802.                     }else{
  1803.                         GestoreAutorizzazione.logger.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  1804.                     }
  1805.                 }
  1806.                                
  1807.                 String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  1808.                 //synchronized (GestoreAutorizzazione.semaphoreAutorizzazioneContenutiPD) {
  1809.                 org.openspcoop2.utils.Semaphore lockAutorizzazioneContenutiPD = getLockAutorizzazioneContenutiPD(tipoAutorizzazione);
  1810.                 SemaphoreLock lock = lockAutorizzazioneContenutiPD.acquire("verificaAutorizzazioneContenutoPortaDelegata", idTransazione);
  1811.                 try {
  1812.                    
  1813.                     response =
  1814.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreAutorizzazione.cacheAutorizzazione.get(keyCache);
  1815.                     if(response != null){
  1816.                         if(response.getObject()!=null){
  1817.                             GestoreAutorizzazione.logger.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) in cache.");
  1818.                             EsitoAutorizzazionePortaDelegata esito = (EsitoAutorizzazionePortaDelegata) response.getObject();
  1819.                             esito.setEsitoPresenteInCache(true);
  1820.                             return esito;
  1821.                         }else if(response.getException()!=null){
  1822.                             GestoreAutorizzazione.logger.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) in cache.");
  1823.                             throw (Exception) response.getException();
  1824.                         }else{
  1825.                             GestoreAutorizzazione.logger.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  1826.                         }
  1827.                     }
  1828.    
  1829.                     // Effettuo la query
  1830.                     GestoreAutorizzazione.logger.debug("oggetto con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaDelegata) ricerco nella configurazione...");
  1831.                     EsitoAutorizzazionePortaDelegata esito = auth.process(datiInvocazione, msg);
  1832.    
  1833.                     // Aggiungo la risposta in cache (se esiste una cache)  
  1834.                     // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  1835.                     // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  1836.                     // - impostare il noCache a true
  1837.                     if(esito!=null){
  1838.                         if(!esito.isNoCache()){
  1839.                             GestoreAutorizzazione.logger.info("Aggiungo oggetto ["+keyCache+"] in cache");
  1840.                             try{    
  1841.                                 org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1842.                                 responseCache.setObject(esito);
  1843.                                 GestoreAutorizzazione.cacheAutorizzazione.put(keyCache,responseCache);
  1844.                             }catch(UtilsException e){
  1845.                                 GestoreAutorizzazione.logger.error("Errore durante l'inserimento in cache ["+keyCache+"]: "+e.getMessage());
  1846.                             }
  1847.                         }
  1848.                         return esito;
  1849.                     }else{
  1850.                         throw new AutorizzazioneException("Metodo (GestoreAutorizzazione.autorizzazionePortaDelegata.process) ha ritornato un valore di esito null");
  1851.                     }
  1852.                 }finally {
  1853.                     lockAutorizzazioneContenutiPD.release(lock, "verificaAutorizzazioneContenutoPortaDelegata", idTransazione);
  1854.                 }
  1855.             }
  1856.         }finally {
  1857.             if(msg!=null) {
  1858.                 auth.cleanPostAuth(msg);
  1859.             }
  1860.         }
  1861.     }
  1862.    
  1863.     public static EsitoAutorizzazionePortaApplicativa verificaAutorizzazioneContenutoPortaApplicativa(String tipoAutorizzazione, DatiInvocazionePortaApplicativa datiInvocazione,
  1864.             PdDContext pddContext,IProtocolFactory<?> protocolFactory, OpenSPCoop2Message msg, Logger log) throws Exception{
  1865.          
  1866.         checkDatiPortaApplicativaAuthContenuto(datiInvocazione, msg);
  1867.    
  1868.         EsitoAutorizzazionePortaApplicativa esito = _verificaAutorizzazioneContenutoPortaApplicativa(tipoAutorizzazione, datiInvocazione, pddContext, protocolFactory, msg);
  1869.         if(esito.isAutorizzato()==false) {
  1870.             return esito;
  1871.         }
  1872.        
  1873.         return esito;
  1874.        
  1875.     }
  1876.     private static EsitoAutorizzazionePortaApplicativa _verificaAutorizzazioneContenutoPortaApplicativa(String tipoAutorizzazione, DatiInvocazionePortaApplicativa datiInvocazione,
  1877.             PdDContext pddContext,IProtocolFactory<?> protocolFactory, OpenSPCoop2Message msg) throws Exception{
  1878.        
  1879.         IAutorizzazioneContenutoPortaApplicativa auth = newInstanceAuthContenutoPortaApplicativa(tipoAutorizzazione, pddContext, protocolFactory);
  1880.        
  1881.         try {
  1882.             if(GestoreAutorizzazione.cacheAutorizzazione==null || !auth.saveAuthorizationResultInCache()){
  1883.                 return auth.process(datiInvocazione, msg);
  1884.             }
  1885.             else{
  1886.                 String keyCache = buildCacheKeyContenuto(false, tipoAutorizzazione, datiInvocazione.getKeyCache(), auth.getSuffixKeyAuthorizationResultInCache(datiInvocazione, msg));
  1887.    
  1888.                 // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  1889.                 org.openspcoop2.utils.cache.CacheResponse response =
  1890.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreAutorizzazione.cacheAutorizzazione.get(keyCache);
  1891.                 if(response != null){
  1892.                     if(response.getObject()!=null){
  1893.                         GestoreAutorizzazione.logger.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) in cache.");
  1894.                         EsitoAutorizzazionePortaApplicativa esito = (EsitoAutorizzazionePortaApplicativa) response.getObject();
  1895.                         esito.setEsitoPresenteInCache(true);
  1896.                         return esito;
  1897.                     }else if(response.getException()!=null){
  1898.                         GestoreAutorizzazione.logger.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) in cache.");
  1899.                         throw (Exception) response.getException();
  1900.                     }else{
  1901.                         GestoreAutorizzazione.logger.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  1902.                     }
  1903.                 }
  1904.                
  1905.                 String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  1906.                 //synchronized (GestoreAutorizzazione.semaphoreAutorizzazioneContenutiPA) {
  1907.                 org.openspcoop2.utils.Semaphore lockAutorizzazioneContenutiPA = getLockAutorizzazioneContenutiPA(tipoAutorizzazione);
  1908.                 SemaphoreLock lock = lockAutorizzazioneContenutiPA.acquire("verificaAutorizzazioneContenutoPortaApplicativa", idTransazione);
  1909.                 try {
  1910.                    
  1911.                     response =
  1912.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreAutorizzazione.cacheAutorizzazione.get(keyCache);
  1913.                     if(response != null){
  1914.                         if(response.getObject()!=null){
  1915.                             GestoreAutorizzazione.logger.debug("Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) in cache.");
  1916.                             EsitoAutorizzazionePortaApplicativa esito = (EsitoAutorizzazionePortaApplicativa) response.getObject();
  1917.                             esito.setEsitoPresenteInCache(true);
  1918.                             return esito;
  1919.                         }else if(response.getException()!=null){
  1920.                             GestoreAutorizzazione.logger.debug("Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) in cache.");
  1921.                             throw (Exception) response.getException();
  1922.                         }else{
  1923.                             GestoreAutorizzazione.logger.error("In cache non e' presente ne un oggetto ne un'eccezione.");
  1924.                         }
  1925.                     }
  1926.    
  1927.                     // Effettuo la query
  1928.                     GestoreAutorizzazione.logger.debug("oggetto con chiave ["+keyCache+"] (method:verificaAutorizzazionePortaApplicativa) ricerco nella configurazione...");
  1929.                     EsitoAutorizzazionePortaApplicativa esito = auth.process(datiInvocazione, msg);
  1930.    
  1931.                     // Aggiungo la risposta in cache (se esiste una cache)  
  1932.                     // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  1933.                     // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  1934.                     // - impostare il noCache a true
  1935.                     if(esito!=null){
  1936.                         if(!esito.isNoCache()){
  1937.                             GestoreAutorizzazione.logger.info("Aggiungo oggetto ["+keyCache+"] in cache");
  1938.                             try{    
  1939.                                 org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1940.                                 responseCache.setObject(esito);
  1941.                                 GestoreAutorizzazione.cacheAutorizzazione.put(keyCache,responseCache);
  1942.                             }catch(UtilsException e){
  1943.                                 GestoreAutorizzazione.logger.error("Errore durante l'inserimento in cache ["+keyCache+"]: "+e.getMessage());
  1944.                             }
  1945.                         }
  1946.                         return esito;
  1947.                     }else{
  1948.                         throw new AutorizzazioneException("Metodo (GestoreAutorizzazione.autorizzazionePortaApplicativa.process) ha ritornato un valore di esito null");
  1949.                     }
  1950.                 }finally {
  1951.                     lockAutorizzazioneContenutiPA.release(lock, "verificaAutorizzazioneContenutoPortaApplicativa", idTransazione);
  1952.                 }
  1953.             }
  1954.         }finally {
  1955.             if(msg!=null) {
  1956.                 auth.cleanPostAuth(msg);
  1957.             }
  1958.         }
  1959.     }
  1960.    
  1961.     private static void checkDatiPortaDelegataAuthContenuto(DatiInvocazionePortaDelegata datiInvocazione, OpenSPCoop2Message msg) throws AutorizzazioneException{
  1962.        
  1963.         checkDatiPortaDelegata(datiInvocazione);
  1964.        
  1965.     }
  1966.    
  1967.     private static void checkDatiPortaApplicativaAuthContenuto(DatiInvocazionePortaApplicativa datiInvocazione, OpenSPCoop2Message msg) throws AutorizzazioneException{
  1968.        
  1969.         checkDatiPortaApplicativa(datiInvocazione);
  1970.        
  1971.     }
  1972.    
  1973.     private static String buildCacheKeyContenuto(boolean portaDelegata, String tipoAutorizzazione, String keyCache, String suffixKeyCache) throws AutorizzazioneException{
  1974.         StringBuilder bf = new StringBuilder();
  1975.        
  1976.         if(portaDelegata)
  1977.             bf.append("PD ");
  1978.         else
  1979.             bf.append("PA ");
  1980.        
  1981.         bf.append(" AuthContenuti:").append(tipoAutorizzazione).append(" ");
  1982.        
  1983.         bf.append(keyCache);
  1984.        
  1985.         if(suffixKeyCache!=null && !"".equals(suffixKeyCache)){
  1986.             bf.append(" ");
  1987.             bf.append(suffixKeyCache);
  1988.         }
  1989.         else {
  1990.             throw new AutorizzazioneException("Per salvare in cache l'esito dell'autorizzazione sui contenuti è richiesta la definizione di un suffisso per la chiave");
  1991.         }
  1992.        
  1993.         return bf.toString();
  1994.     }
  1995.    
  1996.     private static IAutorizzazioneContenutoPortaDelegata newInstanceAuthContenutoPortaDelegata(String tipoAutorizzazione,PdDContext pddContext, IProtocolFactory<?> protocolFactory) throws AutorizzazioneException{
  1997.         IAutorizzazioneContenutoPortaDelegata auth = null;
  1998.         try{
  1999.             PddPluginLoader pluginLoader = PddPluginLoader.getInstance();
  2000.             auth = (IAutorizzazioneContenutoPortaDelegata) pluginLoader.newAutorizzazioneContenutiPortaDelegata(tipoAutorizzazione);
  2001.         }catch(Exception e){
  2002.             throw new AutorizzazioneException(e.getMessage(),e); // descrizione errore già corretta
  2003.         }
  2004.         String classType = null;
  2005.         try{
  2006.             classType = auth.getClass().getName();
  2007.             AbstractCore.init(auth, pddContext, protocolFactory);
  2008.             return auth;
  2009.         }catch(Exception e){
  2010.             throw new AutorizzazioneException("Riscontrato errore durante l'inizializzazione della classe ["+classType+
  2011.                     "] che definisce l'autorizzazione dei contenuti della fruizione: "+e.getMessage(),e);
  2012.         }
  2013.     }
  2014.    
  2015.     private static IAutorizzazioneContenutoPortaApplicativa newInstanceAuthContenutoPortaApplicativa(String tipoAutorizzazione,PdDContext pddContext, IProtocolFactory<?> protocolFactory) throws AutorizzazioneException{
  2016.         IAutorizzazioneContenutoPortaApplicativa auth = null;
  2017.         try{
  2018.             PddPluginLoader pluginLoader = PddPluginLoader.getInstance();
  2019.             auth = (IAutorizzazioneContenutoPortaApplicativa) pluginLoader.newAutorizzazioneContenutiPortaApplicativa(tipoAutorizzazione);
  2020.         }catch(Exception e){
  2021.             throw new AutorizzazioneException(e.getMessage(),e); // descrizione errore già corretta
  2022.         }
  2023.         String classType = null;
  2024.         try{
  2025.             classType = auth.getClass().getName();
  2026.             AbstractCore.init(auth, pddContext, protocolFactory);
  2027.             return auth;
  2028.         }catch(Exception e){
  2029.             throw new AutorizzazioneException("Riscontrato errore durante l'inizializzazione della classe ["+classType+
  2030.                     "] che definisce l'autorizzazione dei contenuti della erogazione: "+e.getMessage(),e);
  2031.         }
  2032.     }
  2033. }