/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to you under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.logging.log4j.fuzz;

import com.code_intelligence.jazzer.api.FuzzerSecurityIssueCritical;
import java.nio.charset.StandardCharsets;
import org.json.JSONObject;
import org.json.JSONTokener;

public final class JsonUtil {

    public static void assertValidJson(final String json) {
        final byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8);
        assertValidJson(jsonBytes);
    }

    public static void assertValidJson(final byte[] jsonBytes) {
        // We deliberately use an external library instead of using `JsonReader` from Log4j.
        // This is to fuzz Log4j components in isolation.
        // We are not using Jackson or Gson, since they have token limitations due to performance reasons.
        // That is, for instance, Jackson supports numbers up to 1000 digits, which the fuzzer quickly bumps into.
        try {
            // `JSONObject` requires the input to be a JSON object, hence we are ensuring it to be so:
            final String json = "{\"x\":" + new String(jsonBytes, StandardCharsets.UTF_8) + "}";
            final JSONTokener jsonTokener = new JSONTokener(json);
            new JSONObject(jsonTokener);
        } catch (final Exception error) {
            throw new FuzzerSecurityIssueCritical("malformed JSON output", error);
        }
    }

    private JsonUtil() {}
}
