Java Code Examples for javax.json.JsonArray#isEmpty()

The following examples show how to use javax.json.JsonArray#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestCaseJson.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the JSON object that represents the given request case.
 */
private static JsonObject toJson( RequestCase requestCase)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  builder.add( ID, requestCase.getId());
  Optional.ofNullable( requestCase.getName()).ifPresent( name -> builder.add( NAME, name));
  Optional.ofNullable( requestCase.getServer()).ifPresent( server -> builder.add( SERVER, server.toString()));
  Optional.ofNullable( requestCase.getVersion()).ifPresent( version -> builder.add( VERSION, version));
  Optional.ofNullable( requestCase.getApi()).ifPresent( api -> builder.add( API, api));
  Optional.ofNullable( requestCase.getPath()).ifPresent( path -> builder.add( PATH, path));
  Optional.ofNullable( requestCase.getOperation()).ifPresent( op -> builder.add( OPERATION, op));

  JsonArrayBuilder paramBuilder = Json.createArrayBuilder();
  toStream( requestCase.getParams()).forEach( paramData -> paramBuilder.add( toJson( paramData)));
  JsonArray params = paramBuilder.build();
  if( !params.isEmpty())
    {
    builder.add( PARAMETERS, params);
    }
  
  Optional.ofNullable( requestCase.getBody()).ifPresent( body -> builder.add( BODY, toJson( body)));
  Optional.ofNullable( requestCase.getInvalidInput()).ifPresent( invalidInput -> builder.add( INVALID_INPUT, invalidInput));
  
  return builder.build();
  }
 
Example 2
Source File: HFCAAffiliation.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
HFCAAffiliationResp(JsonObject result) {
    if (result.containsKey("affiliations")) {
        JsonArray affiliations = result.getJsonArray("affiliations");
        if (affiliations != null && !affiliations.isEmpty()) {
            for (int i = 0; i < affiliations.size(); i++) {
                JsonObject aff = affiliations.getJsonObject(i);
                this.childHFCAAffiliations.add(new HFCAAffiliation(aff));
            }
        }
    }
    if (result.containsKey("identities")) {
        JsonArray ids = result.getJsonArray("identities");
        if (ids != null && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                JsonObject id = ids.getJsonObject(i);
                HFCAIdentity hfcaID = new HFCAIdentity(id);
                this.identities.add(hfcaID);
            }
        }
    }
    if (result.containsKey("statusCode")) {
        this.statusCode = result.getInt("statusCode");
    }
}
 
Example 3
Source File: HFCAIdentity.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private void getHFCAIdentity(JsonObject result) {
    type = result.getString("type");
    if (result.containsKey("secret")) {
        this.secret = result.getString("secret");
    }
    maxEnrollments = result.getInt("max_enrollments");
    affiliation = result.getString("affiliation");
    JsonArray attributes = result.getJsonArray("attrs");

    Collection<Attribute> attrs = new ArrayList<Attribute>();
    if (attributes != null && !attributes.isEmpty()) {
        for (int i = 0; i < attributes.size(); i++) {
            JsonObject attribute = attributes.getJsonObject(i);
            Attribute attr = new Attribute(attribute.getString("name"), attribute.getString("value"), attribute.getBoolean("ecert", false));
            attrs.add(attr);
        }
    }
    this.attrs = attrs;
}
 
Example 4
Source File: DynamicTypeAnalyzer.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
private TypeIdentifier analyzeInternal(final JsonArray jsonArray) {
    final TypeIdentifier containedIdentifier = jsonArray.isEmpty() ? TypeIdentifier.ofType(Types.OBJECT) : analyzeInternal(jsonArray.get(0));
    final TypeRepresentation containedRepresentation = typeRepresentations.getOrDefault(containedIdentifier, TypeRepresentation.ofConcrete(containedIdentifier));

    final TypeIdentifier existingCollection = findExistingCollection(containedRepresentation);
    if (existingCollection != null) {
        return existingCollection;
    }

    final TypeIdentifier identifier = TypeIdentifier.ofDynamic();
    typeRepresentations.put(identifier, TypeRepresentation.ofCollection(identifier, containedRepresentation));
    return identifier;
}
 
Example 5
Source File: SystemInputJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Add any properties from the given value to the given JsonObjectBuilder.
 */
private static JsonObjectBuilder addProperties( JsonObjectBuilder builder, VarValueDef value)
  {
  JsonArrayBuilder properties = Json.createArrayBuilder();
  value.getProperties().forEach( property -> properties.add( property));
  JsonArray json = properties.build();

  if( !json.isEmpty())
    {
    builder.add( PROPERTIES_KEY, json);
    }

  return builder;
  }
 
Example 6
Source File: RegistrationsResource.java    From javaee-bce-pom with Apache License 2.0 5 votes vote down vote up
@GET
public Response all() {
    JsonArray registrationList = this.registrations.allAsJson();
    if (registrationList == null || registrationList.isEmpty()) {
        return Response.noContent().build();
    }
    return Response.ok(registrationList).build();
}
 
Example 7
Source File: BookJsonStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Book bookFromJson(JsonObject obj) {
    final Book book = new Book(obj.getString("name"), obj.getInt("id"));
    final JsonArray chapters = (JsonArray)obj.get("chapters");
    if (chapters != null && !chapters.isEmpty()) {
        for (final JsonObject chapter: chapters.getValuesAs(JsonObject.class)) {
            book.addChapter(chapter.getInt("id"), chapter.getString("title"));
        }
    }

    return book;
}
 
Example 8
Source File: GeoJsonReader.java    From geojson with Apache License 2.0 5 votes vote down vote up
private Optional<Way> createWay(final JsonArray coordinates, final boolean autoClose) {
    if (coordinates.isEmpty()) {
        return Optional.empty();
    }

    final List<LatLon> latlons = coordinates.stream().map(coordinate -> {
        final JsonArray jsonValues = coordinate.asJsonArray();
        return new LatLon(
            jsonValues.getJsonNumber(1).doubleValue(),
            jsonValues.getJsonNumber(0).doubleValue()
        );
    }).collect(Collectors.toList());

    final int size = latlons.size();
    final boolean doAutoclose;
    if (size > 1) {
        if (latlons.get(0).equals(latlons.get(size - 1))) {
            // Remove last coordinate, but later add first node to the end
            latlons.remove(size - 1);
            doAutoclose = true;
        } else {
            doAutoclose = autoClose;
        }
    } else {
        doAutoclose = false;
    }

    final Way way = new Way();
    way.setNodes(latlons.stream().map(Node::new).collect(Collectors.toList()));
    if (doAutoclose) {
        way.addNode(way.getNode(0));
    }

    way.getNodes().stream().distinct().forEach(it -> getDataSet().addPrimitive(it));
    getDataSet().addPrimitive(way);

    return Optional.of(way);
}
 
Example 9
Source File: RegistrationsResource.java    From javaee-bce-archetype with Apache License 2.0 5 votes vote down vote up
@GET
public Response all() {
    JsonArray registrationList = this.registrations.allAsJson();
    if (registrationList == null || registrationList.isEmpty()) {
        return Response.noContent().build();
    }
    return Response.ok(registrationList).build();
}
 
Example 10
Source File: HFCAAffiliation.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void generateResponse(JsonObject result) {
    if (result.containsKey("name")) {
        this.name = result.getString("name");
    }
    if (result.containsKey("affiliations")) {
        JsonArray affiliations = result.getJsonArray("affiliations");
        if (affiliations != null && !affiliations.isEmpty()) {
            for (int i = 0; i < affiliations.size(); i++) {
                JsonObject aff = affiliations.getJsonObject(i);
                this.childHFCAAffiliations.add(new HFCAAffiliation(aff));
            }
        }
    }
    if (result.containsKey("identities")) {
          JsonArray ids = result.getJsonArray("identities");
          if (ids != null && !ids.isEmpty()) {
              for (int i = 0; i < ids.size(); i++) {
                  JsonObject id = ids.getJsonObject(i);
                  HFCAIdentity hfcaID = new HFCAIdentity(id);
                  this.identities.add(hfcaID);
              }
          }
    }
}
 
Example 11
Source File: Message.java    From sample-room-java with Apache License 2.0 5 votes vote down vote up
/**
 * Send information about the room to the client. This message is sent after
 * receiving a `roomHello`.
 * @param userId
 * @param roomDescription Room attributes
 * @return constructed message
 */
public static Message createLocationMessage(String userId, RoomDescription roomDescription) {
    //  player,<userId>,{
    //      "type": "location",
    //      "name": "Room name",
    //      "fullName": "Room's descriptive full name",
    //      "description", "Lots of text about what the room looks like",
    //      "exits": {
    //          "shortDirection" : "currentDescription for Player",
    //          "N" :  "a dark entranceway"
    //      },
    //      "commands": {
    //          "/custom" : "Description of what command does"
    //      },
    //      "roomInventory": ["itemA","itemB"]
    //  }
    JsonObjectBuilder payload = Json.createObjectBuilder();
    payload.add(TYPE, "location");
    payload.add("name", roomDescription.getName());
    payload.add("fullName", roomDescription.getFullName());
    payload.add("description", roomDescription.getDescription());

    // convert map of commands into JsonObject
    JsonObject commands = roomDescription.getCommands();
    if ( !commands.isEmpty()) {
        payload.add("commands", commands);
    }

    // Convert list of items into json array
    JsonArray inventory = roomDescription.getInventory();
    if ( !inventory.isEmpty()) {
        payload.add("roomInventory", inventory);
    }

    return new Message(Target.player, userId, payload.build().toString());
}
 
Example 12
Source File: WebHCatJsonParser.java    From hadoop-etl-udfs with MIT License 5 votes vote down vote up
private static List<HCatTableColumn> parseColumnArray(JsonArray array) {
    List<HCatTableColumn> columns = new ArrayList<HCatTableColumn>();
    if (array != null && !array.isEmpty()) {
        for (JsonValue column : array) {
            JsonObject col = (JsonObject) column;
            columns.add(new HCatTableColumn(col.getString("name"), col.getString("type")));
        }
    }
    return columns;
}
 
Example 13
Source File: SchemalessJsonToIndexedRecord.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private Schema guessSchema(final String recordName, final JsonValue element) {
    switch (element.getValueType()) {
    case STRING:
        return STRING;
    case NUMBER:
        final Number number = JsonNumber.class.cast(element).numberValue();
        if (Long.class.isInstance(number)) {
            return LONG;
        }
        if (Integer.class.isInstance(number)) {
            return INT;
        }
        return DOUBLE;
    case FALSE:
    case TRUE:
        return BOOLEAN;
    case NULL:
        return NULL;
    case OBJECT:
        final Schema record = Schema.createRecord(recordName, null, NAMESPACE, false);
        record
                .setFields(element
                        .asJsonObject()
                        .entrySet()
                        .stream()
                        .map(it -> new Schema.Field(it.getKey(),
                                guessSchema(buildNextName(recordName, it.getKey()), it.getValue()), null, null))
                        .collect(toList()));
        return record;
    case ARRAY:
        final JsonArray array = element.asJsonArray();
        if (!array.isEmpty()) {
            return Schema.createArray(guessSchema(buildNextName(recordName, "Array"), array.iterator().next()));
        }
        return Schema.createArray(Schema.create(Schema.Type.NULL));
    default:
        throw new IllegalArgumentException("Unsupported: " + element.toString());
    }
}
 
Example 14
Source File: Generator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static boolean areEqualsIgnoringOrder(final JsonValue oldValue, final JsonValue newValue) {
    if (!oldValue.getValueType().equals(newValue.getValueType())) {
        return false;
    }
    switch (oldValue.getValueType()) {
    case STRING:
        return JsonString.class.cast(oldValue).getString().equals(JsonString.class.cast(newValue).getString());
    case NUMBER:
        return JsonNumber.class.cast(oldValue).doubleValue() == JsonNumber.class.cast(newValue).doubleValue();
    case OBJECT:
        final JsonObject oldObject = oldValue.asJsonObject();
        final JsonObject newObject = newValue.asJsonObject();
        if (!oldObject.keySet().equals(newObject.keySet())) {
            return false;
        }
        return oldObject
                .keySet()
                .stream()
                .map(key -> areEqualsIgnoringOrder(oldObject.get(key), newObject.get(key)))
                .reduce(true, (a, b) -> a && b);
    case ARRAY:
        final JsonArray oldArray = oldValue.asJsonArray();
        final JsonArray newArray = newValue.asJsonArray();
        if (oldArray.size() != newArray.size()) {
            return false;
        }
        if (oldArray.isEmpty()) {
            return true;
        }
        for (final JsonValue oldItem : oldArray) {
            if (newArray.stream().noneMatch(newitem -> areEqualsIgnoringOrder(oldItem, newitem))) {
                return false;
            }
        }
        return true;
    default:
        // value type check was enough
        return true;
    }
}
 
Example 15
Source File: PayloadMapper.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private void onArray(final Collection<ParameterMeta> definitions, final ParameterMeta definition,
        final Map<String, String> config, final String currentPrefix, final JsonObjectBuilder json,
        final String name) {
    final JsonArray array;
    if (definitions.size() == 1 && definitions.iterator().next().getPath().endsWith("[${index}]")) { // primitive
        final ParameterMeta primitiveMeta = definitions.stream().iterator().next();
        array = config
                .entrySet()
                .stream()
                .filter(it -> it.getKey().startsWith(currentPrefix + '['))
                .map(e -> new ArrayEntry(e, currentPrefix))
                .distinct()
                // sort by index
                .sorted(comparing(it -> it.index))
                .map(entry -> onArrayPrimitive(primitiveMeta, entry))
                .collect(toJsonArray());
    } else {
        array = config
                .entrySet()
                .stream()
                .filter(it -> it.getKey().startsWith(currentPrefix + '['))
                .map(e -> new ArrayEntry(e, currentPrefix).index)
                .distinct()
                // sort by index
                .sorted(comparing(it -> it))
                .map(index -> unflatten(currentPrefix + '[' + index + ']', definitions, config))
                .collect(toJsonArray());
    }
    if (!array.isEmpty()) {
        json.add(name, array);
        parameterVisitor.onParameter(definition, array);
    } else {
        parameterVisitor.onParameter(definition, JsonValue.NULL);
    }
}
 
Example 16
Source File: ExecutionService.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private JsonObjectBuilder addErrorsToResponse(JsonObjectBuilder returnObjectBuilder, ExecutionResult executionResult) {
    List<GraphQLError> errors = executionResult.getErrors();
    if (errors != null) {
        JsonArray jsonArray = errorsService.toJsonErrors(errors);
        if (!jsonArray.isEmpty()) {
            returnObjectBuilder = returnObjectBuilder.add(ERRORS, jsonArray);
        }
        return returnObjectBuilder;
    } else {
        return returnObjectBuilder;
    }

}
 
Example 17
Source File: FHIRSwaggerGenerator.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private static void generateDefinition(Class<?> modelClass, JsonObjectBuilder definitions) throws Exception {
        if (!ModelSupport.isPrimitiveType(modelClass)) {
            JsonObjectBuilder definition = factory.createObjectBuilder();
            JsonObjectBuilder properties = factory.createObjectBuilder();
            JsonArrayBuilder required = factory.createArrayBuilder();

            StructureDefinition structureDefinition = getStructureDefinition(modelClass);

            if (structureDefinition == null) {
                System.err.println("Failed generateDefinition for: " + modelClass.getName());
                return;
            }

            if (Resource.class.isAssignableFrom(modelClass)) {
                // add the 'resourceType' property
                JsonObjectBuilder property = factory.createObjectBuilder();

                // Convert all the primitive types to json types.
                property.add("type", "string");
                if (Resource.class == modelClass) {
                    // TODO: when a filter was passed, limit this to just the resource types included in the filter
                    List<String> typeNames = Arrays.stream(ResourceType.ValueSet.values()).map(ResourceType.ValueSet::value).collect(Collectors.toList());
                    JsonArrayBuilder enumValues = factory.createArrayBuilder(typeNames);
                    property.add("enum", enumValues);
                    properties.add("resourceType", property.build());
                    required.add("resourceType");
                } else {
                    // TODO how to "overwrite" the Resource definition and say that the value is fixed?
                    // https://github.com/OAI/OpenAPI-Specification/issues/1313
//                    property.add("enum", modelClass.getSimpleName());
                }
            }

            for (Field field : modelClass.getDeclaredFields()) {
                if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isVolatile(field.getModifiers())) {
                    if (!ModelSupport.isChoiceElement(modelClass, ModelSupport.getElementName(field)) && field.isAnnotationPresent(Required.class)) {
                        required.add(ModelSupport.getElementName(field));
                    }
                    generateProperties(structureDefinition, modelClass, field, properties);
                }
            }

            JsonArray requiredArray = required.build();

            Class<?> superClass = modelClass.getSuperclass();
            if (superClass != null
                    && superClass.getPackage().getName().startsWith("com.ibm.fhir.model")
                    && !superClass.equals(AbstractVisitable.class)) {
                JsonArrayBuilder allOf = factory.createArrayBuilder();

                JsonObjectBuilder ref = factory.createObjectBuilder();
                ref.add("$ref", "#/definitions/" + superClass.getSimpleName());
                allOf.add(ref);

                JsonObjectBuilder wrapper = factory.createObjectBuilder();
                wrapper.add("type", "object");
                wrapper.add("properties", properties);
                if (!requiredArray.isEmpty()) {
                    wrapper.add("required", requiredArray);
                }
                allOf.add(wrapper);

                definition.add("allOf", allOf);
            } else {
                definition.add("type", "object");
                if (Resource.class.equals(modelClass)) {
                    definition.add("discriminator", "resourceType");
                }
                definition.add("properties", properties);
                if (!requiredArray.isEmpty()) {
                    definition.add("required", requiredArray);
                }
            }

            if (Resource.class.isAssignableFrom(modelClass)) {
                FHIROpenApiGenerator.addExamples(modelClass, definition);
            }

            definitions.add(getSimpleNameWithEnclosingNames(modelClass), definition);
        }
    }
 
Example 18
Source File: FHIROpenApiGenerator.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private static void generateDefinition(Class<?> modelClass, JsonObjectBuilder definitions) throws Exception {
        if (!ModelSupport.isPrimitiveType(modelClass)) {
            JsonObjectBuilder definition = factory.createObjectBuilder();
            JsonObjectBuilder properties = factory.createObjectBuilder();
            JsonArrayBuilder required = factory.createArrayBuilder();

            StructureDefinition structureDefinition = getStructureDefinition(modelClass);

            if (structureDefinition == null) {
                System.err.println("Failed generateDefinition for: " + modelClass.getName());
                return;
            }

            if (Resource.class.isAssignableFrom(modelClass)) {
                // if the modelClass is a resource, then add the 'resourceType' property
                JsonObjectBuilder property = factory.createObjectBuilder();

                // Convert all the primitive types to json types.
                property.add("type", "string");
                if (Resource.class == modelClass) {
                    // TODO: when a filter was passed, limit this to just the resource types included in the filter
                    List<String> typeNames = Arrays.stream(ResourceType.ValueSet.values()).map(ResourceType.ValueSet::value).collect(Collectors.toList());
                    JsonArrayBuilder enumValues = factory.createArrayBuilder(typeNames);
                    property.add("enum", enumValues);
                    properties.add("resourceType", property.build());
                    required.add("resourceType");
                } else {
                    // TODO how to "overwrite" the Resource definition and say that the value is fixed?
                    // https://github.com/OAI/OpenAPI-Specification/issues/1313
//                    property.add("enum", modelClass.getSimpleName());
                }
            }

            for (Field field : modelClass.getDeclaredFields()) {
                if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isVolatile(field.getModifiers())) {
                    if (!ModelSupport.isChoiceElement(modelClass, ModelSupport.getElementName(field)) &&
                            field.isAnnotationPresent(Required.class)) {
                        required.add(ModelSupport.getElementName(field));
                    }
                    generateProperties(structureDefinition, modelClass, field, properties);
                }
            }

            JsonArray requiredArray = required.build();

            Class<?> superClass = modelClass.getSuperclass();
            if (superClass != null && superClass.getPackage().getName().startsWith("com.ibm.fhir.model")
                    && !superClass.equals(AbstractVisitable.class)) {
                JsonArrayBuilder allOf = factory.createArrayBuilder();

                JsonObjectBuilder ref = factory.createObjectBuilder();
                ref.add("$ref", "#/components/schemas/" + superClass.getSimpleName());
                allOf.add(ref);

                JsonObjectBuilder wrapper = factory.createObjectBuilder();
                wrapper.add("type", "object");
                wrapper.add("properties", properties);
                if (!requiredArray.isEmpty()) {
                    wrapper.add("required", requiredArray);
                }
                allOf.add(wrapper);

                definition.add("allOf", allOf);
            } else {
                definition.add("type", "object");
                if (Resource.class.equals(modelClass)) {
                    definition.add("discriminator", "resourceType");
                }
                definition.add("properties", properties);
                if (!requiredArray.isEmpty()) {
                    definition.add("required", requiredArray);
                }
            }

            if (Resource.class.isAssignableFrom(modelClass)) {
                addExamples(modelClass, definition);
            }

            definitions.add(getSimpleNameWithEnclosingNames(modelClass), definition);
        }
    }
 
Example 19
Source File: AndroidSafetynetAttestationStatement.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public Boolean verifySignature(String browserDataBase64, FIDO2AuthenticatorData authData) {
    try {
        //Verify JWT timestamp is valid
        JsonNumber timestampMs = jwt.getBody().getJsonNumber("timestampMs");
        Date now = new Date();
        if (timestampMs == null //timestampMS is missing
                || timestampMs.longValue() > now.getTime() + (30 * 1000)        //timestampMS is in the future (some hardcoded buffer)  (TODO fix hardcode)
                || timestampMs.longValue() < now.getTime() - (60 * 1000)) {     //timestampMS is older than 1 minute
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "FIDO-ERR-0015",
                    "JWT time stamp = " + timestampMs.longValue() + ", current time = " + now.getTime());
            throw new IllegalArgumentException("JWT has invalid timestampMs");
        }

        //Verify JWT certificate chain
        JsonArray x5c = jwt.getHeader().getJsonArray("x5c");
        if (x5c == null || x5c.isEmpty()) {
            throw new IllegalArgumentException("JWT missing x5c information");
        }
        if (x5c.size() < 2) {
            throw new IllegalArgumentException("JWT missing certificate chain");
        }
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BCFIPS");
        Base64.Decoder decoder = Base64.getDecoder();
        List<X509Certificate> certchain = new ArrayList<>();
        X509Certificate rootCert = null;
        for (int i = 0; i < x5c.size(); i++) {
            byte[] certBytes = decoder.decode(x5c.getString(i, null));
            ByteArrayInputStream instr = new ByteArrayInputStream(certBytes);
            X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(instr);
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                "certificate number " + i + " = " + certificate);
            if(i == x5c.size() - 1){
                rootCert = certificate;
            }
            else{
                certchain.add(certificate);
            }
        }
        if(rootCert == null){
            throw new IllegalArgumentException("JWT missing certificate chain root");
        }
        Set<TrustAnchor> trustAnchor = new HashSet<>();
        trustAnchor.add(new TrustAnchor(rootCert, null));
        CertPath certPath = CertificateFactory.getInstance("X.509", "BCFIPS").generateCertPath(certchain);
        if(!PKIXChainValidation.pkixvalidate(certPath, trustAnchor, false, false)){     //TODO check CRLs if they exist, otherwise don't
            throw new IllegalArgumentException("JWT failed PKIX validation");
        }

        //Verify JWT signature
        if (!jwt.verifySignature(certchain.get(0).getPublicKey())) {
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "FIDO-ERR-0015",
                    "JWT Signature verification failed!");
            return false;
        }

        //Verify that response is a valid SafetyNet response of version ver.
        if(version == null || version.isEmpty()){
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "FIDO-ERR-0015",
                    "AndroidSafetynet missing version information");
            return false;
        }

        //Verify that the nonce in the response is identical to the SHA-256 hash of the concatenation of authenticatorData and clientDataHash.
        String nonce = jwt.getBody().getString("nonce", null);
        if(nonce == null || !Arrays.equals(decoder.decode(nonce), skfsCommon.getDigestBytes(concatenateArrays(authData.getAuthDataDecoded(),
                skfsCommon.getDigestBytes(Base64.getDecoder().decode(browserDataBase64), "SHA256")), "SHA256"))){
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "FIDO-ERR-0015",
                    "JWT has incorrect nonce");
            return false;
        }

        //Verify that the attestation certificate is issued to the hostname "attest.android.com" (see SafetyNet online documentation).
        String cn = getFirstCN(certchain.get(0).getSubjectDN().getName());
        if(cn == null || !cn.equals("attest.android.com")){
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "FIDO-ERR-0015",
                    "JWT attestation certificate does not match the specification");
            return false;
        }

        //Verify that the ctsProfileMatch attribute in the payload of response is true.
        if(!jwt.getBody().getBoolean("ctsProfileMatch", false)){
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "FIDO-ERR-0015",
                    "JWT attestation ctsProfileMatch does not match the specification");
            return false;
        }

        return true;
    } catch (UnsupportedEncodingException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException ex) {
        Logger.getLogger(AndroidSafetynetAttestationStatement.class.getName()).log(Level.SEVERE, null, ex);
    }

    return Boolean.FALSE;
}
 
Example 20
Source File: verifyFido2RegistrationPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void verifyMDS(MdsPolicyOptions mdsOp, JsonObject clientJson,
        FIDO2AttestationObject attObject, MDSClient mds, Integer version) throws SKFEException, CertificateException, NoSuchProviderException{
    //MDS not configured, skipping checks
    if(mdsOp == null || mds == null){
        return;
    }

    boolean isPolicyQualifiersRejected = true;
    byte[] aaguidbytes = attObject.getAuthData().getAttCredData().getAaguid();
    byte[] aaguidbytes1 = new byte[8];
    byte[] aaguidbytes2 = new byte[8];
    System.arraycopy(aaguidbytes, 0, aaguidbytes1, 0, 8);
    System.arraycopy(aaguidbytes, 8, aaguidbytes2, 0, 8);
    UUID uuid = new UUID(Longs.fromByteArray(aaguidbytes1),
            Longs.fromByteArray(aaguidbytes2));
    JsonObject trustAnchors = mds.getTrustAnchors(uuid.toString(), mdsOp.getAllowedCertificationLevel());

    FIDO2AttestationStatement attStmt = attObject.getAttStmt();
    if(attStmt == null){
        return;
    }

    if(attObject.getAttFormat().equals("fido-u2f")){
        return;
    }

    if (attObject.getAttFormat().equals("tpm")) {
        isPolicyQualifiersRejected = false;
    }

    //TODO if no certificate chain returned, check/implement ECDAA
    ArrayList attBytesChain = attObject.getAttStmt().getX5c();
    if(attBytesChain == null || attBytesChain.isEmpty()){
        return;
    }

    List<Certificate> certchain = new ArrayList<>();
    X509Certificate leafCert = cryptoCommon.generateX509FromBytes((byte[]) attBytesChain.get(0)); //check leaf if it is self signed
    certchain.add(leafCert);
    if(leafCert.getSubjectDN().equals(leafCert.getIssuerDN())){
        //TODO verify certificate properly self-signs itself
        return;
    }


    //Create certificate path
    if (!attBytesChain.isEmpty()) {
        for (int attCertIndex = 1; attCertIndex < attBytesChain.size(); attCertIndex++) {
            X509Certificate attestationCert = cryptoCommon.generateX509FromBytes((byte[]) attBytesChain.get(attCertIndex));
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.FINE, "FIDO-MSG-2001",
                    "CertPath " + attCertIndex + ": " + attestationCert);
            certchain.add(attestationCert);
        }
    } else {
        throw new SKIllegalArgumentException("Expected Certificate chain missing");
    }
    CertPath certPath = CertificateFactory.getInstance("X.509", "BCFIPS").generateCertPath(certchain);

    //Create list of possible roots from MDS
    Set<TrustAnchor> rootAnchors = new HashSet<>();
    JsonArray roots = trustAnchors.getJsonArray("attestationRootCertificates");

    JsonArray errors = trustAnchors.getJsonArray("errors");
    if(!errors.isEmpty()){
        throw new SKIllegalArgumentException("MDS error(s): " + errors.toString());
    }

    if(roots == null){
        throw new SKIllegalArgumentException("Root certificates not found in MDS");
    }
    for(int rootIndex = 0; rootIndex < roots.size(); rootIndex++) {
        byte[] certBytes = java.util.Base64.getDecoder().decode(roots.getString(rootIndex));
        rootAnchors.add(new TrustAnchor(cryptoCommon.generateX509FromBytes(certBytes), null));
    }

    //Verify chain chains up to one of the roots.
    if(!PKIXChainValidation.pkixvalidate(certPath, rootAnchors, false, isPolicyQualifiersRejected)){    //TODO check CRLs if they exist, otherwise don't
        throw new SKIllegalArgumentException("Failed to verify certificate path");
    }
}