# LegacyServiceHandler.java

    /*
    ** Module   : LegacyServiceHandler.java
    ** Abstract : Handler for legacy service calls.
    **
    ** Copyright (c) 2019-2025, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
    ** 001 CA  20190701 Extracted from RestHandler.
    ** 002 CA  20190710 Moved the HTTP body read APIs from RequestArguments.
    ** 003 CA  20191003 If an external store is specified, we need the entry password, too.
    ** 004 CA  20200514 Added support for SOAP web services.
    **                  Mark this context as 'headless'.
    ** 005 CA  20200910 Fixed path splitting in case of multiple '//' chars.
    **     CA  20210304 The cookies must follow RFC2965.
    **     CA  20211012 Fixed generated WSDL and reworked SOAP support to rely on namespace, when resolving an
    **                  operation.
    **     CA  20211112 The worker must be aware if the appserver is in MSA mode (for error processing and other
    **                  differences between classic and multisession).
    **     CA  20211214 Extracted the worker pool to AppServerConnectionPool, to be used by the legacy java client,
    **                  too.
    **     CA  20211216 Any request while the worker pool has not yet initialized will return a 404/NOT-FOUND
    **                  status code.
    **     CA  20220104 Added custom web response headers to be specified in the directory via the
    **                  'web-response-headers' node: 'web-response-headers/default' is added first, and
    **                  'web-response-headers/[type]' is merged next
    **     CA  20220208 Mark pools which are used for the web services managed by FWD.
    **     CA  20220405 Added authentication and authorization for web requests.  When this is enabled, the target
    **                  API call will be executed under the authenticated FWD context, and not the agent's context.
    **     CA  20220509 Fixed 'getInputStream', in some cases the stream is not read properly (if is chunked).
    ** 006 GBB 20240610 LegacyAppServerWork replaced by Consumer<LegacyServiceWorker>.
    ** 007 SBI 20231206 Added getMask.
    ** 008 GBB 20250403 Added ServiceType enum.
    ** 009 RB2 20250530 Added a request parameter to all handle methods (except the authentication one). Also
    **                  added a request parameter to the prepareResponse method and modified it to handle multiple
    **                  URLs in the Access-Control-Allow-Origin field. The syntax is <URL>, <URL>, <URL> etc.
    ** 010 LS  20250606 Changed 'handle' to bypass OPTIONS requests. Added 'handleCorsPreflight'.
    */

    /*
    ** 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.main;

    import java.io.*;
    import java.util.*;
    import java.util.BitSet;
    import java.util.stream.*;
    import java.util.zip.*;

    import javax.servlet.*;
    import javax.servlet.http.*;

    import org.eclipse.jetty.http.*;
    import org.eclipse.jetty.server.*;
    import org.eclipse.jetty.server.handler.*;

    import com.goldencode.p2j.security.*;
    import com.goldencode.p2j.security.SecurityManager;
    import com.goldencode.p2j.util.*;
    import com.goldencode.p2j.util.Utils.DirScope;

    /**
     * Common APIs for processing legacy services (REST, WebHandler, etc).
     */
    public abstract class LegacyServiceHandler
    extends AbstractHandler
    {
       /** The type of the legacy service. */
       public enum ServiceType
       {
          REST("rest"),
          SOAP("soap"),
          WEB("WebHandler");

          /** The name of the type. */
          private String typeName;

          /**
           * Enum constructor.
           *
           * @param   typeName
           *          The name of the legacy service type.
           */
          ServiceType(String typeName)
          {
             this.typeName = typeName;
          }

          /**
           * Returns the string representation.
           *
           * @return   See above.
           */
          @Override
          public String toString()
          {
             return typeName;
          }
       }

       /** The base path for the service handler. */
       protected String basePath;

       /** The service type. */
       private final ServiceType type;

       /** The appserver connection pool of worker threads. */
       private final AppServerConnectionPool pool;

       /**
        * Additional response headers to add.  Configured in the <code>web-response-headers</code> directory node.
        */
       private Map<String, String> responseHeaders = null;

       /** The authentication handler, if enabled in the directory, for this web service type. */
       private WebAuthHandler authHandler;

       /**
        * Initialize this handler with the given base path.
        *
        * @param    type
        *           The service type, also name of node to get the configuration from the directory.
        * @param    basePath
        *           The implicit basepath.
        */
       public LegacyServiceHandler(ServiceType type, String basePath)
       {
          this.type = type;
          this.pool = new AppServerConnectionPool(type);
          this.basePath = basePath;

          readResponseHeaders();
       }

       /**
        * Code to process web requests.
        *
        * @param    instance
        *           The legacy service instance.
        * @param    work
        *           The work to perform the request.
        * @param    target
        *           The target path.
        * @param    response
        *           The HTTP response.
        * @param    request
        *           The HTTP request.
        */
       public static void handle(LegacyServiceHandler          instance,
                                 LegacyAppServerWork           work,
                                 String                        target,
                                 HttpServletResponse           response,
                                 HttpServletRequest            request)
       throws IOException
       {
          handle(instance, null, work, target, response, request);
       }

       /**
        * Code to process web requests.
        *
        * @param    instance
        *           The legacy service instance.
        * @param    connectionID
        *           When not-null, force to use the worker with the specified connection ID.
        * @param    work
        *           The work to perform the request.
        * @param    target
        *           The target path.
        * @param    response
        *           The HTTP response.
        * @param    request
        *           The HTTP request.
        */
       public static void handle(LegacyServiceHandler          instance,
                                 String                        connectionID,
                                 LegacyAppServerWork           work,
                                 String                        target,
                                 HttpServletResponse           response,
                                 HttpServletRequest            request)
       throws IOException
       {
          instance.prepareResponse(response, request);

          if (!instance.pool.isInitialized())
          {
             response.setStatus(HttpStatus.NOT_FOUND_404);
             return;
          }

          try
          {
             boolean ran = instance.pool.dispatch(connectionID, work, target);
             if (!ran)
             {
                response.setStatus(HttpStatus.GATEWAY_TIMEOUT_504);
             }
          }
          catch (Throwable t)
          {
             if (t instanceof IOException)
             {
                throw (IOException) t;
             }
             else if (t.getCause() instanceof IOException)
             {
                throw (IOException) t.getCause();
             }
             else
             {
                throw new IOException(t);
             }
          }
       }

       /**
        * Get the individual path entries from this path.
        *
        * @param    path
        *           The '/' separated path.
        *
        * @return   The paths.
        */
       public static String[] getPaths(String path)
       {
          if (path.startsWith("/"))
          {
             path = path.substring(1);
          }
          if (path.endsWith("/"))
          {
             path = path.substring(0, path.length() - 1);
          }

          String[] paths = path.split("/");
          paths = Arrays.asList(paths)
                        .stream()
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toList())
                        .toArray(new String[0]);
          return paths;
       }

       /**
        * Get the mask for the given path entries.
        *
        * @param    paths
        *           The given path entries.
        *
        * @return   The bit set that has the i-th 1 bit if the i-th path is not a wildcard parameter.
        */
       public static BitSet getMask(String[] paths)
       {
          int nbits = paths.length;
          BitSet mask = new BitSet(nbits);
          for(int i = 0; i < nbits; i++)
          {
             if (!paths[i].startsWith("{"))
             {
                mask.set(i);
             }
          }

          return mask;
       }

       /**
        * Red the body from a HTTP request.
        *
        * @param    request
        *           The HTTP request payload.
        *
        * @return   The body, as a byte array.
        */
       public static byte[] readBody(HttpServletRequest request)
       throws IOException
       {
          InputStream input = getInputStream(request);

          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          byte[] b = new byte[32];
          while (input.available() > 0)
          {
             int len = input.read(b);
             if (len == -1)
             {
                break;
             }

             baos.write(b, 0, len);
          }
          return baos.toByteArray();
       }

       /**
        * Get the {@link #basePath}.
        *
        * @return   See above.
        */
       public String getBasePath()
       {
          return basePath;
       }

       /**
        * Get the {@link AppServerConnectionPool#timeout}.
        *
        * @return   See above.
        */
       public int getTimeout()
       {
          return pool.getTimeout();
       }

       /**
        * Terminate the service worker threads.
        */
       public void terminateWorkers()
       {
          pool.terminateWorkers();
       }

       /**
        * Initialize the worker(s) and start them.
        */
       public void initializeHandler()
       {
          this.basePath = resolveBasePath(this.basePath);

          // read the authentication details
          SecurityManager mgr = SecurityManager.getInstance();
          boolean authEnabled = Utils.getDirectoryNodeBoolean(null, type + "/authentication/enabled", false, false);
          WebServiceResource wsr = (WebServiceResource) mgr.getPluginInstance("webservice");

          authHandler = null;
          if (authEnabled)
          {
             if (wsr == null)
             {
                throw new IllegalStateException("The authentication for " + type +
                                                " is enabled, but no WebServiceResource plugin is registered.");
             }

             String authType = Utils.getDirectoryNodeString(null, type + "/authentication/type", "basic", false);
             int timeout = Utils.getDirectoryNodeInt(null, type + "/authentication/timeout", 0, false);
             String loginPath = Utils.getDirectoryNodeString(null, type + "/authentication/login_path",
                                                             null, false);
             String logoutPath = null;
             if (loginPath != null)
             {
                logoutPath = Utils.getDirectoryNodeString(null, type + "/authentication/logout_path",
                                                          "/fwdlogout", false);
             }
             else if (timeout != 0)
             {
                throw new IllegalStateException("For " + type + ", if the login path is not set, then timeout " +
                                                "must be set to zero, and authentication will be performed for " +
                                                "each API call.");
             }

             // filters can be registered only with webapp's (WebAppContext).  for legacy services, we are using
             // ContextHandler; for this reason, an auth handler is used.
             authHandler = new WebAuthHandler(type.toString(), authType, loginPath, logoutPath, timeout);
          }

          pool.initialize();
       }

       /**
        * Process web requests:
        * <ul>
        *    <li>
        *       If it is an {@link HttpMethod#OPTIONS OPTIONS} request, handle it accordingly.
        *    </li>
        *    <li>
        *       Otherwise, if {@link #authHandler authorization} is enabled, this will authenicate the
        *       request.  The {@link #authorize authorization} will be responsible of creating the FWD context and
        *       returning the token for this web request.
        *    </li>
        *
        * @param    target
        *           The target path.
        * @param    baseRequest
        *           The base request.
        * @param    request
        *           The HTTP request.
        * @param    response
        *           The HTTP response.
        */
       @Override
       public void handle(String              target,
                          Request             baseRequest,
                          HttpServletRequest  request,
                          HttpServletResponse response)
       throws IOException
       {
          // respond to CORS preflight OPTIONS requests without authentication or further processing
          if (request.getMethod().equals(HttpMethod.OPTIONS.name()))
          {
             handleCorsPreflight(baseRequest, request, response);
          }
          else if (authHandler != null)
          {
             // this part handles only the authentication; the authorization is done later in the process
             authHandler.handle(target, baseRequest, request, response);
          }
       }

       /**
        * Contains any post {@link #handle} code to be executed after the service request has been invoked.
        *
        * @param    token
        *           When set, the web service token used to authenticate and authorize this request.
        */
       protected void postHandle(String token)
       {
          if (authHandler != null)
          {
             // if the login API path is not used, perform the logout
             authHandler.postHandle(token);
          }
       }

       /**
        * Check if the authentication and authorization is enabled for this web service type.
        *
        * @return   <code>true</code> if {@link #authHandler} exists.
        */
       protected boolean useAuthorization()
       {
          return authHandler != null;
       }

       /**
        * If {@link #useAuthorization() authorization is enabled}, perform the
        * {@link WebAuthHandler#authorize authorization} to check if the request configuration is allowed to
        * access this API.
        *
        * @param    target
        *           The target path.
        * @param    request
        *           The HTTP request.
        * @param    response
        *           The HTTP response.
        *
        * @return   If authorization is enabled, it will return the token associated with this service request.
        */
       protected String authorize(String target, HttpServletRequest request, HttpServletResponse response)
       {
          if (authHandler != null)
          {
             // this will return the token used for this API request
             return authHandler.authorize(target, request, response);
          }

          return null;
       }

       /**
        * Resolve the configured basepath for this handler.
        *
        * @param    basePath
        *           The default base path.
        *
        * @return   The configured base path from the directory.
        */
       protected String resolveBasePath(String basePath)
       {
          basePath = Utils.getDirectoryNodeString(null, type + "/basepath", basePath, false);
          if (basePath.isEmpty() || basePath.equals("/"))
          {
             throw new RuntimeException("Invalid " + type + " base path: [" + basePath + "]");
          }

          if (!basePath.startsWith("/"))
          {
             basePath = "/" + basePath;
          }
          if (!basePath.endsWith("/"))
          {
             basePath = basePath + "/";
          }

          return basePath;
       }

       /**
        * Get the service handler's {@link #type}.
        *
        * @return   The service type.
        */
       protected String getType()
       {
          return type.toString();
       }

       /**
        * Handles a CORS preflight (HTTP OPTIONS) request by validating the request origin
        * against the configured CORS policy and setting the appropriate HTTP response status.
        * <p>
        * If the request origin matches the value set in the {@code Access-Control-Allow-Origin}
        * response header, a {@code 204 No Content} status is returned.
        * Otherwise, a {@code 403 Forbidden} status is returned to deny the request.
        * </p>
        *
        * @param    baseRequest
        *           The base request.
        * @param    request
        *           The HTTP request.
        * @param    response
        *           The HTTP response.
        */
       private void handleCorsPreflight(Request baseRequest,
                                        HttpServletRequest request,
                                        HttpServletResponse response)
       {
          prepareResponse(response, request);

          String requestOrigin = request.getHeader("Origin");
          String responseOrigin = response.getHeader("Access-Control-Allow-Origin");
          if (requestOrigin != null && requestOrigin.equals(responseOrigin))
          {
             response.setStatus(HttpStatus.NO_CONTENT_204);
          }
          else
          {
             response.setStatus(HttpStatus.FORBIDDEN_403);
          }
          baseRequest.setHandled(true);
       }

       /**
        * Read any custom response headers configured in the directory.  The building is done by first reading
        * from the <code>web-response-headers/default</code>, and after that overwriting/merging the ones from
        * <code>web-response-headers/{@link #type}</code>.
        */
       private void readResponseHeaders()
       {
          List<String> defaults = Utils.getDirectoryNodeStrings(null, "web-response-headers/default",
                                                                DirScope.BOTH, null);
          List<String> custom = Utils.getDirectoryNodeStrings(null, "web-response-headers/" + type,
                                                              DirScope.BOTH, null);

          if (defaults.isEmpty() && custom.isEmpty())
          {
             return;
          }

          responseHeaders = new HashMap<>();
          for (String h : defaults)
          {
             String[] pair = parseHeader(h);
             responseHeaders.put(pair[0], pair[1]);
          }
          for (String h: custom)
          {
             String[] pair = parseHeader(h);
             responseHeaders.put(pair[0], pair[1]);
          }
       }

       /**
        * Parse a header string, in the <code>name: value</code> format, and return its header name and value.
        *
        * @param    h
        *           The string to parse.
        *
        * @return   See above.
        */
       private String[] parseHeader(String h)
       {
          String split = ": ";
          int idx = h.indexOf(split);
          if (idx == -1)
          {
             throw new IllegalArgumentException("Web response header " + h + " can't be parsed!");
          }

          String name = h.substring(0, idx);
          String value = h.substring(idx + split.length());

          return new String[] { name, value };
       }

       /**
        * Prepare the HTTP response with any custom settings or headers.
        *
        * @param    response
        *           The HTTP response.
        * @param    request
        *           The HTTP request.
        */
       private void prepareResponse(HttpServletResponse response,
                                    HttpServletRequest  request)
       {
          ((Response) response).getHttpChannel()
                               .getHttpConfiguration()
                               .setResponseCookieCompliance(CookieCompliance.RFC2965);

          if (responseHeaders != null)
          {
             String origin = request.getHeader("Origin");
             for (Map.Entry<String, String> header : responseHeaders.entrySet())
             {
                // The Access-Control-Allow-Origin header is documented to be case-insensitive
                if ("Access-Control-Allow-Origin".equalsIgnoreCase(header.getKey()))
                {
                   if (header.getValue().equals("null"))
                   {
                      continue;
                   }
                   else if (header.getValue().equals(origin))
                   {
                      response.addHeader(header.getKey(), header.getValue());
                      continue;
                   }
                   else
                   {
                      if (header.getValue().equals("*"))
                      {
                         response.addHeader(header.getKey(), origin);
                      }
                      else if (origin != null)
                      {
                         String[] allowedOrigins = header.getValue().split(",\\s+");
                         for (String allowed : allowedOrigins)
                         {
                            if (origin.equals(allowed.trim()))
                            {
                               response.addHeader(header.getKey(), origin);
                               break;
                            }
                         }
                      }
                   }
                }
                else
                {
                   response.addHeader(header.getKey(), header.getValue());
                }
             }
          }
       }

       /**
        * Get the input stream to read the request's body.
        * <p>
        * Depending on the 'Content-Encoding', a different stream will read it.
        *
        * @param    request
        *           The HTTP request.
        *
        * @return   The request body's input stream.
        */
       private static InputStream getInputStream(HttpServletRequest request)
       throws IOException
       {
          String encoding = request.getHeader("Content-Encoding");
          if (encoding == null || encoding.isEmpty())
          {
             ByteArrayOutputStream baos = new ByteArrayOutputStream();

             ServletInputStream input = request.getInputStream();
             byte[] b = new byte[32];
             while (!input.isFinished())
             {
                int len = input.read(b);
                if (len == -1)
                {
                   break;
                }

                baos.write(b, 0, len);
             }

             return new ByteArrayInputStream(baos.toByteArray());
          }
          else if (encoding.equals("gzip,deflate") || encoding.equals("gzip"))
          {
             return new GZIPInputStream(request.getInputStream());
          }

          throw new IOException("Unknown encoding: " + encoding);
       }
    }