// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.tenant;

import com.yahoo.config.model.api.EndpointCertificateMetadata;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.TenantName;
import com.yahoo.path.Path;
import com.yahoo.vespa.config.server.MockSecretStore;
import com.yahoo.vespa.curator.mock.MockCurator;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class EndpointCertificateMetadataStoreTest {

    private static final Path tenantPath = Path.createRoot();
    private static final Path endpointCertificateMetadataPath = Path.createRoot().append("tlsSecretsKeys").append("default:test:default");
    private static final ApplicationId applicationId = ApplicationId.from(TenantName.defaultName(),
            ApplicationName.from("test"), InstanceName.defaultName());

    private MockCurator curator;
    private MockSecretStore secretStore = new MockSecretStore();
    private EndpointCertificateMetadataStore endpointCertificateMetadataStore;
    private EndpointCertificateRetriever endpointCertificateRetriever;

    @Before
    public void setUp() {
        curator = new MockCurator();
        endpointCertificateMetadataStore = new EndpointCertificateMetadataStore(curator, tenantPath);
        endpointCertificateRetriever = new EndpointCertificateRetriever(secretStore);

        secretStore.put("vespa.tlskeys.tenant1--app1-cert", "CERT");
        secretStore.put("vespa.tlskeys.tenant1--app1-key", "KEY");
    }

    @Test
    public void reads_string_format() {
        curator.set(endpointCertificateMetadataPath, ("\"vespa.tlskeys.tenant1--app1\"").getBytes());

        // Read from zk and verify cert and key are available
        var endpointCertificateSecrets = endpointCertificateMetadataStore.readEndpointCertificateMetadata(applicationId)
                .flatMap(endpointCertificateRetriever::readEndpointCertificateSecrets);
        assertTrue(endpointCertificateSecrets.isPresent());
        assertEquals("KEY", endpointCertificateSecrets.get().key());
        assertEquals("CERT", endpointCertificateSecrets.get().certificate());
    }

    @Test
    public void reads_object_format() {
        curator.set(endpointCertificateMetadataPath,
                "{\"keyName\": \"vespa.tlskeys.tenant1--app1-key\", \"certName\":\"vespa.tlskeys.tenant1--app1-cert\", \"version\": 0}"
                        .getBytes());

        // Read from zk and verify cert and key are available
        var secrets = endpointCertificateMetadataStore.readEndpointCertificateMetadata(applicationId)
                .flatMap(endpointCertificateRetriever::readEndpointCertificateSecrets);
        assertTrue(secrets.isPresent());
        assertEquals("KEY", secrets.get().key());
        assertEquals("CERT", secrets.get().certificate());
    }

    @Test
    public void can_write_object_format() {
        var endpointCertificateMetadata = new EndpointCertificateMetadata("key-name", "cert-name", 1);

        endpointCertificateMetadataStore.writeEndpointCertificateMetadata(applicationId, endpointCertificateMetadata);

        assertEquals("{\"keyName\":\"key-name\",\"certName\":\"cert-name\",\"version\":1}",
                new String(curator.getData(endpointCertificateMetadataPath).orElseThrow()));
    }
}

@@ -459,139 +459,573 @@
 hoo.
-vespa.config.server.MockSecretStore;%0Aimport com.yahoo.vespa.curator.mock.MockCurator;%0Aimport org.junit.Before;%0Aimport org.junit.Tes
+security.KeyAlgorithm;%0Aimport com.yahoo.security.KeyUtils;%0Aimport com.yahoo.security.SignatureAlgorithm;%0Aimport com.yahoo.security.X509CertificateBuilder;%0Aimport com.yahoo.security.X509CertificateUtils;%0Aimport com.yahoo.vespa.config.server.MockSecretStore;%0Aimport com.yahoo.vespa.curator.mock.MockCurator;%0Aimport org.junit.Before;%0Aimport org.junit.Test;%0A%0Aimport javax.security.auth.x500.X500Principal;%0Aimport java.math.BigInteger;%0Aimport java.security.KeyPair;%0Aimport java.security.cert.X509Certificate;%0Aimport java.time.Instant;%0Aimport java.time.temporal.ChronoUni
 t;%0A%0A
@@ -1786,16 +1786,354 @@
 triever;
+%0A    private KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);%0A    private X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair, new X500Principal(%22CN=subject%22),%0A            Instant.now(), Instant.now().plus(1, ChronoUnit.DAYS), SignatureAlgorithm.SHA512_WITH_ECDSA, BigInteger.valueOf(12345)).build();
 %0A%0A    @B
@@ -2450,22 +2450,55 @@
 -cert%22, 
-%22CERT%22
+X509CertificateUtils.toPem(certificate)
 );%0A     
@@ -2551,21 +2551,52 @@
 1-key%22, 
-%22KEY%22
+KeyUtils.toPem(keyPair.getPrivate())
 );%0A    %7D
@@ -3095,30 +3095,21 @@
   assert
-Equals(%22KEY%22, 
+True(
 endpoint
@@ -3130,32 +3130,72 @@
 rets.get().key()
+.startsWith(%22-----BEGIN EC PRIVATE KEY%22)
 );%0A        asser
@@ -3195,31 +3195,21 @@
   assert
-Equals(%22CERT%22, 
+True(
 endpoint
@@ -3238,32 +3238,69 @@
 ().certificate()
+.startsWith(%22-----BEGIN CERTIFICATE%22)
 );%0A    %7D%0A%0A    @T
@@ -3882,22 +3882,13 @@
 sert
-Equals(%22KEY%22, 
+True(
 secr
@@ -3902,16 +3902,56 @@
 ().key()
+.startsWith(%22-----BEGIN EC PRIVATE KEY%22)
 );%0A     
@@ -3963,23 +3963,13 @@
 sert
-Equals(%22CERT%22, 
+True(
 secr
@@ -3991,16 +3991,53 @@
 ficate()
+.startsWith(%22-----BEGIN CERTIFICATE%22)
 );%0A    %7D

use valid cert/key in test