From d025ac30b9c65a19535c7d6955b084960b4d0621 Mon Sep 17 00:00:00 2001 From: lalber Date: Mon, 8 Mar 2021 18:27:55 +0100 Subject: First version of feature --- .../impl/idp/auth/services/ErrorTicketService.java | 212 ++++++++++++++ .../services/ProtocolAuthenticationService.java | 306 +++++++++------------ .../controller/ProtocolFinalizationController.java | 84 +++++- .../services/IProtocolAuthenticationService.java | 11 +- 4 files changed, 415 insertions(+), 198 deletions(-) create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java new file mode 100644 index 00000000..c5bac225 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -0,0 +1,212 @@ +package at.gv.egiz.eaaf.core.impl.idp.auth.services; + +import at.gv.egiz.eaaf.core.api.IStatusMessenger; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.controller.ProtocolFinalizationController; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; +import lombok.Getter; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +@Service() +public class ErrorTicketService { + private static final Logger log = LoggerFactory.getLogger(ErrorTicketService.class); + + private static final String CONFIG_PROP_ERRORHANDLING_ACTION_PATH = "core.errorhandling.action"; + private static final String TECH_LOG_MSG = "errorCode={} Message={}"; + private static final String TICKET_LOG_MSG = "Ticket={} errorCode={} Message={}"; + + private final HashMap propertyMap = new HashMap(); + + + public enum ActionType { + TICKET_REDIRECT("ticket_redirect"), TICKET_NOREDIRECT("ticket_noredirect"), NOTICKET_REDIRECT( + "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"); + + private final String name; + + ActionType(final String text) { + this.name = text; + } + + @Override + public String toString() { + return name; + } + } + + @Autowired(required = true) + IConfiguration basicConfig; + @Autowired(required = true) + ResourceLoader resourceLoader; + + @PostConstruct + private void initialize() throws EaafException { + log.info("initErrorTicketService"); + + final String ticketConfPath = basicConfig.getBasicConfiguration(CONFIG_PROP_ERRORHANDLING_ACTION_PATH); + log.info("ticketConfPath" + ticketConfPath); + + + if (StringUtils.isEmpty(ticketConfPath)) { + log.error("Error: Path to errorhandling action configuration not known"); + throw new EaafException("Error: Path to errorhandling action configuration not known"); + } else { + + Properties getProperties = new Properties(); + try { + + final String fullFilePath = FileUtils + .makeAbsoluteUrl(ticketConfPath, basicConfig.getConfigurationRootDirectory()); + final Resource ressource = resourceLoader.getResource(fullFilePath); + final InputStream is = ressource.getInputStream(); + getProperties.load(is); + is.close(); + propertyMap.putAll((Map) getProperties); + + // log.error(propertyMap.toString()); + // log.error("working: " + propertyMap.get("auth.00")); + + } catch (Exception e) { + log.error("Error: something went wrong"); + throw new EaafException("Error: Parsing errorhandling actions failed"); + } + } + } + + public HandleData createHandleData(Throwable throwable, HttpServletRequest req) { + HandleData data = new HandleData(throwable, req); + extractErrorCode(data); + setUpErrorData(data); + + return data; + } + + private void extractErrorCode(HandleData data) { + Throwable originalException; + if (data.throwable instanceof TaskExecutionException + && ((TaskExecutionException) data.throwable).getOriginalException() != null) { + originalException = ((TaskExecutionException) data.throwable).getOriginalException(); + + } else { + originalException = data.throwable; + + } + + if (!(originalException instanceof EaafException)) { + data.errorCode = IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC; + + } else { + data.errorCode = ((EaafException) originalException).getErrorId(); + + } + } + + private void setUpErrorData(HandleData data) { + + if (propertyMap.containsKey(data.errorCode)) { + String action = propertyMap.get(data.errorCode); + + if (action.equals(ActionType.TICKET_REDIRECT.toString())) { + data.actionType = ActionType.TICKET_REDIRECT; + data.generateSupportTicket(); + data.generateRedirect(); + + } else if (action.equals(ActionType.TICKET_NOREDIRECT.toString())) { + data.actionType = ActionType.TICKET_NOREDIRECT; + data.generateSupportTicket(); + + } else if (action.equals(ActionType.NOTICKET_REDIRECT.toString())) { + data.actionType = ActionType.NOTICKET_REDIRECT; + data.generateRedirect(); + + } else {// ActionType.NOTICKET_NOREDIRECT -> nothing to be done + data.actionType = ActionType.NOTICKET_NOREDIRECT; + + } + + } else { + data.generateSupportTicket(); + // TODO log with ticket gernal internal error + } + } + + public class HandleData { + private final HttpServletRequest req; + @Getter private String supportTicket; + @Getter private String redirectUrl; + @Getter private final Throwable throwable; + @Getter private String errorCode; + @Getter private ActionType actionType; + + + private HandleData(Throwable throwable, HttpServletRequest req) { + this.throwable = throwable; + this.req = req; + } + + private void generateRedirect() { + redirectUrl = ServletUtils.getBaseUrl(req); + redirectUrl += "/" + ProtocolFinalizationController.ENDPOINT_ERROR_REDIRECT + + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + + StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE));; + + } + + private void generateSupportTicket() { + + String randomCode = RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + + RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + + RandomStringUtils.randomAlphanumeric(4).toUpperCase(); + supportTicket = randomCode; + } + + public void log_error() { + + if (supportTicket != null) { + log.error(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), + throwable); + } else { + log.error(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); + } + } + + public void log_info() { + + if (supportTicket != null) { + log.info(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); + + } else { + log.info(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); + } + } + + public void log_warn() { + + if (supportTicket != null) { + log.warn(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); + + } else { + log.warn(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); + } + } + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 925d6fe2..9b7fcce4 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -15,30 +15,10 @@ * This product combines work with different licenses. See the "NOTICE" text file for details on the * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative * works that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.gv.egiz.eaaf.core.impl.idp.auth.services; -import java.io.IOException; -import java.util.HashSet; - -import javax.annotation.PostConstruct; -import javax.naming.ConfigurationException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.StringEscapeUtils; -import org.owasp.encoder.Encode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.lang.NonNull; -import org.springframework.lang.Nullable; -import org.springframework.stereotype.Service; - import at.gv.egiz.components.eventlog.api.EventConstants; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; @@ -52,7 +32,6 @@ import at.gv.egiz.eaaf.core.api.idp.IAction; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.idp.IAuthenticationDataBuilder; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.IModulInfo; import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; import at.gv.egiz.eaaf.core.api.idp.auth.ISsoManager; @@ -69,7 +48,6 @@ import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.exceptions.ProtocolNotActiveException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.gui.AbstractGuiFormBuilderConfiguration; import at.gv.egiz.eaaf.core.impl.http.HttpUtils; @@ -77,14 +55,30 @@ import at.gv.egiz.eaaf.core.impl.idp.controller.ProtocolFinalizationController; import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.owasp.encoder.Encode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.naming.ConfigurationException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.HashSet; @Service public class ProtocolAuthenticationService implements IProtocolAuthenticationService { private static final Logger log = LoggerFactory.getLogger(ProtocolAuthenticationService.class); - private static final String CONFIG_PROP_LOGGER_ON_INFO_LEVEL = - "core.logging.level.info.errorcodes"; - private static final String TECH_LOG_MSG = "errorCode={} Message={}"; + private static final String CONFIG_PROP_LOGGER_ON_INFO_LEVEL = "core.logging.level.info.errorcodes"; @Autowired(required = true) private ApplicationContext applicationContext; @@ -100,7 +94,11 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer private IRequestStorage requestStorage; @Autowired(required = true) IPendingRequestIdGenerationStrategy pendingReqIdGenerationStrategy; - @Autowired private IConfiguration basicConfig; + @Autowired + private IConfiguration basicConfig; + + @Autowired(required = true) + private ErrorTicketService errorTicketService; @Autowired(required = false) private ISsoManager ssoManager; @@ -136,9 +134,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer final ISpConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); if (oaParam == null) { - throw new EaafAuthenticationException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOSPCONFIG, - new Object[] { pendingReq.getSpEntityId() }); + throw new EaafAuthenticationException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOSPCONFIG, + new Object[]{pendingReq.getSpEntityId()}); } if (authmanager.doAuthentication(req, resp, pendingReq)) { @@ -148,8 +145,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer finalizeAuthentication(req, resp, pendingReq); // transaction is finished, log transaction finished event - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, - pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); } @@ -183,9 +179,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer if (pendingReq.isAbortedByUser()) { // send authentication aborted error to Service Provider buildProtocolSpecificErrorResponse( - new EaafAuthenticationException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_USERSTOP, - new Object[] {}), - req, resp, pendingReq); + new EaafAuthenticationException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_USERSTOP, new Object[]{}), req, + resp, pendingReq); // check if pending-request are authenticated } else if (pendingReq.isAuthenticated() && !pendingReq.isNeedUserConsent()) { @@ -193,12 +188,11 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } else { // suspect state: pending-request is not aborted but also are not authenticated - log.warn("PendingRequest flag for 'authenticated':{} and 'needConsent':{}", - pendingReq.isAuthenticated(), pendingReq.isNeedUserConsent()); + log.warn("PendingRequest flag for 'authenticated':{} and 'needConsent':{}", pendingReq.isAuthenticated(), + pendingReq.isNeedUserConsent()); if (pendingReq.isNeedUserConsent()) { - log.error( - "PendingRequest NEEDS user-consent. " - + "Can NOT fininalize authentication --> Abort authentication process!"); + log.error("PendingRequest NEEDS user-consent. " + + "Can NOT fininalize authentication --> Abort authentication process!"); } else { log.error("PendingRequest is NOT authenticated --> Abort authentication process!"); @@ -216,44 +210,34 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } finally { // remove pending-request requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, - pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); } } + @Override - public void buildProtocolSpecificErrorResponse(final Throwable throwable, - final HttpServletRequest req, final HttpServletResponse resp, final IRequest protocolRequest) - throws EaafException, IOException { + public void buildProtocolSpecificErrorResponse(final Throwable throwable, final HttpServletRequest req, + final HttpServletResponse resp, final IRequest protocolRequest) throws EaafException, IOException { try { - final Class clazz = Class.forName(protocolRequest.requestedModule()); + ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { - log.error( - "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - throw new ClassCastException( - "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - - } - final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT) || + errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { - if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { + displayException(req, resp, errorData); // log Error to technical log - logExceptionToTechnicalLog(throwable); + logExceptionToTechnicalLog(errorData); // log Error Message statisticLogger.logErrorOperation(throwable, protocolRequest); - // write revision log entries - revisionsLogger.logEvent(protocolRequest, EventConstants.TRANSACTION_ERROR, - protocolRequest.getUniqueTransactionIdentifier()); } else { - handleErrorNoRedirect(throwable, req, resp, true); + throw throwable; //through it on to handleErrorNoRedirect } @@ -266,8 +250,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer @Override public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, - final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) - throws IOException, EaafException { + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) throws IOException, EaafException { + + ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); // log Exception into statistic database if (writeExceptionToStatisticLog) { @@ -275,30 +260,17 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } // write errror to console - logExceptionToTechnicalLog(throwable); + logExceptionToTechnicalLog(errorData); // return error to Web browser - if (throwable instanceof EaafException || throwable instanceof ProcessExecutionException) { - internalMoaidExceptionHandler(req, resp, (Exception) throwable, false); - - } else { - // write generic message for general exceptions - final String msg = - statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); - final String internalErrorCode = statusMessager.getResponseErrorCode(throwable); - - writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); - - } - + displayException(req, resp, errorData); } @Override public void forwardToErrorHandler(Pair errorToHandle, String errorKey, final HttpServletRequest req, final HttpServletResponse resp) throws GuiBuildException { - final IGuiBuilderConfiguration parentHopGuiConfig = - evaluateRequiredErrorHandlingMethod(errorToHandle.getFirst(), errorKey); + final IGuiBuilderConfiguration parentHopGuiConfig = evaluateRequiredErrorHandlingMethod(errorToHandle.getFirst(), + errorKey); if (parentHopGuiConfig != null) { log.trace("iFrame to parent hop requested. Building GUI step for error handling ... "); guiBuilder.build(req, resp, parentHopGuiConfig, "iFrame-to-parent"); @@ -321,15 +293,13 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer /** * Finalize the requested protocol operation. * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @param moaSession MOASession object, which is used to generate the - * protocol specific authentication information + * @param req HttpServletRequest + * @param resp HttpServletResponse + * @param pendingReq Authentication request which is actually in process * @throws Exception In case of an error */ - protected void internalFinalizeAuthenticationProcess(final HttpServletRequest req, - final HttpServletResponse resp, final IRequest pendingReq) throws Exception { + protected void internalFinalizeAuthenticationProcess(final HttpServletRequest req, final HttpServletResponse resp, + final IRequest pendingReq) throws Exception { String newSsoSessionId = null; @@ -351,8 +321,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer final IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq); // execute the protocol-specific action - final SloInformationInterface sloInformation = - executeProtocolSpecificAction(req, resp, pendingReq, authData); + final SloInformationInterface sloInformation = executeProtocolSpecificAction(req, resp, pendingReq, authData); // Store OA specific SSO session information if an SSO cookie is set if (StringUtils.isNotEmpty(newSsoSessionId)) { @@ -372,52 +341,42 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } // Advanced statistic logging - statisticLogger.logSuccessOperation(pendingReq, authData, - StringUtils.isNotEmpty(newSsoSessionId)); + statisticLogger.logSuccessOperation(pendingReq, authData, StringUtils.isNotEmpty(newSsoSessionId)); } /** * Write a Exception to the MOA-ID-Auth internal technical log. * - * @param loggedException Exception to log + * @param data errordata structure */ - protected void logExceptionToTechnicalLog(final Throwable loggedException) { + protected void logExceptionToTechnicalLog(ErrorTicketService.HandleData data) { // In case of a TaskExecutionException, which is only a container for process-errors, - // extract internal exception - Throwable toLog; - if (loggedException instanceof TaskExecutionException - && ((TaskExecutionException)loggedException).getOriginalException() != null) { - toLog = ((TaskExecutionException)loggedException).getOriginalException(); - - } else { - toLog = loggedException; - - } + // extract internal exception + // Log exception - if (!(toLog instanceof EaafException)) { - log.error(TECH_LOG_MSG, IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, - toLog.getMessage(), toLog); + if (!(data.getThrowable() instanceof EaafException)) { + data.log_error(); - } else { - if (logOnInfoLevel.contains(((EaafException) toLog).getErrorId())) { - log.info(TECH_LOG_MSG, ((EaafException) toLog).getErrorId(), - toLog.getMessage(), toLog); + } else { + + if (logOnInfoLevel.contains(data.getErrorCode())) { + data.log_info(); } else { - log.warn(TECH_LOG_MSG, ((EaafException) toLog).getErrorId(), - toLog.getMessage(), toLog); + data.log_warn(); } } } + @PostConstruct private void initializer() { log.trace("Initializing {} ...", ProtocolAuthenticationService.class.getName()); - logOnInfoLevel.addAll(KeyValueUtils.getListOfCsvValues( - basicConfig.getBasicConfiguration(CONFIG_PROP_LOGGER_ON_INFO_LEVEL))); + logOnInfoLevel + .addAll(KeyValueUtils.getListOfCsvValues(basicConfig.getBasicConfiguration(CONFIG_PROP_LOGGER_ON_INFO_LEVEL))); log.info("Set errorCodes={} to LogLevel:INFO", String.join(",", logOnInfoLevel)); } @@ -425,24 +384,20 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer /** * Executes the requested protocol action. * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @param authData Service-provider specific authentication data - * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param pendingReq Authentication request which is actually in process + * @param authData Service-provider specific authentication data * @return Return Single LogOut information or null if protocol supports no SSO - * * @throws Exception in case of an error */ private SloInformationInterface executeProtocolSpecificAction(final HttpServletRequest httpReq, - final HttpServletResponse httpResp, final IRequest pendingReq, final IAuthData authData) - throws Exception { + final HttpServletResponse httpResp, final IRequest pendingReq, final IAuthData authData) throws Exception { try { // request needs no authentication --> start request processing final Class clazz = Class.forName(pendingReq.requestedAction()); if (clazz == null || !IAction.class.isAssignableFrom(clazz)) { - log.error( - "Requested protocol-action processing Class is NULL or does not implement the IAction interface."); + log.error("Requested protocol-action processing Class is NULL or does not implement the IAction interface."); throw new ClassCastException( "Requested protocol-action processing Class is NULL or does not implement the IAction interface."); @@ -452,25 +407,31 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer return protocolAction.processRequest(pendingReq, httpReq, httpResp, authData); } catch (final ClassNotFoundException e) { - log.error( - "Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); + log.error("Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); throw new ClassNotFoundException( "Requested Auth. protocol processing Class is NULL or does not implement the IAction interface.", e); } } - private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, - @NonNull final HttpServletResponse httpResp, @NonNull final String msg, - @NonNull final String errorCode, @Nullable final Object[] params, String externalErrorCode) throws EaafException { + +// private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, +// @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, +// @Nullable final Object[] params, String externalErrorCode) throws EaafException { +// this.writeHtmlErrorResponse(httpReq, httpResp, msg, errorCode, params, externalErrorCode, null, null); +// } + + public void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, + @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, + @Nullable final Object[] params, String externalErrorCode, String url, String ticket) throws EaafException { try { - final IGuiBuilderConfiguration config = - guiConfigFactory.getDefaultErrorGui(HttpUtils.extractAuthUrlFromRequest(httpReq)); + final IGuiBuilderConfiguration config = guiConfigFactory + .getDefaultErrorGui(HttpUtils.extractAuthUrlFromRequest(httpReq)); String[] errorCodeParams = null; if (params == null) { - errorCodeParams = new String[] {}; + errorCodeParams = new String[]{}; } else { errorCodeParams = new String[params.length]; for (int i = 0; i < params.length; i++) { @@ -485,20 +446,18 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // add errorcode and errormessage if (config instanceof ModifyableGuiBuilderConfiguration) { - ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( - AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); - ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( - AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); - ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( - AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, - externalErrorCode); - ((ModifyableGuiBuilderConfiguration) config).putCustomParameterWithOutEscaption( - AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODEPARAMS, - ArrayUtils.toString(errorCodeParams)); + ModifyableGuiBuilderConfiguration c = ((ModifyableGuiBuilderConfiguration) config); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, + externalErrorCode); + c.putCustomParameterWithOutEscaption(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, + PARAM_GUI_ERRORCODEPARAMS, ArrayUtils.toString(errorCodeParams)); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_TICKET, ticket); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_REDIRECT, url); } else { - log.info( - "Can not ADD error message, because 'GUIBuilderConfiguration' is not modifieable "); + log.info("Can not ADD error message, because 'GUIBuilderConfiguration' is not modifieable "); } guiBuilder.build(httpReq, httpResp, config, "Error-Message"); @@ -511,68 +470,57 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } - private void internalMoaidExceptionHandler(final HttpServletRequest req, - final HttpServletResponse resp, final Exception e, final boolean writeExceptionToStatisicLog) - throws IOException, EaafException { - final String internalErrorCode = statusMessager.getResponseErrorCode(e); - + private void displayException(final HttpServletRequest req, final HttpServletResponse resp, + final ErrorTicketService.HandleData errorData) + throws IOException, EaafException { + final Throwable e = errorData.getThrowable(); + final String internalErrorCode = errorData.getErrorCode(); + + // send error response if (e instanceof ProtocolNotActiveException) { resp.getWriter().write(Encode.forHtml(e.getMessage())); resp.setContentType(EaafConstants.CONTENTTYPE_HTML_UTF8); resp.sendError(HttpServletResponse.SC_FORBIDDEN, StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(e.getMessage()))); - } else if (e instanceof AuthnRequestValidatorException) { - final AuthnRequestValidatorException ex = (AuthnRequestValidatorException) e; - // log Error Message - if (writeExceptionToStatisicLog) { - statisticLogger.logErrorOperation(ex, ex.getErrorRequest()); - } - + } else if (e instanceof AuthnRequestValidatorException || e instanceof InvalidProtocolRequestException || + e instanceof ProcessExecutionException || e instanceof ConfigurationException) { // write error message writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); - - } else if (e instanceof InvalidProtocolRequestException) { - // send error response - writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); - - } else if (e instanceof ConfigurationException) { - // send HTML formated error message - writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), + errorData.getSupportTicket()); } else if (e instanceof EaafException) { // send HTML formated error message - writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, - ((EaafException) e).getParams(), statusMessager.mapInternalErrorToExternalError(internalErrorCode)); + writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, ((EaafException) e).getParams(), + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), + errorData.getSupportTicket()); - } else if (e instanceof ProcessExecutionException) { - // send HTML formated error message - writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); + } else { + // write generic message for general exceptions + final String msg = statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); + writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), + errorData.getSupportTicket()); } - } private IGuiBuilderConfiguration evaluateRequiredErrorHandlingMethod(IRequest first, String errorId) { if (first != null && first.isProcessInIframe()) { - return guiConfigFactory.getDefaultIFrameParentHopGui(first, - "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING, - errorId); + return guiConfigFactory + .getDefaultIFrameParentHopGui(first, "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING, errorId); } - return null; } private String generateErrorRedirectUrl(final HttpServletRequest req, String errorKey) { String redirectUrl = null; redirectUrl = ServletUtils.getBaseUrl(req); - redirectUrl += "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" - + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + errorKey; + redirectUrl += + "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + + errorKey; return redirectUrl; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index 4ff41836..f0be9a5e 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -19,20 +19,6 @@ package at.gv.egiz.eaaf.core.impl.idp.controller; -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.util.SerializationUtils; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - import at.gv.egiz.components.eventlog.api.EventConstants; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; @@ -42,6 +28,18 @@ import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.util.SerializationUtils; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; /** * Protocol finialization end-point. @@ -54,11 +52,68 @@ public class ProtocolFinalizationController extends AbstractController { private static final Logger log = LoggerFactory.getLogger(ProtocolFinalizationController.class); public static final String ENDPOINT_FINALIZEPROTOCOL = "finalizeAuthProtocol"; public static final String ENDPOINT_ERRORHANDLING = "errorHandling"; + public static final String ENDPOINT_ERROR_REDIRECT = "errorRedirect"; @Autowired(required = true) IRequestStorage requestStorage; @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + @RequestMapping(value = ENDPOINT_ERROR_REDIRECT, method = { RequestMethod.GET, RequestMethod.POST }) + public void errorRedirect(final HttpServletRequest req, final HttpServletResponse resp) + throws EaafException, IOException { + + final String errorToken = + StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + if (errorToken != null) { + IRequest pendingReq = null; + try { + String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(errorToken); + log.debug("Searching exception with internal error-token: {}", errorId); + + // load stored exception from database + final byte[] containerSerialized = transactionStorage.get(errorId, byte[].class); + if (containerSerialized != null) { + // remove exception if it was found + transactionStorage.remove(errorId); + log.trace("Find exception with internal error-token: {}", errorId); + + //final Object containerObj = EaafSerializationUtils.deserialize(containerSerialized, + // Arrays.asList( + // ExceptionContainer.class.getName() + // )); + final Object containerObj = SerializationUtils.deserialize(containerSerialized); + + if (containerObj instanceof ExceptionContainer) { + final ExceptionContainer container = (ExceptionContainer) containerObj; + final Throwable throwable = container.getExceptionThrown(); + pendingReq = container.getPendingRequest(); + + if (pendingReq != null) { + + } + } + } + } catch (Exception e) { + } + } + + //TODO finish +// final Class clazz = Class.forName(req.requestedModule()); +// +// if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { +// log.error( +// "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); +// throw new ClassCastException( +// "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); +// +// } +// +// final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); +// +// handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest); + + } + /** * End-Point to handle errors. * @@ -67,6 +122,7 @@ public class ProtocolFinalizationController extends AbstractController { * @throws EaafException In case of an internal error * @throws IOException In case of a servlet error */ + // TODO reuse for the redirection to SP or own enpoint @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = { RequestMethod.GET, RequestMethod.POST }) public void errorHandling(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java index 6580fa30..7387f706 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java @@ -19,17 +19,16 @@ package at.gv.egiz.eaaf.core.api.idp.auth.services; -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; import at.gv.egiz.eaaf.core.impl.data.Pair; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + public interface IProtocolAuthenticationService { String PARAM_GUI_ERROMSG = "errorMsg"; @@ -37,6 +36,8 @@ public interface IProtocolAuthenticationService { String PARAM_GUI_EXTERNAL_ERRORCODE = "extErrorCode"; String PARAM_GUI_ERRORCODEPARAMS = "errorParams"; String PARAM_GUI_ERRORSTACKTRACE = "stacktrace"; + String PARAM_GUI_TICKET = "supportTicket"; + String PARAM_GUI_REDIRECT = "redirectLink"; /** * Initialize an authentication process for this protocol request. -- cgit v1.2.3 From 74db625dddb157781963d798942ca1d87b09e300 Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Tue, 9 Mar 2021 18:01:22 +0100 Subject: refactor SL20EidDataValidationException to optimize error handling --- .../sl20/exceptions/SL20EidDataValidationException.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20EidDataValidationException.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20EidDataValidationException.java index 027501bd..f0d993ca 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20EidDataValidationException.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20EidDataValidationException.java @@ -5,12 +5,22 @@ public class SL20EidDataValidationException extends SL20Exception { private static final long serialVersionUID = -2604130523926584663L; public SL20EidDataValidationException(final Object[] parameters) { - super("sl20.07", parameters); + this("99", parameters); } - + public SL20EidDataValidationException(final Object[] parameters, final Throwable e) { - super("sl20.07", parameters, e); + this("99", parameters, e); + + } + + public SL20EidDataValidationException(final String subErrorId, final Object[] parameters) { + super("sl20.07." + subErrorId, parameters); + + } + + public SL20EidDataValidationException(final String subErrorId, final Object[] parameters, final Throwable e) { + super("sl20.07." + subErrorId, parameters, e); } -- cgit v1.2.3 From b8119f581482297d3142d2a4c6b0405a15afaa26 Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 10 Mar 2021 10:24:40 +0100 Subject: Second version of feature --- .../services/ProtocolAuthenticationService.java | 17 ++++ .../controller/ProtocolFinalizationController.java | 107 +++++++++++---------- 2 files changed, 71 insertions(+), 53 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 9b7fcce4..63e84dcb 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -24,6 +24,7 @@ import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.IStatusMessenger; import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfiguration; import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfigurationFactory; import at.gv.egiz.eaaf.core.api.gui.IGuiFormBuilder; @@ -39,6 +40,7 @@ import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; @@ -66,6 +68,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; import org.springframework.stereotype.Service; +import org.springframework.util.SerializationUtils; import javax.annotation.PostConstruct; import javax.naming.ConfigurationException; @@ -107,6 +110,12 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer @Autowired private IRevisionLogger revisionsLogger; + @Autowired(required = true) + protected ITransactionStorage transactionStorage; + + @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + + private IGuiFormBuilder guiBuilder; private final HashSet logOnInfoLevel = new HashSet<>(); @@ -229,6 +238,14 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer displayException(req, resp, errorData); + // Put pending request + ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); + byte[] serialized = SerializationUtils.serialize(exceptionContainer); +// transactionStorage.put(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE), serialized, -1); + String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + transactionStorage.put(errorId, serialized, -1); + + // log Error to technical log logExceptionToTechnicalLog(errorData); diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index f0be9a5e..37aab8df 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -15,7 +15,7 @@ * This product combines work with different licenses. See the "NOTICE" text file for details on the * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative * works that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.gv.egiz.eaaf.core.impl.idp.controller; @@ -25,6 +25,7 @@ import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.IStatusMessenger; import at.gv.egiz.eaaf.core.api.data.EaafConstants; import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; +import at.gv.egiz.eaaf.core.api.idp.IModulInfo; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; @@ -45,7 +46,6 @@ import java.io.IOException; * Protocol finialization end-point. * * @author tlenz - * */ @Controller public class ProtocolFinalizationController extends AbstractController { @@ -56,14 +56,14 @@ public class ProtocolFinalizationController extends AbstractController { @Autowired(required = true) IRequestStorage requestStorage; - @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + @Autowired + IPendingRequestIdGenerationStrategy requestIdValidationStragegy; - @RequestMapping(value = ENDPOINT_ERROR_REDIRECT, method = { RequestMethod.GET, RequestMethod.POST }) + @RequestMapping(value = ENDPOINT_ERROR_REDIRECT, method = {RequestMethod.GET, RequestMethod.POST}) public void errorRedirect(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { - final String errorToken = - StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + final String errorToken = StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); if (errorToken != null) { IRequest pendingReq = null; try { @@ -89,29 +89,34 @@ public class ProtocolFinalizationController extends AbstractController { pendingReq = container.getPendingRequest(); if (pendingReq != null) { + //TODO finish + final Class clazz = Class.forName(pendingReq.requestedModule()); + + if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { + log.error("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + throw new ClassCastException( + "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + + } + final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); + + handlingModule.generateErrorMessage(throwable, req, resp, pendingReq); } } } - } catch (Exception e) { + } catch (Throwable e) { + log.error(e.getMessage(), e); + protAuthService.handleErrorNoRedirect(e, req, resp, false); + } finally { + // remove pending-request + if (pendingReq != null) { + requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); + + } } } - - //TODO finish -// final Class clazz = Class.forName(req.requestedModule()); -// -// if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { -// log.error( -// "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); -// throw new ClassCastException( -// "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); -// -// } -// -// final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); -// -// handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest); - } /** @@ -123,32 +128,30 @@ public class ProtocolFinalizationController extends AbstractController { * @throws IOException In case of a servlet error */ // TODO reuse for the redirection to SP or own enpoint - @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = { RequestMethod.GET, RequestMethod.POST }) + @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = {RequestMethod.GET, RequestMethod.POST}) public void errorHandling(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { // receive an authentication error - final String errorToken = - StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + final String errorToken = StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); if (errorToken != null) { IRequest pendingReq = null; - try { - String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(errorToken); + try { + String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(errorToken); log.debug("Searching exception with internal error-token: {}", errorId); - + // load stored exception from database - final byte[] containerSerialized = - transactionStorage.get(errorId, byte[].class); + final byte[] containerSerialized = transactionStorage.get(errorId, byte[].class); if (containerSerialized != null) { // remove exception if it was found transactionStorage.remove(errorId); log.trace("Find exception with internal error-token: {}", errorId); - + //final Object containerObj = EaafSerializationUtils.deserialize(containerSerialized, // Arrays.asList( // ExceptionContainer.class.getName() // )); final Object containerObj = SerializationUtils.deserialize(containerSerialized); - + if (containerObj instanceof ExceptionContainer) { final ExceptionContainer container = (ExceptionContainer) containerObj; final Throwable throwable = container.getExceptionThrown(); @@ -157,7 +160,7 @@ public class ProtocolFinalizationController extends AbstractController { if (pendingReq != null) { //set MDC variables TransactionIdUtils.setAllLoggingVariables(pendingReq); - + // build protocol-specific error message if possible protAuthService.buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); @@ -170,17 +173,17 @@ public class ProtocolFinalizationController extends AbstractController { } } else { - protAuthService.handleErrorNoRedirect( - new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null), - req, resp, false); + protAuthService + .handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null), req, + resp, false); } } else { log.info("Find no exception with internal error-token: {}", errorId); - protAuthService.handleErrorNoRedirect( - new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), - req, resp, false); + protAuthService + .handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), + req, resp, false); } @@ -192,11 +195,10 @@ public class ProtocolFinalizationController extends AbstractController { // remove pending-request if (pendingReq != null) { requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, - pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); } - + //remove all Logger variables TransactionIdUtils.removeAllLoggingVariables(); @@ -204,9 +206,9 @@ public class ProtocolFinalizationController extends AbstractController { } else { log.debug("Request contains NO ErrorId"); - protAuthService.handleErrorNoRedirect( - new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), req, - resp, false); + protAuthService + .handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), req, + resp, false); } @@ -220,7 +222,7 @@ public class ProtocolFinalizationController extends AbstractController { * @throws EaafException In case of an internal error * @throws IOException In case of a servlet error */ - @RequestMapping(value = ENDPOINT_FINALIZEPROTOCOL, method = { RequestMethod.GET }) + @RequestMapping(value = ENDPOINT_FINALIZEPROTOCOL, method = {RequestMethod.GET}) public void finalizeAuthProtocol(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { @@ -232,19 +234,18 @@ public class ProtocolFinalizationController extends AbstractController { if (pendingReq == null) { log.error("No PendingRequest with ID " + pendingRequestID + " found.!"); protAuthService.handleErrorNoRedirect( - new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, - new Object[] { pendingRequestID, }), - req, resp, false); + new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, new Object[]{pendingRequestID,}), req, + resp, false); } else { //set MDC variables TransactionIdUtils.setAllLoggingVariables(pendingReq); - + //perform protocol finalization steps protAuthService.finalizeAuthentication(req, resp, pendingReq); - + } - + } } -- cgit v1.2.3 From 4b71edc5036c28f861007543233991d02b11d778 Mon Sep 17 00:00:00 2001 From: lalber Date: Fri, 12 Mar 2021 15:22:56 +0100 Subject: no ticket or link fix --- .../services/ProtocolAuthenticationService.java | 25 +++++++++++----------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 63e84dcb..8300c31f 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -113,7 +113,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer @Autowired(required = true) protected ITransactionStorage transactionStorage; - @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + @Autowired + IPendingRequestIdGenerationStrategy requestIdValidationStragegy; private IGuiFormBuilder guiBuilder; @@ -241,8 +242,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); byte[] serialized = SerializationUtils.serialize(exceptionContainer); -// transactionStorage.put(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE), serialized, -1); - String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + // transactionStorage.put(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE), serialized, -1); + String errorId = requestIdValidationStragegy + .validateAndGetPendingRequestId(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); transactionStorage.put(errorId, serialized, -1); @@ -432,11 +434,11 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } -// private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, -// @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, -// @Nullable final Object[] params, String externalErrorCode) throws EaafException { -// this.writeHtmlErrorResponse(httpReq, httpResp, msg, errorCode, params, externalErrorCode, null, null); -// } + // private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, + // @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, + // @Nullable final Object[] params, String externalErrorCode) throws EaafException { + // this.writeHtmlErrorResponse(httpReq, httpResp, msg, errorCode, params, externalErrorCode, null, null); + // } public void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, @@ -467,9 +469,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, - externalErrorCode); + externalErrorCode); c.putCustomParameterWithOutEscaption(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, - PARAM_GUI_ERRORCODEPARAMS, ArrayUtils.toString(errorCodeParams)); + PARAM_GUI_ERRORCODEPARAMS, ArrayUtils.toString(errorCodeParams)); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_TICKET, ticket); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_REDIRECT, url); @@ -488,8 +490,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } private void displayException(final HttpServletRequest req, final HttpServletResponse resp, - final ErrorTicketService.HandleData errorData) - throws IOException, EaafException { + final ErrorTicketService.HandleData errorData) throws IOException, EaafException { final Throwable e = errorData.getThrowable(); final String internalErrorCode = errorData.getErrorCode(); -- cgit v1.2.3 From b8d3937a99e54036be491b5df606ab6c5a81f480 Mon Sep 17 00:00:00 2001 From: lalber Date: Fri, 12 Mar 2021 16:11:07 +0100 Subject: added some error Handling --- .../core/impl/idp/auth/services/ErrorTicketService.java | 7 ++++--- .../auth/services/ProtocolAuthenticationService.java | 17 ++++++++++++----- .../idp/controller/ProtocolFinalizationController.java | 2 -- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java index c5bac225..3471aebe 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -92,7 +92,7 @@ public class ErrorTicketService { } } - public HandleData createHandleData(Throwable throwable, HttpServletRequest req) { + public HandleData createHandleData(Throwable throwable, HttpServletRequest req) throws EaafException { HandleData data = new HandleData(throwable, req); extractErrorCode(data); setUpErrorData(data); @@ -120,7 +120,7 @@ public class ErrorTicketService { } } - private void setUpErrorData(HandleData data) { + private void setUpErrorData(HandleData data) throws EaafException { if (propertyMap.containsKey(data.errorCode)) { String action = propertyMap.get(data.errorCode); @@ -145,7 +145,8 @@ public class ErrorTicketService { } else { data.generateSupportTicket(); - // TODO log with ticket gernal internal error + throw new EaafException("internal.configuration.00", new Object[] {data.errorCode + "in on_error_action" + + ".properties"}); } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 8300c31f..bb6f45d0 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -77,6 +77,8 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashSet; +import static at.gv.egiz.eaaf.core.api.IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC; + @Service public class ProtocolAuthenticationService implements IProtocolAuthenticationService { private static final Logger log = LoggerFactory.getLogger(ProtocolAuthenticationService.class); @@ -260,11 +262,10 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } - } catch (final Throwable e) { + } catch (final Throwable e) { // handleErrorNoRedirect(throwable, req, resp, true); } - } @Override @@ -281,8 +282,14 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // write errror to console logExceptionToTechnicalLog(errorData); - // return error to Web browser - displayException(req, resp, errorData); + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || + errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { + // return error to Web browser + displayException(req, resp, errorData); + } else { + throw new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, + new Exception("On Erroraction mapping mismatch", throwable)); + } } @Override @@ -516,7 +523,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } else { // write generic message for general exceptions - final String msg = statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); + final String msg = statusMessager.getMessage(CODES_INTERNAL_ERROR_GENERIC, null); writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), errorData.getSupportTicket()); diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index 37aab8df..26feb3db 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -89,7 +89,6 @@ public class ProtocolFinalizationController extends AbstractController { pendingReq = container.getPendingRequest(); if (pendingReq != null) { - //TODO finish final Class clazz = Class.forName(pendingReq.requestedModule()); if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { @@ -127,7 +126,6 @@ public class ProtocolFinalizationController extends AbstractController { * @throws EaafException In case of an internal error * @throws IOException In case of a servlet error */ - // TODO reuse for the redirection to SP or own enpoint @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = {RequestMethod.GET, RequestMethod.POST}) public void errorHandling(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { -- cgit v1.2.3 From 5abcd67602145c06715f71a7e420a1b10271e1a6 Mon Sep 17 00:00:00 2001 From: lalber Date: Mon, 15 Mar 2021 15:57:20 +0100 Subject: added some error Handling --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8848df24..a6d9d859 100644 --- a/pom.xml +++ b/pom.xml @@ -89,7 +89,7 @@ 2.0.9 - 1.18.12 + 1.18.16 0.8.6 -- cgit v1.2.3 From 5bd780462933b439d2e323c18a5404da60e764a5 Mon Sep 17 00:00:00 2001 From: lalber Date: Tue, 16 Mar 2021 14:45:30 +0100 Subject: add some Junit fixes and other spotbug based ones --- eaaf_core/checks/spotbugs-exclude.xml | 6 +++ .../impl/idp/auth/services/ErrorTicketService.java | 58 +++++++++++++++------- .../services/ProtocolAuthenticationService.java | 28 +++++------ .../controller/ProtocolFinalizationController.java | 7 +++ 4 files changed, 66 insertions(+), 33 deletions(-) diff --git a/eaaf_core/checks/spotbugs-exclude.xml b/eaaf_core/checks/spotbugs-exclude.xml index aa11a955..44642450 100644 --- a/eaaf_core/checks/spotbugs-exclude.xml +++ b/eaaf_core/checks/spotbugs-exclude.xml @@ -25,6 +25,12 @@ + + + + + + diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java index 3471aebe..673b53c2 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -86,12 +86,19 @@ public class ErrorTicketService { // log.error("working: " + propertyMap.get("auth.00")); } catch (Exception e) { - log.error("Error: something went wrong"); - throw new EaafException("Error: Parsing errorhandling actions failed"); + log.error("Error: something went wrong", e); + throw new EaafException("Error: Parsing errorhandling actions failed", new Object[]{}, e); } } } + /** + * creates error handling data. + * @param throwable error + * @param req http request + * @return eror handle Data + * @throws EaafException In case of an internal error + */ public HandleData createHandleData(Throwable throwable, HttpServletRequest req) throws EaafException { HandleData data = new HandleData(throwable, req); extractErrorCode(data); @@ -138,25 +145,30 @@ public class ErrorTicketService { data.actionType = ActionType.NOTICKET_REDIRECT; data.generateRedirect(); - } else {// ActionType.NOTICKET_NOREDIRECT -> nothing to be done + } else { // ActionType.NOTICKET_NOREDIRECT -> nothing to be done data.actionType = ActionType.NOTICKET_NOREDIRECT; } } else { data.generateSupportTicket(); - throw new EaafException("internal.configuration.00", new Object[] {data.errorCode + "in on_error_action" + - ".properties"}); + throw new EaafException("internal.configuration.00", + new Object[]{data.errorCode + "in on_error_action" + ".properties"}); } } - public class HandleData { + static class HandleData { private final HttpServletRequest req; - @Getter private String supportTicket; - @Getter private String redirectUrl; - @Getter private final Throwable throwable; - @Getter private String errorCode; - @Getter private ActionType actionType; + @Getter + private String supportTicket; + @Getter + private String redirectUrl; + @Getter + private final Throwable throwable; + @Getter + private String errorCode; + @Getter + private ActionType actionType; private HandleData(Throwable throwable, HttpServletRequest req) { @@ -166,30 +178,35 @@ public class ErrorTicketService { private void generateRedirect() { redirectUrl = ServletUtils.getBaseUrl(req); - redirectUrl += "/" + ProtocolFinalizationController.ENDPOINT_ERROR_REDIRECT - + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + - StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE));; + redirectUrl += + "/" + ProtocolFinalizationController.ENDPOINT_ERROR_REDIRECT + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + + StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); } private void generateSupportTicket() { - String randomCode = RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + - RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + - RandomStringUtils.randomAlphanumeric(4).toUpperCase(); + String randomCode = + RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + RandomStringUtils.randomAlphanumeric(4) + .toUpperCase() + '-' + RandomStringUtils.randomAlphanumeric(4).toUpperCase(); supportTicket = randomCode; } + /** + * Logs error to technical log. + */ public void log_error() { if (supportTicket != null) { - log.error(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), - throwable); + log.error(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); } else { log.error(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); } } + /** + * Logs info to technical log. + */ public void log_info() { if (supportTicket != null) { @@ -200,6 +217,9 @@ public class ErrorTicketService { } } + /** + * Logs warn to technical log. + */ public void log_warn() { if (supportTicket != null) { diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index bb6f45d0..6cbd72a5 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -77,7 +77,6 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashSet; -import static at.gv.egiz.eaaf.core.api.IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC; @Service public class ProtocolAuthenticationService implements IProtocolAuthenticationService { @@ -203,8 +202,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer log.warn("PendingRequest flag for 'authenticated':{} and 'needConsent':{}", pendingReq.isAuthenticated(), pendingReq.isNeedUserConsent()); if (pendingReq.isNeedUserConsent()) { - log.error("PendingRequest NEEDS user-consent. " + - "Can NOT fininalize authentication --> Abort authentication process!"); + log.error("PendingRequest NEEDS user-consent. " + + "Can NOT fininalize authentication --> Abort authentication process!"); } else { log.error("PendingRequest is NOT authenticated --> Abort authentication process!"); @@ -236,8 +235,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT) || - errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT) || errorData.getActionType() + .equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { displayException(req, resp, errorData); @@ -282,8 +281,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // write errror to console logExceptionToTechnicalLog(errorData); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || - errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData.getActionType() + .equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { // return error to Web browser displayException(req, resp, errorData); } else { @@ -447,7 +446,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // this.writeHtmlErrorResponse(httpReq, httpResp, msg, errorCode, params, externalErrorCode, null, null); // } - public void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, + + private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, @Nullable final Object[] params, String externalErrorCode, String url, String ticket) throws EaafException { @@ -472,7 +472,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // add errorcode and errormessage if (config instanceof ModifyableGuiBuilderConfiguration) { - ModifyableGuiBuilderConfiguration c = ((ModifyableGuiBuilderConfiguration) config); + ModifyableGuiBuilderConfiguration c = (ModifyableGuiBuilderConfiguration) config; c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, @@ -508,8 +508,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer resp.sendError(HttpServletResponse.SC_FORBIDDEN, StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(e.getMessage()))); - } else if (e instanceof AuthnRequestValidatorException || e instanceof InvalidProtocolRequestException || - e instanceof ProcessExecutionException || e instanceof ConfigurationException) { + } else if (e instanceof AuthnRequestValidatorException || e instanceof InvalidProtocolRequestException + || e instanceof ProcessExecutionException || e instanceof ConfigurationException) { // write error message writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), @@ -523,7 +523,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } else { // write generic message for general exceptions - final String msg = statusMessager.getMessage(CODES_INTERNAL_ERROR_GENERIC, null); + final String msg = statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), errorData.getSupportTicket()); @@ -544,8 +544,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer String redirectUrl = null; redirectUrl = ServletUtils.getBaseUrl(req); redirectUrl += - "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + - errorKey; + "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + + errorKey; return redirectUrl; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index 26feb3db..acb9b84c 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -59,6 +59,13 @@ public class ProtocolFinalizationController extends AbstractController { @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + /** + * Handles incoming requests for redirects to IDP. + * @param req http request + * @param resp http response + * @throws EaafException In case of an internal error + * @throws IOException In case of a servlet error + */ @RequestMapping(value = ENDPOINT_ERROR_REDIRECT, method = {RequestMethod.GET, RequestMethod.POST}) public void errorRedirect(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { -- cgit v1.2.3 From bf258e421c55baf64eb9bb30b95e4d29bfdef5eb Mon Sep 17 00:00:00 2001 From: lalber Date: Sun, 21 Mar 2021 12:52:27 +0100 Subject: Junit fixes --- .../impl/idp/auth/services/ErrorTicketService.java | 13 ++- .../services/ProtocolAuthenticationService.java | 103 ++++++++++++++++----- .../controller/ProtocolFinalizationController.java | 14 +-- 3 files changed, 93 insertions(+), 37 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java index 673b53c2..8bcb5305 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -68,13 +68,15 @@ public class ErrorTicketService { if (StringUtils.isEmpty(ticketConfPath)) { log.error("Error: Path to errorhandling action configuration not known"); - throw new EaafException("Error: Path to errorhandling action configuration not known"); + throw new EaafException("internal.configuration.00", + new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH}); } else { Properties getProperties = new Properties(); + String fullFilePath = null; try { - final String fullFilePath = FileUtils + fullFilePath = FileUtils .makeAbsoluteUrl(ticketConfPath, basicConfig.getConfigurationRootDirectory()); final Resource ressource = resourceLoader.getResource(fullFilePath); final InputStream is = ressource.getInputStream(); @@ -86,8 +88,9 @@ public class ErrorTicketService { // log.error("working: " + propertyMap.get("auth.00")); } catch (Exception e) { - log.error("Error: something went wrong", e); - throw new EaafException("Error: Parsing errorhandling actions failed", new Object[]{}, e); + log.error("Error: could not found file.", e); + throw new EaafException("internal.configuration.01", + new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH, "File cloud not be found."}); } } } @@ -153,7 +156,7 @@ public class ErrorTicketService { } else { data.generateSupportTicket(); throw new EaafException("internal.configuration.00", - new Object[]{data.errorCode + "in on_error_action" + ".properties"}); + new Object[]{data.errorCode + " in on_error_action" + ".properties"}); } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 6cbd72a5..d078d085 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -33,6 +33,7 @@ import at.gv.egiz.eaaf.core.api.idp.IAction; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.idp.IAuthenticationDataBuilder; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IModulInfo; import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; import at.gv.egiz.eaaf.core.api.idp.auth.ISsoManager; @@ -231,14 +232,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer public void buildProtocolSpecificErrorResponse(final Throwable throwable, final HttpServletRequest req, final HttpServletResponse resp, final IRequest protocolRequest) throws EaafException, IOException { try { - ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT) || errorData.getActionType() - .equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { - - displayException(req, resp, errorData); + if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); @@ -255,6 +251,27 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // log Error Message statisticLogger.logErrorOperation(throwable, protocolRequest); + displayException(req, resp, errorData); + + } else if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { + IModulInfo handlingModule = extractShibbolethHandling(protocolRequest, applicationContext); + + if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { + + // log Error to technical log + logExceptionToTechnicalLog(errorData); + + // log Error Message + statisticLogger.logErrorOperation(throwable, protocolRequest); + + // write revision log entries + revisionsLogger.logEvent(protocolRequest, EventConstants.TRANSACTION_ERROR, + protocolRequest.getUniqueTransactionIdentifier()); + + } else { + throw throwable; //through it on to handleErrorNoRedirect + + } } else { throw throwable; //through it on to handleErrorNoRedirect @@ -262,32 +279,73 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } } catch (final Throwable e) { // - handleErrorNoRedirect(throwable, req, resp, true); + // if building error response results in error, we try with with handleErrorNoRedirect + handleErrorNoRedirect(e, req, resp, true); } } + /** + * Retrieves shibboleth module info. + * @param protocolRequest current request + * @param applicationContext spring context + * @return IModulInfo + * @throws ClassNotFoundException If no shibboleth handling implementation found + */ + public static IModulInfo extractShibbolethHandling(IRequest protocolRequest, + ApplicationContext applicationContext) throws ClassNotFoundException { + final Class clazz = Class.forName(protocolRequest.requestedModule()); + + if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { + log.error( + "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + throw new ClassCastException( + "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + + } + + return (IModulInfo) applicationContext.getBean(clazz); + } + @Override public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, - final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) throws IOException, EaafException { + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) { + handleErrorNoRedirect(throwable, req, resp, writeExceptionToStatisticLog, false); + } - ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); + private void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog, final boolean recall) { + ErrorTicketService.HandleData errorData = null; + try { + errorData = errorTicketService.createHandleData(throwable, req); - // log Exception into statistic database - if (writeExceptionToStatisticLog) { - statisticLogger.logErrorOperation(throwable); - } + // log Exception into statistic database + if (writeExceptionToStatisticLog) { + statisticLogger.logErrorOperation(throwable); + } - // write errror to console - logExceptionToTechnicalLog(errorData); + // write errror to console + logExceptionToTechnicalLog(errorData); + + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData + .getActionType().equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT) || recall) { + // return error to Web browser + displayException(req, resp, errorData); + } else { + // TODO introduce separate error type? + throw new EaafException("internal.configuration.01", new Object[]{ + errorData.getErrorCode() + " in on_error_action" + ".properties", "Erroraction mapping mismatch"}); + } + + } catch (EaafException e) { + // retry + handleErrorNoRedirect(e, req, resp, writeExceptionToStatisticLog, true); + + } catch (IOException e) { + // retry + handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, e), req, resp, + writeExceptionToStatisticLog, true); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData.getActionType() - .equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { - // return error to Web browser - displayException(req, resp, errorData); - } else { - throw new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, - new Exception("On Erroraction mapping mismatch", throwable)); } } @@ -475,6 +533,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer ModifyableGuiBuilderConfiguration c = (ModifyableGuiBuilderConfiguration) config; c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); + // TODO: should we keep the internal errorcode secret? c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, externalErrorCode); c.putCustomParameterWithOutEscaption(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index acb9b84c..20f4c6ea 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -28,6 +28,7 @@ import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; import at.gv.egiz.eaaf.core.api.idp.IModulInfo; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.idp.auth.services.ProtocolAuthenticationService; import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; import org.apache.commons.text.StringEscapeUtils; import org.slf4j.Logger; @@ -59,6 +60,7 @@ public class ProtocolFinalizationController extends AbstractController { @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + /** * Handles incoming requests for redirects to IDP. * @param req http request @@ -96,16 +98,8 @@ public class ProtocolFinalizationController extends AbstractController { pendingReq = container.getPendingRequest(); if (pendingReq != null) { - final Class clazz = Class.forName(pendingReq.requestedModule()); - - if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { - log.error("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - throw new ClassCastException( - "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - - } - - final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); + IModulInfo handlingModule = ProtocolAuthenticationService + .extractShibbolethHandling(pendingReq, applicationContext); handlingModule.generateErrorMessage(throwable, req, resp, pendingReq); } -- cgit v1.2.3 From f76af302b54a0ddc0668ae93a2d32a07b60e6495 Mon Sep 17 00:00:00 2001 From: lalber Date: Fri, 26 Mar 2021 08:48:10 +0100 Subject: better error conf and some fixes --- .../core/impl/idp/auth/services/ErrorTicketService.java | 11 ++++++++--- .../auth/services/ProtocolAuthenticationService.java | 17 +++++++++-------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java index 8bcb5305..08fb04c6 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -39,7 +39,8 @@ public class ErrorTicketService { public enum ActionType { TICKET_REDIRECT("ticket_redirect"), TICKET_NOREDIRECT("ticket_noredirect"), NOTICKET_REDIRECT( - "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"); + "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"), NOTICKET_AUTOREDIRECT( + "noticket_autoredirect"); private final String name; @@ -67,7 +68,7 @@ public class ErrorTicketService { if (StringUtils.isEmpty(ticketConfPath)) { - log.error("Error: Path to errorhandling action configuration not known"); + log.error("Error: Path to errorhandling-action mapping not known"); throw new EaafException("internal.configuration.00", new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH}); } else { @@ -90,7 +91,8 @@ public class ErrorTicketService { } catch (Exception e) { log.error("Error: could not found file.", e); throw new EaafException("internal.configuration.01", - new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH, "File cloud not be found."}); + new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH, "File for errorhandling-action mapping cloud " + + "not be found."}); } } } @@ -148,6 +150,9 @@ public class ErrorTicketService { data.actionType = ActionType.NOTICKET_REDIRECT; data.generateRedirect(); + } else if (action.equals(ActionType.NOTICKET_AUTOREDIRECT.toString())) { + data.actionType = ActionType.NOTICKET_AUTOREDIRECT; + } else { // ActionType.NOTICKET_NOREDIRECT -> nothing to be done data.actionType = ActionType.NOTICKET_NOREDIRECT; diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index d078d085..09977f52 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -234,7 +234,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer try { ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { + if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT) + || errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); @@ -253,7 +254,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer displayException(req, resp, errorData); - } else if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { + } else if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_AUTOREDIRECT)) { IModulInfo handlingModule = extractShibbolethHandling(protocolRequest, applicationContext); if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { @@ -278,7 +279,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } - } catch (final Throwable e) { // + } catch (final Throwable e) { // if building error response results in error, we try with with handleErrorNoRedirect handleErrorNoRedirect(e, req, resp, true); @@ -287,18 +288,18 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer /** * Retrieves shibboleth module info. - * @param protocolRequest current request + * + * @param protocolRequest current request * @param applicationContext spring context * @return IModulInfo * @throws ClassNotFoundException If no shibboleth handling implementation found */ - public static IModulInfo extractShibbolethHandling(IRequest protocolRequest, - ApplicationContext applicationContext) throws ClassNotFoundException { + public static IModulInfo extractShibbolethHandling(IRequest protocolRequest, ApplicationContext applicationContext) + throws ClassNotFoundException { final Class clazz = Class.forName(protocolRequest.requestedModule()); if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { - log.error( - "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + log.error("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); throw new ClassCastException( "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); -- cgit v1.2.3 From 4e9499a1c39498f8646799e947e38f5f491c1428 Mon Sep 17 00:00:00 2001 From: lalber Date: Mon, 8 Mar 2021 18:27:55 +0100 Subject: First version of feature --- .../impl/idp/auth/services/ErrorTicketService.java | 212 +++++++++++++++++ .../services/ProtocolAuthenticationService.java | 260 +++++++++------------ .../controller/ProtocolFinalizationController.java | 60 +++++ .../services/IProtocolAuthenticationService.java | 11 +- 4 files changed, 383 insertions(+), 160 deletions(-) create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java new file mode 100644 index 00000000..c5bac225 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -0,0 +1,212 @@ +package at.gv.egiz.eaaf.core.impl.idp.auth.services; + +import at.gv.egiz.eaaf.core.api.IStatusMessenger; +import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.controller.ProtocolFinalizationController; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; +import lombok.Getter; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +@Service() +public class ErrorTicketService { + private static final Logger log = LoggerFactory.getLogger(ErrorTicketService.class); + + private static final String CONFIG_PROP_ERRORHANDLING_ACTION_PATH = "core.errorhandling.action"; + private static final String TECH_LOG_MSG = "errorCode={} Message={}"; + private static final String TICKET_LOG_MSG = "Ticket={} errorCode={} Message={}"; + + private final HashMap propertyMap = new HashMap(); + + + public enum ActionType { + TICKET_REDIRECT("ticket_redirect"), TICKET_NOREDIRECT("ticket_noredirect"), NOTICKET_REDIRECT( + "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"); + + private final String name; + + ActionType(final String text) { + this.name = text; + } + + @Override + public String toString() { + return name; + } + } + + @Autowired(required = true) + IConfiguration basicConfig; + @Autowired(required = true) + ResourceLoader resourceLoader; + + @PostConstruct + private void initialize() throws EaafException { + log.info("initErrorTicketService"); + + final String ticketConfPath = basicConfig.getBasicConfiguration(CONFIG_PROP_ERRORHANDLING_ACTION_PATH); + log.info("ticketConfPath" + ticketConfPath); + + + if (StringUtils.isEmpty(ticketConfPath)) { + log.error("Error: Path to errorhandling action configuration not known"); + throw new EaafException("Error: Path to errorhandling action configuration not known"); + } else { + + Properties getProperties = new Properties(); + try { + + final String fullFilePath = FileUtils + .makeAbsoluteUrl(ticketConfPath, basicConfig.getConfigurationRootDirectory()); + final Resource ressource = resourceLoader.getResource(fullFilePath); + final InputStream is = ressource.getInputStream(); + getProperties.load(is); + is.close(); + propertyMap.putAll((Map) getProperties); + + // log.error(propertyMap.toString()); + // log.error("working: " + propertyMap.get("auth.00")); + + } catch (Exception e) { + log.error("Error: something went wrong"); + throw new EaafException("Error: Parsing errorhandling actions failed"); + } + } + } + + public HandleData createHandleData(Throwable throwable, HttpServletRequest req) { + HandleData data = new HandleData(throwable, req); + extractErrorCode(data); + setUpErrorData(data); + + return data; + } + + private void extractErrorCode(HandleData data) { + Throwable originalException; + if (data.throwable instanceof TaskExecutionException + && ((TaskExecutionException) data.throwable).getOriginalException() != null) { + originalException = ((TaskExecutionException) data.throwable).getOriginalException(); + + } else { + originalException = data.throwable; + + } + + if (!(originalException instanceof EaafException)) { + data.errorCode = IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC; + + } else { + data.errorCode = ((EaafException) originalException).getErrorId(); + + } + } + + private void setUpErrorData(HandleData data) { + + if (propertyMap.containsKey(data.errorCode)) { + String action = propertyMap.get(data.errorCode); + + if (action.equals(ActionType.TICKET_REDIRECT.toString())) { + data.actionType = ActionType.TICKET_REDIRECT; + data.generateSupportTicket(); + data.generateRedirect(); + + } else if (action.equals(ActionType.TICKET_NOREDIRECT.toString())) { + data.actionType = ActionType.TICKET_NOREDIRECT; + data.generateSupportTicket(); + + } else if (action.equals(ActionType.NOTICKET_REDIRECT.toString())) { + data.actionType = ActionType.NOTICKET_REDIRECT; + data.generateRedirect(); + + } else {// ActionType.NOTICKET_NOREDIRECT -> nothing to be done + data.actionType = ActionType.NOTICKET_NOREDIRECT; + + } + + } else { + data.generateSupportTicket(); + // TODO log with ticket gernal internal error + } + } + + public class HandleData { + private final HttpServletRequest req; + @Getter private String supportTicket; + @Getter private String redirectUrl; + @Getter private final Throwable throwable; + @Getter private String errorCode; + @Getter private ActionType actionType; + + + private HandleData(Throwable throwable, HttpServletRequest req) { + this.throwable = throwable; + this.req = req; + } + + private void generateRedirect() { + redirectUrl = ServletUtils.getBaseUrl(req); + redirectUrl += "/" + ProtocolFinalizationController.ENDPOINT_ERROR_REDIRECT + + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + + StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE));; + + } + + private void generateSupportTicket() { + + String randomCode = RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + + RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + + RandomStringUtils.randomAlphanumeric(4).toUpperCase(); + supportTicket = randomCode; + } + + public void log_error() { + + if (supportTicket != null) { + log.error(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), + throwable); + } else { + log.error(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); + } + } + + public void log_info() { + + if (supportTicket != null) { + log.info(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); + + } else { + log.info(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); + } + } + + public void log_warn() { + + if (supportTicket != null) { + log.warn(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); + + } else { + log.warn(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); + } + } + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index abb3d685..687a5401 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -15,7 +15,7 @@ * This product combines work with different licenses. See the "NOTICE" text file for details on the * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative * works that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.gv.egiz.eaaf.core.impl.idp.auth.services; @@ -52,7 +52,6 @@ import at.gv.egiz.eaaf.core.api.idp.IAction; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.idp.IAuthenticationDataBuilder; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.IModulInfo; import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; import at.gv.egiz.eaaf.core.api.idp.auth.ISsoManager; @@ -69,7 +68,6 @@ import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.exceptions.ProtocolNotActiveException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.gui.AbstractGuiFormBuilderConfiguration; import at.gv.egiz.eaaf.core.impl.http.HttpUtils; @@ -82,9 +80,7 @@ import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; public class ProtocolAuthenticationService implements IProtocolAuthenticationService { private static final Logger log = LoggerFactory.getLogger(ProtocolAuthenticationService.class); - private static final String CONFIG_PROP_LOGGER_ON_INFO_LEVEL = - "core.logging.level.info.errorcodes"; - private static final String TECH_LOG_MSG = "errorCode={} Message={}"; + private static final String CONFIG_PROP_LOGGER_ON_INFO_LEVEL = "core.logging.level.info.errorcodes"; @Autowired(required = true) private ApplicationContext applicationContext; @@ -100,7 +96,11 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer private IRequestStorage requestStorage; @Autowired(required = true) IPendingRequestIdGenerationStrategy pendingReqIdGenerationStrategy; - @Autowired private IConfiguration basicConfig; + @Autowired + private IConfiguration basicConfig; + + @Autowired(required = true) + private ErrorTicketService errorTicketService; @Autowired(required = false) private ISsoManager ssoManager; @@ -136,9 +136,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer final ISpConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); if (oaParam == null) { - throw new EaafAuthenticationException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOSPCONFIG, - new Object[] { pendingReq.getSpEntityId() }); + throw new EaafAuthenticationException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOSPCONFIG, + new Object[]{pendingReq.getSpEntityId()}); } if (authmanager.doAuthentication(req, resp, pendingReq)) { @@ -148,8 +147,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer finalizeAuthentication(req, resp, pendingReq); // transaction is finished, log transaction finished event - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, - pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); } @@ -183,9 +181,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer if (pendingReq.isAbortedByUser()) { // send authentication aborted error to Service Provider buildProtocolSpecificErrorResponse( - new EaafAuthenticationException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_USERSTOP, - new Object[] {}), - req, resp, pendingReq); + new EaafAuthenticationException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_USERSTOP, new Object[]{}), req, + resp, pendingReq); // check if pending-request are authenticated } else if (pendingReq.isAuthenticated() && !pendingReq.isNeedUserConsent()) { @@ -193,12 +190,11 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } else { // suspect state: pending-request is not aborted but also are not authenticated - log.warn("PendingRequest flag for 'authenticated':{} and 'needConsent':{}", - pendingReq.isAuthenticated(), pendingReq.isNeedUserConsent()); + log.warn("PendingRequest flag for 'authenticated':{} and 'needConsent':{}", pendingReq.isAuthenticated(), + pendingReq.isNeedUserConsent()); if (pendingReq.isNeedUserConsent()) { - log.error( - "PendingRequest NEEDS user-consent. " - + "Can NOT fininalize authentication --> Abort authentication process!"); + log.error("PendingRequest NEEDS user-consent. " + + "Can NOT fininalize authentication --> Abort authentication process!"); } else { log.error("PendingRequest is NOT authenticated --> Abort authentication process!"); @@ -216,44 +212,34 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } finally { // remove pending-request requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, - pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); } } + @Override - public void buildProtocolSpecificErrorResponse(final Throwable throwable, - final HttpServletRequest req, final HttpServletResponse resp, final IRequest protocolRequest) - throws EaafException, IOException { + public void buildProtocolSpecificErrorResponse(final Throwable throwable, final HttpServletRequest req, + final HttpServletResponse resp, final IRequest protocolRequest) throws EaafException, IOException { try { - final Class clazz = Class.forName(protocolRequest.requestedModule()); + ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { - log.error( - "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - throw new ClassCastException( - "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - } + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT) || + errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { - final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); - - if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { + displayException(req, resp, errorData); // log Error to technical log - logExceptionToTechnicalLog(throwable); + logExceptionToTechnicalLog(errorData); // log Error Message statisticLogger.logErrorOperation(throwable, protocolRequest); - // write revision log entries - revisionsLogger.logEvent(protocolRequest, EventConstants.TRANSACTION_ERROR, - protocolRequest.getUniqueTransactionIdentifier()); } else { - handleErrorNoRedirect(throwable, req, resp, true); + throw throwable; //through it on to handleErrorNoRedirect } @@ -266,8 +252,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer @Override public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, - final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) - throws IOException, EaafException { + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) throws IOException, EaafException { + + ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); // log Exception into statistic database if (writeExceptionToStatisticLog) { @@ -275,30 +262,17 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } // write errror to console - logExceptionToTechnicalLog(throwable); + logExceptionToTechnicalLog(errorData); // return error to Web browser - if (throwable instanceof EaafException || throwable instanceof ProcessExecutionException) { - internalMoaidExceptionHandler(req, resp, (Exception) throwable, false); - - } else { - // write generic message for general exceptions - final String msg = - statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); - final String internalErrorCode = statusMessager.getResponseErrorCode(throwable); - - writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); - - } - + displayException(req, resp, errorData); } @Override public void forwardToErrorHandler(Pair errorToHandle, String errorKey, final HttpServletRequest req, final HttpServletResponse resp) throws GuiBuildException { - final IGuiBuilderConfiguration parentHopGuiConfig = - evaluateRequiredErrorHandlingMethod(errorToHandle.getFirst(), errorKey); + final IGuiBuilderConfiguration parentHopGuiConfig = evaluateRequiredErrorHandlingMethod(errorToHandle.getFirst(), + errorKey); if (parentHopGuiConfig != null) { log.trace("iFrame to parent hop requested. Building GUI step for error handling ... "); guiBuilder.build(req, resp, parentHopGuiConfig, "iFrame-to-parent"); @@ -321,15 +295,13 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer /** * Finalize the requested protocol operation. * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @param moaSession MOASession object, which is used to generate the - * protocol specific authentication information + * @param req HttpServletRequest + * @param resp HttpServletResponse + * @param pendingReq Authentication request which is actually in process * @throws Exception In case of an error */ - protected void internalFinalizeAuthenticationProcess(final HttpServletRequest req, - final HttpServletResponse resp, final IRequest pendingReq) throws Exception { + protected void internalFinalizeAuthenticationProcess(final HttpServletRequest req, final HttpServletResponse resp, + final IRequest pendingReq) throws Exception { String newSsoSessionId = null; @@ -351,8 +323,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer final IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq); // execute the protocol-specific action - final SloInformationInterface sloInformation = - executeProtocolSpecificAction(req, resp, pendingReq, authData); + final SloInformationInterface sloInformation = executeProtocolSpecificAction(req, resp, pendingReq, authData); // Store OA specific SSO session information if an SSO cookie is set if (StringUtils.isNotEmpty(newSsoSessionId)) { @@ -372,52 +343,42 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } // Advanced statistic logging - statisticLogger.logSuccessOperation(pendingReq, authData, - StringUtils.isNotEmpty(newSsoSessionId)); + statisticLogger.logSuccessOperation(pendingReq, authData, StringUtils.isNotEmpty(newSsoSessionId)); } /** * Write a Exception to the MOA-ID-Auth internal technical log. * - * @param loggedException Exception to log + * @param data errordata structure */ - protected void logExceptionToTechnicalLog(final Throwable loggedException) { + protected void logExceptionToTechnicalLog(ErrorTicketService.HandleData data) { // In case of a TaskExecutionException, which is only a container for process-errors, - // extract internal exception - Throwable toLog; - if (loggedException instanceof TaskExecutionException - && ((TaskExecutionException)loggedException).getOriginalException() != null) { - toLog = ((TaskExecutionException)loggedException).getOriginalException(); - - } else { - toLog = loggedException; - - } + // extract internal exception + // Log exception - if (!(toLog instanceof EaafException)) { - log.error(TECH_LOG_MSG, IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, - toLog.getMessage(), toLog); + if (!(data.getThrowable() instanceof EaafException)) { + data.log_error(); - } else { - if (logOnInfoLevel.contains(((EaafException) toLog).getErrorId())) { - log.info(TECH_LOG_MSG, ((EaafException) toLog).getErrorId(), - toLog.getMessage(), toLog); + } else { + + if (logOnInfoLevel.contains(data.getErrorCode())) { + data.log_info(); } else { - log.warn(TECH_LOG_MSG, ((EaafException) toLog).getErrorId(), - toLog.getMessage(), toLog); + data.log_warn(); } } } + @PostConstruct private void initializer() { log.trace("Initializing {} ...", ProtocolAuthenticationService.class.getName()); - logOnInfoLevel.addAll(KeyValueUtils.getListOfCsvValues( - basicConfig.getBasicConfiguration(CONFIG_PROP_LOGGER_ON_INFO_LEVEL))); + logOnInfoLevel + .addAll(KeyValueUtils.getListOfCsvValues(basicConfig.getBasicConfiguration(CONFIG_PROP_LOGGER_ON_INFO_LEVEL))); log.info("Set errorCodes={} to LogLevel:INFO", String.join(",", logOnInfoLevel)); } @@ -425,24 +386,20 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer /** * Executes the requested protocol action. * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @param authData Service-provider specific authentication data - * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param pendingReq Authentication request which is actually in process + * @param authData Service-provider specific authentication data * @return Return Single LogOut information or null if protocol supports no SSO - * * @throws Exception in case of an error */ private SloInformationInterface executeProtocolSpecificAction(final HttpServletRequest httpReq, - final HttpServletResponse httpResp, final IRequest pendingReq, final IAuthData authData) - throws Exception { + final HttpServletResponse httpResp, final IRequest pendingReq, final IAuthData authData) throws Exception { try { // request needs no authentication --> start request processing final Class clazz = Class.forName(pendingReq.requestedAction()); if (clazz == null || !IAction.class.isAssignableFrom(clazz)) { - log.error( - "Requested protocol-action processing Class is NULL or does not implement the IAction interface."); + log.error("Requested protocol-action processing Class is NULL or does not implement the IAction interface."); throw new ClassCastException( "Requested protocol-action processing Class is NULL or does not implement the IAction interface."); @@ -452,25 +409,31 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer return protocolAction.processRequest(pendingReq, httpReq, httpResp, authData); } catch (final ClassNotFoundException e) { - log.error( - "Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); + log.error("Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); throw new ClassNotFoundException( "Requested Auth. protocol processing Class is NULL or does not implement the IAction interface.", e); } } - private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, - @NonNull final HttpServletResponse httpResp, @NonNull final String msg, - @NonNull final String errorCode, @Nullable final Object[] params, String externalErrorCode) throws EaafException { + +// private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, +// @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, +// @Nullable final Object[] params, String externalErrorCode) throws EaafException { +// this.writeHtmlErrorResponse(httpReq, httpResp, msg, errorCode, params, externalErrorCode, null, null); +// } + + public void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, + @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, + @Nullable final Object[] params, String externalErrorCode, String url, String ticket) throws EaafException { try { - final IGuiBuilderConfiguration config = - guiConfigFactory.getDefaultErrorGui(HttpUtils.extractAuthUrlFromRequest(httpReq)); + final IGuiBuilderConfiguration config = guiConfigFactory + .getDefaultErrorGui(HttpUtils.extractAuthUrlFromRequest(httpReq)); String[] errorCodeParams = null; if (params == null) { - errorCodeParams = new String[] {}; + errorCodeParams = new String[]{}; } else { errorCodeParams = new String[params.length]; for (int i = 0; i < params.length; i++) { @@ -485,20 +448,18 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // add errorcode and errormessage if (config instanceof ModifyableGuiBuilderConfiguration) { - ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( - AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); - ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( - AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); - ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( - AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, - externalErrorCode); - ((ModifyableGuiBuilderConfiguration) config).putCustomParameterWithOutEscaption( - AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODEPARAMS, - ArrayUtils.toString(errorCodeParams)); + ModifyableGuiBuilderConfiguration c = ((ModifyableGuiBuilderConfiguration) config); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, + externalErrorCode); + c.putCustomParameterWithOutEscaption(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, + PARAM_GUI_ERRORCODEPARAMS, ArrayUtils.toString(errorCodeParams)); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_TICKET, ticket); + c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_REDIRECT, url); } else { - log.info( - "Can not ADD error message, because 'GUIBuilderConfiguration' is not modifieable "); + log.info("Can not ADD error message, because 'GUIBuilderConfiguration' is not modifieable "); } guiBuilder.build(httpReq, httpResp, config, "Error-Message"); @@ -511,50 +472,40 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } - private void internalMoaidExceptionHandler(final HttpServletRequest req, - final HttpServletResponse resp, final Exception e, final boolean writeExceptionToStatisicLog) - throws IOException, EaafException { - final String internalErrorCode = statusMessager.getResponseErrorCode(e); - + private void displayException(final HttpServletRequest req, final HttpServletResponse resp, + final ErrorTicketService.HandleData errorData) + throws IOException, EaafException { + final Throwable e = errorData.getThrowable(); + final String internalErrorCode = errorData.getErrorCode(); + + // send error response if (e instanceof ProtocolNotActiveException) { resp.getWriter().write(Encode.forHtml(e.getMessage())); resp.setContentType(EaafConstants.CONTENTTYPE_HTML_UTF8); resp.sendError(HttpServletResponse.SC_FORBIDDEN, StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(e.getMessage()))); - } else if (e instanceof AuthnRequestValidatorException) { - final AuthnRequestValidatorException ex = (AuthnRequestValidatorException) e; - // log Error Message - if (writeExceptionToStatisicLog) { - statisticLogger.logErrorOperation(ex, ex.getErrorRequest()); - } - + } else if (e instanceof AuthnRequestValidatorException || e instanceof InvalidProtocolRequestException || + e instanceof ProcessExecutionException || e instanceof ConfigurationException) { // write error message writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); - - } else if (e instanceof InvalidProtocolRequestException) { - // send error response - writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); - - } else if (e instanceof ConfigurationException) { - // send HTML formated error message - writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), + errorData.getSupportTicket()); } else if (e instanceof EaafException) { // send HTML formated error message - writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, - ((EaafException) e).getParams(), statusMessager.mapInternalErrorToExternalError(internalErrorCode)); + writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, ((EaafException) e).getParams(), + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), + errorData.getSupportTicket()); - } else if (e instanceof ProcessExecutionException) { - // send HTML formated error message - writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode)); + } else { + // write generic message for general exceptions + final String msg = statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); + writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), + errorData.getSupportTicket()); } - } private IGuiBuilderConfiguration evaluateRequiredErrorHandlingMethod(IRequest first, String errorId) { @@ -562,9 +513,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer return guiConfigFactory.getDefaultIFrameParentHopGui(first, ProtocolFinalizationController.ENDPOINT_ERRORHANDLING, errorId); - } - return null; } @@ -573,6 +522,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer redirectUrl = ServletUtils.getBaseUrl(req); redirectUrl += ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + errorKey; + return redirectUrl; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index b2130fb4..13a93e73 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -56,11 +56,70 @@ public class ProtocolFinalizationController extends AbstractController { EaafConstants.ENDPOINT_PREFIX_SECURED + "/finalizeAuthProtocol"; public static final String ENDPOINT_ERRORHANDLING = EaafConstants.ENDPOINT_PREFIX_SECURED + "/errorHandling"; + public static final String ENDPOINT_ERROR_REDIRECT = + EaafConstants.ENDPOINT_PREFIX_SECURED + "errorRedirect"; + @Autowired(required = true) IRequestStorage requestStorage; @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + @RequestMapping(value = ENDPOINT_ERROR_REDIRECT, method = { RequestMethod.GET, RequestMethod.POST }) + public void errorRedirect(final HttpServletRequest req, final HttpServletResponse resp) + throws EaafException, IOException { + + final String errorToken = + StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + if (errorToken != null) { + IRequest pendingReq = null; + try { + String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(errorToken); + log.debug("Searching exception with internal error-token: {}", errorId); + + // load stored exception from database + final byte[] containerSerialized = transactionStorage.get(errorId, byte[].class); + if (containerSerialized != null) { + // remove exception if it was found + transactionStorage.remove(errorId); + log.trace("Find exception with internal error-token: {}", errorId); + + //final Object containerObj = EaafSerializationUtils.deserialize(containerSerialized, + // Arrays.asList( + // ExceptionContainer.class.getName() + // )); + final Object containerObj = SerializationUtils.deserialize(containerSerialized); + + if (containerObj instanceof ExceptionContainer) { + final ExceptionContainer container = (ExceptionContainer) containerObj; + final Throwable throwable = container.getExceptionThrown(); + pendingReq = container.getPendingRequest(); + + if (pendingReq != null) { + + } + } + } + } catch (Exception e) { + } + } + + //TODO finish +// final Class clazz = Class.forName(req.requestedModule()); +// +// if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { +// log.error( +// "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); +// throw new ClassCastException( +// "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); +// +// } +// +// final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); +// +// handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest); + + } + /** * End-Point to handle errors. * @@ -69,6 +128,7 @@ public class ProtocolFinalizationController extends AbstractController { * @throws EaafException In case of an internal error * @throws IOException In case of a servlet error */ + // TODO reuse for the redirection to SP or own enpoint @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = { RequestMethod.GET, RequestMethod.POST }) public void errorHandling(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java index 6580fa30..7387f706 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java @@ -19,17 +19,16 @@ package at.gv.egiz.eaaf.core.api.idp.auth.services; -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; import at.gv.egiz.eaaf.core.impl.data.Pair; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + public interface IProtocolAuthenticationService { String PARAM_GUI_ERROMSG = "errorMsg"; @@ -37,6 +36,8 @@ public interface IProtocolAuthenticationService { String PARAM_GUI_EXTERNAL_ERRORCODE = "extErrorCode"; String PARAM_GUI_ERRORCODEPARAMS = "errorParams"; String PARAM_GUI_ERRORSTACKTRACE = "stacktrace"; + String PARAM_GUI_TICKET = "supportTicket"; + String PARAM_GUI_REDIRECT = "redirectLink"; /** * Initialize an authentication process for this protocol request. -- cgit v1.2.3 From c8873b5d8fbd5dd2ae7b35e6426f36bc42e107a0 Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 10 Mar 2021 10:24:40 +0100 Subject: Second version of feature --- .../services/ProtocolAuthenticationService.java | 18 ++++ .../controller/ProtocolFinalizationController.java | 108 +++++++++++---------- 2 files changed, 73 insertions(+), 53 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 687a5401..ec2c8b04 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -38,12 +38,14 @@ import org.springframework.context.ApplicationContext; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; import org.springframework.stereotype.Service; +import org.springframework.util.SerializationUtils; import at.gv.egiz.components.eventlog.api.EventConstants; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.IStatusMessenger; import at.gv.egiz.eaaf.core.api.data.EaafConstants; +import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfiguration; import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfigurationFactory; import at.gv.egiz.eaaf.core.api.gui.IGuiFormBuilder; @@ -59,6 +61,7 @@ import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; @@ -76,6 +79,7 @@ import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; + @Service public class ProtocolAuthenticationService implements IProtocolAuthenticationService { private static final Logger log = LoggerFactory.getLogger(ProtocolAuthenticationService.class); @@ -109,6 +113,12 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer @Autowired private IRevisionLogger revisionsLogger; + @Autowired(required = true) + protected ITransactionStorage transactionStorage; + + @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + + private IGuiFormBuilder guiBuilder; private final HashSet logOnInfoLevel = new HashSet<>(); @@ -231,6 +241,14 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer displayException(req, resp, errorData); + // Put pending request + ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); + byte[] serialized = SerializationUtils.serialize(exceptionContainer); +// transactionStorage.put(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE), serialized, -1); + String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + transactionStorage.put(errorId, serialized, -1); + + // log Error to technical log logExceptionToTechnicalLog(errorData); diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index 13a93e73..e81b9058 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -15,10 +15,11 @@ * This product combines work with different licenses. See the "NOTICE" text file for details on the * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative * works that you distribute must include a readable copy of the "NOTICE" text file. -*/ + */ package at.gv.egiz.eaaf.core.impl.idp.controller; + import java.io.IOException; import javax.servlet.http.HttpServletRequest; @@ -39,6 +40,7 @@ import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.IStatusMessenger; import at.gv.egiz.eaaf.core.api.data.EaafConstants; import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; +import at.gv.egiz.eaaf.core.api.idp.IModulInfo; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; @@ -47,7 +49,6 @@ import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; * Protocol finialization end-point. * * @author tlenz - * */ @Controller public class ProtocolFinalizationController extends AbstractController { @@ -62,14 +63,14 @@ public class ProtocolFinalizationController extends AbstractController { @Autowired(required = true) IRequestStorage requestStorage; - @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + @Autowired + IPendingRequestIdGenerationStrategy requestIdValidationStragegy; - @RequestMapping(value = ENDPOINT_ERROR_REDIRECT, method = { RequestMethod.GET, RequestMethod.POST }) + @RequestMapping(value = ENDPOINT_ERROR_REDIRECT, method = {RequestMethod.GET, RequestMethod.POST}) public void errorRedirect(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { - final String errorToken = - StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + final String errorToken = StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); if (errorToken != null) { IRequest pendingReq = null; try { @@ -95,29 +96,34 @@ public class ProtocolFinalizationController extends AbstractController { pendingReq = container.getPendingRequest(); if (pendingReq != null) { + //TODO finish + final Class clazz = Class.forName(pendingReq.requestedModule()); + + if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { + log.error("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + throw new ClassCastException( + "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + } + + final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); + + handlingModule.generateErrorMessage(throwable, req, resp, pendingReq); } } } - } catch (Exception e) { + } catch (Throwable e) { + log.error(e.getMessage(), e); + protAuthService.handleErrorNoRedirect(e, req, resp, false); + } finally { + // remove pending-request + if (pendingReq != null) { + requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); + + } } } - - //TODO finish -// final Class clazz = Class.forName(req.requestedModule()); -// -// if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { -// log.error( -// "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); -// throw new ClassCastException( -// "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); -// -// } -// -// final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); -// -// handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest); - } /** @@ -129,32 +135,30 @@ public class ProtocolFinalizationController extends AbstractController { * @throws IOException In case of a servlet error */ // TODO reuse for the redirection to SP or own enpoint - @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = { RequestMethod.GET, RequestMethod.POST }) + @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = {RequestMethod.GET, RequestMethod.POST}) public void errorHandling(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { // receive an authentication error - final String errorToken = - StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + final String errorToken = StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); if (errorToken != null) { IRequest pendingReq = null; - try { - String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(errorToken); + try { + String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(errorToken); log.debug("Searching exception with internal error-token: {}", errorId); - + // load stored exception from database - final byte[] containerSerialized = - transactionStorage.get(errorId, byte[].class); + final byte[] containerSerialized = transactionStorage.get(errorId, byte[].class); if (containerSerialized != null) { // remove exception if it was found transactionStorage.remove(errorId); log.trace("Find exception with internal error-token: {}", errorId); - + //final Object containerObj = EaafSerializationUtils.deserialize(containerSerialized, // Arrays.asList( // ExceptionContainer.class.getName() // )); final Object containerObj = SerializationUtils.deserialize(containerSerialized); - + if (containerObj instanceof ExceptionContainer) { final ExceptionContainer container = (ExceptionContainer) containerObj; final Throwable throwable = container.getExceptionThrown(); @@ -163,7 +167,7 @@ public class ProtocolFinalizationController extends AbstractController { if (pendingReq != null) { //set MDC variables TransactionIdUtils.setAllLoggingVariables(pendingReq); - + // build protocol-specific error message if possible protAuthService.buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); @@ -176,17 +180,17 @@ public class ProtocolFinalizationController extends AbstractController { } } else { - protAuthService.handleErrorNoRedirect( - new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null), - req, resp, false); + protAuthService + .handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null), req, + resp, false); } } else { log.info("Find no exception with internal error-token: {}", errorId); - protAuthService.handleErrorNoRedirect( - new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), - req, resp, false); + protAuthService + .handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), + req, resp, false); } @@ -198,11 +202,10 @@ public class ProtocolFinalizationController extends AbstractController { // remove pending-request if (pendingReq != null) { requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, - pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); } - + //remove all Logger variables TransactionIdUtils.removeAllLoggingVariables(); @@ -210,9 +213,9 @@ public class ProtocolFinalizationController extends AbstractController { } else { log.debug("Request contains NO ErrorId"); - protAuthService.handleErrorNoRedirect( - new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), req, - resp, false); + protAuthService + .handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), req, + resp, false); } @@ -226,7 +229,7 @@ public class ProtocolFinalizationController extends AbstractController { * @throws EaafException In case of an internal error * @throws IOException In case of a servlet error */ - @RequestMapping(value = ENDPOINT_FINALIZEPROTOCOL, method = { RequestMethod.GET }) + @RequestMapping(value = ENDPOINT_FINALIZEPROTOCOL, method = {RequestMethod.GET}) public void finalizeAuthProtocol(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { @@ -239,19 +242,18 @@ public class ProtocolFinalizationController extends AbstractController { log.info("PendingReqId was valid but no PendingRequest with ID: {}. Looks already used", pendingRequestID); protAuthService.handleErrorNoRedirect( - new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, - new Object[] { pendingRequestID, }), - req, resp, false); + new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, new Object[]{pendingRequestID,}), req, + resp, false); } else { //set MDC variables TransactionIdUtils.setAllLoggingVariables(pendingReq); - + //perform protocol finalization steps protAuthService.finalizeAuthentication(req, resp, pendingReq); - + } - + } } -- cgit v1.2.3 From c43d3f075ebf165a55935cd985fcfaf7426dc38d Mon Sep 17 00:00:00 2001 From: lalber Date: Fri, 12 Mar 2021 15:22:56 +0100 Subject: no ticket or link fix --- .../services/ProtocolAuthenticationService.java | 25 +++++++++++----------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index ec2c8b04..d915910b 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -116,7 +116,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer @Autowired(required = true) protected ITransactionStorage transactionStorage; - @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + @Autowired + IPendingRequestIdGenerationStrategy requestIdValidationStragegy; private IGuiFormBuilder guiBuilder; @@ -244,8 +245,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); byte[] serialized = SerializationUtils.serialize(exceptionContainer); -// transactionStorage.put(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE), serialized, -1); - String errorId = requestIdValidationStragegy.validateAndGetPendingRequestId(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); + // transactionStorage.put(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE), serialized, -1); + String errorId = requestIdValidationStragegy + .validateAndGetPendingRequestId(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); transactionStorage.put(errorId, serialized, -1); @@ -435,11 +437,11 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } -// private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, -// @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, -// @Nullable final Object[] params, String externalErrorCode) throws EaafException { -// this.writeHtmlErrorResponse(httpReq, httpResp, msg, errorCode, params, externalErrorCode, null, null); -// } + // private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, + // @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, + // @Nullable final Object[] params, String externalErrorCode) throws EaafException { + // this.writeHtmlErrorResponse(httpReq, httpResp, msg, errorCode, params, externalErrorCode, null, null); + // } public void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, @@ -470,9 +472,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, - externalErrorCode); + externalErrorCode); c.putCustomParameterWithOutEscaption(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, - PARAM_GUI_ERRORCODEPARAMS, ArrayUtils.toString(errorCodeParams)); + PARAM_GUI_ERRORCODEPARAMS, ArrayUtils.toString(errorCodeParams)); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_TICKET, ticket); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_REDIRECT, url); @@ -491,8 +493,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } private void displayException(final HttpServletRequest req, final HttpServletResponse resp, - final ErrorTicketService.HandleData errorData) - throws IOException, EaafException { + final ErrorTicketService.HandleData errorData) throws IOException, EaafException { final Throwable e = errorData.getThrowable(); final String internalErrorCode = errorData.getErrorCode(); -- cgit v1.2.3 From 9b5b4233e0ffbcd62de74770a492e24c3efe9b05 Mon Sep 17 00:00:00 2001 From: lalber Date: Fri, 12 Mar 2021 16:11:07 +0100 Subject: added some error Handling --- .../core/impl/idp/auth/services/ErrorTicketService.java | 7 ++++--- .../auth/services/ProtocolAuthenticationService.java | 17 ++++++++++++----- .../idp/controller/ProtocolFinalizationController.java | 2 -- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java index c5bac225..3471aebe 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -92,7 +92,7 @@ public class ErrorTicketService { } } - public HandleData createHandleData(Throwable throwable, HttpServletRequest req) { + public HandleData createHandleData(Throwable throwable, HttpServletRequest req) throws EaafException { HandleData data = new HandleData(throwable, req); extractErrorCode(data); setUpErrorData(data); @@ -120,7 +120,7 @@ public class ErrorTicketService { } } - private void setUpErrorData(HandleData data) { + private void setUpErrorData(HandleData data) throws EaafException { if (propertyMap.containsKey(data.errorCode)) { String action = propertyMap.get(data.errorCode); @@ -145,7 +145,8 @@ public class ErrorTicketService { } else { data.generateSupportTicket(); - // TODO log with ticket gernal internal error + throw new EaafException("internal.configuration.00", new Object[] {data.errorCode + "in on_error_action" + + ".properties"}); } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index d915910b..9627e01a 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -80,6 +80,8 @@ import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; +import static at.gv.egiz.eaaf.core.api.IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC; + @Service public class ProtocolAuthenticationService implements IProtocolAuthenticationService { private static final Logger log = LoggerFactory.getLogger(ProtocolAuthenticationService.class); @@ -263,11 +265,10 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } - } catch (final Throwable e) { + } catch (final Throwable e) { // handleErrorNoRedirect(throwable, req, resp, true); } - } @Override @@ -284,8 +285,14 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // write errror to console logExceptionToTechnicalLog(errorData); - // return error to Web browser - displayException(req, resp, errorData); + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || + errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { + // return error to Web browser + displayException(req, resp, errorData); + } else { + throw new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, + new Exception("On Erroraction mapping mismatch", throwable)); + } } @Override @@ -519,7 +526,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } else { // write generic message for general exceptions - final String msg = statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); + final String msg = statusMessager.getMessage(CODES_INTERNAL_ERROR_GENERIC, null); writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), errorData.getSupportTicket()); diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index e81b9058..9b7b0a02 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -96,7 +96,6 @@ public class ProtocolFinalizationController extends AbstractController { pendingReq = container.getPendingRequest(); if (pendingReq != null) { - //TODO finish final Class clazz = Class.forName(pendingReq.requestedModule()); if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { @@ -134,7 +133,6 @@ public class ProtocolFinalizationController extends AbstractController { * @throws EaafException In case of an internal error * @throws IOException In case of a servlet error */ - // TODO reuse for the redirection to SP or own enpoint @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = {RequestMethod.GET, RequestMethod.POST}) public void errorHandling(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { -- cgit v1.2.3 From ae656225445f45b26c2ebdf4ebe8bc820e1c3db0 Mon Sep 17 00:00:00 2001 From: lalber Date: Mon, 15 Mar 2021 15:57:20 +0100 Subject: added some error Handling --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 01311d6b..c21433a8 100644 --- a/pom.xml +++ b/pom.xml @@ -89,7 +89,7 @@ 2.0.9 - 1.18.12 + 1.18.16 0.8.6 -- cgit v1.2.3 From faa131a65b46a5c42a7b6b85e0ff3b414c93bea5 Mon Sep 17 00:00:00 2001 From: lalber Date: Tue, 16 Mar 2021 14:45:30 +0100 Subject: add some Junit fixes and other spotbug based ones --- eaaf_core/checks/spotbugs-exclude.xml | 6 +++ .../impl/idp/auth/services/ErrorTicketService.java | 58 +++++++++++++++------- .../services/ProtocolAuthenticationService.java | 25 +++++----- .../controller/ProtocolFinalizationController.java | 7 +++ 4 files changed, 64 insertions(+), 32 deletions(-) diff --git a/eaaf_core/checks/spotbugs-exclude.xml b/eaaf_core/checks/spotbugs-exclude.xml index d1cc43e3..70f27b81 100644 --- a/eaaf_core/checks/spotbugs-exclude.xml +++ b/eaaf_core/checks/spotbugs-exclude.xml @@ -18,6 +18,12 @@ + + + + + + diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java index 3471aebe..673b53c2 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -86,12 +86,19 @@ public class ErrorTicketService { // log.error("working: " + propertyMap.get("auth.00")); } catch (Exception e) { - log.error("Error: something went wrong"); - throw new EaafException("Error: Parsing errorhandling actions failed"); + log.error("Error: something went wrong", e); + throw new EaafException("Error: Parsing errorhandling actions failed", new Object[]{}, e); } } } + /** + * creates error handling data. + * @param throwable error + * @param req http request + * @return eror handle Data + * @throws EaafException In case of an internal error + */ public HandleData createHandleData(Throwable throwable, HttpServletRequest req) throws EaafException { HandleData data = new HandleData(throwable, req); extractErrorCode(data); @@ -138,25 +145,30 @@ public class ErrorTicketService { data.actionType = ActionType.NOTICKET_REDIRECT; data.generateRedirect(); - } else {// ActionType.NOTICKET_NOREDIRECT -> nothing to be done + } else { // ActionType.NOTICKET_NOREDIRECT -> nothing to be done data.actionType = ActionType.NOTICKET_NOREDIRECT; } } else { data.generateSupportTicket(); - throw new EaafException("internal.configuration.00", new Object[] {data.errorCode + "in on_error_action" + - ".properties"}); + throw new EaafException("internal.configuration.00", + new Object[]{data.errorCode + "in on_error_action" + ".properties"}); } } - public class HandleData { + static class HandleData { private final HttpServletRequest req; - @Getter private String supportTicket; - @Getter private String redirectUrl; - @Getter private final Throwable throwable; - @Getter private String errorCode; - @Getter private ActionType actionType; + @Getter + private String supportTicket; + @Getter + private String redirectUrl; + @Getter + private final Throwable throwable; + @Getter + private String errorCode; + @Getter + private ActionType actionType; private HandleData(Throwable throwable, HttpServletRequest req) { @@ -166,30 +178,35 @@ public class ErrorTicketService { private void generateRedirect() { redirectUrl = ServletUtils.getBaseUrl(req); - redirectUrl += "/" + ProtocolFinalizationController.ENDPOINT_ERROR_REDIRECT - + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + - StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE));; + redirectUrl += + "/" + ProtocolFinalizationController.ENDPOINT_ERROR_REDIRECT + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + + StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); } private void generateSupportTicket() { - String randomCode = RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + - RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + - RandomStringUtils.randomAlphanumeric(4).toUpperCase(); + String randomCode = + RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + RandomStringUtils.randomAlphanumeric(4) + .toUpperCase() + '-' + RandomStringUtils.randomAlphanumeric(4).toUpperCase(); supportTicket = randomCode; } + /** + * Logs error to technical log. + */ public void log_error() { if (supportTicket != null) { - log.error(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), - throwable); + log.error(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); } else { log.error(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); } } + /** + * Logs info to technical log. + */ public void log_info() { if (supportTicket != null) { @@ -200,6 +217,9 @@ public class ErrorTicketService { } } + /** + * Logs warn to technical log. + */ public void log_warn() { if (supportTicket != null) { diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 9627e01a..5d656e76 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -80,7 +80,6 @@ import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; -import static at.gv.egiz.eaaf.core.api.IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC; @Service public class ProtocolAuthenticationService implements IProtocolAuthenticationService { @@ -206,8 +205,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer log.warn("PendingRequest flag for 'authenticated':{} and 'needConsent':{}", pendingReq.isAuthenticated(), pendingReq.isNeedUserConsent()); if (pendingReq.isNeedUserConsent()) { - log.error("PendingRequest NEEDS user-consent. " + - "Can NOT fininalize authentication --> Abort authentication process!"); + log.error("PendingRequest NEEDS user-consent. " + + "Can NOT fininalize authentication --> Abort authentication process!"); } else { log.error("PendingRequest is NOT authenticated --> Abort authentication process!"); @@ -239,8 +238,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT) || - errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT) || errorData.getActionType() + .equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { displayException(req, resp, errorData); @@ -285,8 +284,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // write errror to console logExceptionToTechnicalLog(errorData); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || - errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData.getActionType() + .equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { // return error to Web browser displayException(req, resp, errorData); } else { @@ -450,7 +449,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // this.writeHtmlErrorResponse(httpReq, httpResp, msg, errorCode, params, externalErrorCode, null, null); // } - public void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, + + private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, @Nullable final Object[] params, String externalErrorCode, String url, String ticket) throws EaafException { @@ -475,7 +475,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // add errorcode and errormessage if (config instanceof ModifyableGuiBuilderConfiguration) { - ModifyableGuiBuilderConfiguration c = ((ModifyableGuiBuilderConfiguration) config); + ModifyableGuiBuilderConfiguration c = (ModifyableGuiBuilderConfiguration) config; c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, @@ -511,8 +511,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer resp.sendError(HttpServletResponse.SC_FORBIDDEN, StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(e.getMessage()))); - } else if (e instanceof AuthnRequestValidatorException || e instanceof InvalidProtocolRequestException || - e instanceof ProcessExecutionException || e instanceof ConfigurationException) { + } else if (e instanceof AuthnRequestValidatorException || e instanceof InvalidProtocolRequestException + || e instanceof ProcessExecutionException || e instanceof ConfigurationException) { // write error message writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), @@ -526,7 +526,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } else { // write generic message for general exceptions - final String msg = statusMessager.getMessage(CODES_INTERNAL_ERROR_GENERIC, null); + final String msg = statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), errorData.getSupportTicket()); @@ -548,7 +548,6 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer redirectUrl = ServletUtils.getBaseUrl(req); redirectUrl += ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + errorKey; - return redirectUrl; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index 9b7b0a02..d874cff6 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -66,6 +66,13 @@ public class ProtocolFinalizationController extends AbstractController { @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + /** + * Handles incoming requests for redirects to IDP. + * @param req http request + * @param resp http response + * @throws EaafException In case of an internal error + * @throws IOException In case of a servlet error + */ @RequestMapping(value = ENDPOINT_ERROR_REDIRECT, method = {RequestMethod.GET, RequestMethod.POST}) public void errorRedirect(final HttpServletRequest req, final HttpServletResponse resp) throws EaafException, IOException { -- cgit v1.2.3 From ae6d01d3eef70fb5892430aee88438dc15c02cf9 Mon Sep 17 00:00:00 2001 From: lalber Date: Sun, 21 Mar 2021 12:52:27 +0100 Subject: Junit fixes --- .../impl/idp/auth/services/ErrorTicketService.java | 13 ++- .../services/ProtocolAuthenticationService.java | 103 ++++++++++++++++----- .../controller/ProtocolFinalizationController.java | 14 +-- 3 files changed, 93 insertions(+), 37 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java index 673b53c2..8bcb5305 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -68,13 +68,15 @@ public class ErrorTicketService { if (StringUtils.isEmpty(ticketConfPath)) { log.error("Error: Path to errorhandling action configuration not known"); - throw new EaafException("Error: Path to errorhandling action configuration not known"); + throw new EaafException("internal.configuration.00", + new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH}); } else { Properties getProperties = new Properties(); + String fullFilePath = null; try { - final String fullFilePath = FileUtils + fullFilePath = FileUtils .makeAbsoluteUrl(ticketConfPath, basicConfig.getConfigurationRootDirectory()); final Resource ressource = resourceLoader.getResource(fullFilePath); final InputStream is = ressource.getInputStream(); @@ -86,8 +88,9 @@ public class ErrorTicketService { // log.error("working: " + propertyMap.get("auth.00")); } catch (Exception e) { - log.error("Error: something went wrong", e); - throw new EaafException("Error: Parsing errorhandling actions failed", new Object[]{}, e); + log.error("Error: could not found file.", e); + throw new EaafException("internal.configuration.01", + new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH, "File cloud not be found."}); } } } @@ -153,7 +156,7 @@ public class ErrorTicketService { } else { data.generateSupportTicket(); throw new EaafException("internal.configuration.00", - new Object[]{data.errorCode + "in on_error_action" + ".properties"}); + new Object[]{data.errorCode + " in on_error_action" + ".properties"}); } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 5d656e76..e04fc626 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -54,6 +54,7 @@ import at.gv.egiz.eaaf.core.api.idp.IAction; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.idp.IAuthenticationDataBuilder; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IModulInfo; import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; import at.gv.egiz.eaaf.core.api.idp.auth.ISsoManager; @@ -234,14 +235,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer public void buildProtocolSpecificErrorResponse(final Throwable throwable, final HttpServletRequest req, final HttpServletResponse resp, final IRequest protocolRequest) throws EaafException, IOException { try { - ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT) || errorData.getActionType() - .equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { - - displayException(req, resp, errorData); + if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); @@ -258,6 +254,27 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // log Error Message statisticLogger.logErrorOperation(throwable, protocolRequest); + displayException(req, resp, errorData); + + } else if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { + IModulInfo handlingModule = extractShibbolethHandling(protocolRequest, applicationContext); + + if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { + + // log Error to technical log + logExceptionToTechnicalLog(errorData); + + // log Error Message + statisticLogger.logErrorOperation(throwable, protocolRequest); + + // write revision log entries + revisionsLogger.logEvent(protocolRequest, EventConstants.TRANSACTION_ERROR, + protocolRequest.getUniqueTransactionIdentifier()); + + } else { + throw throwable; //through it on to handleErrorNoRedirect + + } } else { throw throwable; //through it on to handleErrorNoRedirect @@ -265,32 +282,73 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } } catch (final Throwable e) { // - handleErrorNoRedirect(throwable, req, resp, true); + // if building error response results in error, we try with with handleErrorNoRedirect + handleErrorNoRedirect(e, req, resp, true); } } + /** + * Retrieves shibboleth module info. + * @param protocolRequest current request + * @param applicationContext spring context + * @return IModulInfo + * @throws ClassNotFoundException If no shibboleth handling implementation found + */ + public static IModulInfo extractShibbolethHandling(IRequest protocolRequest, + ApplicationContext applicationContext) throws ClassNotFoundException { + final Class clazz = Class.forName(protocolRequest.requestedModule()); + + if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { + log.error( + "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + throw new ClassCastException( + "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + + } + + return (IModulInfo) applicationContext.getBean(clazz); + } + @Override public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, - final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) throws IOException, EaafException { + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) { + handleErrorNoRedirect(throwable, req, resp, writeExceptionToStatisticLog, false); + } - ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); + private void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog, final boolean recall) { + ErrorTicketService.HandleData errorData = null; + try { + errorData = errorTicketService.createHandleData(throwable, req); - // log Exception into statistic database - if (writeExceptionToStatisticLog) { - statisticLogger.logErrorOperation(throwable); - } + // log Exception into statistic database + if (writeExceptionToStatisticLog) { + statisticLogger.logErrorOperation(throwable); + } - // write errror to console - logExceptionToTechnicalLog(errorData); + // write errror to console + logExceptionToTechnicalLog(errorData); + + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData + .getActionType().equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT) || recall) { + // return error to Web browser + displayException(req, resp, errorData); + } else { + // TODO introduce separate error type? + throw new EaafException("internal.configuration.01", new Object[]{ + errorData.getErrorCode() + " in on_error_action" + ".properties", "Erroraction mapping mismatch"}); + } + + } catch (EaafException e) { + // retry + handleErrorNoRedirect(e, req, resp, writeExceptionToStatisticLog, true); + + } catch (IOException e) { + // retry + handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, e), req, resp, + writeExceptionToStatisticLog, true); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData.getActionType() - .equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { - // return error to Web browser - displayException(req, resp, errorData); - } else { - throw new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, - new Exception("On Erroraction mapping mismatch", throwable)); } } @@ -478,6 +536,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer ModifyableGuiBuilderConfiguration c = (ModifyableGuiBuilderConfiguration) config; c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); + // TODO: should we keep the internal errorcode secret? c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_EXTERNAL_ERRORCODE, externalErrorCode); c.putCustomParameterWithOutEscaption(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index d874cff6..90d8a28d 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -43,6 +43,7 @@ import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; import at.gv.egiz.eaaf.core.api.idp.IModulInfo; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.idp.auth.services.ProtocolAuthenticationService; import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; /** @@ -66,6 +67,7 @@ public class ProtocolFinalizationController extends AbstractController { @Autowired IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + /** * Handles incoming requests for redirects to IDP. * @param req http request @@ -103,16 +105,8 @@ public class ProtocolFinalizationController extends AbstractController { pendingReq = container.getPendingRequest(); if (pendingReq != null) { - final Class clazz = Class.forName(pendingReq.requestedModule()); - - if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { - log.error("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - throw new ClassCastException( - "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - - } - - final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); + IModulInfo handlingModule = ProtocolAuthenticationService + .extractShibbolethHandling(pendingReq, applicationContext); handlingModule.generateErrorMessage(throwable, req, resp, pendingReq); } -- cgit v1.2.3 From b8b5f661b4b16f2ae82e9a63bf1e2d9279e1dcbc Mon Sep 17 00:00:00 2001 From: lalber Date: Fri, 26 Mar 2021 08:48:10 +0100 Subject: better error conf and some fixes --- .../core/impl/idp/auth/services/ErrorTicketService.java | 11 ++++++++--- .../auth/services/ProtocolAuthenticationService.java | 17 +++++++++-------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java index 8bcb5305..08fb04c6 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -39,7 +39,8 @@ public class ErrorTicketService { public enum ActionType { TICKET_REDIRECT("ticket_redirect"), TICKET_NOREDIRECT("ticket_noredirect"), NOTICKET_REDIRECT( - "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"); + "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"), NOTICKET_AUTOREDIRECT( + "noticket_autoredirect"); private final String name; @@ -67,7 +68,7 @@ public class ErrorTicketService { if (StringUtils.isEmpty(ticketConfPath)) { - log.error("Error: Path to errorhandling action configuration not known"); + log.error("Error: Path to errorhandling-action mapping not known"); throw new EaafException("internal.configuration.00", new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH}); } else { @@ -90,7 +91,8 @@ public class ErrorTicketService { } catch (Exception e) { log.error("Error: could not found file.", e); throw new EaafException("internal.configuration.01", - new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH, "File cloud not be found."}); + new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH, "File for errorhandling-action mapping cloud " + + "not be found."}); } } } @@ -148,6 +150,9 @@ public class ErrorTicketService { data.actionType = ActionType.NOTICKET_REDIRECT; data.generateRedirect(); + } else if (action.equals(ActionType.NOTICKET_AUTOREDIRECT.toString())) { + data.actionType = ActionType.NOTICKET_AUTOREDIRECT; + } else { // ActionType.NOTICKET_NOREDIRECT -> nothing to be done data.actionType = ActionType.NOTICKET_NOREDIRECT; diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index e04fc626..ac2be693 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -237,7 +237,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer try { ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT)) { + if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT) + || errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); @@ -256,7 +257,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer displayException(req, resp, errorData); - } else if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { + } else if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_AUTOREDIRECT)) { IModulInfo handlingModule = extractShibbolethHandling(protocolRequest, applicationContext); if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { @@ -281,7 +282,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } - } catch (final Throwable e) { // + } catch (final Throwable e) { // if building error response results in error, we try with with handleErrorNoRedirect handleErrorNoRedirect(e, req, resp, true); @@ -290,18 +291,18 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer /** * Retrieves shibboleth module info. - * @param protocolRequest current request + * + * @param protocolRequest current request * @param applicationContext spring context * @return IModulInfo * @throws ClassNotFoundException If no shibboleth handling implementation found */ - public static IModulInfo extractShibbolethHandling(IRequest protocolRequest, - ApplicationContext applicationContext) throws ClassNotFoundException { + public static IModulInfo extractShibbolethHandling(IRequest protocolRequest, ApplicationContext applicationContext) + throws ClassNotFoundException { final Class clazz = Class.forName(protocolRequest.requestedModule()); if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { - log.error( - "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + log.error("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); throw new ClassCastException( "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); -- cgit v1.2.3 From 997119b8c25bb256c1bf937d427febf975d570ce Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 31 Mar 2021 15:38:44 +0200 Subject: inf recursion fix --- .../services/ProtocolAuthenticationService.java | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 09977f52..c666eaa9 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -234,8 +234,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer try { ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT) - || errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { + if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT) || errorData.getActionType() + .equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); @@ -340,13 +340,15 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } catch (EaafException e) { // retry - handleErrorNoRedirect(e, req, resp, writeExceptionToStatisticLog, true); - + if (recall) { + handleErrorNoRedirect(e, req, resp, writeExceptionToStatisticLog, true); + } } catch (IOException e) { // retry - handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, e), req, resp, - writeExceptionToStatisticLog, true); - + if (recall) { + handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, e), req, resp, + writeExceptionToStatisticLog, true); + } } } @@ -603,9 +605,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer private String generateErrorRedirectUrl(final HttpServletRequest req, String errorKey) { String redirectUrl = null; redirectUrl = ServletUtils.getBaseUrl(req); - redirectUrl += - "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" - + errorKey; + redirectUrl += "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" + errorKey; return redirectUrl; } -- cgit v1.2.3 From 5dc061db54f17780d3dc8c41d842a496f523af31 Mon Sep 17 00:00:00 2001 From: lalber Date: Thu, 1 Apr 2021 12:38:38 +0200 Subject: new handleErroNoRedirect --- .../services/ProtocolAuthenticationService.java | 50 +++++++--------------- 1 file changed, 16 insertions(+), 34 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index c666eaa9..4ac8bba2 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -310,45 +310,27 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer @Override public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, - final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) { - handleErrorNoRedirect(throwable, req, resp, writeExceptionToStatisticLog, false); - } + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) throws EaafException, IOException { - private void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, - final HttpServletResponse resp, final boolean writeExceptionToStatisticLog, final boolean recall) { ErrorTicketService.HandleData errorData = null; - try { - errorData = errorTicketService.createHandleData(throwable, req); + errorData = errorTicketService.createHandleData(throwable, req); - // log Exception into statistic database - if (writeExceptionToStatisticLog) { - statisticLogger.logErrorOperation(throwable); - } + // log Exception into statistic database + if (writeExceptionToStatisticLog) { + statisticLogger.logErrorOperation(throwable); + } - // write errror to console - logExceptionToTechnicalLog(errorData); + // write errror to console + logExceptionToTechnicalLog(errorData); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData - .getActionType().equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT) || recall) { - // return error to Web browser - displayException(req, resp, errorData); - } else { - // TODO introduce separate error type? - throw new EaafException("internal.configuration.01", new Object[]{ - errorData.getErrorCode() + " in on_error_action" + ".properties", "Erroraction mapping mismatch"}); - } - - } catch (EaafException e) { - // retry - if (recall) { - handleErrorNoRedirect(e, req, resp, writeExceptionToStatisticLog, true); - } - } catch (IOException e) { - // retry - if (recall) { - handleErrorNoRedirect(new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null, e), req, resp, - writeExceptionToStatisticLog, true); - } + if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData.getActionType() + .equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { + // return error to Web browser + displayException(req, resp, errorData); + } else { + // TODO introduce separate error type? + throw new EaafException("internal.configuration.01", new Object[]{ + errorData.getErrorCode() + " in on_error_action" + ".properties", "Erroraction mapping mismatch"}); } } -- cgit v1.2.3 From f18e44490057ba6e5fa719fefc47c8fd2e039b04 Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 7 Apr 2021 16:56:26 +0200 Subject: Interface extraction --- .../impl/idp/auth/services/ErrorTicketService.java | 241 --------------------- .../idp/auth/services/IErrorTicketService.java | 92 ++++++++ .../services/ProtocolAuthenticationService.java | 41 ++-- .../services/IProtocolAuthenticationService.java | 3 +- 4 files changed, 112 insertions(+), 265 deletions(-) delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorTicketService.java diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java deleted file mode 100644 index 08fb04c6..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java +++ /dev/null @@ -1,241 +0,0 @@ -package at.gv.egiz.eaaf.core.impl.idp.auth.services; - -import at.gv.egiz.eaaf.core.api.IStatusMessenger; -import at.gv.egiz.eaaf.core.api.data.EaafConstants; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EaafException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.controller.ProtocolFinalizationController; -import at.gv.egiz.eaaf.core.impl.utils.FileUtils; -import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; -import lombok.Getter; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.stereotype.Service; - -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -@Service() -public class ErrorTicketService { - private static final Logger log = LoggerFactory.getLogger(ErrorTicketService.class); - - private static final String CONFIG_PROP_ERRORHANDLING_ACTION_PATH = "core.errorhandling.action"; - private static final String TECH_LOG_MSG = "errorCode={} Message={}"; - private static final String TICKET_LOG_MSG = "Ticket={} errorCode={} Message={}"; - - private final HashMap propertyMap = new HashMap(); - - - public enum ActionType { - TICKET_REDIRECT("ticket_redirect"), TICKET_NOREDIRECT("ticket_noredirect"), NOTICKET_REDIRECT( - "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"), NOTICKET_AUTOREDIRECT( - "noticket_autoredirect"); - - private final String name; - - ActionType(final String text) { - this.name = text; - } - - @Override - public String toString() { - return name; - } - } - - @Autowired(required = true) - IConfiguration basicConfig; - @Autowired(required = true) - ResourceLoader resourceLoader; - - @PostConstruct - private void initialize() throws EaafException { - log.info("initErrorTicketService"); - - final String ticketConfPath = basicConfig.getBasicConfiguration(CONFIG_PROP_ERRORHANDLING_ACTION_PATH); - log.info("ticketConfPath" + ticketConfPath); - - - if (StringUtils.isEmpty(ticketConfPath)) { - log.error("Error: Path to errorhandling-action mapping not known"); - throw new EaafException("internal.configuration.00", - new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH}); - } else { - - Properties getProperties = new Properties(); - String fullFilePath = null; - try { - - fullFilePath = FileUtils - .makeAbsoluteUrl(ticketConfPath, basicConfig.getConfigurationRootDirectory()); - final Resource ressource = resourceLoader.getResource(fullFilePath); - final InputStream is = ressource.getInputStream(); - getProperties.load(is); - is.close(); - propertyMap.putAll((Map) getProperties); - - // log.error(propertyMap.toString()); - // log.error("working: " + propertyMap.get("auth.00")); - - } catch (Exception e) { - log.error("Error: could not found file.", e); - throw new EaafException("internal.configuration.01", - new Object[]{CONFIG_PROP_ERRORHANDLING_ACTION_PATH, "File for errorhandling-action mapping cloud " - + "not be found."}); - } - } - } - - /** - * creates error handling data. - * @param throwable error - * @param req http request - * @return eror handle Data - * @throws EaafException In case of an internal error - */ - public HandleData createHandleData(Throwable throwable, HttpServletRequest req) throws EaafException { - HandleData data = new HandleData(throwable, req); - extractErrorCode(data); - setUpErrorData(data); - - return data; - } - - private void extractErrorCode(HandleData data) { - Throwable originalException; - if (data.throwable instanceof TaskExecutionException - && ((TaskExecutionException) data.throwable).getOriginalException() != null) { - originalException = ((TaskExecutionException) data.throwable).getOriginalException(); - - } else { - originalException = data.throwable; - - } - - if (!(originalException instanceof EaafException)) { - data.errorCode = IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC; - - } else { - data.errorCode = ((EaafException) originalException).getErrorId(); - - } - } - - private void setUpErrorData(HandleData data) throws EaafException { - - if (propertyMap.containsKey(data.errorCode)) { - String action = propertyMap.get(data.errorCode); - - if (action.equals(ActionType.TICKET_REDIRECT.toString())) { - data.actionType = ActionType.TICKET_REDIRECT; - data.generateSupportTicket(); - data.generateRedirect(); - - } else if (action.equals(ActionType.TICKET_NOREDIRECT.toString())) { - data.actionType = ActionType.TICKET_NOREDIRECT; - data.generateSupportTicket(); - - } else if (action.equals(ActionType.NOTICKET_REDIRECT.toString())) { - data.actionType = ActionType.NOTICKET_REDIRECT; - data.generateRedirect(); - - } else if (action.equals(ActionType.NOTICKET_AUTOREDIRECT.toString())) { - data.actionType = ActionType.NOTICKET_AUTOREDIRECT; - - } else { // ActionType.NOTICKET_NOREDIRECT -> nothing to be done - data.actionType = ActionType.NOTICKET_NOREDIRECT; - - } - - } else { - data.generateSupportTicket(); - throw new EaafException("internal.configuration.00", - new Object[]{data.errorCode + " in on_error_action" + ".properties"}); - } - } - - static class HandleData { - private final HttpServletRequest req; - @Getter - private String supportTicket; - @Getter - private String redirectUrl; - @Getter - private final Throwable throwable; - @Getter - private String errorCode; - @Getter - private ActionType actionType; - - - private HandleData(Throwable throwable, HttpServletRequest req) { - this.throwable = throwable; - this.req = req; - } - - private void generateRedirect() { - redirectUrl = ServletUtils.getBaseUrl(req); - redirectUrl += - "/" + ProtocolFinalizationController.ENDPOINT_ERROR_REDIRECT + "?" + EaafConstants.PARAM_HTTP_ERROR_CODE + "=" - + StringEscapeUtils.escapeHtml4(req.getParameter(EaafConstants.PARAM_HTTP_ERROR_CODE)); - - } - - private void generateSupportTicket() { - - String randomCode = - RandomStringUtils.randomAlphanumeric(4).toUpperCase() + '-' + RandomStringUtils.randomAlphanumeric(4) - .toUpperCase() + '-' + RandomStringUtils.randomAlphanumeric(4).toUpperCase(); - supportTicket = randomCode; - } - - /** - * Logs error to technical log. - */ - public void log_error() { - - if (supportTicket != null) { - log.error(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); - } else { - log.error(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); - } - } - - /** - * Logs info to technical log. - */ - public void log_info() { - - if (supportTicket != null) { - log.info(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); - - } else { - log.info(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); - } - } - - /** - * Logs warn to technical log. - */ - public void log_warn() { - - if (supportTicket != null) { - log.warn(TICKET_LOG_MSG, supportTicket, errorCode, throwable.getMessage(), throwable); - - } else { - log.warn(TECH_LOG_MSG, errorCode, throwable.getMessage(), throwable); - } - } - } -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorTicketService.java new file mode 100644 index 00000000..15a4c7b1 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorTicketService.java @@ -0,0 +1,92 @@ +package at.gv.egiz.eaaf.core.impl.idp.auth.services; + +import at.gv.egiz.eaaf.core.api.gui.ModifyableGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafException; + +import javax.servlet.http.HttpServletRequest; + +public interface IErrorTicketService { + /** + * Describes the kind of action that should be taken. + */ + enum ActionType { + TICKET_REDIRECT("ticket_redirect"), TICKET_NOREDIRECT("ticket_noredirect"), NOTICKET_REDIRECT( + "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"), NOTICKET_AUTOREDIRECT( + "noticket_autoredirect"); + + private final String name; + + ActionType(final String text) { + this.name = text; + } + + @Override + public String toString() { + return name; + } + } + + String PARAM_GUI_TICKET = "supportTicket"; + String PARAM_GUI_REDIRECT = "redirectLink"; + + /** + * creates error handling data. + * + * @param throwable error + * @param req http request + * @return eror handle Data + * @throws EaafException In case of an internal error + */ + IHandleData createHandleData(Throwable throwable, HttpServletRequest req) throws EaafException; + + /** + * Displays the error using suitable errordata. + * + * @param c guibuilder + * @param errorData Data to handle + * @throws EaafException In case of an internal error + */ + void displayErrorData(ModifyableGuiBuilderConfiguration c, IErrorTicketService.IHandleData errorData) + throws EaafException; + + /** + * Contains all the Model data for Error Handling. + */ + interface IHandleData { + /** + * Describes the kind of action that should be taken. + * + * @return The appropriate action + */ + ActionType getActionType(); + + /** + * Get internal errorCode describing the problem. + * + * @return internal error Code. + */ + String getInternalErrorCode(); + + /** + * Get the original throwable of the error. + * + * @return causing throwable + */ + Throwable getThrowable(); + + /** + * Logs error to technical log. + */ + void log_error(); + + /** + * Logs info to technical log. + */ + void log_info(); + + /** + * Logs warn to technical log. + */ + void log_warn(); + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 4ac8bba2..c1c2ab00 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -103,7 +103,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer private IConfiguration basicConfig; @Autowired(required = true) - private ErrorTicketService errorTicketService; + private IErrorTicketService errorTicketService; @Autowired(required = false) private ISsoManager ssoManager; @@ -232,10 +232,10 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer public void buildProtocolSpecificErrorResponse(final Throwable throwable, final HttpServletRequest req, final HttpServletResponse resp, final IRequest protocolRequest) throws EaafException, IOException { try { - ErrorTicketService.HandleData errorData = errorTicketService.createHandleData(throwable, req); + IErrorTicketService.IHandleData errorData = errorTicketService.createHandleData(throwable, req); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.TICKET_REDIRECT) || errorData.getActionType() - .equals(ErrorTicketService.ActionType.NOTICKET_REDIRECT)) { + if (errorData.getActionType().equals(IErrorTicketService.ActionType.TICKET_REDIRECT) || errorData.getActionType() + .equals(IErrorTicketService.ActionType.NOTICKET_REDIRECT)) { // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); @@ -254,7 +254,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer displayException(req, resp, errorData); - } else if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_AUTOREDIRECT)) { + } else if (errorData.getActionType().equals(IErrorTicketService.ActionType.NOTICKET_AUTOREDIRECT)) { IModulInfo handlingModule = extractShibbolethHandling(protocolRequest, applicationContext); if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { @@ -312,7 +312,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) throws EaafException, IOException { - ErrorTicketService.HandleData errorData = null; + IErrorTicketService.IHandleData errorData = null; errorData = errorTicketService.createHandleData(throwable, req); // log Exception into statistic database @@ -323,14 +323,14 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // write errror to console logExceptionToTechnicalLog(errorData); - if (errorData.getActionType().equals(ErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData.getActionType() - .equals(ErrorTicketService.ActionType.TICKET_NOREDIRECT)) { + if (errorData.getActionType().equals(IErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData + .getActionType().equals(IErrorTicketService.ActionType.TICKET_NOREDIRECT)) { // return error to Web browser displayException(req, resp, errorData); } else { // TODO introduce separate error type? throw new EaafException("internal.configuration.01", new Object[]{ - errorData.getErrorCode() + " in on_error_action" + ".properties", "Erroraction mapping mismatch"}); + errorData.getInternalErrorCode() + " in on_error_action" + ".properties", "Erroraction mapping mismatch"}); } } @@ -418,7 +418,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer * * @param data errordata structure */ - protected void logExceptionToTechnicalLog(ErrorTicketService.HandleData data) { + protected void logExceptionToTechnicalLog(IErrorTicketService.IHandleData data) { // In case of a TaskExecutionException, which is only a container for process-errors, // extract internal exception @@ -429,7 +429,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } else { - if (logOnInfoLevel.contains(data.getErrorCode())) { + if (logOnInfoLevel.contains(data.getInternalErrorCode())) { data.log_info(); } else { @@ -492,7 +492,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, - @Nullable final Object[] params, String externalErrorCode, String url, String ticket) throws EaafException { + @Nullable final Object[] params, String externalErrorCode, IErrorTicketService.IHandleData errorData) + throws EaafException { try { final IGuiBuilderConfiguration config = guiConfigFactory @@ -523,8 +524,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer externalErrorCode); c.putCustomParameterWithOutEscaption(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODEPARAMS, ArrayUtils.toString(errorCodeParams)); - c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_TICKET, ticket); - c.putCustomParameter(AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_REDIRECT, url); + errorTicketService.displayErrorData(c, errorData); } else { log.info("Can not ADD error message, because 'GUIBuilderConfiguration' is not modifieable "); @@ -541,9 +541,9 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } private void displayException(final HttpServletRequest req, final HttpServletResponse resp, - final ErrorTicketService.HandleData errorData) throws IOException, EaafException { + final IErrorTicketService.IHandleData errorData) throws IOException, EaafException { final Throwable e = errorData.getThrowable(); - final String internalErrorCode = errorData.getErrorCode(); + final String internalErrorCode = errorData.getInternalErrorCode(); // send error response if (e instanceof ProtocolNotActiveException) { @@ -556,21 +556,18 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer || e instanceof ProcessExecutionException || e instanceof ConfigurationException) { // write error message writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), - errorData.getSupportTicket()); + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData); } else if (e instanceof EaafException) { // send HTML formated error message writeHtmlErrorResponse(req, resp, e.getMessage(), internalErrorCode, ((EaafException) e).getParams(), - statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), - errorData.getSupportTicket()); + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData); } else { // write generic message for general exceptions final String msg = statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); writeHtmlErrorResponse(req, resp, msg, internalErrorCode, null, - statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData.getRedirectUrl(), - errorData.getSupportTicket()); + statusMessager.mapInternalErrorToExternalError(internalErrorCode), errorData); } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java index 7387f706..ad48e8ee 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java @@ -36,8 +36,7 @@ public interface IProtocolAuthenticationService { String PARAM_GUI_EXTERNAL_ERRORCODE = "extErrorCode"; String PARAM_GUI_ERRORCODEPARAMS = "errorParams"; String PARAM_GUI_ERRORSTACKTRACE = "stacktrace"; - String PARAM_GUI_TICKET = "supportTicket"; - String PARAM_GUI_REDIRECT = "redirectLink"; + /** * Initialize an authentication process for this protocol request. -- cgit v1.2.3 From a83cb260d07d54aba1ea354f76f0eb8943cc8c6f Mon Sep 17 00:00:00 2001 From: lalber Date: Thu, 8 Apr 2021 12:41:01 +0200 Subject: Rename interface --- .../core/impl/idp/auth/services/IErrorService.java | 92 ++++++++++++++++++++++ .../idp/auth/services/IErrorTicketService.java | 92 ---------------------- .../services/ProtocolAuthenticationService.java | 22 +++--- 3 files changed, 103 insertions(+), 103 deletions(-) create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorTicketService.java diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java new file mode 100644 index 00000000..7c9c34c9 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java @@ -0,0 +1,92 @@ +package at.gv.egiz.eaaf.core.impl.idp.auth.services; + +import at.gv.egiz.eaaf.core.api.gui.ModifyableGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafException; + +import javax.servlet.http.HttpServletRequest; + +public interface IErrorService { + /** + * Describes the kind of action that should be taken. + */ + enum ActionType { + TICKET_REDIRECT("ticket_redirect"), TICKET_NOREDIRECT("ticket_noredirect"), NOTICKET_REDIRECT( + "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"), NOTICKET_AUTOREDIRECT( + "noticket_autoredirect"); + + private final String name; + + ActionType(final String text) { + this.name = text; + } + + @Override + public String toString() { + return name; + } + } + + String PARAM_GUI_TICKET = "supportTicket"; + String PARAM_GUI_REDIRECT = "redirectLink"; + + /** + * creates error handling data. + * + * @param throwable error + * @param req http request + * @return eror handle Data + * @throws EaafException In case of an internal error + */ + IHandleData createHandleData(Throwable throwable, HttpServletRequest req) throws EaafException; + + /** + * Displays the error using suitable errordata. + * + * @param c guibuilder + * @param errorData Data to handle + * @throws EaafException In case of an internal error + */ + void displayErrorData(ModifyableGuiBuilderConfiguration c, IErrorService.IHandleData errorData) + throws EaafException; + + /** + * Contains all the Model data for Error Handling. + */ + interface IHandleData { + /** + * Describes the kind of action that should be taken. + * + * @return The appropriate action + */ + ActionType getActionType(); + + /** + * Get internal errorCode describing the problem. + * + * @return internal error Code. + */ + String getInternalErrorCode(); + + /** + * Get the original throwable of the error. + * + * @return causing throwable + */ + Throwable getThrowable(); + + /** + * Logs error to technical log. + */ + void log_error(); + + /** + * Logs info to technical log. + */ + void log_info(); + + /** + * Logs warn to technical log. + */ + void log_warn(); + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorTicketService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorTicketService.java deleted file mode 100644 index 15a4c7b1..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorTicketService.java +++ /dev/null @@ -1,92 +0,0 @@ -package at.gv.egiz.eaaf.core.impl.idp.auth.services; - -import at.gv.egiz.eaaf.core.api.gui.ModifyableGuiBuilderConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EaafException; - -import javax.servlet.http.HttpServletRequest; - -public interface IErrorTicketService { - /** - * Describes the kind of action that should be taken. - */ - enum ActionType { - TICKET_REDIRECT("ticket_redirect"), TICKET_NOREDIRECT("ticket_noredirect"), NOTICKET_REDIRECT( - "noticket_redirect"), NOTICKET_NOREDIRECT("noticket_noredirect"), NOTICKET_AUTOREDIRECT( - "noticket_autoredirect"); - - private final String name; - - ActionType(final String text) { - this.name = text; - } - - @Override - public String toString() { - return name; - } - } - - String PARAM_GUI_TICKET = "supportTicket"; - String PARAM_GUI_REDIRECT = "redirectLink"; - - /** - * creates error handling data. - * - * @param throwable error - * @param req http request - * @return eror handle Data - * @throws EaafException In case of an internal error - */ - IHandleData createHandleData(Throwable throwable, HttpServletRequest req) throws EaafException; - - /** - * Displays the error using suitable errordata. - * - * @param c guibuilder - * @param errorData Data to handle - * @throws EaafException In case of an internal error - */ - void displayErrorData(ModifyableGuiBuilderConfiguration c, IErrorTicketService.IHandleData errorData) - throws EaafException; - - /** - * Contains all the Model data for Error Handling. - */ - interface IHandleData { - /** - * Describes the kind of action that should be taken. - * - * @return The appropriate action - */ - ActionType getActionType(); - - /** - * Get internal errorCode describing the problem. - * - * @return internal error Code. - */ - String getInternalErrorCode(); - - /** - * Get the original throwable of the error. - * - * @return causing throwable - */ - Throwable getThrowable(); - - /** - * Logs error to technical log. - */ - void log_error(); - - /** - * Logs info to technical log. - */ - void log_info(); - - /** - * Logs warn to technical log. - */ - void log_warn(); - } -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index c1c2ab00..be24d586 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -103,7 +103,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer private IConfiguration basicConfig; @Autowired(required = true) - private IErrorTicketService errorTicketService; + private IErrorService errorTicketService; @Autowired(required = false) private ISsoManager ssoManager; @@ -232,10 +232,10 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer public void buildProtocolSpecificErrorResponse(final Throwable throwable, final HttpServletRequest req, final HttpServletResponse resp, final IRequest protocolRequest) throws EaafException, IOException { try { - IErrorTicketService.IHandleData errorData = errorTicketService.createHandleData(throwable, req); + IErrorService.IHandleData errorData = errorTicketService.createHandleData(throwable, req); - if (errorData.getActionType().equals(IErrorTicketService.ActionType.TICKET_REDIRECT) || errorData.getActionType() - .equals(IErrorTicketService.ActionType.NOTICKET_REDIRECT)) { + if (errorData.getActionType().equals(IErrorService.ActionType.TICKET_REDIRECT) || errorData.getActionType() + .equals(IErrorService.ActionType.NOTICKET_REDIRECT)) { // Put pending request ExceptionContainer exceptionContainer = new ExceptionContainer(protocolRequest, throwable); @@ -254,7 +254,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer displayException(req, resp, errorData); - } else if (errorData.getActionType().equals(IErrorTicketService.ActionType.NOTICKET_AUTOREDIRECT)) { + } else if (errorData.getActionType().equals(IErrorService.ActionType.NOTICKET_AUTOREDIRECT)) { IModulInfo handlingModule = extractShibbolethHandling(protocolRequest, applicationContext); if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { @@ -312,7 +312,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) throws EaafException, IOException { - IErrorTicketService.IHandleData errorData = null; + IErrorService.IHandleData errorData = null; errorData = errorTicketService.createHandleData(throwable, req); // log Exception into statistic database @@ -323,8 +323,8 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // write errror to console logExceptionToTechnicalLog(errorData); - if (errorData.getActionType().equals(IErrorTicketService.ActionType.NOTICKET_NOREDIRECT) || errorData - .getActionType().equals(IErrorTicketService.ActionType.TICKET_NOREDIRECT)) { + if (errorData.getActionType().equals(IErrorService.ActionType.NOTICKET_NOREDIRECT) || errorData + .getActionType().equals(IErrorService.ActionType.TICKET_NOREDIRECT)) { // return error to Web browser displayException(req, resp, errorData); } else { @@ -418,7 +418,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer * * @param data errordata structure */ - protected void logExceptionToTechnicalLog(IErrorTicketService.IHandleData data) { + protected void logExceptionToTechnicalLog(IErrorService.IHandleData data) { // In case of a TaskExecutionException, which is only a container for process-errors, // extract internal exception @@ -492,7 +492,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, - @Nullable final Object[] params, String externalErrorCode, IErrorTicketService.IHandleData errorData) + @Nullable final Object[] params, String externalErrorCode, IErrorService.IHandleData errorData) throws EaafException { try { @@ -541,7 +541,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } private void displayException(final HttpServletRequest req, final HttpServletResponse resp, - final IErrorTicketService.IHandleData errorData) throws IOException, EaafException { + final IErrorService.IHandleData errorData) throws IOException, EaafException { final Throwable e = errorData.getThrowable(); final String internalErrorCode = errorData.getInternalErrorCode(); -- cgit v1.2.3 From b14c0c9ff91a9ef1a3236f5bbf41278f6d0a4725 Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 14 Apr 2021 20:10:38 +0200 Subject: ready for Tests --- .../at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java index 7c9c34c9..3f4b7f5e 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java @@ -29,6 +29,13 @@ public interface IErrorService { String PARAM_GUI_TICKET = "supportTicket"; String PARAM_GUI_REDIRECT = "redirectLink"; + /** + * Maps internal error codes to external ones. + * @param internalCode internal error code + * @return external error code + */ + String getExternalCodeFromInternal(String internalCode); + /** * creates error handling data. * -- cgit v1.2.3 From 4a418d3a55752850891dbb9a6b10d03728a27520 Mon Sep 17 00:00:00 2001 From: lalber Date: Wed, 14 Apr 2021 21:54:08 +0200 Subject: log level via config --- .../core/impl/idp/auth/services/IErrorService.java | 17 ++++-------- .../services/ProtocolAuthenticationService.java | 32 ++-------------------- 2 files changed, 8 insertions(+), 41 deletions(-) diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java index 3f4b7f5e..812a5171 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/IErrorService.java @@ -4,6 +4,7 @@ import at.gv.egiz.eaaf.core.api.gui.ModifyableGuiBuilderConfiguration; import at.gv.egiz.eaaf.core.exceptions.EaafException; import javax.servlet.http.HttpServletRequest; +import java.util.HashSet; public interface IErrorService { /** @@ -82,18 +83,10 @@ public interface IErrorService { Throwable getThrowable(); /** - * Logs error to technical log. - */ - void log_error(); - - /** - * Logs info to technical log. - */ - void log_info(); - - /** - * Logs warn to technical log. + * Write a Exception to the MOA-ID-Auth internal technical log. + * + * @param logOnInfoLevel set of what to log on info logging lvl */ - void log_warn(); + void logExceptionToTechnicalLog(HashSet logOnInfoLevel); } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index be24d586..ffa1163f 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -247,7 +247,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer // log Error to technical log - logExceptionToTechnicalLog(errorData); + errorData.logExceptionToTechnicalLog(logOnInfoLevel); // log Error Message statisticLogger.logErrorOperation(throwable, protocolRequest); @@ -260,7 +260,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { // log Error to technical log - logExceptionToTechnicalLog(errorData); + errorData.logExceptionToTechnicalLog(logOnInfoLevel); // log Error Message statisticLogger.logErrorOperation(throwable, protocolRequest); @@ -321,7 +321,7 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } // write errror to console - logExceptionToTechnicalLog(errorData); + errorData.logExceptionToTechnicalLog(logOnInfoLevel); if (errorData.getActionType().equals(IErrorService.ActionType.NOTICKET_NOREDIRECT) || errorData .getActionType().equals(IErrorService.ActionType.TICKET_NOREDIRECT)) { @@ -413,32 +413,6 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer } - /** - * Write a Exception to the MOA-ID-Auth internal technical log. - * - * @param data errordata structure - */ - protected void logExceptionToTechnicalLog(IErrorService.IHandleData data) { - // In case of a TaskExecutionException, which is only a container for process-errors, - // extract internal exception - - - // Log exception - if (!(data.getThrowable() instanceof EaafException)) { - data.log_error(); - - } else { - - if (logOnInfoLevel.contains(data.getInternalErrorCode())) { - data.log_info(); - - } else { - data.log_warn(); - - } - } - } - @PostConstruct private void initializer() { -- cgit v1.2.3 From a849dd49daf60128db79311293d7f5c466bd0642 Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Fri, 16 Apr 2021 22:08:42 +0200 Subject: Use custom SSLContext builder to generate BouncyCastle specific TrustManager in case of keys base on HSM-Facade, because SSLContext based on BCJSSE needs BCJSSE TrustManager BCJSSE is not compatible to SunJSSE TrustManager in Java >= 9 --- eaaf_core_utils/pom.xml | 17 +- .../eaaf/core/impl/http/EaafSslContextBuilder.java | 433 +++++++++++++++++++++ .../at/gv/egiz/eaaf/core/impl/http/HttpUtils.java | 22 +- .../test/http/HttpClientFactoryProdHostTest.java | 98 +++++ .../eaaf/core/test/http/HttpClientFactoryTest.java | 96 +++++ .../test/resources/data/hsm_ee-RSA_rootcert.crt | 3 + .../src/test/resources/data/hsm_ee_eecert.crt | 3 + .../src/test/resources/data/hsm_ee_rootcert.crt | 3 + .../src/test/resources/data/server_host.crt | 18 + .../src/test/resources/data/ssL_truststore.jks | Bin 0 -> 799 bytes .../src/test/resources/data/ssl_host.jks | Bin 0 -> 2081 bytes pom.xml | 4 +- 12 files changed, 682 insertions(+), 15 deletions(-) create mode 100644 eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/http/EaafSslContextBuilder.java create mode 100644 eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/http/HttpClientFactoryProdHostTest.java create mode 100644 eaaf_core_utils/src/test/resources/data/hsm_ee-RSA_rootcert.crt create mode 100644 eaaf_core_utils/src/test/resources/data/hsm_ee_eecert.crt create mode 100644 eaaf_core_utils/src/test/resources/data/hsm_ee_rootcert.crt create mode 100644 eaaf_core_utils/src/test/resources/data/server_host.crt create mode 100644 eaaf_core_utils/src/test/resources/data/ssL_truststore.jks create mode 100644 eaaf_core_utils/src/test/resources/data/ssl_host.jks diff --git a/eaaf_core_utils/pom.xml b/eaaf_core_utils/pom.xml index 4e3bbeee..e0cb88e3 100644 --- a/eaaf_core_utils/pom.xml +++ b/eaaf_core_utils/pom.xml @@ -121,8 +121,23 @@ com.squareup.okhttp3 okhttp-tls test + + + org.bouncycastle + bctls-jdk15on + + + org.bouncycastle + bcpkix-jdk15on + + + + + ch.qos.logback + logback-classic + 1.2.3 + test - diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/http/EaafSslContextBuilder.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/http/EaafSslContextBuilder.java new file mode 100644 index 00000000..1cd739de --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/http/EaafSslContextBuilder.java @@ -0,0 +1,433 @@ +package at.gv.egiz.eaaf.core.impl.http; + +import java.net.Socket; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.SecureRandom; +import java.security.Security; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509ExtendedKeyManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.http.ssl.PrivateKeyDetails; +import org.apache.http.ssl.PrivateKeyStrategy; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.TrustStrategy; +import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider; + +/** + * Fork of {@link SSLContextBuilder} that uses JSSE provider to get TrustManager. + * + *

This implementation fix an incompatibility between {@link BouncyCastleJsseProvider} and JAVA JDK >= v9

+ * + * @author tlenz + * + */ +public class EaafSslContextBuilder { + + static final String TLS = "TLS"; + + private String protocol; + private final Set keyManagers; + private String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); + private String keyStoreType = KeyStore.getDefaultType(); + private final Set trustManagers; + private String trustManagerFactoryAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); + private SecureRandom secureRandom; + private Provider provider; + + public static EaafSslContextBuilder create() { + return new EaafSslContextBuilder(); + } + + /** + * Get a new SSLContext builder object. + */ + public EaafSslContextBuilder() { + super(); + this.keyManagers = new LinkedHashSet<>(); + this.trustManagers = new LinkedHashSet<>(); + } + + /** + * Sets the SSLContext protocol algorithm name. + * + * @param protocol the SSLContext protocol algorithm name of the requested + * protocol. See the SSLContext section in the Java + * Cryptography Architecture Standard Algorithm Name + * Documentation for more information. + * @return this builder + * @see Java + * Cryptography Architecture Standard Algorithm Name Documentation + * @deprecated Use {@link #setProtocol(String)}. + */ + @Deprecated + public EaafSslContextBuilder useProtocol(final String protocol) { + this.protocol = protocol; + return this; + } + + /** + * Sets the SSLContext protocol algorithm name. + * + * @param protocol the SSLContext protocol algorithm name of the requested + * protocol. See the SSLContext section in the Java + * Cryptography Architecture Standard Algorithm Name + * Documentation for more information. + * @return this builder + * @see Java + * Cryptography Architecture Standard Algorithm Name Documentation + * @since 4.4.7 + */ + public EaafSslContextBuilder setProtocol(final String protocol) { + this.protocol = protocol; + return this; + } + + public EaafSslContextBuilder setSecureRandom(final SecureRandom secureRandom) { + this.secureRandom = secureRandom; + return this; + } + + public EaafSslContextBuilder setProvider(final Provider provider) { + this.provider = provider; + return this; + } + + public EaafSslContextBuilder setProvider(final String name) { + this.provider = Security.getProvider(name); + return this; + } + + /** + * Sets the key store type. + * + * @param keyStoreType the SSLkey store type. See the KeyStore section in the + * Java + * Cryptography Architecture Standard Algorithm Name + * Documentation for more information. + * @return this builder + * @see Java + * Cryptography Architecture Standard Algorithm Name Documentation + * @since 4.4.7 + */ + public EaafSslContextBuilder setKeyStoreType(final String keyStoreType) { + this.keyStoreType = keyStoreType; + return this; + } + + /** + * Sets the key manager factory algorithm name. + * + * @param keyManagerFactoryAlgorithm the key manager factory algorithm name of + * the requested protocol. See the + * KeyManagerFactory section in the Java + * Cryptography Architecture Standard + * Algorithm Name Documentation for more + * information. + * @return this builder + * @see Java + * Cryptography Architecture Standard Algorithm Name Documentation + * @since 4.4.7 + */ + public EaafSslContextBuilder setKeyManagerFactoryAlgorithm(final String keyManagerFactoryAlgorithm) { + this.keyManagerFactoryAlgorithm = keyManagerFactoryAlgorithm; + return this; + } + + /** + * Sets the trust manager factory algorithm name. + * + * @param trustManagerFactoryAlgorithm the trust manager algorithm name of the + * requested protocol. See the + * TrustManagerFactory section in the + * Java + * Cryptography Architecture Standard + * Algorithm Name Documentation for more + * information. + * @return this builder + * @see Java + * Cryptography Architecture Standard Algorithm Name Documentation + * @since 4.4.7 + */ + public EaafSslContextBuilder setTrustManagerFactoryAlgorithm(final String trustManagerFactoryAlgorithm) { + this.trustManagerFactoryAlgorithm = trustManagerFactoryAlgorithm; + return this; + } + + /** + * Load custom truststore. + * + * @param truststore {@link KeyStore} if trusted certificates + * @param trustStrategy Trust validation strategy + * @return {@link EaafSslContextBuilder} + * @throws NoSuchAlgorithmException In case of an invalid TrustManager algorithm + * @throws KeyStoreException In case of an invalid KeyStore + */ + public EaafSslContextBuilder loadTrustMaterial( + final KeyStore truststore, + final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException { + + final String alg = trustManagerFactoryAlgorithm == null + ? TrustManagerFactory.getDefaultAlgorithm() + : trustManagerFactoryAlgorithm; + + final TrustManagerFactory tmfactory = provider != null + ? TrustManagerFactory.getInstance(alg, provider) + : TrustManagerFactory.getInstance(alg); + tmfactory.init(truststore); + final TrustManager[] tms = tmfactory.getTrustManagers(); + if (tms != null) { + if (trustStrategy != null) { + for (int i = 0; i < tms.length; i++) { + final TrustManager tm = tms[i]; + if (tm instanceof X509TrustManager) { + tms[i] = new TrustManagerDelegate((X509TrustManager) tm, trustStrategy); + } + } + } + Collections.addAll(this.trustManagers, tms); + } + return this; + } + + public EaafSslContextBuilder loadTrustMaterial( + final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException { + return loadTrustMaterial(null, trustStrategy); + } + + + /** + * Load SSL client-authentication key-material into SSL context. + * + * @param keystore {@link KeyStore} for SSL client-authentication + * @param keyPassword Password for this keystore + * @param aliasStrategy Stategy to select keys by alias + * @return {@link EaafSslContextBuilder} + * @throws NoSuchAlgorithmException In case of an invalid KeyManagerFactory algorithm + * @throws KeyStoreException In case of an invalid KeyStore + * @throws UnrecoverableKeyException In case of a invalid Key in this KeyStore + */ + public EaafSslContextBuilder loadKeyMaterial( + final KeyStore keystore, + final char[] keyPassword, + final PrivateKeyStrategy aliasStrategy) + throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { + final KeyManagerFactory kmfactory = KeyManagerFactory + .getInstance(keyManagerFactoryAlgorithm == null ? KeyManagerFactory.getDefaultAlgorithm() + : keyManagerFactoryAlgorithm); + kmfactory.init(keystore, keyPassword); + final KeyManager[] kms = kmfactory.getKeyManagers(); + if (kms != null) { + if (aliasStrategy != null) { + for (int i = 0; i < kms.length; i++) { + final KeyManager km = kms[i]; + if (km instanceof X509ExtendedKeyManager) { + kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy); + } + } + } + Collections.addAll(keyManagers, kms); + } + return this; + } + + public EaafSslContextBuilder loadKeyMaterial( + final KeyStore keystore, + final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, + UnrecoverableKeyException { + return loadKeyMaterial(keystore, keyPassword, null); + } + + protected void initSslContext( + final SSLContext sslContext, + final Collection keyManagers, + final Collection trustManagers, + final SecureRandom secureRandom) throws KeyManagementException { + sslContext.init( + !keyManagers.isEmpty() ? keyManagers.toArray(new KeyManager[keyManagers.size()]) : null, + !trustManagers.isEmpty() ? trustManagers.toArray(new TrustManager[trustManagers.size()]) : null, + secureRandom); + } + + /** + * Build a {@link SSLContext} from this builder. + * + * @return new {@link SSLContext} + * @throws NoSuchAlgorithmException In case of an unknown SSL protocol + * @throws KeyManagementException In case of a key-access error + */ + public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException { + final SSLContext sslContext; + final String protocolStr = this.protocol != null ? this.protocol : TLS; + if (this.provider != null) { + sslContext = SSLContext.getInstance(protocolStr, this.provider); + } else { + sslContext = SSLContext.getInstance(protocolStr); + } + initSslContext(sslContext, keyManagers, trustManagers, secureRandom); + return sslContext; + } + + static class TrustManagerDelegate implements X509TrustManager { + + private final X509TrustManager trustManager; + private final TrustStrategy trustStrategy; + + TrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) { + super(); + this.trustManager = trustManager; + this.trustStrategy = trustStrategy; + } + + @Override + public void checkClientTrusted( + final X509Certificate[] chain, final String authType) throws CertificateException { + this.trustManager.checkClientTrusted(chain, authType); + } + + @Override + public void checkServerTrusted( + final X509Certificate[] chain, final String authType) throws CertificateException { + if (!this.trustStrategy.isTrusted(chain, authType)) { + this.trustManager.checkServerTrusted(chain, authType); + } + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return this.trustManager.getAcceptedIssuers(); + } + + } + + static class KeyManagerDelegate extends X509ExtendedKeyManager { + + private final X509ExtendedKeyManager keyManager; + private final PrivateKeyStrategy aliasStrategy; + + KeyManagerDelegate(final X509ExtendedKeyManager keyManager, final PrivateKeyStrategy aliasStrategy) { + super(); + this.keyManager = keyManager; + this.aliasStrategy = aliasStrategy; + } + + @Override + public String[] getClientAliases( + final String keyType, final Principal[] issuers) { + return this.keyManager.getClientAliases(keyType, issuers); + } + + public Map getClientAliasMap( + final String[] keyTypes, final Principal[] issuers) { + final Map validAliases = new HashMap<>(); + for (final String keyType : keyTypes) { + final String[] aliases = this.keyManager.getClientAliases(keyType, issuers); + if (aliases != null) { + for (final String alias : aliases) { + validAliases.put(alias, + new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); + } + } + } + return validAliases; + } + + public Map getServerAliasMap( + final String keyType, final Principal[] issuers) { + final Map validAliases = new HashMap<>(); + final String[] aliases = this.keyManager.getServerAliases(keyType, issuers); + if (aliases != null) { + for (final String alias : aliases) { + validAliases.put(alias, + new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); + } + } + return validAliases; + } + + @Override + public String chooseClientAlias( + final String[] keyTypes, final Principal[] issuers, final Socket socket) { + final Map validAliases = getClientAliasMap(keyTypes, issuers); + return this.aliasStrategy.chooseAlias(validAliases, socket); + } + + @Override + public String[] getServerAliases( + final String keyType, final Principal[] issuers) { + return this.keyManager.getServerAliases(keyType, issuers); + } + + @Override + public String chooseServerAlias( + final String keyType, final Principal[] issuers, final Socket socket) { + final Map validAliases = getServerAliasMap(keyType, issuers); + return this.aliasStrategy.chooseAlias(validAliases, socket); + } + + @Override + public X509Certificate[] getCertificateChain(final String alias) { + return this.keyManager.getCertificateChain(alias); + } + + @Override + public PrivateKey getPrivateKey(final String alias) { + return this.keyManager.getPrivateKey(alias); + } + + @Override + public String chooseEngineClientAlias( + final String[] keyTypes, final Principal[] issuers, final SSLEngine sslEngine) { + final Map validAliases = getClientAliasMap(keyTypes, issuers); + return this.aliasStrategy.chooseAlias(validAliases, null); + } + + @Override + public String chooseEngineServerAlias( + final String keyType, final Principal[] issuers, final SSLEngine sslEngine) { + final Map validAliases = getServerAliasMap(keyType, issuers); + return this.aliasStrategy.chooseAlias(validAliases, null); + } + + } + + @Override + public String toString() { + return "[provider=" + provider + ", protocol=" + protocol + ", keyStoreType=" + keyStoreType + + ", keyManagerFactoryAlgorithm=" + keyManagerFactoryAlgorithm + ", keyManagers=" + keyManagers + + ", trustManagerFactoryAlgorithm=" + trustManagerFactoryAlgorithm + ", trustManagers=" + + trustManagers + + ", secureRandom=" + secureRandom + "]"; + } +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/http/HttpUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/http/HttpUtils.java index 365e969d..3058c9b5 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/http/HttpUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/http/HttpUtils.java @@ -40,8 +40,6 @@ import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.conn.ssl.TrustAllStrategy; import org.apache.http.entity.ContentType; -import org.apache.http.ssl.SSLContextBuilder; -import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider; @@ -56,7 +54,6 @@ import lombok.extern.slf4j.Slf4j; public class HttpUtils { private static final String ERROR_03 = "internal.httpclient.03"; - /** * Simple Http response-handler that only give http status-code as result. @@ -174,7 +171,7 @@ public class HttpUtils { * @param url URL * @param paramname Name of the parameter. * @param paramvalue Value of the parameter. - * @return + * @return Url with parameter */ public static String addUrlParameter(final String url, final String paramname, final String paramvalue) { @@ -210,7 +207,7 @@ public class HttpUtils { boolean trustAllServerCertificates, @Nonnull String friendlyName) throws EaafConfigurationException, EaafFactoryException { try { - SSLContextBuilder sslContextBuilder = SSLContexts.custom(); + EaafSslContextBuilder sslContextBuilder = EaafSslContextBuilder.create(); injectKeyStore(sslContextBuilder, keyStore, keyAlias, keyPasswordString, friendlyName); @@ -251,7 +248,7 @@ public class HttpUtils { @Nonnull String friendlyName) throws EaafConfigurationException, EaafFactoryException { try { - SSLContextBuilder sslContextBuilder = SSLContexts.custom(); + EaafSslContextBuilder sslContextBuilder = EaafSslContextBuilder.create(); injectKeyStore(sslContextBuilder, keyStore, keyAlias, keyPasswordString, friendlyName); @@ -266,7 +263,7 @@ public class HttpUtils { } } - private static void injectTrustStore(SSLContextBuilder sslContextBuilder, + private static void injectTrustStore(EaafSslContextBuilder sslContextBuilder, Pair trustStore, boolean trustAllServerCertificates, String friendlyName) throws NoSuchAlgorithmException, KeyStoreException { @@ -276,7 +273,7 @@ public class HttpUtils { trustStrategy = new TrustAllStrategy(); } - + KeyStore trustStoreImpl = null; if (trustStore != null) { log.info("Http-client: {} uses custom TrustStore.", friendlyName); @@ -288,16 +285,18 @@ public class HttpUtils { } - private static void injectKeyStore(SSLContextBuilder sslContextBuilder, Pair keyStore, + private static void injectKeyStore(EaafSslContextBuilder sslContextBuilder, Pair keyStore, String keyAlias, String keyPasswordString, String friendlyName) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { + + Provider provider; if (keyStore.getSecond() != null) { - Provider provider = new BouncyCastleJsseProvider(keyStore.getSecond()); + provider = new BouncyCastleJsseProvider(keyStore.getSecond()); log.debug("KeyStore: {} provide special security-provider. Inject: {} into SSLContext", friendlyName, provider.getName()); sslContextBuilder.setProvider(provider); - } + } log.trace("Open SSL Client-Auth keystore with password: {}", keyPasswordString); final char[] keyPassword = keyPasswordString == null ? StringUtils.EMPTY.toCharArray() @@ -313,5 +312,4 @@ public class HttpUtils { } } - } diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/http/HttpClientFactoryProdHostTest.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/http/HttpClientFactoryProdHostTest.java new file mode 100644 index 00000000..55c17ee8 --- /dev/null +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/http/HttpClientFactoryProdHostTest.java @@ -0,0 +1,98 @@ +package at.gv.egiz.eaaf.core.test.http; + +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.Base64; + +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.MethodMode; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.http.HttpClientConfiguration; +import at.gv.egiz.eaaf.core.impl.http.IHttpClientFactory; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/spring/test_eaaf_pvp_not_lazy.beans.xml") +@DirtiesContext +public class HttpClientFactoryProdHostTest { + + @Autowired private IHttpClientFactory httpClientFactory; + @Autowired private EaafKeyStoreFactory keyStoreFactory; + + /** + * Initialize full class. + */ + @BeforeClass + public static void classInitializer() { + final Logger logger = (Logger) LoggerFactory.getLogger("org.bouncycastle.jsse"); + logger.setLevel(Level.TRACE); + + } + + /** + * JUnit test set-up. + * + */ + @Before + public void setup() { + + } + + @Test + @DirtiesContext(methodMode = MethodMode.BEFORE_METHOD) + public void getCustomClientX509AuthWithHsmFacadeTrustStore() throws EaafException, ClientProtocolException, + IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, + CertificateEncodingException { + System.setProperty("javax.net.debug", "ssl:handshake"); + + final HttpClientConfiguration clientConfig = new HttpClientConfiguration("jUnit-client"); + clientConfig.setAuthMode("ssl"); + //clientConfig.buildKeyStoreConfig("hsmfacade", null, null, "eid-junit"); + //clientConfig.setSslKeyAlias("rsa-key-1"); + clientConfig.buildKeyStoreConfig("hsmfacade", null, null, "authhandler"); + clientConfig.setSslKeyAlias("authhandler-sign"); + clientConfig.setDisableTlsHostCertificateValidation(false); + + final CloseableHttpClient client = httpClientFactory.getHttpClient(clientConfig); + Assert.assertNotNull("httpClient", client); + + final Pair sslClientKeyStore = + keyStoreFactory.buildNewKeyStore(clientConfig.getKeyStoreConfig()); + final X509Certificate clientRootCert = (X509Certificate) sslClientKeyStore.getFirst() + .getCertificateChain(clientConfig.getSslKeyAlias())[1]; + final X509Certificate clientEeCert = (X509Certificate) sslClientKeyStore.getFirst() + .getCertificateChain(clientConfig.getSslKeyAlias())[0]; + Base64.getEncoder().encodeToString(clientEeCert.getEncoded()); + + //perform test request + final HttpUriRequest httpGet2 = new HttpGet("https://apps.egiz.gv.at//sslclientcertdemo/"); + final CloseableHttpResponse httpResp2 = client.execute(httpGet2); + Assert.assertEquals("http statusCode", 200, httpResp2.getStatusLine().getStatusCode()); + + } + +} diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/http/HttpClientFactoryTest.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/http/HttpClientFactoryTest.java index baedadc8..c71d8352 100644 --- a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/http/HttpClientFactoryTest.java +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/test/http/HttpClientFactoryTest.java @@ -5,9 +5,14 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.SocketTimeoutException; +import java.security.Key; +import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; import java.security.Provider; +import java.security.UnrecoverableKeyException; import java.security.cert.X509Certificate; import org.apache.commons.lang3.RandomStringUtils; @@ -20,10 +25,13 @@ import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.MethodMode; @@ -32,12 +40,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.impl.credential.EaafKeyStoreFactory; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration; +import at.gv.egiz.eaaf.core.impl.credential.KeyStoreConfiguration.KeyStoreType; import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.data.Triple; import at.gv.egiz.eaaf.core.impl.http.HttpClientConfiguration; import at.gv.egiz.eaaf.core.impl.http.HttpUtils; import at.gv.egiz.eaaf.core.impl.http.IHttpClientFactory; import at.gv.egiz.eaaf.core.impl.utils.StreamUtils; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; import okhttp3.HttpUrl; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; @@ -57,6 +69,27 @@ public class HttpClientFactoryTest { private MockWebServer mockWebServer = null; private HttpUrl mockServerUrl; + /** + * Initialize full class. + */ + @BeforeClass + public static void classInitializer() { + final Logger logger = (Logger) LoggerFactory.getLogger("org.bouncycastle.jsse"); + logger.setLevel(Level.TRACE); + + } + + /** + * Reset test environment. + */ + @AfterClass + public static void classReset() { + System.clearProperty("javax.net.ssl.trustStoreType"); + System.clearProperty("javax.net.ssl.trustStore"); + System.clearProperty("javax.net.ssl.trustStorePassword"); + + } + /** * JUnit test set-up. * @@ -595,4 +628,67 @@ public class HttpClientFactoryTest { } + @Test + @DirtiesContext(methodMode = MethodMode.BEFORE_METHOD) + public void getCustomClientX509AuthWithHsmFacadeTrustStore() throws EaafException, ClientProtocolException, + IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { + + final String current = new java.io.File(".").getCanonicalPath(); + System.setProperty("javax.net.ssl.trustStoreType", "jks"); + System.setProperty("javax.net.ssl.trustStore", + current + "/src/test/resources/data/ssL_truststore.jks"); + System.setProperty("javax.net.ssl.trustStorePassword", + "password"); + + final KeyStoreConfiguration sslServerCertConfig = new KeyStoreConfiguration(); + sslServerCertConfig.setKeyStoreType(KeyStoreType.JKS); + sslServerCertConfig.setFriendlyName("SSL host cert"); + sslServerCertConfig.setSoftKeyStoreFilePath("src/test/resources/data/ssl_host.jks"); + sslServerCertConfig.setSoftKeyStorePassword("password"); + + Pair sslServerHostKeyStore = + keyStoreFactory.buildNewKeyStore(sslServerCertConfig); + + + final HttpClientConfiguration clientConfig = new HttpClientConfiguration("jUnit-client"); + clientConfig.setAuthMode("ssl"); + clientConfig.buildKeyStoreConfig("hsmfacade", null, null, "authhandler"); + clientConfig.setSslKeyAlias("authhandler-sign"); + clientConfig.setDisableTlsHostCertificateValidation(false); + + final CloseableHttpClient client = httpClientFactory.getHttpClient(clientConfig); + Assert.assertNotNull("httpClient", client); + + //set-up mock-up web-server with SSL client authentication + final Pair sslClientKeyStore = + keyStoreFactory.buildNewKeyStore(clientConfig.getKeyStoreConfig()); + final X509Certificate clientRootCert = (X509Certificate) sslClientKeyStore.getFirst() + .getCertificateChain(clientConfig.getSslKeyAlias())[1]; + final X509Certificate clientEeCert = (X509Certificate) sslClientKeyStore.getFirst() + .getCertificateChain(clientConfig.getSslKeyAlias())[0]; + + Key sslKey = sslServerHostKeyStore.getFirst().getKey("ssl", "password".toCharArray()); + X509Certificate sslCert = (X509Certificate) sslServerHostKeyStore.getFirst().getCertificate("ssl"); + KeyPair keyPair = new KeyPair(sslCert.getPublicKey(), (PrivateKey) sslKey); + HeldCertificate localhostCertificate = new HeldCertificate(keyPair, sslCert); + final HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder() + .addTrustedCertificate(clientEeCert) + .addTrustedCertificate(clientRootCert) + .heldCertificate(localhostCertificate) + .build(); + mockWebServer = new MockWebServer(); + + mockWebServer.useHttps(serverCertificates.sslSocketFactory(), false); + mockWebServer.requireClientAuth(); + mockWebServer.enqueue(new MockResponse().setResponseCode(200) + .setBody("Successful auth!")); + mockServerUrl = mockWebServer.url("/sp/junit"); + + //perform test request + final HttpUriRequest httpGet2 = new HttpGet(mockServerUrl.url().toString()); + final CloseableHttpResponse httpResp2 = client.execute(httpGet2); + Assert.assertEquals("http statusCode", 200, httpResp2.getStatusLine().getStatusCode()); + + } + } diff --git a/eaaf_core_utils/src/test/resources/data/hsm_ee-RSA_rootcert.crt b/eaaf_core_utils/src/test/resources/data/hsm_ee-RSA_rootcert.crt new file mode 100644 index 00000000..aa83c8d9 --- /dev/null +++ b/eaaf_core_utils/src/test/resources/data/hsm_ee-RSA_rootcert.crt @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +MIICDTCCAbOgAwIBAgIIVLxIFI8kRpkwCgYIKoZIzj0EAwIwEjEQMA4GA1UEAwwHRUMtUm9vdDAeFw0yMDA2MTgwNzM2MTBaFw0yNTA2MTgwNzM2MTBaMDwxGzAZBgNVBAMMEmludC1yc2Eta2V5LTEtMDAwMTERMA8GA1UECgwIc29mdHdhcmUxCjAIBgNVBAUTATEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDrM1ocQqtch95Dm21JHi0V35nlWZibsjLqR+g8ERdD1qFgun/X0I/Rbft+KxB8QsDX7UmIjXGdavNcEjY/XcbiJxUcpv7vn/2+x3JxZO6Iye/ut001okICt3OGIqP93ZEnIaTTNhDsK7OnvD/eUjlmuHiTaFq1dZLKYDQlz9jl/9F4axfrz1V7oo60iqFIW+7tlUeh8VGDUPjQpHghzjHXTJv/OIAt752K31Tn8KR3kvkn6WTPo8eOWVaPQ480Dik0e2afTPPJNZJ7BW111IwqBAOKp586yVsQ4XVEF8H64Cq+s+b4/HBboo9TDJKTJvo2yQmcTsahbH+Rlm20ifUTAgMBAAEwCgYIKoZIzj0EAwIDSAAwRQIhANKN/N2Atb5fbeHSB2Myv/JcNf9JonxFe92AOu4f62NNAiBjOEeg4OyJZKPiDl6aqYVtz1Qroo6xzUC9UVA4qNe4LA== +-----END CERTIFICATE----- diff --git a/eaaf_core_utils/src/test/resources/data/hsm_ee_eecert.crt b/eaaf_core_utils/src/test/resources/data/hsm_ee_eecert.crt new file mode 100644 index 00000000..b4c47c78 --- /dev/null +++ b/eaaf_core_utils/src/test/resources/data/hsm_ee_eecert.crt @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +MIIDEzCCArqgAwIBAgIIMrAOP6EqywMwCgYIKoZIzj0EAwIwEjEQMA4GA1UEAwwHRUMtUm9vdDAeFw0yMDA2MTgwNzM2MDlaFw0yNTA2MTgwNzM2MDlaMEMxIjAgBgNVBAMMGWludC1hdXRoaGFuZGxlci1zaWduLTAwMDExETAPBgNVBAoMCHNvZnR3YXJlMQowCAYDVQQFEwExMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA5j2vR8ZV88fOJzFHmLuPizHXk+aiE0fX8Bu63FqCNa2Vy343u2k+4HVQBWpAtyRej8nL7JQuhFa11YRtVF+Vos9cyUDk482sUlYA2LdAFIuHJP6iTRrrHYdiTskc3FQUm9m9KorVFwnfzqJ40wjn9hD0xKCE0odk9IHA5aLTul0mSMcHQ+MMu2cbelK2TWTEC0wcGum2NrTWukhf0E4/e4SuqMgEUPdHSEaNZLGKZU0kyVtXKK0HCtWF8OKGay4V504dk3qnmRHHO8ik3oyPk2yLipQAPL0bUGMZ7tlRLo5VxJvkZSsJfAzvYn1JzcQIt6bXszQGU/JS6dw7Jq99Ckzox/vk8p1YUPd4tCuUJPXzhFhI7CedHKGItwk7mQf5llgeVJy40sVrFwHLDPufY5mlm9C+gVBs71+ibT/sJ96gCueWqduzDX8fHzeaNVj2NFEx2pT46D5cbRWZBow3+Rx+hpge6SDMzaebpbkgLPX+35D952bMLjm+9T0DulGk1tLL2k4YK+1WWUprlo+rm65OA5FxnO5YxNmGk2Uizu3tSoZMxmXwEWoFfYaMsTt5Not3+CLPjfs6pE4ML9ifAOxW+pPsmanDiNaMiL0/aSddvvkv3lSMRiU9nYh3DuOu6sGIMaPdyYF0V/9Fua2SDZV3QKIbzPbJfEsXFKtjtzUCAwEAATAKBggqhkjOPQQDAgNHADBEAiBHsK819KfxVn91KAmjRjb7zx8TLLBApyaZHXi5HVrYUwIgQbF6u6bXziAWdijlJC0IOWdBuTLWmTvFqBH7uX1HL9c= +-----END CERTIFICATE----- diff --git a/eaaf_core_utils/src/test/resources/data/hsm_ee_rootcert.crt b/eaaf_core_utils/src/test/resources/data/hsm_ee_rootcert.crt new file mode 100644 index 00000000..fa7b132f --- /dev/null +++ b/eaaf_core_utils/src/test/resources/data/hsm_ee_rootcert.crt @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +MIIBPDCB46ADAgECAghZ0/gtbA6FrjAKBggqhkjOPQQDAjASMRAwDgYDVQQDDAdFQy1Sb290MB4XDTIwMDYxODA3MzU1M1oXDTMwMDYxODA3MzU1M1owEjEQMA4GA1UEAwwHRUMtUm9vdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABIjgL+6qiE9oj2yWCkVm6s7AaYkbDhTptYXTW92MhASiTqxL6g8tr28MlRA2P8HPrNSK9payeMe5QW9Kxn+EMPejIzAhMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgWgMAoGCCqGSM49BAMCA0gAMEUCIDq2f4xjYD8pzr+mdzuT8wzePRnj/EatjmimGnvNt3FjAiEArezudh6G+wE+ds6S0dnFxG0o/BrbR0fiRNTQwiZA9ec= +-----END CERTIFICATE----- diff --git a/eaaf_core_utils/src/test/resources/data/server_host.crt b/eaaf_core_utils/src/test/resources/data/server_host.crt new file mode 100644 index 00000000..21d3a1e4 --- /dev/null +++ b/eaaf_core_utils/src/test/resources/data/server_host.crt @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC2TCCAcECBGB5WpEwDQYJKoZIhvcNAQELBQAwMTELMAkGA1UEBhMCQVQxDjAM +BgNVBAsMBWpVbml0MRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMjEwNDE2MDkzNjE3 +WhcNMjQwMTEwMDkzNjE3WjAxMQswCQYDVQQGEwJBVDEOMAwGA1UECwwFalVuaXQx +EjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAJVYLzPzq7oBGS5Wer0++rHbp+DWI7srAV1lGHdq8ST6APh/7fEVWpdZDpMY +bOXl6uIiVmMsx/jUhQwOu4rFXThiQlwyQOv57SO7WHqNPqbRs/EUVnzW35aXU/DB +CmkqKyjK/+vuq7tIahlpqrppCzBVC9/Z15U+RMTdnATrohALNJovydH3VSkdkKX0 +5BDx779/8malTgyWTUgl+p3F/91iIIl4ZvIngo2ZYQCFm1nV6jmpErGFkG6YVrO7 +oe3OlGKFiXtqCmq+NSFeXsv/SaXWNUw82pYKuK/5EFSLX49HLBBDI14eOCuVLnGA +H/kG3tGteYMBNzSMmC/kcKgRDnUCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAAJn2 +a/VbtXGmHe9wmtu8K3noyECfG5fbu9URUjXhCBlXGcdjfz1gzrOHcmaBndk0a566 +R2W0fLvjLpjWChrj7r34EpNYGPMLV2gp3ZkiSGl9kv8mf9iChK6+ga3SlyHJuXXu +gw6eOIAxBrE/vLw+pZtCEV9yPrIydkt19jjejf1wjs5y2G7m5r5pBIh6Wlmmc4f2 +3M6l6Dge78WVdUaU5AeAHjgGgXwULxmLGxi6yiS5HsSeb79oGz9psHbq1EAvwOVY +sLepTbDQvX/VAAG7HOJXhdGM0fRIkM7HFA5+6joTHvAKhuMlFIJ8Y4QIG2QaIBAh +eBBh91x/aB2xOKs+Kg== +-----END CERTIFICATE----- diff --git a/eaaf_core_utils/src/test/resources/data/ssL_truststore.jks b/eaaf_core_utils/src/test/resources/data/ssL_truststore.jks new file mode 100644 index 00000000..4d7bc2f3 Binary files /dev/null and b/eaaf_core_utils/src/test/resources/data/ssL_truststore.jks differ diff --git a/eaaf_core_utils/src/test/resources/data/ssl_host.jks b/eaaf_core_utils/src/test/resources/data/ssl_host.jks new file mode 100644 index 00000000..4ca07595 Binary files /dev/null and b/eaaf_core_utils/src/test/resources/data/ssl_host.jks differ diff --git a/pom.xml b/pom.xml index c43076fa..e333b276 100644 --- a/pom.xml +++ b/pom.xml @@ -52,8 +52,8 @@ 3.4.5 2.2.0 1.2.4 - 1.67 - 1.67 + 1.68 + 1.68 1.7.30 1.2.3 -- cgit v1.2.3 From 3e3ba151078537a04dadce070934685c754336ff Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Fri, 16 Apr 2021 22:14:10 +0200 Subject: build eaaf-components with JDK11 in Gitlab CI --- .gitlab-ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 82dd4609..f97b1f15 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,4 +1,5 @@ -image: maven:latest +#image: maven:latest +image: maven:3.6.3-jdk-11 variables: LC_ALL: "en_US.UTF-8" -- cgit v1.2.3