Skip to content

Commit

Permalink
Fixed bug with custom keystore being used for auth request which made…
Browse files Browse the repository at this point in the history
… the request fail due to certificate not being trusted
  • Loading branch information
danechitoaie committed Dec 17, 2019
1 parent db5efa8 commit a5d7069
Show file tree
Hide file tree
Showing 2 changed files with 165 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -897,7 +897,6 @@ public DataImportResult invoke(File dir, VirtualChannel channel) throws IOExcept
logger.println(" + Ok");
/* Cleaning up leftover data from current data import */

openCommerceAPI.close();
return new DataImportResult(currentDataFingerprints, "IMPORTED");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
Expand Down Expand Up @@ -57,15 +58,16 @@

class OpenCommerceAPI {
private String hostname;
private HTTPProxyCredentials httpProxyCredentials;
private Boolean disableSSLValidation;
private TwoFactorAuthCredentials tfCredentials;
private OpenCommerceAPICredentials ocCredentials;
private String ocVersion;

private String cacheAuthType;
private String cacheAuthToken;
private Long cacheAuthExpire;

private CloseableHttpClient httpClient;

OpenCommerceAPI(
String hostname,
HTTPProxyCredentials httpProxyCredentials,
Expand All @@ -75,14 +77,18 @@ class OpenCommerceAPI {
String ocVersion) throws IOException {

this.hostname = hostname;
this.httpProxyCredentials = httpProxyCredentials;
this.disableSSLValidation = disableSSLValidation;
this.tfCredentials = tfCredentials;
this.ocCredentials = ocCredentials;
this.ocVersion = ocVersion;

this.cacheAuthType = "";
this.cacheAuthToken = "";
this.cacheAuthExpire = 0L;
}

/* Setup HTTP Client */
private CloseableHttpClient getCloseableHttpClient() throws AbortException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setUserAgent("Jenkins (OSF Builder Suite For Salesforce Commerce Cloud)");
httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
Expand Down Expand Up @@ -121,8 +127,6 @@ class OpenCommerceAPI {
.build()
);

org.apache.http.client.CredentialsProvider httpCredentialsProvider = new BasicCredentialsProvider();

// Proxy Auth
if (httpProxyCredentials != null) {
String httpProxyHost = httpProxyCredentials.getHost();
Expand Down Expand Up @@ -151,6 +155,8 @@ class OpenCommerceAPI {
HttpHost httpClientProxy = new HttpHost(httpProxyHost, httpProxyPortInteger);
httpClientBuilder.setProxy(httpClientProxy);

CredentialsProvider httpCredentialsProvider = new BasicCredentialsProvider();

if (StringUtils.isNotEmpty(httpProxyUsername) && StringUtils.isNotEmpty(httpProxyPassword)) {
if (httpProxyUsername.contains("\\")) {
String domain = httpProxyUsername.substring(0, httpProxyUsername.indexOf("\\"));
Expand All @@ -167,9 +173,101 @@ class OpenCommerceAPI {
);
}
}

httpClientBuilder.setDefaultCredentialsProvider(httpCredentialsProvider);
}

httpClientBuilder.setDefaultCredentialsProvider(httpCredentialsProvider);
return httpClientBuilder.build();
}

private CloseableHttpClient getCloseableHttpClientWithTwoFactorAuth() throws AbortException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setUserAgent("Jenkins (OSF Builder Suite For Salesforce Commerce Cloud)");
httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());

httpClientBuilder.addInterceptorFirst((HttpRequestInterceptor) (request, context) -> {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
});

httpClientBuilder.addInterceptorFirst((HttpResponseInterceptor) (response, context) -> {
HttpEntity entity = response.getEntity();
if (entity != null) {
Header header = entity.getContentEncoding();
if (header != null) {
for (HeaderElement headerElement : header.getElements()) {
if (headerElement.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});

httpClientBuilder.setDefaultConnectionConfig(ConnectionConfig.custom()
.setBufferSize(5242880 /* 5 MegaBytes */)
.setFragmentSizeHint(5242880 /* 5 MegaBytes */)
.build()
);

httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
.setSocketTimeout(300000 /* 5 minutes */)
.setConnectTimeout(300000 /* 5 minutes */)
.setConnectionRequestTimeout(300000 /* 5 minutes */)
.build()
);

// Proxy Auth
if (httpProxyCredentials != null) {
String httpProxyHost = httpProxyCredentials.getHost();
String httpProxyPort = httpProxyCredentials.getPort();
String httpProxyUsername = httpProxyCredentials.getUsername();
String httpProxyPassword = httpProxyCredentials.getPassword().getPlainText();

int httpProxyPortInteger;

try {
httpProxyPortInteger = Integer.parseInt(httpProxyPort);
} catch (NumberFormatException e) {
throw new AbortException(
String.format("Invalid value \"%s\" for HTTP proxy port!", httpProxyPort) + " " +
"Please enter a valid port number."
);
}

if (httpProxyPortInteger <= 0 || httpProxyPortInteger > 65535) {
throw new AbortException(
String.format("Invalid value \"%s\" for HTTP proxy port!", httpProxyPort) + " " +
"Please enter a valid port number."
);
}

HttpHost httpClientProxy = new HttpHost(httpProxyHost, httpProxyPortInteger);
httpClientBuilder.setProxy(httpClientProxy);

CredentialsProvider httpCredentialsProvider = new BasicCredentialsProvider();

if (StringUtils.isNotEmpty(httpProxyUsername) && StringUtils.isNotEmpty(httpProxyPassword)) {
if (httpProxyUsername.contains("\\")) {
String domain = httpProxyUsername.substring(0, httpProxyUsername.indexOf("\\"));
String user = httpProxyUsername.substring(httpProxyUsername.indexOf("\\") + 1);

httpCredentialsProvider.setCredentials(
new AuthScope(httpProxyHost, httpProxyPortInteger),
new NTCredentials(user, httpProxyPassword, "", domain)
);
} else {
httpCredentialsProvider.setCredentials(
new AuthScope(httpProxyHost, httpProxyPortInteger),
new UsernamePasswordCredentials(httpProxyUsername, httpProxyPassword)
);
}
}

httpClientBuilder.setDefaultCredentialsProvider(httpCredentialsProvider);
}

SSLContextBuilder sslContextBuilder = SSLContexts.custom();

Expand Down Expand Up @@ -451,8 +549,7 @@ class OpenCommerceAPI {
);
}

httpClient = httpClientBuilder.build();
/* Setup HTTP Client */
return httpClientBuilder.build();
}

private AuthResponse auth() throws IOException {
Expand All @@ -479,6 +576,7 @@ private AuthResponse auth() throws IOException {
requestBuilder.setUri("https://account.demandware.com/dwsso/oauth2/access_token");
requestBuilder.setEntity(new UrlEncodedFormEntity(httpPostParams, Consts.UTF_8));

CloseableHttpClient httpClient = getCloseableHttpClient();
CloseableHttpResponse httpResponse;

try {
Expand Down Expand Up @@ -516,6 +614,17 @@ private AuthResponse auth() throws IOException {
throw abortException;
}

try {
httpClient.close();
} catch (IOException e) {
AbortException abortException = new AbortException(String.format(
"Exception thrown while closing HTTP client!\n%s",
ExceptionUtils.getStackTrace(e)
));
abortException.initCause(e);
throw abortException;
}

StatusLine httpStatusLine = httpResponse.getStatusLine();

if (httpStatusLine.getStatusCode() != HttpStatus.SC_OK) {
Expand Down Expand Up @@ -586,6 +695,7 @@ void cleanupLeftoverData(String path) throws IOException {
URLEncoder.encode(path, "UTF-8")
));

CloseableHttpClient httpClient = getCloseableHttpClientWithTwoFactorAuth();
CloseableHttpResponse httpResponse;

try {
Expand All @@ -610,6 +720,17 @@ void cleanupLeftoverData(String path) throws IOException {
throw abortException;
}

try {
httpClient.close();
} catch (IOException e) {
AbortException abortException = new AbortException(String.format(
"Exception thrown while closing HTTP client!\n%s",
ExceptionUtils.getStackTrace(e)
));
abortException.initCause(e);
throw abortException;
}

StatusLine httpStatusLine = httpResponse.getStatusLine();

if (!Arrays.asList(HttpStatus.SC_NOT_FOUND, HttpStatus.SC_NO_CONTENT).contains(httpStatusLine.getStatusCode())) {
Expand All @@ -636,6 +757,7 @@ void uploadData(File dataZip, String archiveName) throws IOException {
URLEncoder.encode(archiveName, "UTF-8")
));

CloseableHttpClient httpClient = getCloseableHttpClientWithTwoFactorAuth();
CloseableHttpResponse httpResponse;

try {
Expand All @@ -660,6 +782,17 @@ void uploadData(File dataZip, String archiveName) throws IOException {
throw abortException;
}

try {
httpClient.close();
} catch (IOException e) {
AbortException abortException = new AbortException(String.format(
"Exception thrown while closing HTTP client!\n%s",
ExceptionUtils.getStackTrace(e)
));
abortException.initCause(e);
throw abortException;
}

StatusLine httpStatusLine = httpResponse.getStatusLine();

if (httpStatusLine.getStatusCode() != HttpStatus.SC_CREATED) {
Expand Down Expand Up @@ -691,6 +824,7 @@ JobExecutionResult executeSiteArchiveImportJob(String archiveName) throws IOExce
URLEncoder.encode(ocCredentials.getClientId(), "UTF-8")
));

CloseableHttpClient httpClient = getCloseableHttpClientWithTwoFactorAuth();
CloseableHttpResponse httpResponse;

try {
Expand Down Expand Up @@ -728,6 +862,17 @@ JobExecutionResult executeSiteArchiveImportJob(String archiveName) throws IOExce
throw abortException;
}

try {
httpClient.close();
} catch (IOException e) {
AbortException abortException = new AbortException(String.format(
"Exception thrown while closing HTTP client!\n%s",
ExceptionUtils.getStackTrace(e)
));
abortException.initCause(e);
throw abortException;
}

JsonElement jsonElement;

try {
Expand Down Expand Up @@ -794,6 +939,7 @@ JobExecutionResult checkSiteArchiveImportJob(String archiveName, String jobId) t
URLEncoder.encode(ocCredentials.getClientId(), "UTF-8")
));

CloseableHttpClient httpClient = getCloseableHttpClientWithTwoFactorAuth();
CloseableHttpResponse httpResponse;

try {
Expand Down Expand Up @@ -831,6 +977,17 @@ JobExecutionResult checkSiteArchiveImportJob(String archiveName, String jobId) t
throw abortException;
}

try {
httpClient.close();
} catch (IOException e) {
AbortException abortException = new AbortException(String.format(
"Exception thrown while closing HTTP client!\n%s",
ExceptionUtils.getStackTrace(e)
));
abortException.initCause(e);
throw abortException;
}

JsonElement jsonElement;

try {
Expand Down Expand Up @@ -910,21 +1067,6 @@ JobExecutionResult checkSiteArchiveImportJob(String archiveName, String jobId) t
return new JobExecutionResult(jobId, jobStatus);
}

void close() throws IOException {
/* Close HTTP Client */
try {
httpClient.close();
} catch (IOException e) {
AbortException abortException = new AbortException(String.format(
"Exception thrown while closing HTTP client!\n%s",
ExceptionUtils.getStackTrace(e)
));
abortException.initCause(e);
throw abortException;
}
/* Close HTTP Client */
}

private static final class AuthResponse {
private String authToken;
private String authType;
Expand Down

0 comments on commit a5d7069

Please sign in to comment.