MultiSessionAppserverSecurityManager.java

/*
** Module   : MultiSessionAppserverSecurityManager.java
** Abstract : Multi-session agent appserver security manager.
**
** Copyright (c) 2025, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------Description----------------------------------
** 001 GBB 20250122 Created initial version.
*/
/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
**
** Additional terms under GNU Affero GPL version 3 section 7:
**
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
**
**   0. Attribution Requirement.
**
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
**
**   1. No License To Use Trademarks.
**
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
**
**   2. No Misrepresentation of Affiliation.
**
**     You may not represent yourself as Golden Code Development Corporation or FWD.
**
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
**
**   3. No Misrepresentation of Source or Origin.
**
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/
package com.goldencode.p2j.security;

import com.goldencode.p2j.util.*;
import com.goldencode.p2j.util.logging.*;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

/** Multi-session agent appserver security manager. */
public class MultiSessionAppserverSecurityManager
{
   /** Initialization on demand idiom singleton holder */
   private static class SingletonHolder
   {
      /** Singleton instance */
      private static final MultiSessionAppserverSecurityManager INSTANCE = new MultiSessionAppserverSecurityManager();
   }

   /** Logger. */
   private static final CentralLogger LOG = CentralLogger.get(MultiSessionAppserverSecurityManager.class);

   /** 
    * Executor used to cleanup SecurityContext, when the appserver app is terminated. The executor uses a 
    * factory for threads with the right initial context to be able to perform the tasks. 
    */
   private static final Executor contextCleanupExecutor = Executors.newSingleThreadExecutor(
      runnable -> new Thread(runnable, "MSA Context Cleanup Thread")
      {
         @Override
         public void run()
         {
            try
            {
               setInitialContext();
            }
            catch (RestrictedUseException e)
            {
               LOG.warning("Couldn't set initial context on thread " + Thread.currentThread().getName(), e);
            }
            super.run();
         }
      }
   );

   /** Map of the security contexts by appserver */
   private final Map<String, Map<Integer, SecurityContext>> appContextMaps = new ConcurrentHashMap<>();

   /**
    * Map of the context id counters by appserver. The ids are ordinal number starting at 1. If multi-session 
    * agents are implemented, the counters should be separate for each agent.
    */
   private final Map<String, AtomicInteger> appContextIdCounters = new ConcurrentHashMap<>();

   /**
    * Static method for access to the singleton instance of the manager 
    *
    * @return   The singleton instance of the manager 
    */
   public static MultiSessionAppserverSecurityManager getInstance()
   {
      return SingletonHolder.INSTANCE;
   }

   /**
    * Sets the initial security context on the thread.
    * 
    * @throws   RestrictedUseException
    *           If called from an unexpected caller.
    */
   public static void setInitialContext()
   throws RestrictedUseException
   {
      SecurityManager.getInstance().contextSm.setUniqueInitialSecurityContext();
   }

   /**
    * Creates a new SecurityContext with an incremental id for this application, and saves a reference to 
    * the context.
    * 
    * @param    appName
    *           The appserver app name.
    * @param    processId
    *           The FWD process account id.
    *           
    * @return   The id of the newly created context.
    * 
    * @throws   RestrictedUseException
    *           If called from an unexpected caller.
    */
   public int createContext(String appName, String processId)
   throws RestrictedUseException
   {
      // restrict the use of this method
      SecurityUtil.checkCallerAbort(new String[]
      {
         "com.goldencode.p2j.util.appserver.MultiSessionAppserver.createSession"
      });
      
      SecurityManager sm = SecurityManager.getInstance();

      SecurityContext newContext = null;
      try
      {
         newContext = sm.contextSm.createSecurityContext(sm.getCache(), processId, null);
      }
      catch (RestrictedUseException e)
      {
         LOG.warning("", e);
      }

      if (!appContextIdCounters.containsKey(appName))
      {
         appContextIdCounters.put(appName, new AtomicInteger(1));
      }
      int contextId = appContextIdCounters.get(appName).getAndIncrement();
      
      if (!appContextMaps.containsKey(appName))
      {
         appContextMaps.put(appName, new HashMap<Integer, SecurityContext>());
      }
      appContextMaps.get(appName).put(contextId, newContext);
      
      return contextId;
   }

   /**
    * Finds the SecurityContext for the application by its id and sets it on the current security context 
    * stack.
    *
    * @param    appName
    *           The appserver app name.
    * @param    contextId
    *           The context id.
    *
    * @return   <code>true</code> if the context is successfully changed, <code>false</code> otherwise.
    *
    * @throws   RestrictedUseException
    *           If called from an unexpected caller.
    */
   public boolean setContext(String appName, int contextId)
   throws RestrictedUseException
   {
      // restrict the use of this method
      SecurityUtil.checkCallerAbort(new String[]
      {
         "com.goldencode.p2j.util.appserver.MultiSessionAppserver.switchSession"
      });
      
      if (!appContextMaps.containsKey(appName) || !appContextMaps.get(appName).containsKey(contextId))
      {
         return false;
      }
      
      SecurityContext sc = appContextMaps.get(appName).get(contextId);
      
      // should be called for each task on MSA workers
      SecurityContextStack.setContext(new SecurityContextStack(sc));

      ErrorManager.getErrorHelper().setHeadless(true);
      return true;
   }
   
   /**
    * Finds the SecurityContext for the application by its id and resets it.
    *
    * @param    appName
    *           The appserver app name.
    * @param    contextId
    *           The context id.
    *
    * @throws   RestrictedUseException
    *           If called from an unexpected caller.
    */
   public void resetContext(String appName, Integer contextId)
   throws RestrictedUseException
   {
      // restrict the use of this method
      SecurityUtil.checkCallerAbort(new String[]
      {
         "com.goldencode.p2j.util.appserver.MultiSessionAppserver.resetSession"
      });
      
      if (!appContextMaps.containsKey(appName))
      {
         return;
      }

      Map<Integer, SecurityContext> securityContextMap = appContextMaps.get(appName);
      if (!securityContextMap.containsKey(contextId))
      {
         return;
      }
      
      SecurityContext context = securityContextMap.get(contextId);
      context.reset();
   }

   /**
    * Finds the SecurityContext for the application by its id and deletes it. This method expects to be 
    * executed on a thread with the same security context already set.
    *
    * @param    appName
    *           The appserver app name.
    * @param    contextId
    *           The context id.
    *
    * @throws   RestrictedUseException
    *           If called from an unexpected caller.
    */
   public void deleteCurrentContext(String appName, Integer contextId)
   throws RestrictedUseException
   {
      // restrict the use of this method
      SecurityUtil.checkCallerAbort(new String[]
      {
         "com.goldencode.p2j.util.appserver.MultiSessionAppserver.finalizeCurrentContext"
      });

      if (!appContextMaps.containsKey(appName))
      {
         return;
      }
      
      Map<Integer, SecurityContext> securityContextMap = appContextMaps.get(appName);
      if (!securityContextMap.containsKey(contextId))
      {
         return;
      }
      
      SecurityContext context = securityContextMap.remove(contextId);
      context.cleanup();
   }

   /**
    * Removes references to the app and deletes all contexts by running the cleanup in threads with 
    * the right context in {@link #contextCleanupExecutor} asynchronously.
    * 
    * @param    appName
    *           The appserver app name.
    *           
    * @throws   RestrictedUseException
    *           If called from an unexpected caller.
    */
   public void removeApp(String appName)
   throws RestrictedUseException
   {
      // restrict the use of this method
      SecurityUtil.checkCallerAbort(new String[]
      {
         "com.goldencode.p2j.util.appserver.MultiSessionAppserver$AgentTerminationTask.run"
      });

      appContextIdCounters.remove(appName);
      
      Map<Integer, SecurityContext> securityContextMap = appContextMaps.remove(appName);
      if (securityContextMap == null)
      {
         return;
      }
      
      for (SecurityContext context : securityContextMap.values())
      {
         cleanupContext(context);
      }
   }

   /**
    * Checks if the context for the session exists.
    * 
    * @param    appName
    *           The appserver app name.
    * @param    sessionId
    *           The session id.
    *           
    * @return   <code>true</code> if the context for the session exists, <code>false</code> otherwise.
    */
   public boolean hasContext(String appName, Integer sessionId)
   {
      if (sessionId == null || !appContextMaps.containsKey(appName))
      {
         return false;
      }
      return appContextMaps.get(appName).containsKey(sessionId);
   }

   /**
    * Deletes the security context async in a thread that is prepared with the right initial context.
    * 
    * @param    context
    *           The security context to be deleted.
    */
   private void cleanupContext(SecurityContext context)
   {
      contextCleanupExecutor.execute(() ->
                                     {
                                        SecurityContextStack.setContext(new SecurityContextStack(context));
                                        context.cleanup();
                                     });
   }
}