diff options
Diffstat (limited to 'eaaf_core/src')
16 files changed, 666 insertions, 1185 deletions
| diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/AuthenticationData.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/AuthenticationData.java index 0b352334..a8695885 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/AuthenticationData.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/AuthenticationData.java @@ -30,7 +30,7 @@ import java.util.TimeZone;  import at.gv.egiz.eaaf.core.api.idp.IAuthData;  import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink;  import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; -import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BpkBuilder; +import at.gv.egiz.eaaf.core.impl.builder.BpkBuilder;  import org.apache.commons.collections4.map.HashedMap;  import org.apache.commons.lang3.StringUtils; diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/AbstractAuthenticationDataBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/AbstractAuthenticationDataBuilder.java index c2f85fef..f1811022 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/AbstractAuthenticationDataBuilder.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/AbstractAuthenticationDataBuilder.java @@ -24,7 +24,6 @@ import java.io.IOException;  import java.io.InputStream;  import java.util.ArrayList;  import java.util.Collection; -import java.util.Map.Entry;  import org.apache.commons.lang3.StringUtils;  import org.slf4j.Logger; @@ -54,6 +53,7 @@ import at.gv.egiz.eaaf.core.exceptions.EaafException;  import at.gv.egiz.eaaf.core.exceptions.EaafParserException;  import at.gv.egiz.eaaf.core.exceptions.EaafStorageException;  import at.gv.egiz.eaaf.core.exceptions.XPathException; +import at.gv.egiz.eaaf.core.impl.builder.BpkBuilder;  import at.gv.egiz.eaaf.core.impl.data.Pair;  import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData;  import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; @@ -204,22 +204,18 @@ public abstract class AbstractAuthenticationDataBuilder implements IAuthenticati      setCitizenCountryCode(internalAuthData, authProcessData);      // set generic authProcessData to authdata -    for (final Entry<String, Object> el : authProcessData.getGenericSessionDataStorage() -        .entrySet()) { -      if (el.getKey().startsWith(GENERIC_AUTHDATA_IDENTIFIER)) { -        log.trace("Find generic authProcessData {}. Map it directly to authData", el.getKey()); -        try { -          internalAuthData.setGenericData(el.getKey(), el.getValue()); - -        } catch (final EaafStorageException e) { -          log.warn("Can NOT set authData with key: {}", el.getKey(), null, e); - -        } - -      } +    authProcessData.getGenericSessionDataStream() +        .filter(el -> el.getKey().startsWith(GENERIC_AUTHDATA_IDENTIFIER)) +        .forEach(el -> { +          log.trace("Find generic authProcessData {}. Map it directly to authData", el.getKey()); +          try { +            internalAuthData.setGenericData(el.getKey(), el.getValue()); -    } +          } catch (final EaafStorageException e) { +            log.warn("Can NOT set authData with key: {}", el.getKey(), null, e); +          }            +        });       }    /** diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilder.java deleted file mode 100644 index 17d0099e..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilder.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between - * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European - * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in - * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software distributed under the Licence - * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the Licence for the specific language governing permissions and limitations under - * the Licence. - * - * 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.builder; - -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map.Entry; - -import javax.annotation.Nonnull; -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.lang.Nullable; -import org.springframework.util.Assert; -import org.springframework.util.Base64Utils; - -import at.gv.egiz.eaaf.core.api.data.EaafConstants; -import at.gv.egiz.eaaf.core.exceptions.EaafBuilderException; -import at.gv.egiz.eaaf.core.impl.data.Pair; -import lombok.extern.slf4j.Slf4j; - - -/** - * Builder for the bPK, as defined in - * <code>"Ableitung f¨r die bereichsspezifische Personenkennzeichnung"</code> - * version <code>1.0.1</code> from - * <code>"reference.e-government.gv.at"</code>. - * - */ -@Slf4j -public class BpkBuilder { -   -  private static final String ERROR_CODE_33 = "builder.33"; -     -  private static final String ERROR_MSG_WRONG_TARGET_FORMAT = "bPK-target format must be full URI"; -   -   -  /** -   * Calculates an area specific unique person-identifier from a baseID. -   * -   * @param baseID           baseId from user but never null -   * @param targetIdentifier target identifier for area specific identifier -   *                         calculation but never null -   * @return Pair consists of (unique person identifier for this target, -   *         targetArea) but never null -   * @throws EaafBuilderException if some input data are not valid -   */ -  public static Pair<String, String> generateAreaSpecificPersonIdentifier(final String baseID, -      final String targetIdentifier) throws EaafBuilderException { -    return generateAreaSpecificPersonIdentifier(baseID, EaafConstants.URN_PREFIX_BASEID, -        targetIdentifier); - -  } - -  /** -   * Calculates an area specific unique person-identifier from an unique -   * identifier with a specific type. -   * -   * @param baseID           baseId from user but never null -   * @param baseIdType       Type of the baseID but never null -   * @param targetIdentifier target identifier for area specific identifier -   *                         calculation but never null -   * @return Pair consists of (unique person identifier for this target, -   *         targetArea) but never null -   * @throws EaafBuilderException if some input data are not valid -   */ -  public static Pair<String, String> generateAreaSpecificPersonIdentifier(final String baseID, -      final String baseIdType, final String targetIdentifier) throws EaafBuilderException { -    if (StringUtils.isEmpty(baseID)) { -      throw new EaafBuilderException(ERROR_CODE_33, new Object[] { "baseID is empty or null" }, -          "BaseId is empty or null"); -    } - -    if (StringUtils.isEmpty(baseIdType)) { -      throw new EaafBuilderException(ERROR_CODE_33, -          new Object[] { "the type of baseID is empty or null" }, "Type of baseId is empty or null"); -    } - -    if (StringUtils.isEmpty(targetIdentifier)) { -      throw new EaafBuilderException(ERROR_CODE_33, -          new Object[] { "SP specific target identifier is empty or null" }, -          "SP specific target identifier is empty or null"); -    } - -    if (baseIdType.equals(EaafConstants.URN_PREFIX_BASEID)) { -      log.trace("Find baseID. Starting unique identifier caluclation for this target"); - -      if (targetIdentifier.startsWith(EaafConstants.URN_PREFIX_CDID)) { -        log.trace("Calculate bPK identifier for target: " + targetIdentifier); -        return Pair.newInstance(calculatebPKwbPK(baseID + "+" + targetIdentifier), -            targetIdentifier); - -      } else if (targetIdentifier.startsWith(EaafConstants.URN_PREFIX_WBPK)) { -        log.trace("Calculate  wbPK identifier for target: " + targetIdentifier); -        String commonBpkTarget = normalizeBpkTargetIdentifierToCommonFormat(targetIdentifier); -        return Pair.newInstance(calculatebPKwbPK( -            baseID + "+" + normalizeBpkTargetIdentifierToBpkCalculationFormat(commonBpkTarget)), -            commonBpkTarget); -         -      } else if (targetIdentifier.startsWith(EaafConstants.URN_PREFIX_EIDAS)) { -        log.trace("Calculate eIDAS identifier for target: " + targetIdentifier); -        final String[] splittedTarget = targetIdentifier.split("\\+"); -        final String cititzenCountryCode = splittedTarget[1]; -        final String eidasOutboundCountry = splittedTarget[2]; - -        if (cititzenCountryCode.equalsIgnoreCase(eidasOutboundCountry)) { -          log.warn("Suspect configuration FOUND!!! CitizenCountry equals DestinationCountry"); - -        } -        return buildEidasIdentifer(baseID, baseIdType, cititzenCountryCode, eidasOutboundCountry); - -      } else { -        throw new EaafBuilderException(ERROR_CODE_33, -            new Object[] { "Target identifier: " + targetIdentifier + " is NOT allowed or unknown" }, -            "Target identifier: " + targetIdentifier + " is NOT allowed or unknown"); -      } - -    } else { -      log.trace("BaseID is not of type " + EaafConstants.URN_PREFIX_BASEID -          + ". Check type against requested target ..."); -      if (baseIdType.equals(targetIdentifier)) { -        log.debug("Unique identifier is already area specific. Is nothing todo"); -        return Pair.newInstance(baseID, targetIdentifier); - -      } else { -        log.warn("Get unique identifier for target: " + baseIdType + " but target: " -            + targetIdentifier + " is required!"); -        throw new EaafBuilderException(ERROR_CODE_33, -            new Object[] { "Get unique identifier for target: " + baseIdType + " but target: " -                + targetIdentifier + " is required" }, -            "Get unique identifier for target: " + baseIdType + " but target: " + targetIdentifier -                + " is required"); - -      } -    } -  } - - - -  /** -   * Create an encrypted bPK. -   * -   * @param bpk       unencrypted bPK -   * @param target    bPK target in full form -   * @param publicKey Public-Key used for encryption -   * @return encrypted bPK -   * @throws EaafBuilderException In case of an error -   */ -  public static String encryptBpk(final String bpk, String target, final PublicKey publicKey) -      throws EaafBuilderException { -    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); -     -    if (!target.startsWith(EaafConstants.URN_PREFIX_WITH_COLON)) { -      throw new EaafBuilderException("builder.32",  -          null, ERROR_MSG_WRONG_TARGET_FORMAT); -       -    } -     -    target = normalizeBpkTargetIdentifierToBpkCalculationFormat( -        normalizeBpkTargetIdentifierToCommonFormat(target)); - -    final String input = -        "V1::" + target + "::" + bpk + "::" + sdf.format(new Date()); -    // System.out.println(input); -    byte[] result; -    try { -      final byte[] inputBytes = input.getBytes("ISO-8859-1"); -      result = encrypt(inputBytes, publicKey); -      return new String(Base64Utils.encode(result), "ISO-8859-1").replaceAll("\r\n", ""); -      // return new String(Base64Utils.encode(result, -      // "ISO-8859-1")).replaceAll("\r\n", ""); - -    } catch (final Exception e) { -      throw new EaafBuilderException("bPK encryption FAILED", null, e.getMessage(), e); - -    } -  } - -  /** -   * Decrypt an encrypted bPK. -   * -   * @param encryptedBpk encrypted bPK -   * @param target       bPK target in full form -   * @param privateKey   private-key for decryption -   * @return bPK Pair consists of (unique person identifier for this target, -   *         targetArea) but never null -   * @throws EaafBuilderException In case of an error -   */ -  public static Pair<String, String> decryptBpk(final String encryptedBpk, String target, -      final PrivateKey privateKey) throws EaafBuilderException { -    String decryptedString; -     -    if (!target.startsWith(EaafConstants.URN_PREFIX_WITH_COLON)) { -      throw new EaafBuilderException("builder.32",  -          null, ERROR_MSG_WRONG_TARGET_FORMAT); -       -    } -     -    try { -      final byte[] encryptedBytes = Base64Utils.decode(encryptedBpk.getBytes("ISO-8859-1")); -      final byte[] decryptedBytes = decrypt(encryptedBytes, privateKey); -      decryptedString = new String(decryptedBytes, "ISO-8859-1"); - -    } catch (final Exception e) { -      throw new EaafBuilderException("bPK decryption FAILED", null, e.getMessage(), e); - -    } - -    String[] parts = decryptedString.split("::"); -    if (parts.length != 4) { -      log.trace("Encrypted bPK has value: {}", decryptedString); -      throw new EaafBuilderException("builder.31", new Object[] {parts.length},  -          "encBpk has a suspect format"); -       -    } -     -    final String sector = parts[1]; -    final String bPK = parts[2]; - -    if (target.equals(normalizeBpkTargetIdentifierToCommonFormat(sector))) { -      return Pair.newInstance(bPK, target); -       -    } else { -      throw new EaafBuilderException("builder.30", new Object[] {sector, target},  -          "Decrypted bPK-target does not match"); -       -    } -  } - -  /** -   * Normalize wbPK target identifier for FN, ZVR, and ERSB to XFN, XZVR, and XERSB. -   *  -   * <p>If the target is not of this types the target will be returned as it is</p> -   * @param targetIdentifier bPK input target -   * @return XFN, XZVR, XERSB, or targetIdentfier if no normalization is required  -   */ -  @Nullable -  public static String normalizeBpkTargetIdentifierToCommonFormat(@Nullable String targetIdentifier) { -    if (targetIdentifier != null  -        && !targetIdentifier.startsWith(EaafConstants.URN_PREFIX_WBPK_TARGET_WITH_X)) { -      for (Entry<String, String> mapper : EaafConstants.URN_WBPK_TARGET_X_TO_NONE_MAPPER.entrySet()) { -        if (targetIdentifier.startsWith(mapper.getValue())) { -          String wbpkTarget = mapper.getKey() + targetIdentifier.substring(mapper.getValue().length());  -          log.trace("Normalize wbPK target: {} to {}", targetIdentifier, wbpkTarget); -          return wbpkTarget; -         -        } -      } -    }  -     -    return targetIdentifier; -  } -   -  /** -   * Normalize wbPK target identifier for XFN, XZVR, and XERSB to bPK non-X format like, FN, ZVR, and ERSB. -   *  -   * <p>If the target is not of this types the target will be returned as it is</p> -   *  -   * @param targetIdentifier bPK input target -   * @return FN, ZVR, ERSB, or targetIdentfier if no normalization is required  -   */ -  @Nullable -  public static String normalizeBpkTargetIdentifierToNonXFormat(@Nullable String targetIdentifier) { -    if (targetIdentifier != null && targetIdentifier.startsWith(EaafConstants.URN_PREFIX_WBPK)) { -      for (Entry<String, String> mapper : EaafConstants.URN_WBPK_TARGET_X_TO_NONE_MAPPER.entrySet()) { -        if (targetIdentifier.startsWith(mapper.getKey())) { -          String wbpkTarget = mapper.getValue() + targetIdentifier.substring(mapper.getKey().length());  -          log.trace("Find new wbPK target: {}. Replace it by: {}", targetIdentifier, wbpkTarget); -          return wbpkTarget; -       -        } -      } -    } -     -    return targetIdentifier;     -  } -   -  /** -   * Normalize wbPK target identifier for XFN, XZVR, and XERSB to bPK calculation format like, FN, VR, and ERJ. -   *  -   * <p>If the target is not of this types the target will be returned as it is</p> -   *  -   * @param targetIdentifier bPK input target -   * @return FN, VR, ERJ, or targetIdentfier if no normalization is required  -   */ -  @Nullable -  public static String normalizeBpkTargetIdentifierToBpkCalculationFormat(@Nullable String targetIdentifier) { -    if (targetIdentifier != null && targetIdentifier.startsWith(EaafConstants.URN_PREFIX_WBPK)) { -      for (Entry<String, String> mapper : EaafConstants.URN_WBPK_TARGET_X_TO_CALC_TARGET_MAPPER.entrySet()) { -        if (targetIdentifier.startsWith(mapper.getKey())) { -          String wbpkTarget = mapper.getValue() + targetIdentifier.substring(mapper.getKey().length());  -          log.trace("Find new wbPK target: {}. Replace it by: {}", targetIdentifier, wbpkTarget); -          return wbpkTarget; -       -        } -      } -    } -     -    return targetIdentifier;     -  } -   -  /** -   * Remove prefixes from bPK target identifier and get only the SP specific part. -   *  -   * @param type full qualified bPK target with 'urn:publicid:gv.at:' prefix -   * @return SP specific part, or full type if reduction is not supported  -   */ -  @Nonnull -  public static String removeBpkTypePrefix(@Nonnull final String type) { -    Assert.isTrue(type != null, "bPKType is 'NULL'"); -    if (type.startsWith(EaafConstants.URN_PREFIX_WBPK)) { -      return type.substring(EaafConstants.URN_PREFIX_WBPK.length()); -       -    } else if (type.startsWith(EaafConstants.URN_PREFIX_CDID)) { -      return type.substring(EaafConstants.URN_PREFIX_CDID.length()); -       -    } else if (type.startsWith(EaafConstants.URN_PREFIX_EIDAS)) { -      return type.substring(EaafConstants.URN_PREFIX_EIDAS.length()); -       -    } else { -      return type; -       -    } -  } -   -  /** -   * Builds the eIDAS from the given parameters. -   * -   * @param baseId             baseID of the citizen -   * @param baseIdType         Type of the baseID -   * @param sourceCountry      CountryCode of that country, which build the eIDAs -   *                           ID -   * @param destinationCountry CountryCode of that country, which receives the -   *                           eIDAs ID -   * -   * @return Pair eIDAs/bPKType in a BASE64 encoding -   * @throws EaafBuilderException if some input data are not valid -   */ -  private static Pair<String, String> buildEidasIdentifer(final String baseId, -      final String baseIdType, final String sourceCountry, final String destinationCountry) -      throws EaafBuilderException { -    String bpk = null; -    String bpkType = null; - -    // check if we have been called by public sector application -    if (baseIdType.startsWith(EaafConstants.URN_PREFIX_BASEID)) { -      bpkType = EaafConstants.URN_PREFIX_EIDAS + sourceCountry + "+" + destinationCountry; -      log.debug("Building eIDAS identification from: [identValue]+" + bpkType); -      bpk = calculatebPKwbPK(baseId + "+" + bpkType); - -    } else { // if not, sector identification value is already calculated by BKU -      log.debug("eIDAS eIdentifier already provided by BKU"); -      bpk = baseId; -    } - -    if (StringUtils.isEmpty(bpk) || StringUtils.isEmpty(sourceCountry) -        || StringUtils.isEmpty(destinationCountry)) { -      throw new EaafBuilderException("builder.00", -          new Object[] { "eIDAS-ID", -              "Unvollständige Parameterangaben: identificationValue=" + bpk + ", Zielland=" -                  + destinationCountry + ", Ursprungsland=" + sourceCountry }, -          "eIDAS-ID: Unvollständige Parameterangaben: identificationValue=" + bpk + ", Zielland=" -              + destinationCountry + ", Ursprungsland=" + sourceCountry); -    } - -    log.trace("eIDAS pseudonym generation finished. "); -    final String eIdentifier = sourceCountry + "/" + destinationCountry + "/" + bpk; - -    return Pair.newInstance(eIdentifier, bpkType); -  } -   -  private static String calculatebPKwbPK(final String basisbegriff) throws EaafBuilderException { -    try { -      final MessageDigest md = MessageDigest.getInstance("SHA-1"); -      final byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); -      final String hashBase64 = -          new String(Base64Utils.encode(hash), "ISO-8859-1").replaceAll("\r\n", ""); // Base64Utils.encode(hash); -      return hashBase64; - -    } catch (final Exception ex) { -      throw new EaafBuilderException(ERROR_CODE_33, new Object[] {ex.toString() }, -          ex.getMessage(), ex); - -    } - -  } - -  private static byte[] encrypt(final byte[] inputBytes, final PublicKey publicKey) -      throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, -      IllegalBlockSizeException, BadPaddingException { -    byte[] result; -    Cipher cipher = null; -    try { -      cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); // try with bouncycastle - -    } catch (final NoSuchAlgorithmException e) { -      cipher = Cipher.getInstance("RSA/ECB/OAEP"); // try with iaik provider -    } -    cipher.init(Cipher.ENCRYPT_MODE, publicKey); -    result = cipher.doFinal(inputBytes); - -    return result; -  } - -  private static byte[] decrypt(final byte[] encryptedBytes, final PrivateKey privateKey) -      throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, -      IllegalBlockSizeException, BadPaddingException { -    byte[] result; -    Cipher cipher = null; -    try { -      cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); // try with bouncycastle - -    } catch (final NoSuchAlgorithmException e) { -      cipher = Cipher.getInstance("RSA/ECB/OAEP"); // try with iaik provider - -    } -    cipher.init(Cipher.DECRYPT_MODE, privateKey); -    result = cipher.doFinal(encryptedBytes); -    return result; - -  } -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/AuthProcessDataWrapper.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/AuthProcessDataWrapper.java index 8eef4a8e..368652be 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/AuthProcessDataWrapper.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/AuthProcessDataWrapper.java @@ -22,9 +22,11 @@ package at.gv.egiz.eaaf.core.impl.idp.auth.data;  import java.text.ParseException;  import java.text.SimpleDateFormat;  import java.util.Date; -import java.util.HashMap;  import java.util.Map; +import java.util.Map.Entry;  import java.util.TimeZone; +import java.util.stream.Collectors; +import java.util.stream.Stream;  import javax.annotation.Nullable; @@ -264,16 +266,20 @@ public class AuthProcessDataWrapper     * getGenericSessionDataStorage()     */    @Override -  public Map<String, Object> getGenericSessionDataStorage() { -    final Map<String, Object> result = new HashMap<>(); -    for (final Map.Entry<String, Object> el : authProcessData.entrySet()) { -      if (el.getKey().startsWith(GENERIC_PREFIX)) { -        result.put(el.getKey().substring(GENERIC_PREFIX.length()), el.getValue()); -      } - -    } - -    return result; +  public Map<String, Object> getGenericSessionDataStorage() {     +    return authProcessData.entrySet().stream() +        .filter(el -> el.getKey().startsWith(GENERIC_PREFIX)) +        .collect( +            Collectors.toMap( +                el -> el.getKey().substring(GENERIC_PREFIX.length()),  +                value -> value.getValue())); +     +  } +   +  @Override +  public Stream<Entry<String, Object>> getGenericSessionDataStream() { +    return getGenericSessionDataStorage().entrySet().stream(); +        }    /* diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/EidAuthProcessDataWrapper.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/EidAuthProcessDataWrapper.java new file mode 100644 index 00000000..48a2206b --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/EidAuthProcessDataWrapper.java @@ -0,0 +1,34 @@ +package at.gv.egiz.eaaf.core.impl.idp.auth.data; + +import java.util.Map; + +import at.gv.egiz.eaaf.core.api.idp.auth.data.IEidAuthProcessData; + +/** + * Authentication session-data that adds ID Austria specific information.   + *  + * @author tlenz + * + */ +public class EidAuthProcessDataWrapper extends AuthProcessDataWrapper implements IEidAuthProcessData { + +  private static final String VALUE_INTERNAL_TEST_IDENTITY_PROCESS = "direct_is_testidentity"; +   +  public EidAuthProcessDataWrapper(Map<String, Object> authProcessData) { +    super(authProcessData); +     +  } +   +  @Override +  public boolean isTestIdentity() { +    return wrapStoredObject(VALUE_INTERNAL_TEST_IDENTITY_PROCESS, false, Boolean.class); + +  } + +  @Override +  public void setTestIdentity(boolean flag) { +    authProcessData.put(VALUE_INTERNAL_TEST_IDENTITY_PROCESS, flag); + +  } +   +} 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..0834aa27 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ErrorTicketService.java @@ -0,0 +1,243 @@ +package at.gv.egiz.eaaf.core.impl.idp.auth.services; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; + +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 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; + +@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<String, String> propertyMap = new HashMap<String, String>(); + + +  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/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..812a5171 --- /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; +import java.util.HashSet; + +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"; + +  /** +   * Maps internal error codes to external ones. +   * @param internalCode internal error code +   * @return external error code +   */ +  String getExternalCodeFromInternal(String internalCode); + +  /** +   * 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(); + +    /** +     * Write a Exception to the MOA-ID-Auth internal technical log. +     * +     * @param logOnInfoLevel set of what to log on info logging lvl +     */ +    void logExceptionToTechnicalLog(HashSet<String> 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 abb3d685..a64ad45e 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; @@ -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; @@ -60,6 +62,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; @@ -69,7 +72,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; @@ -78,13 +80,14 @@ 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); -  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,15 +103,28 @@ 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 IErrorService errorTicketService;    @Autowired(required = false)    private ISsoManager ssoManager; +    @Autowired    private IStatisticLogger statisticLogger; +      @Autowired    private IRevisionLogger revisionsLogger; +  @Autowired(required = true) +  protected ITransactionStorage transactionStorage; + +  @Autowired +  IPendingRequestIdGenerationStrategy requestIdValidationStragegy; + +    private IGuiFormBuilder guiBuilder;    private final HashSet<String> logOnInfoLevel = new HashSet<>(); @@ -136,9 +152,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 +163,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 +197,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,11 +206,10 @@ 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. " +          log.error("PendingRequest NEEDS user-consent. "                + "Can NOT fininalize authentication --> Abort authentication process!");          } else { @@ -216,58 +228,97 @@ 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 { +      IErrorService.IHandleData errorData = errorTicketService.createHandleData(throwable, req); +       +      if (errorData.getActionType().equals(IErrorService.ActionType.TICKET_REDIRECT) || errorData.getActionType() +          .equals(IErrorService.ActionType.NOTICKET_REDIRECT)) { -      final Class<?> clazz = Class.forName(protocolRequest.requestedModule()); +        // 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); -      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."); +        // log Error to technical log +        errorData.logExceptionToTechnicalLog(logOnInfoLevel); -      } +        // log Error Message +        statisticLogger.logErrorOperation(throwable, protocolRequest); -      final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); +        displayException(req, resp, errorData); -      if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { +      } else if (errorData.getActionType().equals(IErrorService.ActionType.NOTICKET_AUTOREDIRECT)) { +        IModulInfo handlingModule = extractShibbolethHandling(protocolRequest, applicationContext); -        // log Error to technical log -        logExceptionToTechnicalLog(throwable); +        if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { -        // log Error Message -        statisticLogger.logErrorOperation(throwable, protocolRequest); +          // log Error to technical log +          errorData.logExceptionToTechnicalLog(logOnInfoLevel); + +          // log Error Message +          statisticLogger.logErrorOperation(throwable, protocolRequest); + +          // write revision log entries +          revisionsLogger.logEvent(protocolRequest, EventConstants.TRANSACTION_ERROR, +              protocolRequest.getUniqueTransactionIdentifier()); -        // write revision log entries -        revisionsLogger.logEvent(protocolRequest, EventConstants.TRANSACTION_ERROR, -            protocolRequest.getUniqueTransactionIdentifier()); +        } else { +          throw throwable; //through it on to handleErrorNoRedirect + +        }        } else { -        handleErrorNoRedirect(throwable, req, resp, true); +        throw throwable; //through it on to handleErrorNoRedirect        }      } 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) throws EaafException, IOException { + +    IErrorService.IHandleData errorData = null; +    errorData = errorTicketService.createHandleData(throwable, req);      // log Exception into statistic database      if (writeExceptionToStatisticLog) { @@ -275,30 +326,25 @@ public class ProtocolAuthenticationService implements IProtocolAuthenticationSer      }      // write errror to console -    logExceptionToTechnicalLog(throwable); - -    // return error to Web browser -    if (throwable instanceof EaafException || throwable instanceof ProcessExecutionException) { -      internalMoaidExceptionHandler(req, resp, (Exception) throwable, false); +    errorData.logExceptionToTechnicalLog(logOnInfoLevel); +    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 { -      // 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)); - +      // TODO introduce separate error type? +      throw new EaafException("internal.configuration.01", new Object[]{ +          errorData.getInternalErrorCode() + " in on_error_action" + ".properties", "Erroraction mapping mismatch"});      } -    } +    @Override    public void forwardToErrorHandler(Pair<IRequest, Throwable> 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 +367,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 +395,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 +415,15 @@ 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 -   */ -  protected void logExceptionToTechnicalLog(final Throwable loggedException) {     -    // 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; -       -    } - -    // Log exception -    if (!(toLog instanceof EaafException)) { -      log.error(TECH_LOG_MSG, IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, -          toLog.getMessage(), toLog); - -    } else {             -      if (logOnInfoLevel.contains(((EaafException) toLog).getErrorId())) { -        log.info(TECH_LOG_MSG, ((EaafException) toLog).getErrorId(), -            toLog.getMessage(), toLog); - -      } else { -        log.warn(TECH_LOG_MSG, ((EaafException) toLog).getErrorId(), -            toLog.getMessage(), toLog); - -      } -    } -  } -    @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 +431,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 +454,33 @@ 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 { +  //    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 { +      @NonNull final HttpServletResponse httpResp, @NonNull final String msg, @NonNull final String errorCode, +      @Nullable final Object[] params, String externalErrorCode, IErrorService.IHandleData errorData) +      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 +495,19 @@ 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); +        // 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, +            PARAM_GUI_ERRORCODEPARAMS, ArrayUtils.toString(errorCodeParams)); +        errorTicketService.displayErrorData(c, errorData); +        } 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,60 +520,44 @@ 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 IErrorService.IHandleData errorData) throws IOException, EaafException { +    final Throwable e = errorData.getThrowable(); +    final String internalErrorCode = errorData.getInternalErrorCode(); + +    // 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);      } 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); -    } 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);      } -    }    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;    } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/AttributeBuilderRegistration.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/AttributeBuilderRegistration.java index 135bd789..b554ad05 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/AttributeBuilderRegistration.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/AttributeBuilderRegistration.java @@ -24,7 +24,7 @@ public class AttributeBuilderRegistration {      log.info("Loading protocol attribut-builder modules:");      if (attributBuilderLoader != null) { -      final Iterator<IAttributeBuilder> moduleLoaderInterator = attributBuilderLoader.iterator(); +      final Iterator<IAttributeBuilder> moduleLoaderInterator = attributBuilderLoader.iterator();                   while (moduleLoaderInterator.hasNext()) {          try {            final IAttributeBuilder modul = moduleLoaderInterator.next(); diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BpkAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BpkAttributeBuilder.java index 70e0f6d1..5cbfec01 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BpkAttributeBuilder.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BpkAttributeBuilder.java @@ -29,14 +29,13 @@ import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder;  import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration;  import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException;  import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; -import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BpkBuilder; +import at.gv.egiz.eaaf.core.impl.builder.BpkBuilder;  @PvpMetadata  public class BpkAttributeBuilder implements IPvpAttributeBuilder {    private static final Logger log = LoggerFactory.getLogger(BpkAttributeBuilder.class); -  public static final String DELIMITER_BPKTYPE_BPK = ":"; - +      @Override    public String getName() {      return BPK_NAME; diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSectorForIdAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSectorForIdAttributeBuilder.java index 42b729fe..ba993b0c 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSectorForIdAttributeBuilder.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSectorForIdAttributeBuilder.java @@ -27,7 +27,7 @@ import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder;  import at.gv.egiz.eaaf.core.api.idp.ISpConfiguration;  import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException;  import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; -import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BpkBuilder; +import at.gv.egiz.eaaf.core.impl.builder.BpkBuilder;  @PvpMetadata  public class EidSectorForIdAttributeBuilder implements IPvpAttributeBuilder { 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..a8b0a961 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; @@ -39,15 +39,16 @@ 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.idp.auth.services.ProtocolAuthenticationService;  import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils;  /**   * Protocol finialization end-point.   *   * @author tlenz - *   */  @Controller  public class ProtocolFinalizationController extends AbstractController { @@ -56,10 +57,72 @@ 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; +  @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 { + +    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) { +              IModulInfo handlingModule = ProtocolAuthenticationService +                  .extractShibbolethHandling(pendingReq, applicationContext); + +              handlingModule.generateErrorMessage(throwable, req, resp, pendingReq); +            } +          } +        } +      } 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()); + +        } +      } +    } +  }    /**     * End-Point to handle errors. @@ -69,32 +132,30 @@ public class ProtocolFinalizationController extends AbstractController {     * @throws EaafException In case of an internal error     * @throws IOException   In case of a servlet error     */ -  @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(); @@ -103,7 +164,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); @@ -116,17 +177,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);          } @@ -138,11 +199,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(); @@ -150,9 +210,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);      } @@ -166,7 +226,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 { @@ -179,19 +239,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); -                   +      } -     +    }  } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java index 328a25c5..08bf588f 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java @@ -19,8 +19,6 @@  package at.gv.egiz.eaaf.core.impl.idp.controller.tasks; -import java.util.Set; -  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse; @@ -73,12 +71,9 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask {        } else {          // create a new execution context and copy all elements to new context          final ExecutionContext newec = new ExecutionContextImpl(); -        final Set<String> entries = executionContext.keySet(); -        for (final String key : entries) { -          newec.put(key, executionContext.get(key)); - -        } - +        executionContext.keySet().stream().forEach( +            key -> newec.put(key, executionContext.get(key))); +                  log.debug("Select new auth.-process and restart restart process-engine ... ");          // select and create new process instance diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessEngineImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessEngineImpl.java index 61d2eb28..6e83a201 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessEngineImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessEngineImpl.java @@ -24,7 +24,6 @@ import java.io.Serializable;  import java.text.MessageFormat;  import java.util.HashMap;  import java.util.Map; -import java.util.Map.Entry;  import java.util.concurrent.ConcurrentHashMap;  import org.apache.commons.collections4.IterableUtils; @@ -452,11 +451,9 @@ public class ProcessEngineImpl implements ProcessEngine {      final ExecutionContext executionContext =          new ExecutionContextImpl(piStore.getProcessInstanceId()); - -    final Map<String, Serializable> executionContextData = piStore.getExecutionContextData(); -    for (final Entry<String, Serializable> el : executionContextData.entrySet()) { -      executionContext.put(el.getKey(), el.getValue()); -    } +     +    piStore.getExecutionContextData().entrySet().stream().forEach( +        el -> executionContext.put(el.getKey(), el.getValue()));      final ProcessInstance pi = new ProcessInstance(          processDefinitions.get(piStore.getProcessDefinitionId()), executionContext); diff --git a/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder b/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder index a088f824..6805d5e7 100644 --- a/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder +++ b/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder @@ -17,3 +17,4 @@ at.gv.egiz.eaaf.core.impl.idp.builder.attributes.TransactionIdAttributeBuilder  at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PiiTransactionIdAttributeBuilder  at.gv.egiz.eaaf.core.impl.idp.builder.attributes.SpFriendlyNameAttributeBuilder  at.gv.egiz.eaaf.core.impl.idp.builder.attributes.SpUniqueIdAttributeBuilder +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.SpUsesMandates diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilderTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilderTest.java deleted file mode 100644 index b8c630fe..00000000 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilderTest.java +++ /dev/null @@ -1,488 +0,0 @@ -package at.gv.egiz.eaaf.core.impl.idp.auth.builder; - -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; - -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; - -import at.gv.egiz.eaaf.core.api.data.EaafConstants; -import at.gv.egiz.eaaf.core.exceptions.EaafBuilderException; -import at.gv.egiz.eaaf.core.impl.data.Pair; - -@RunWith(BlockJUnit4ClassRunner.class) -public class BpkBuilderTest { - -  private static final String BASEID = "RUxHQVRlc3RQQjBYWFjFkHpnw7xyX1hYWFTDvHpla8OnaQ=="; -   -  private KeyPair keyPair; -   -   -  /** -   * jUnit test initializer. -   * @throws NoSuchProviderException In case of an error -   * @throws NoSuchAlgorithmException  In case of an error -   */ -  @Before -  public void initialize() throws NoSuchAlgorithmException, NoSuchProviderException { -    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); -    keyPair = keyGen.generateKeyPair(); -     -  } -   -  @Test -  public void encBpkWrongTarget() throws InvalidKeyException { -    String bpk = RandomStringUtils.randomAlphanumeric(25); -    String target = RandomStringUtils.randomAlphanumeric(25); -     -    try { -      BpkBuilder.encryptBpk(bpk, target, keyPair.getPublic()); -      Assert.fail("Wrong parameters not detected"); -       -    } catch (EaafBuilderException e) { -      Assert.assertEquals("Wrong errorMsg", "builder.32", e.getErrorId()); -       -    } -  } -   -  @Test -  public void decBpkWrongTarget() throws InvalidKeyException { -    String bpk = RandomStringUtils.randomAlphanumeric(25); -    String target = RandomStringUtils.randomAlphanumeric(25); -     -    try { -      BpkBuilder.decryptBpk(bpk, target, keyPair.getPrivate()); -      Assert.fail("Wrong parameters not detected"); -       -    } catch (EaafBuilderException e) { -      Assert.assertEquals("Wrong errorMsg", "builder.32", e.getErrorId()); -       -    } -  } -   -  @Test -  public void decBpkWrongTargetInEncBpk() throws InvalidKeyException, EaafBuilderException { -    String bpk = RandomStringUtils.randomAlphanumeric(25); -    String target = EaafConstants.URN_PREFIX_CDID + "AA"; -     -    String encBpk = BpkBuilder.encryptBpk(bpk, target, keyPair.getPublic()); -    try { -      BpkBuilder.decryptBpk(encBpk,  -          EaafConstants.URN_PREFIX_CDID + "BB", keyPair.getPrivate()); -      Assert.fail("Wrong parameters not detected"); -       -    } catch (EaafBuilderException e) { -      Assert.assertEquals("Wrong errorMsg", "builder.30", e.getErrorId()); -       -    } -  } -   -  @Test -  public void encBpkSuccess() throws EaafBuilderException, InvalidKeyException { -    String bpk = RandomStringUtils.randomAlphanumeric(25); -    String target = EaafConstants.URN_PREFIX_CDID + "AA"; -     -    String encBpk = BpkBuilder.encryptBpk(bpk, target, keyPair.getPublic()); -     -    Assert.assertNotNull("encBpk", encBpk); -     -    Pair<String, String> decBpk = BpkBuilder.decryptBpk(encBpk, target, keyPair.getPrivate()); -     -    Assert.assertEquals("wrong bBK", bpk, decBpk.getFirst()); -    Assert.assertEquals("wrong bBK-Target", target, decBpk.getSecond()); -     -  } -   -  @Test -  public void encWbpkSuccess() throws EaafBuilderException, InvalidKeyException { -    String bpk = RandomStringUtils.randomAlphanumeric(25); -    String target = EaafConstants.URN_PREFIX_WBPK + "XFN+123456i"; -     -    String encBpk = BpkBuilder.encryptBpk(bpk, target, keyPair.getPublic()); -     -    Assert.assertNotNull("encBpk", encBpk); -     -    Pair<String, String> decBpk = BpkBuilder.decryptBpk(encBpk, target, keyPair.getPrivate()); -     -    Assert.assertEquals("wrong bBK", bpk, decBpk.getFirst()); -    Assert.assertEquals("wrong bBK-Target", target, decBpk.getSecond()); -     -  } -   -  @Test -  public void encWbpkSuccessSecond() throws EaafBuilderException, InvalidKeyException { -    String bpk = RandomStringUtils.randomAlphanumeric(25); -    String target = EaafConstants.URN_PREFIX_WBPK + "FN+123456i"; -     -    String encBpk = BpkBuilder.encryptBpk(bpk, target, keyPair.getPublic()); -     -    Assert.assertNotNull("encBpk", encBpk); -     -    Pair<String, String> decBpk = BpkBuilder.decryptBpk(encBpk,  -        EaafConstants.URN_PREFIX_WBPK + "XFN+123456i", keyPair.getPrivate()); -     -    Assert.assertEquals("wrong bBK", bpk, decBpk.getFirst()); -    Assert.assertEquals("wrong bBK-Target",  -        EaafConstants.URN_PREFIX_WBPK + "XFN+123456i", decBpk.getSecond()); -     -  } -   -   -  @Test -  public void noBaseId() { -    try { -      BpkBuilder.generateAreaSpecificPersonIdentifier(null, EaafConstants.URN_PREFIX_CDID + "AA"); -       -    } catch (EaafBuilderException e) { -      Assert.assertEquals("Wrong errorCode", "builder.33", e.getErrorId()); -    } -  } -   -  @Test -  public void noTarget() { -    try { -      BpkBuilder.generateAreaSpecificPersonIdentifier(BASEID, null); -       -    } catch (EaafBuilderException e) { -      Assert.assertEquals("Wrong errorCode", "builder.33", e.getErrorId()); -    } -  } -   -  @Test -  public void noBaseIdType() { -    try { -      BpkBuilder.generateAreaSpecificPersonIdentifier(BASEID,  -          null, EaafConstants.URN_PREFIX_CDID + "AA"); -       -    } catch (EaafBuilderException e) { -      Assert.assertEquals("Wrong errorCode", "builder.33", e.getErrorId()); -    } -  } -   -  @Test -  public void wrongBaseIdType() { -    try { -      BpkBuilder.generateAreaSpecificPersonIdentifier(BASEID,  -          EaafConstants.URN_PREFIX_CDID + "BB", EaafConstants.URN_PREFIX_CDID + "AA"); -       -    } catch (EaafBuilderException e) { -      Assert.assertEquals("Wrong errorCode", "builder.33", e.getErrorId()); -    } -  } -   -  @Test -  public void baseIdTypeEqualsTarget() throws EaafBuilderException { -    Pair<String, String> result1 =  BpkBuilder.generateAreaSpecificPersonIdentifier(BASEID,  -          EaafConstants.URN_PREFIX_CDID + "AA", EaafConstants.URN_PREFIX_CDID + "AA"); -     -    Assert.assertEquals("first bPK", BASEID, -        result1.getFirst()); -    Assert.assertEquals("first bPK", "urn:publicid:gv.at:cdid+AA", -        result1.getSecond()); -   -  } -   -  @Test -  public void buildBpk() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_CDID + "AA"); -    Pair<String, String> result2 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_CDID + "BB"); -     -    Assert.assertEquals("first bPK", "b1Ip610zZq/Or/uCqgb51lnAdZM=", -        result1.getFirst()); -    Assert.assertEquals("first bPK", "urn:publicid:gv.at:cdid+AA", -        result1.getSecond()); -     -    Assert.assertEquals("second bPK", "uYst6hjKJvyp7s/ezD8zsnkcj9k=", -        result2.getFirst()); -    Assert.assertEquals("second bPK", "urn:publicid:gv.at:cdid+BB", -        result2.getSecond()); -     -  } -   -  @Test -  public void buildWbpkFn() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_WBPK + "FN+123456i"); -     -    Assert.assertEquals("wbPK", "k65HRxpVcoZ2OPZHo3j2LEn/JQE=", -        result1.getFirst()); -    Assert.assertEquals("wbPK", "urn:publicid:gv.at:wbpk+XFN+123456i", -        result1.getSecond()); -     -  } -   -  @Test -  public void buildWbpkZvr() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_WBPK + "ZVR+123456"); -     -    Assert.assertEquals("wbPK", "1WvaBLiTxcc3kVzfB71Zh2sCtvA=", -        result1.getFirst()); -    Assert.assertEquals("wbPK", "urn:publicid:gv.at:wbpk+XZVR+123456", -        result1.getSecond()); -     -  } -   -  @Test -  public void buildWbpkErsb() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_WBPK + "ERSB+123456"); -     -    Assert.assertEquals("wbPK", "xtAWGAiblvhYJiCpUB3dwdRFPpg=", -        result1.getFirst()); -    Assert.assertEquals("wbPK", "urn:publicid:gv.at:wbpk+XERSB+123456", -        result1.getSecond()); -     -  } -   -  @Test -  public void buildWbpkXFn() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_WBPK + "XFN+123456i"); -     -    Assert.assertEquals("wbPK", "k65HRxpVcoZ2OPZHo3j2LEn/JQE=", -        result1.getFirst()); -    Assert.assertEquals("wbPK", "urn:publicid:gv.at:wbpk+XFN+123456i", -        result1.getSecond()); -     -  } -   -  @Test -  public void buildWbpkXZvr() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_WBPK + "XZVR+123456"); -     -    Assert.assertEquals("wbPK", "1WvaBLiTxcc3kVzfB71Zh2sCtvA=", -        result1.getFirst()); -    Assert.assertEquals("wbPK", "urn:publicid:gv.at:wbpk+XZVR+123456", -        result1.getSecond()); -     -  } -   -  @Test -  public void buildWbpkXErsb() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_WBPK + "XERSB+123456"); -     -    Assert.assertEquals("wbPK", "xtAWGAiblvhYJiCpUB3dwdRFPpg=", -        result1.getFirst()); -    Assert.assertEquals("wbPK", "urn:publicid:gv.at:wbpk+XERSB+123456", -        result1.getSecond()); -     -  } -   -  @Test -  public void buildWbpkOthers() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_WBPK + "XABC+123456"); -     -    Assert.assertEquals("wbPK", "wv96/xKUyi6YoYGv7IcIlFTsJIk=", -        result1.getFirst()); -    Assert.assertEquals("wbPK", "urn:publicid:gv.at:wbpk+XABC+123456", -        result1.getSecond()); -     -  } -   -  @Test -  public void buildEidasId() throws EaafBuilderException { -     -    Pair<String, String> result1 = BpkBuilder.generateAreaSpecificPersonIdentifier( -        BASEID, EaafConstants.URN_PREFIX_EIDAS + "AT+ES"); -     -    Assert.assertEquals("eidas", "AT/ES/7AuLZNKsiRr97yvLsQ16SZ6r0q0=", -        result1.getFirst()); -    Assert.assertEquals("wbPK", "urn:publicid:gv.at:eidasid+AT+ES", -        result1.getSecond()); -     -  } -   -  @Test -  public void normalizeNullTarget() { -    Assert.assertNull("Wrong normalized target",   -        BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(null)); -      -  } -   -  @Test -  public void normalizeBpkTarget() { -    String target = EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong normalized target",  -        target,  -        BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(target)); -     -  } -   -  @Test -  public void normalizeWbpkTargetWithX() { -    String target = EaafConstants.URN_PREFIX_WBPK_TARGET_WITH_X + RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong normalized target",  -        target,  -        BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(target)); -     -  } -   -  @Test -  public void normalizeWbpkTargetWithOutXNoMapping() { -    String target = EaafConstants.URN_PREFIX_WBPK + RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong normalized target",  -        target,  -        BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(target)); -     -  } -   -  @Test -  public void normalizeWbpkTargetWithOutXMappingFn() { -    Assert.assertEquals("Wrong normalized target",  -        EaafConstants.URN_PREFIX_WBPK + "XFN+123456i",  -        BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(EaafConstants.URN_PREFIX_WBPK + "FN+123456i")); -     -  } -   -  @Test -  public void normalizeWbpkTargetWithOutXMappingZvr() { -    Assert.assertEquals("Wrong normalized target",  -        EaafConstants.URN_PREFIX_WBPK + "XZVR+1122334455",  -        BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(EaafConstants.URN_PREFIX_WBPK + "ZVR+1122334455")); -     -  } -   -  @Test -  public void normalizeWbpkTargetWithOutXMappingErsb() { -    Assert.assertEquals("Wrong normalized target",  -        EaafConstants.URN_PREFIX_WBPK + "XERSB+998877665544",  -        BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(EaafConstants.URN_PREFIX_WBPK + "ERSB+998877665544")); -     -  } -   -  @Test -  public void normalizeEidasTarget() { -    String target = EaafConstants.URN_PREFIX_EIDAS + RandomStringUtils.randomAlphabetic(2)  -        + "+" + RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong normalized target",  -        target,  -        BpkBuilder.normalizeBpkTargetIdentifierToCommonFormat(target)); -     -  } -   -  @Test -  public void calcNormalizeNullTarget() { -    Assert.assertNull("Wrong normalized target",   -        BpkBuilder.normalizeBpkTargetIdentifierToNonXFormat(null)); -      -  } -   -  @Test -  public void calcNormalizeBpkTarget() { -    String target = EaafConstants.URN_PREFIX_CDID + RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong normalized target",  -        target,  -        BpkBuilder.normalizeBpkTargetIdentifierToNonXFormat(target)); -     -  } -   -  @Test -  public void calcNormalizeWbpkTargetWithoutX() { - -    Assert.assertEquals("Wrong normalized target",  -        EaafConstants.URN_PREFIX_WBPK + "FN+123456i",  -        BpkBuilder.normalizeBpkTargetIdentifierToNonXFormat(EaafConstants.URN_PREFIX_WBPK + "FN+123456i")); -     -  } -   -  @Test -  public void calcNormalizeWbpkTargetWithOutXNoMapping() { -    String target = EaafConstants.URN_PREFIX_WBPK + RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong normalized target",  -        target,  -        BpkBuilder.normalizeBpkTargetIdentifierToNonXFormat(target)); -     -  } -   -  @Test -  public void calcNormalizeWbpkTargetWithXMappingFn() { -    Assert.assertEquals("Wrong normalized target",  -        EaafConstants.URN_PREFIX_WBPK + "FN+123456i",  -        BpkBuilder.normalizeBpkTargetIdentifierToNonXFormat(EaafConstants.URN_PREFIX_WBPK + "XFN+123456i")); -     -  } -   -  @Test -  public void calcNormalizeWbpkTargetWithXMappingZvr() { -    Assert.assertEquals("Wrong normalized target",  -        EaafConstants.URN_PREFIX_WBPK + "ZVR+1122334455",  -        BpkBuilder.normalizeBpkTargetIdentifierToNonXFormat(EaafConstants.URN_PREFIX_WBPK + "XZVR+1122334455")); -     -  } -   -  @Test -  public void calcNormalizeWbpkTargetWithXMappingErsb() { -    Assert.assertEquals("Wrong normalized target",  -        EaafConstants.URN_PREFIX_WBPK + "ERSB+998877665544",  -        BpkBuilder.normalizeBpkTargetIdentifierToNonXFormat( -            EaafConstants.URN_PREFIX_WBPK + "XERSB+998877665544")); -     -  } -   -  @Test -  public void calcNormalizeEidasTarget() { -    String target = EaafConstants.URN_PREFIX_EIDAS + RandomStringUtils.randomAlphabetic(2)  -        + "+" + RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong normalized target",  -        target,  -        BpkBuilder.normalizeBpkTargetIdentifierToNonXFormat(target)); -     -  } -   -  @Test -  public void removeBpkPrefix() { -    String spTarget = RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong SP target without prefix",  -        spTarget,  -        BpkBuilder.removeBpkTypePrefix(EaafConstants.URN_PREFIX_CDID + spTarget)); -     -  } -   -  @Test -  public void removeWpbkPrefix() { -    String spTarget = RandomStringUtils.randomAlphabetic(10); -    Assert.assertEquals("Wrong SP target without prefix",  -        spTarget,  -        BpkBuilder.removeBpkTypePrefix(EaafConstants.URN_PREFIX_WBPK + spTarget)); -     -  } -   -  @Test -  public void removeEidasPbkPrefix() { -    String spTarget = RandomStringUtils.randomAlphabetic(2) + "+" + RandomStringUtils.randomAlphabetic(2); -    Assert.assertEquals("Wrong SP target without prefix",  -        spTarget,  -        BpkBuilder.removeBpkTypePrefix(EaafConstants.URN_PREFIX_EIDAS + spTarget)); -     -  } -   -  @Test -  public void removeUnknownPbkPrefix() { -    String spTarget = RandomStringUtils.randomAlphabetic(10); -    Assert.assertEquals("Wrong SP target without prefix",  -        EaafConstants.URN_PREFIX_BASEID + spTarget,  -        BpkBuilder.removeBpkTypePrefix(EaafConstants.URN_PREFIX_BASEID + spTarget)); -     -  } -} | 
