Skip to content
This repository has been archived by the owner on Feb 1, 2023. It is now read-only.

Commit

Permalink
Merge pull request #24 from snyk/feat/disable-ssl-validation
Browse files Browse the repository at this point in the history
feat: allow to skip ssl validation [ROAD-21]
  • Loading branch information
pavel-snyk authored May 14, 2021
2 parents c3b7249 + 9d5462a commit 7536ce7
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 23 deletions.
5 changes: 4 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,7 @@ jobs:
restore-keys: ${{ runner.os }}-gradle

- name: Run tests
run: ./gradlew clean test
env:
DEEPROXY_API_URL: ${{secrets.DEEPROXY_API_URL}}
SNYK_TOKEN: ${{secrets.SNYK_TOKEN}}
run: ./gradlew clean test integTest
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ plugins {

group = "io.snyk.code.sdk"
archivesBaseName = "snyk-code-client"
version = "2.1.9"
version = "2.1.10"

repositories {
mavenCentral()
Expand Down Expand Up @@ -61,6 +61,7 @@ task integTest(type: Test) {
shouldRunAfter test

testLogging {
exceptionFormat "full"
showStandardStreams = true
}
outputs.upToDateWhen { false }
Expand Down
32 changes: 18 additions & 14 deletions src/integTest/java/ai/deepcode/javaclient/DeepCodeRestApiTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import java.util.Collections;
import java.util.List;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.*;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
Expand All @@ -37,8 +39,8 @@ public class DeepCodeRestApiTest {
+ "}\n";

// !!! Will works only with already logged sessionToken
private static final String loggedToken = System.getenv("DEEPCODE_API_KEY");
private final String deepcodedLoggedToken = System.getenv("DEEPCODE_API_KEY_STAGING");
private static final String loggedToken = System.getenv("SNYK_TOKEN");
private static final String baseUrl = System.getenv("DEEPROXY_API_URL");

private static String bundleId = null;

Expand Down Expand Up @@ -70,17 +72,8 @@ public void _020_checkSession() {
System.out.printf("Check Session call with token [%1$s] return [%2$d] code.\n", token, status);
assertEquals(401, status);

token = DeepCodeRestApi.newLogin(userAgent).getSessionToken();
status = DeepCodeRestApi.checkSession(token).getStatusCode();
System.out.printf(
"Check Session call with newly requested but not yet logged token [%1$s] return [%2$d] code.\n",
token, status);
assertEquals(
"Check Session call with newly requested but not yet logged token should return 304 code.",
304,
status);

token = loggedToken;
DeepCodeRestApi.setBaseUrl(baseUrl);
status = DeepCodeRestApi.checkSession(token).getStatusCode();
System.out.printf(
"Check Session call with logged user's token [%1$s] return [%2$d] code.\n", token, status);
Expand All @@ -94,8 +87,7 @@ public void _022_setBaseUrl() {
try {
doSetBaseUrlTest("", "blabla", 401);
doSetBaseUrlTest("https://www.google.com/", "blabla", 404);
doSetBaseUrlTest("https://www.deepcoded.com/", "blabla", 401);
doSetBaseUrlTest("https://www.deepcoded.com/", deepcodedLoggedToken, 200);
doSetBaseUrlTest("https://deeproxy.snyk.io/", "blabla", 401);
} finally {
DeepCodeRestApi.setBaseUrl("");
}
Expand Down Expand Up @@ -134,6 +126,7 @@ public void _025_getFilters() {
@Test
public void _030_createBundle_from_source() {
System.out.println("\n--------------Create Bundle from Source----------------\n");
DeepCodeRestApi.setBaseUrl(baseUrl);
int status = DeepCodeRestApi.checkSession(loggedToken).getStatusCode();
assertEquals(200, status);
FileContent fileContent = new FileContent("/AnnotatorTest.java", testFileContent);
Expand Down Expand Up @@ -270,6 +263,7 @@ public void _036_Check_Bundle() {
}

private FileHashRequest createFileHashRequest(String fakeFileName) {
DeepCodeRestApi.setBaseUrl(baseUrl);
int status = DeepCodeRestApi.checkSession(loggedToken).getStatusCode();
assertEquals(200, status);
final File testFile =
Expand Down Expand Up @@ -429,4 +423,14 @@ private void assertAndPrintGetAnalysisResponse(GetAnalysisResponse response) {
// assertEquals("DONE", response.getStatus());
assertEquals("Get Analysis request not succeed", 200, response.getStatusCode());
}

@Test
public void setBaseUrl_shouldUseEmptyTrustManager_whenDisableSslVerificationIsTrue() {
DeepCodeRestApi.setBaseUrl(baseUrl, true);

EmptyResponse emptyResponse = DeepCodeRestApi.checkSession(loggedToken);

assertThat(emptyResponse, notNullValue());
assertThat(emptyResponse.getStatusCode(), equalTo(200));
}
}
57 changes: 51 additions & 6 deletions src/main/java/ai/deepcode/javaclient/DeepCodeRestApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
*/
package ai.deepcode.javaclient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import ai.deepcode.javaclient.requests.*;
import ai.deepcode.javaclient.responses.*;

Expand All @@ -16,6 +21,10 @@
import retrofit2.http.*;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.concurrent.TimeUnit;

Expand All @@ -31,29 +40,65 @@ private DeepCodeRestApi() {}

private static final String API_URL = "https://www.deepcode.ai/";

private static Retrofit retrofit = buildRetrofit(API_URL);
private static Retrofit retrofit = buildRetrofit(API_URL, false);

// Create simple REST adapter which points the baseUrl.
private static Retrofit buildRetrofit(String baseUrl) {
OkHttpClient client = new OkHttpClient.Builder()
private static Retrofit buildRetrofit(String baseUrl, boolean disableSslVerification) {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(100, TimeUnit.SECONDS)
.writeTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS).build();
.readTimeout(100, TimeUnit.SECONDS);
if (disableSslVerification) {
X509TrustManager x509TrustManager = buildUnsafeTrustManager();
final TrustManager[] trustAllCertificates = new TrustManager[]{ x509TrustManager };

try {
final String sslProtocol = "SSL";
SSLContext sslContext = SSLContext.getInstance(sslProtocol);
sslContext.init(null, trustAllCertificates, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
builder.sslSocketFactory(sslSocketFactory, x509TrustManager);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
//TODO(pavel): extract Retrofit and OkHttpClient into configuration object to simplify API client building.
e.printStackTrace();
}
}
OkHttpClient client = builder.build();
return new Retrofit.Builder()
.baseUrl(baseUrl + "publicapi/")
.client(client)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}

@NotNull
private static X509TrustManager buildUnsafeTrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {}

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {}

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
};
}

/**
* Re-set baseUrl for retrofit instance
*
* @param baseUrl new baseUrl. <b>Null</b> or empty "" value will reset to default {@code
* #API_URL}
*/
public static void setBaseUrl(@Nullable String baseUrl) {
retrofit = buildRetrofit((baseUrl == null || baseUrl.isEmpty()) ? API_URL : baseUrl);
setBaseUrl(baseUrl, false);
}

public static void setBaseUrl(@Nullable String baseUrl, boolean disableSslVerification) {
retrofit = buildRetrofit((baseUrl == null || baseUrl.isEmpty()) ? API_URL : baseUrl, disableSslVerification);
}

private interface LoginCall {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public abstract class DeepCodeParamsBase {
// Settings
private boolean isEnable;
private String apiUrl;
private boolean disableSslVerification;
private boolean useLinter;
private int minSeverity;
private String sessionToken;
Expand All @@ -19,13 +20,15 @@ public abstract class DeepCodeParamsBase {
protected DeepCodeParamsBase(
boolean isEnable,
String apiUrl,
boolean disableSslVerification,
boolean useLinter,
int minSeverity,
String sessionToken,
String loginUrl,
String ideProductName) {
this.isEnable = isEnable;
this.apiUrl = apiUrl;
this.disableSslVerification = disableSslVerification;
this.useLinter = useLinter;
this.minSeverity = minSeverity;
this.sessionToken = sessionToken;
Expand Down Expand Up @@ -78,11 +81,24 @@ public String getApiUrl() {
}

public void setApiUrl(@NotNull String apiUrl) {
setApiUrl(apiUrl, false);
}

public void setApiUrl(@NotNull String apiUrl, boolean disableSslVerification) {
if (apiUrl.isEmpty()) apiUrl = "https://www.deepcode.ai/";
if (!apiUrl.endsWith("/")) apiUrl += "/";
if (apiUrl.equals(this.apiUrl)) return;
this.apiUrl = apiUrl;
DeepCodeRestApi.setBaseUrl(apiUrl);
this.disableSslVerification = disableSslVerification;
DeepCodeRestApi.setBaseUrl(apiUrl, disableSslVerification);
}

public boolean isDisableSslVerification() {
return disableSslVerification;
}

public void setDisableSslVerification(boolean disableSslVerification) {
this.disableSslVerification = disableSslVerification;
}

public boolean isEnable() {
Expand Down

0 comments on commit 7536ce7

Please sign in to comment.