package ai.vespa.hosted.auth;

import ai.vespa.hosted.api.ControllerHttpClient;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SslContextBuilder;
import com.yahoo.security.X509CertificateUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.http.HttpRequest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.Optional;

/**
 * Authenticates {@link HttpRequest}s against a hosted Vespa application based on mutual TLS.
 *
 * @author jonmv
 */
public class Authenticator {

    /** Returns an SSLContext which provides authentication against a Vespa endpoint.
     *
     * If {@code System.getProperty("vespa.test.credentials.root")} is set, key and certificate files
     * "key" and "cert" in that directory are used; otherwise, the system default SSLContext is returned. */
    public SSLContext sslContext() {
        try {
            Path credentialsRoot = Path.of(System.getProperty("vespa.test.credentials.root"));
            Path certificateFile = credentialsRoot.resolve("cert");
            Path privateKeyFile = credentialsRoot.resolve("key");

            X509Certificate certificate = X509CertificateUtils.fromPem(new String(Files.readAllBytes(certificateFile)));
            if (   Instant.now().isBefore(certificate.getNotBefore().toInstant())
                || Instant.now().isAfter(certificate.getNotAfter().toInstant()))
                throw new IllegalStateException("Certificate at '" + certificateFile + "' is valid between " +
                                                certificate.getNotBefore() + " and " + certificate.getNotAfter() + " — not now.");

            PrivateKey privateKey = KeyUtils.fromPemEncodedPrivateKey(new String(Files.readAllBytes(privateKeyFile)));
            return new SslContextBuilder().withKeyStore(privateKey, certificate).build();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    /** Adds necessary authentication to the given HTTP request builder, to be verified by a Vespa endpoint. */
    public HttpRequest.Builder authenticated(HttpRequest.Builder request) {
        return request;
    }

    /** Returns an authenticated controller client. */
    public ControllerHttpClient controller() {
        ApplicationId id = ApplicationId.from(requireNonBlankProperty("tenant"),
                                              requireNonBlankProperty("application"),
                                              getNonBlankProperty("instance").orElse("default"));
        URI endpoint = URI.create(requireNonBlankProperty("endpoint"));
        Path privateKeyFile = Paths.get(requireNonBlankProperty("privateKeyFile"));

        return ControllerHttpClient.withSignatureKey(endpoint, privateKeyFile, id);
    }

    static Optional<String> getNonBlankProperty(String name) {
        return Optional.ofNullable(System.getProperty(name)).filter(value -> ! value.isBlank());
    }

    static String requireNonBlankProperty(String name) {
        return getNonBlankProperty(name).orElseThrow(() -> new IllegalStateException("Missing required property '" + name + "'"));
    }

}

@@ -488,16 +488,63 @@
 .Paths;%0A
+import java.security.NoSuchAlgorithmException;%0A
 import j
@@ -568,16 +568,16 @@
 ateKey;%0A
-
 import j
@@ -1188,87 +1188,274 @@
     
-Path credentialsRoot = Path.of(System.getProperty(%22vespa.test.credentials.root%22
+Optional%3CString%3E credentialsRootProperty = getNonBlankProperty(%22vespa.test.credentials.root%22);%0A            if (credentialsRootProperty.isEmpty())%0A                return SSLContext.getDefault();%0A%0A            Path credentialsRoot = Path.of(credentialsRootProperty.get(
 ));%0A
@@ -2355,24 +2355,24 @@
 eption e) %7B%0A
-
             
@@ -2416,16 +2416,119 @@
       %7D%0A
+        catch (NoSuchAlgorithmException e) %7B%0A            throw new IllegalStateException(e);%0A        %7D%0A
     %7D%0A%0A 

Use Default SSLContext when none is set