/*
 * Copyright (C) 2025 The Android Open Source Project
 *
 * Licensed 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 com.android.devicelockcontroller.util;


import static com.google.common.truth.Truth.assertThat;

import com.android.devicelockcontroller.shadows.FakeAndroidKeystore;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

@RunWith(RobolectricTestRunner.class)
public class KeyAttestationUtilTest {

    @Before
    public void setup() {
        Security.addProvider(new FakeAndroidKeystore.FakeSecurityProvider());
    }

    @Test
    public void getKeyAttestationLeafCertificate_returnsLeafCertificate()
            throws InvalidAlgorithmParameterException, CertificateException,
            NoSuchAlgorithmException, IOException, KeyStoreException, NoSuchProviderException {
        X509Certificate[] testCertificates = TestCertificateProviderUtil.getTestCertificates();
        FakeAndroidKeystore.SingletonKeystore.certs.put("DLCKeyAttestation", testCertificates);

        byte[] attestationCertificates = KeyAttestationUtil.getKeyAttestationLeafCertificate();

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream inStream = new ByteArrayInputStream(attestationCertificates);
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        assertThat(cert).isEqualTo(testCertificates[0]);
    }
}
