package at.gv.egiz.eaaf.modules.auth.sl20.utils; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.utils.URIBuilder; import org.apache.http.util.EntityUtils; import org.jose4j.base64url.Base64Url; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoParserException; public class SL20JSONExtractorUtils { private static final Logger log = LoggerFactory.getLogger(SL20JSONExtractorUtils.class); private static JsonMapper mapper = new JsonMapper(); /** * Extract String value from JSON * * @param input * @param keyID * @param isRequired * @return * @throws SLCommandoParserException */ public static String getStringValue(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { try { final JsonNode internal = getAndCheck(input, keyID, isRequired); if (internal != null) return internal.asText(); else return null; } catch (final SLCommandoParserException e) { throw e; } catch (final Exception e) { throw new SLCommandoParserException("Can not extract String value with keyId: " + keyID, e); } } /** * Extract Boolean value from JSON * * @param input * @param keyID * @param isRequired * @return * @throws SLCommandoParserException */ public static boolean getBooleanValue(ObjectNode input, String keyID, boolean isRequired, boolean defaultValue) throws SLCommandoParserException { try { final JsonNode internal = getAndCheck(input, keyID, isRequired); if (internal != null) return internal.asBoolean(); else return defaultValue; } catch (final SLCommandoParserException e) { throw e; } catch (final Exception e) { throw new SLCommandoParserException("Can not extract Boolean value with keyId: " + keyID, e); } } /** * Extract JSONObject value from JSON * * @param input * @param keyID * @param isRequired * @return * @throws SLCommandoParserException */ public static JsonNode getJSONObjectValue(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { try { final JsonNode internal = getAndCheck(input, keyID, isRequired); if (internal != null) return internal; else return null; } catch (final SLCommandoParserException e) { throw e; } catch (final Exception e) { throw new SLCommandoParserException("Can not extract Boolean value with keyId: " + keyID, e); } } /** * Extract a List of String elements from a JSON element * * @param input * @return * @throws SLCommandoParserException */ public static List getListOfStringElements(JsonNode input) throws SLCommandoParserException { final List result = new ArrayList(); if (input != null) { if (input.isArray()) { final Iterator arrayIterator = input.iterator(); while(arrayIterator.hasNext()) { final JsonNode next = arrayIterator.next(); if (next.isTextual()) result.add(next.asText()); } } else if (input.isTextual()) { result.add(input.asText()); } else { log.warn("JSON Element IS NOT a JSON array or a JSON Primitive"); throw new SLCommandoParserException("JSON Element IS NOT a JSON array or a JSON Primitive"); } } return result; } /** * Extract Map of Key/Value pairs from a JSON Element * * @param input parent JSON object * @param keyID KeyId of the child that should be parsed * @param isRequired * @return * @throws SLCommandoParserException */ public static Map getMapOfStringElements(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { final JsonNode internal = getAndCheck(input, keyID, isRequired); return getMapOfStringElements(internal); } /** * Extract Map of Key/Value pairs from a JSON Element * * @param input * @return * @throws SLCommandoParserException */ public static Map getMapOfStringElements(JsonNode input) throws SLCommandoParserException { final Map result = new HashMap(); if (input != null) { if (input.isArray()) { final Iterator arrayIterator = input.iterator(); while(arrayIterator.hasNext()) { final JsonNode next = arrayIterator.next(); final Iterator> entry = next.fields(); entitySetToMap(result, entry); } } else if (input.isObject()) { final Iterator> objectKeys = input.fields(); entitySetToMap(result, objectKeys); } else throw new SLCommandoParserException("JSON Element IS NOT a JSON array or a JSON object"); } return result; } private static void entitySetToMap(Map result, Iterator> entry) { while (entry.hasNext()) { final Entry el = entry.next(); if (result.containsKey(el.getKey())) log.info("Attr. Map already contains Element with Key: " + el.getKey() + ". Overwrite element ... "); result.put(el.getKey(), el.getValue().asText()); } } public static JsonNode extractSL20Result(JsonNode command, IJOSETools decrypter, boolean mustBeEncrypted) throws SL20Exception { final JsonNode result = command.get(SL20Constants.SL20_COMMAND_CONTAINER_RESULT); final JsonNode encryptedResult = command.get(SL20Constants.SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT); if (result == null && encryptedResult == null) throw new SLCommandoParserException("NO result OR encryptedResult FOUND."); else if (encryptedResult == null && mustBeEncrypted) throw new SLCommandoParserException("result MUST be encrypted."); else if (encryptedResult != null && encryptedResult.isTextual()) { try { return decrypter.decryptPayload(encryptedResult.asText()); } catch (final Exception e) { log.info("Can NOT decrypt SL20 result. Reason:" + e.getMessage()); if (!mustBeEncrypted) { log.warn("Decrypted results are disabled by configuration. Parse result in plain if it is possible"); //dummy code try { final String[] signedPayload = encryptedResult.toString().split("\\."); final JsonNode payLoad = mapper.getMapper().readTree(new String(Base64.getUrlDecoder().decode(signedPayload[1]))); return payLoad; } catch (final Exception e1) { log.debug("DummyCode FAILED, Reason: " + e1.getMessage() + " Ignore it ..."); throw new SL20Exception(e.getMessage(), null, e); } } else throw e; } } else if (result != null) { return result; } else throw new SLCommandoParserException("Internal build error"); } /** * Extract payLoad from generic transport container * * @param container * @param joseTools * @return * @throws SLCommandoParserException */ public static VerificationResult extractSL20PayLoad(JsonNode container, IJOSETools joseTools, boolean mustBeSigned) throws SL20Exception { final JsonNode sl20Payload = container.get(SL20Constants.SL20_PAYLOAD); final JsonNode sl20SignedPayload = container.get(SL20Constants.SL20_SIGNEDPAYLOAD); if (mustBeSigned && joseTools == null) throw new SLCommandoParserException("'joseTools' MUST be set if 'mustBeSigned' is 'true'"); if (sl20Payload == null && sl20SignedPayload == null) throw new SLCommandoParserException("NO payLoad OR signedPayload FOUND."); else if (sl20SignedPayload == null && mustBeSigned) throw new SLCommandoParserException("payLoad MUST be signed."); else if (joseTools != null && sl20SignedPayload != null && sl20SignedPayload.isTextual()) { return joseTools.validateSignature(sl20SignedPayload.asText()); } else if (sl20Payload != null) return new VerificationResult(sl20Payload); else throw new SLCommandoParserException("Internal build error"); } /** * Extract generic transport container from httpResponse * * @param httpResp * @return * @throws SLCommandoParserException */ public static JsonNode getSL20ContainerFromResponse(HttpResponse httpResp) throws SLCommandoParserException { try { JsonNode sl20Resp = null; if (httpResp.getStatusLine().getStatusCode() == 307) { final Header[] locationHeader = httpResp.getHeaders("Location"); if (locationHeader == null) throw new SLCommandoParserException("Find Redirect statuscode but not Location header"); final String sl20RespString = new URIBuilder(locationHeader[0].getValue()).getQueryParams().get(0).getValue(); sl20Resp = mapper.getMapper().readTree(Base64Url.encode((sl20RespString.getBytes()))); } else if (httpResp.getStatusLine().getStatusCode() == 200) { if (!httpResp.getEntity().getContentType().getValue().startsWith("application/json")) throw new SLCommandoParserException("SL20 response with a wrong ContentType: " + httpResp.getEntity().getContentType().getValue()); sl20Resp = parseSL20ResultFromResponse(httpResp.getEntity()); } else if ( (httpResp.getStatusLine().getStatusCode() == 500) || (httpResp.getStatusLine().getStatusCode() == 401) || (httpResp.getStatusLine().getStatusCode() == 400) ) { log.info("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode() + ". Search for error message"); try { sl20Resp = parseSL20ResultFromResponse(httpResp.getEntity()); } catch (final Exception e) { log.warn("SL20 response contains no valid JSON", e); throw new SLCommandoParserException("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode() + " AND NO valid JSON errormsg", e); } } else throw new SLCommandoParserException("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode()); log.info("Find JSON object in http response"); return sl20Resp; } catch (final Exception e) { throw new SLCommandoParserException("SL20 response parsing FAILED! Reason: " + e.getMessage(), e); } } private static JsonNode parseSL20ResultFromResponse(HttpEntity resp) throws Exception { if (resp != null && resp.getContent() != null) { final String rawSL20Resp = EntityUtils.toString(resp); final JsonNode sl20Resp = mapper.getMapper().readTree(rawSL20Resp); //TODO: check sl20Resp type like && sl20Resp.isJsonObject() if (sl20Resp != null) { return sl20Resp; } else throw new SLCommandoParserException("SL2.0 can NOT parse to a JSON object"); } else throw new SLCommandoParserException("Can NOT find content in http response"); } private static JsonNode getAndCheck(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { final JsonNode internal = input.get(keyID); if (internal == null && isRequired) throw new SLCommandoParserException("REQUIRED Element with keyId: " + keyID + " does not exist"); return internal; } }