// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.util.http;

import com.yahoo.security.tls.MixedMode;
import com.yahoo.security.tls.TlsContext;
import com.yahoo.security.tls.TransportSecurityUtils;
import org.glassfish.jersey.client.internal.HttpUrlConnector;
import org.glassfish.jersey.process.internal.ExecutorProviders;

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Optional;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.Logger;

import static java.util.logging.Level.CONFIG;

/**
 * Factory for JAX-RS http client builder for internal Vespa communications over http/https.
 *
 * Notes:
 *  - hostname verification is not enabled - CN/SAN verification is assumed to be handled by the underlying x509 trust manager.
 *  - ssl context or hostname verifier must not be overriden by the caller
 *
 * @author bjorncs
 */
public class VespaClientBuilderFactory implements AutoCloseable {

    private static final Logger log = Logger.getLogger(VespaClientBuilderFactory.class.getName());

    static {
        // CONFIG log message are logged repeatedly from these classes.
        disableConfigLogging(HttpUrlConnector.class);
        disableConfigLogging(ExecutorProviders.class);
    }

    // This method will hook a filter into the Jersey logger removing unwanted messages.
    private static void disableConfigLogging(Class<?> klass) {
        @SuppressWarnings("LoggerInitializedWithForeignClass")
        Logger logger = Logger.getLogger(klass.getName());
        Optional<Filter> currentFilter = Optional.ofNullable(logger.getFilter());
        Filter filter = logRecord ->
                !logRecord.getMessage().startsWith("Restricted headers are not enabled")
                        && !logRecord.getMessage().startsWith("Selected ExecutorServiceProvider implementation")
                        && !logRecord.getLevel().equals(CONFIG)
                        && currentFilter.map(f -> f.isLoggable(logRecord)).orElse(true); // Honour existing filter if exists
        logger.setFilter(filter);
    }


    private final TlsContext tlsContext = TransportSecurityUtils.createTlsContext().orElse(null);
    private final MixedMode mixedMode = TransportSecurityUtils.getInsecureMixedMode();

    public ClientBuilder newBuilder() {
        ClientBuilder builder = ClientBuilder.newBuilder();
        setSslConfiguration(builder);
        return builder;
    }

    private void setSslConfiguration(ClientBuilder builder) {
        if (tlsContext != null) {
            builder.sslContext(tlsContext.context());
            builder.hostnameVerifier((hostname, sslSession) -> true); // disable hostname verification
            if (mixedMode != MixedMode.PLAINTEXT_CLIENT_MIXED_SERVER) {
                builder.register(new UriRewritingRequestFilter());
            }
        }
    }

    @Override
    public void close() {
        if (tlsContext != null) {
            tlsContext.close();
        }
    }

    static class UriRewritingRequestFilter implements ClientRequestFilter {
        @Override
        public void filter(ClientRequestContext requestContext) {
            requestContext.setUri(rewriteUri(requestContext.getUri()));
        }

        private static URI rewriteUri(URI originalUri) {
            if (!originalUri.getScheme().equals("http")) {
                return originalUri;
            }
            int port = originalUri.getPort();
            int rewrittenPort = port != -1 ? port : 80;
            URI rewrittenUri = UriBuilder.fromUri(originalUri).scheme("https").port(rewrittenPort).build();
            log.log(Level.FINE, () -> String.format("Uri rewritten from '%s' to '%s'", originalUri, rewrittenUri));
            return rewrittenUri;
        }
    }
}

@@ -275,134 +275,8 @@
 ils;
-%0Aimport org.glassfish.jersey.client.internal.HttpUrlConnector;%0Aimport org.glassfish.jersey.process.internal.ExecutorProviders;
 %0A%0Aim
@@ -470,68 +470,8 @@
 RI;%0A
-import java.util.Optional;%0Aimport java.util.logging.Filter;%0A
 impo
@@ -536,55 +536,8 @@
 r;%0A%0A
-import static java.util.logging.Level.CONFIG;%0A%0A
 /**%0A
@@ -938,16 +938,16 @@
 able %7B%0A%0A
+
     priv
@@ -1042,1035 +1042,8 @@
 );%0A%0A
-    static %7B%0A        // CONFIG log message are logged repeatedly from these classes.%0A        disableConfigLogging(HttpUrlConnector.class);%0A        disableConfigLogging(ExecutorProviders.class);%0A    %7D%0A%0A    // This method will hook a filter into the Jersey logger removing unwanted messages.%0A    private static void disableConfigLogging(Class%3C?%3E klass) %7B%0A        @SuppressWarnings(%22LoggerInitializedWithForeignClass%22)%0A        Logger logger = Logger.getLogger(klass.getName());%0A        Optional%3CFilter%3E currentFilter = Optional.ofNullable(logger.getFilter());%0A        Filter filter = logRecord -%3E%0A                !logRecord.getMessage().startsWith(%22Restricted headers are not enabled%22)%0A                        && !logRecord.getMessage().startsWith(%22Selected ExecutorServiceProvider implementation%22)%0A                        && !logRecord.getLevel().equals(CONFIG)%0A                        && currentFilter.map(f -%3E f.isLoggable(logRecord)).orElse(true); // Honour existing filter if exists%0A        logger.setFilter(filter);%0A    %7D%0A%0A%0A
     

Revert "Filter out unwanted log messages from Jersey client."