OsSsoAuthenticator.java

/*
 ** Module   : OsSsoAuthenticator.java
 ** Abstract : SSO authenticator implementation which accepts OS credentials and maps them to a single FWD user.
 **
 ** Copyright (c) 2025, Golden Code Development Corporation.
 **
 ** -#- -I- --Date-- ---------------------------------Description---------------------------------
 ** 001 CA  20250221 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.main.*;
import com.goldencode.p2j.main.WebDriverHandler.SupportedHttpCode;
import com.goldencode.p2j.util.*;

import javax.servlet.http.*;

import java.io.*;
import java.util.*;

/** 
 * SSO authenticator hook, which accepts OS credentials, validates them, and returns both the FWD user and
 * OS user which will be used to spawn the FWD client.
 * <p>
 * This implementation uses the {@link #defaultFwdUser} configured {@link #setOption at the SSO plugin}, for
 * the FWD client's username.  More complex implementations can expand the plugin to resolve the FWD user 
 * account which is associated with the OS user, or even create the FWD user account automatically (note that
 * this may also include ACLs).
 * <p>
 * Cookies are not used for this authenticator. 
 */
public class OsSsoAuthenticator
implements SsoAuthenticator
{
   /** The FWD user returned by default for all in-app users. */
   private String defaultFwdUser = null;

   /**
    * The FWD server creates a singleton of this plugin - read the config when is created, under the server
    * context.
    * <p>
    * Do not use driver type, as the Java class for the driver can't be initialized when the SSO plugin is
    * instantiated.
    */
   private final String spawner = ConfigItem.SPAWNER.read(null);
   
   /** The spawner folder. */
   private final File spawnerDir = new File(spawner).getAbsoluteFile().getParentFile();
   
   /**
    * Validates the POST request data against an authentication provider (DB, 3rd party directory, custom 
    * auth server, etc) and returns a container with all details needed by the FWD framework to respond to 
    * the auth request and eventually spawn a new client with the specified authorization. If the FWD SDK
    * script is used on the login page, the parameters map contains {@link #FWD_SDK_LOGIN_PARAM_USER} and
    * {@link #FWD_SDK_LOGIN_PARAM_PASS}.
    * <p>
    * This implementation authenticates the given credentials as OS credentials.  If it passes, return in the 
    * result both the configured FWD user and the entered OS user/password.
    *
    * @param    paramMap
    *           A map of all query / form params.
    * @param    cookies
    *           All cookies coming with the HTTP request.
    * @param    licensingData
    *           Data that can be used for enforcing licensing policy.
    *
    * @return   A container with all details needed by the FWD framework to spawn a new client.
    */
   @Override
   public Result authenticate(Map<String, String[]> paramMap, Cookie[] cookies, LicensingData licensingData)
   {
      if (defaultFwdUser == null)
      {
         return new Result(false, SupportedHttpCode.UNEXPECTED_ERROR, null);
      }
      
      // cookies are not used
      
      String osUser = paramMap.get(FWD_SDK_LOGIN_PARAM_USER)[0];
      String osPass = paramMap.get(FWD_SDK_LOGIN_PARAM_PASS)[0];

      SupportedHttpCode error = checkUser(osUser, osPass);
      if (error != null)
      {
         return new Result(false, error, null);
      }
      
      Result result = new Result(true, defaultFwdUser, "storage-" + osUser, null, null);
      result.setOsUser(osUser);
      result.setOsPassword(osPass);
      result.setSessionDescription("Session for end user " + osUser);
      return result;
   }
   
   /**
    * Invalidates the web session associated with the authentication cookie by communicating with the auth 
    * server or updating the DB and returns a cookie with the same name, but invalid value.
    * <p>
    * This implementation does not use cookies, so this is a no-op.
    *
    * @param    cookies
    *           The cookie to be returned to the browser and used in the next auth requests.
    *
    * @return   <code>null</code> if the web session / cookie invalidation failed, otherwise an 
    *           authentication Cookie with invalid value.
    */
   @Override
   public Cookie logout(Cookie[] cookies)
   {
      // nothing to do, cookies are not used
      return null;
   }

   /**
    * Auto-login interface. Searches for a recognizable cookie to validate the session against an 
    * authentication provider (DB, 3rd party directory, custom auth server, etc) and returns a container 
    * with all details needed by the FWD framework to respond to the auth request and eventually spawn a 
    * new client with the specified authorization. On failure,
    * {@link #authenticate(Map, Cookie[], LicensingData)} will be later called by the login page on form 
    * submission.
    * <p>
    * This implementation does not use cookies, so this is a no-op.
    * 
    * @param    cookies
    *           All cookies coming with the HTTP request for authentication.
    * @param    licensingData
    *           Data that can be used for enforcing licensing policy.
    *
    * @return   A container with all details needed by the FWD framework to spawn a new client.
    */
   @Override
   public Result authenticate(Cookie[] cookies, LicensingData licensingData)
   {
      // this needs to check the cookie value against some storage to validate it, but they are not used
      return null;
   }

   /**
    * Returns the name of the cookie used for auto-login. Enables the framework to do validation of the 
    * cookies present in the request and determine if auto-login is possible. If <code>null</code> is 
    * returned, that indicates the auto-login function is disabled.
    *
    * @return   The name of the cookie used for auto-login.
    *           This implementation does not use cookies, so <code>null</code> is returned.
    */
   @Override
   public String getAuthCookieName()
   {
      return null;
   }
   
   /**
    * Provides options configured in directory under config/auth-mode/ssopluginoption. Plain text that can 
    * contain any number of configs to be parsed by the custom implementation of the authenticator. The 
    * method is called right after the current object is instantiated, before any authentication takes place.
    * 
    * @param    option
    *           The {@link #defaultFwdUser FWD user name} which will be used by the FWD client.
    */
   @Override
   public void setOption(String option)
   {
      this.defaultFwdUser = option;
   }

   /**
    * Receives as an argument the html template loaded from the standard location in the custom package or 
    * null if no resource present.
    *
    * @param    loadedTemplate
    *           The html template loaded from the standard location in the custom root package or null.
    *
    * @return   The inflated template ready to be served as login page.
    *           This implementation returns <code>null</code>, to use the default template.
    */
   @Override
   public String getLoginPage(String loadedTemplate)
   {
      return null;
   }
   
   /**
    * Check the specified credentials if are valid as OS user/password.
    * 
    * @param    user
    *           The OS username.
    * @param    pw
    *           The OS password.
    *           
    * @return   <code>null</code> in case of success, an error code otherwise.
    */
   private SupportedHttpCode checkUser(String user, String pw)
   {
      ProcessBuilder pb = new ProcessBuilder();
      pb.directory(spawnerDir);
      pb.command(new ArrayList<String>(Arrays.asList(spawner, ClientSpawner.MODE_CREDENTIALS_CHECK, user)));
      try
      {
         Process shell = pb.start();
         // write password
         OutputStreamWriter os = new OutputStreamWriter(shell.getOutputStream());
         os.write(pw);
         os.close();
         shell.waitFor();
         int exitCode = shell.exitValue();
         return exitCode == 0 ? null : SupportedHttpCode.UNAUTHORIZED;
      }
      catch (Throwable t)
      {
         return SupportedHttpCode.UNEXPECTED_ERROR;
      }
   }
}