HTTPUtil.java 11.1 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.auth.oauth.AccessTokenProvider
 *  com.adobe.granite.crypto.CryptoException
 *  com.adobe.granite.crypto.CryptoSupport
 *  org.apache.http.NoHttpResponseException
 *  org.apache.http.auth.AuthScope
 *  org.apache.http.auth.Credentials
 *  org.apache.http.auth.UsernamePasswordCredentials
 *  org.apache.http.client.CredentialsProvider
 *  org.apache.http.client.HttpClient
 *  org.apache.http.client.HttpRequestRetryHandler
 *  org.apache.http.client.config.RequestConfig
 *  org.apache.http.client.config.RequestConfig$Builder
 *  org.apache.http.impl.client.BasicCredentialsProvider
 *  org.apache.http.impl.client.CloseableHttpClient
 *  org.apache.http.impl.client.HttpClientBuilder
 *  org.apache.http.message.BasicHeader
 *  org.apache.http.osgi.services.HttpClientBuilderFactory
 *  org.apache.http.protocol.HttpContext
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.dam.mac.sync.helper.impl.http;

import com.adobe.cq.dam.mac.sync.helper.impl.MACTenantConfiguration;
import com.adobe.granite.auth.oauth.AccessTokenProvider;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.http.protocol.HttpContext;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HTTPUtil {
    public static final int MAX_RETRIES = 1;
    public static final int DEFAULT_SO_TIMEOUT = 30000;
    private static final String BEARER_AUTHENTICATION_FORMAT = "Bearer %s";
    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static Logger log = LoggerFactory.getLogger(HTTPUtil.class);
    private static final Map<String, Object> REPLICATION_SERVICE_AUTH_INFO = Collections.singletonMap("sling.service.subservice", "dam-replication-helper");

    public static HttpClient getClient(int socketTimeout, String tenantURL, HttpClientBuilderFactory httpClientBuilderFactory) {
        if (socketTimeout <= 0) {
            socketTimeout = 30000;
        }
        try {
            URI uri = new URI(tenantURL);
            RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(socketTimeout).setSocketTimeout(socketTimeout);
            RequestConfig requestConfig = requestConfigBuilder.build();
            HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler(){

                public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                    boolean sent;
                    if (executionCount >= 1) {
                        return false;
                    }
                    if (exception instanceof NoHttpResponseException) {
                        return true;
                    }
                    Boolean b = (Boolean)context.getAttribute("http.request_sent");
                    boolean bl = sent = b != null && b != false;
                    if (!sent) {
                        return true;
                    }
                    return false;
                }
            };
            CloseableHttpClient client = httpClientBuilderFactory.newBuilder().setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler).build();
            return client;
        }
        catch (URISyntaxException e) {
            log.error("Malformed tenant URL: " + tenantURL, (Throwable)e);
            throw new RuntimeException(e);
        }
    }

    public static HttpClient getClient(int socketTimeout, MACTenantConfiguration macConfiguration, ResourceResolverFactory rrf, AccessTokenProvider accessTokenProvider, CryptoSupport crypto, HttpClientBuilderFactory httpClientBuilderFactory) throws LoginException, IOException, URISyntaxException, CryptoException {
        if (socketTimeout <= 0) {
            socketTimeout = 30000;
        }
        Object resolver = null;
        try {
            String password;
            UsernamePasswordCredentials defaultCreds = null;
            boolean useBasicAuth = (Boolean)macConfiguration.getProperties().get("basicEnabled", (Object)Boolean.FALSE);
            if (useBasicAuth) {
                password = (String)macConfiguration.getProperties().get("macSyncUserPassword", String.class);
                String userName = (String)macConfiguration.getProperties().get("macSyncUser", String.class);
                if (password == null || userName == null) {
                    throw new IllegalArgumentException("username/password not set for basic authentication");
                }
                if (crypto.isProtected(password)) {
                    password = crypto.unprotect(password);
                }
                defaultCreds = new UsernamePasswordCredentials(userName, password);
                password = null;
            }
            password = HTTPUtil.getClient(socketTimeout, macConfiguration.getTenantURL(), macConfiguration.getDAMUser(), useBasicAuth, (Credentials)defaultCreds, rrf, accessTokenProvider, httpClientBuilderFactory);
            return password;
        }
        catch (CryptoException e) {
            log.error("Error impersonating the user ", (Throwable)e);
            throw e;
        }
        finally {
            if (resolver != null) {
                resolver.close();
            }
        }
    }

    /*
     * Enabled aggressive block sorting
     * Enabled unnecessary exception pruning
     * Enabled aggressive exception aggregation
     */
    public static HttpClient getClient(int socketTimeout, String tenantUrl, String damUser, boolean useBasicAuth, Credentials defaultCreds, ResourceResolverFactory rrf, AccessTokenProvider accessTokenProvider, HttpClientBuilderFactory httpClientBuilderFactory) throws CryptoException, IOException, URISyntaxException, LoginException {
        if (socketTimeout <= 0) {
            socketTimeout = 30000;
        }
        ResourceResolver resolver = null;
        try {
            CloseableHttpClient authScope;
            CloseableHttpClient client;
            URI uri = new URI(tenantUrl);
            RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(socketTimeout).setSocketTimeout(socketTimeout);
            ArrayList<BasicHeader> defaultHeaders = new ArrayList<BasicHeader>();
            boolean setCredentials = false;
            if ("https".equals(uri.getScheme())) {
                if (!useBasicAuth) {
                    log.debug("* Using OAuth 2.0 Authorization Grants");
                    if (accessTokenProvider == null) {
                        log.error("Access token provider is not bind");
                        throw new IllegalArgumentException("Access token provider is not bind");
                    }
                    String keyStoreUser = damUser;
                    log.debug("* OAuth 2.0 User: {}", (Object)keyStoreUser);
                    resolver = rrf.getServiceResourceResolver(REPLICATION_SERVICE_AUTH_INFO);
                    try {
                        String accessToken = accessTokenProvider.getAccessToken(resolver, keyStoreUser, null);
                        String authorization = String.format("Bearer %s", accessToken);
                        BasicHeader header = new BasicHeader("Authorization", authorization);
                        defaultHeaders.add(header);
                    }
                    catch (CryptoException e) {
                        log.error("Failed to get an access token for user: {} msg: {}", (Object)keyStoreUser, (Object)e.getMessage());
                        throw e;
                    }
                    catch (IOException e) {
                        log.error("Failed to get an access token for user: {} msg: {}", (Object)keyStoreUser, (Object)e.getMessage());
                        throw e;
                    }
                } else {
                    setCredentials = true;
                }
            } else {
                setCredentials = true;
            }
            HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler(){

                public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                    boolean sent;
                    if (executionCount >= 1) {
                        return false;
                    }
                    if (exception instanceof NoHttpResponseException) {
                        return true;
                    }
                    Boolean b = (Boolean)context.getAttribute("http.request_sent");
                    boolean bl = sent = b != null && b != false;
                    if (!sent) {
                        return true;
                    }
                    return false;
                }
            };
            RequestConfig requestConfig = requestConfigBuilder.build();
            HttpClientBuilder clientBuilder = httpClientBuilderFactory.newBuilder().setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler);
            if (setCredentials && defaultCreds != null) {
                BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                authScope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM);
                credentialsProvider.setCredentials((AuthScope)authScope, defaultCreds);
                clientBuilder.setDefaultCredentialsProvider((CredentialsProvider)credentialsProvider);
            }
            if (!defaultHeaders.isEmpty()) {
                clientBuilder.setDefaultHeaders(defaultHeaders);
            }
            authScope = client = clientBuilder.build();
            return authScope;
        }
        catch (URISyntaxException e) {
            log.error("Malformed tenant URL: " + tenantUrl, (Throwable)e);
            throw e;
        }
        catch (LoginException e) {
            log.error("Error impersonating the user ", (Throwable)e);
            throw e;
        }
        finally {
            if (resolver != null) {
                resolver.close();
            }
        }
    }

}