// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import java.net.Socket;
import java.security.KeyStore;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.WeakHashMap;

/**
 * A {@link X509ExtendedKeyManager} which can be updated with new certificate chain and private key while in use.
 *
 * The implementations assumes that aliases are retrieved from the same thread as the certificate chain and private key.
 * This is case for OpenJDK 11.
 *
 * @author bjorncs
 */
public class MutableX509KeyManager extends X509ExtendedKeyManager {

    // Not using ThreadLocal as we want the x509 key manager instances to be collected
    // when either the thread dies or the MutableX509KeyManager instance is collected (latter not the case for ThreadLocal).
    private final WeakHashMap<Thread, X509ExtendedKeyManager> threadLocalManager = new WeakHashMap<>();
    private volatile X509ExtendedKeyManager currentManager;

    public MutableX509KeyManager(KeyStore keystore, char[] password) {
        this.currentManager = KeyManagerUtils.createDefaultX509KeyManager(keystore, password);
    }

    public MutableX509KeyManager() {
        this.currentManager = KeyManagerUtils.createDefaultX509KeyManager();
    }

    public void updateKeystore(KeyStore keystore, char[] password) {
        this.currentManager = KeyManagerUtils.createDefaultX509KeyManager(keystore, password);
    }

    public void useDefaultKeystore() {
        this.currentManager = KeyManagerUtils.createDefaultX509KeyManager();
    }

    @Override
    public String[] getServerAliases(String keyType, Principal[] issuers) {
        return updateAndGetThreadLocalManager()
                .getServerAliases(keyType, issuers);
    }

    @Override
    public String[] getClientAliases(String keyType, Principal[] issuers) {
        return updateAndGetThreadLocalManager()
                .getClientAliases(keyType, issuers);
    }

    @Override
    public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
        return updateAndGetThreadLocalManager()
                .chooseServerAlias(keyType, issuers, socket);
    }

    @Override
    public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
        return updateAndGetThreadLocalManager()
                .chooseClientAlias(keyType, issuers, socket);
    }

    @Override
    public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
        return updateAndGetThreadLocalManager()
                .chooseEngineServerAlias(keyType, issuers, engine);
    }

    @Override
    public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
        return updateAndGetThreadLocalManager()
                .chooseEngineClientAlias(keyType, issuers, engine);
    }

    private X509ExtendedKeyManager updateAndGetThreadLocalManager() {
        X509ExtendedKeyManager currentManager = this.currentManager;
        threadLocalManager.put(Thread.currentThread(), currentManager);
        return currentManager;
    }

    @Override
    public X509Certificate[] getCertificateChain(String alias) {
        if (alias == null) return null; // this method can be called with 'null' alias prior to any alias getter methods.
        return getThreadLocalManager()
                .getCertificateChain(alias);
    }

    @Override
    public PrivateKey getPrivateKey(String alias) {
        if (alias == null) return null; // this method can be called with 'null' alias prior to any alias getter methods.
        return getThreadLocalManager()
                .getPrivateKey(alias);
    }

    private X509ExtendedKeyManager getThreadLocalManager() {
        X509ExtendedKeyManager manager = threadLocalManager.get(Thread.currentThread());
        if (manager == null) {
            throw new IllegalStateException("Methods to retrieve valid aliases has not been called previously from this thread");
        }
        return manager;
    }

}

@@ -779,16 +779,65 @@
 ager %7B%0A%0A
+    private final Object monitor = new Object();%0A
     // N
@@ -872,16 +872,29 @@
 ant the 
+thread local 
 x509 key
@@ -918,16 +918,24 @@
 s to be 
+garbage 
 collecte
@@ -1181,17 +1181,8 @@
 ate 
-volatile 
 X509
@@ -1280,32 +1280,69 @@
 r%5B%5D password) %7B%0A
+        synchronized (monitor) %7B%0A    
         this.cur
@@ -1412,32 +1412,42 @@
 ore, password);%0A
+        %7D%0A
     %7D%0A%0A    publi
@@ -1466,32 +1466,69 @@
 9KeyManager() %7B%0A
+        synchronized (monitor) %7B%0A    
         this.cur
@@ -1580,32 +1580,42 @@
 09KeyManager();%0A
+        %7D%0A
     %7D%0A%0A    publi
@@ -1666,32 +1666,69 @@
 r%5B%5D password) %7B%0A
+        synchronized (monitor) %7B%0A    
         this.cur
@@ -1802,24 +1802,34 @@
  password);%0A
+        %7D%0A
     %7D%0A%0A    p
@@ -1858,24 +1858,61 @@
 eystore() %7B%0A
+        synchronized (monitor) %7B%0A    
         this
@@ -1972,24 +1972,34 @@
 yManager();%0A
+        %7D%0A
     %7D%0A%0A    @
@@ -3369,32 +3369,69 @@
 ocalManager() %7B%0A
+        synchronized (monitor) %7B%0A    
         X509Exte
@@ -3479,24 +3479,28 @@
 entManager;%0A
+    
         thre
@@ -3563,24 +3563,28 @@
 r);%0A        
+ 
+   
 return curre
@@ -3590,24 +3590,34 @@
 entManager;%0A
+        %7D%0A
     %7D%0A%0A    @
@@ -4229,32 +4229,69 @@
 ocalManager() %7B%0A
+        synchronized (monitor) %7B%0A    
         X509Exte
@@ -4367,24 +4367,28 @@
 ));%0A        
+    
 if (manager 
@@ -4394,24 +4394,28 @@
  == null) %7B%0A
+    
             
@@ -4536,26 +4536,34 @@
 %22);%0A        
+   
+ 
 %7D%0A
+    
         retu
@@ -4570,21 +4570,31 @@
 rn manager;%0A
+        %7D%0A
     %7D%0A%0A%7D%0A

Make access to hashmap and current manager synchronized