Skip to content

Commit

Permalink
Fix #31542: improve and refactor tests
Browse files Browse the repository at this point in the history
  • Loading branch information
LEDfan committed Oct 12, 2023
1 parent 769e47f commit 898a2f9
Show file tree
Hide file tree
Showing 34 changed files with 1,485 additions and 1,807 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import java.util.List;
import java.util.Map;


@RestController
Expand Down Expand Up @@ -239,18 +241,34 @@ public ResponseEntity<ApiResponse<Proxy>> getProxy(@PathVariable String proxyId)
})
@JsonView(Views.UserApi.class)
@RequestMapping(value="/api/proxy/{proxySpecId}", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ApiResponse<Proxy>> startProxy(@PathVariable String proxySpecId) throws InvalidParametersException {
public ResponseEntity<ApiResponse<Proxy>> startProxy(@PathVariable String proxySpecId, @RequestBody(required = false) ParametersBody parametersBody) throws InvalidParametersException {
ProxySpec baseSpec = proxyService.findProxySpec(s -> s.getId().equals(proxySpecId), false);
if (baseSpec == null) {
return ApiResponse.failForbidden();
}

try {
Proxy proxy = proxyService.startProxy(baseSpec);
Proxy proxy = proxyService.startProxy(baseSpec, (parametersBody != null) ? parametersBody.getParameters() : null);
return ApiResponse.created(proxy);
} catch (InvalidParametersException ex) {
return ApiResponse.fail(ex.getMessage());
} catch (Throwable t ) {
return ApiResponse.error("Failed to start proxy");
}
}

public static class ParametersBody {
private Map<String, String> parameters;

@Schema(description = "Map of parameters for the app.", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
public Map<String, String> getParameters() {
return parameters;
}

public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,14 @@ public Proxy startProxy(ProxySpec spec) {
return getProxy(id);
}

/**
public Proxy startProxy(ProxySpec spec, Map<String, String> parameters) {
String id = UUID.randomUUID().toString();
startProxy(userService.getCurrentAuth(), spec, null, id, parameters).run();
return getProxy(id);
}


/**
* Launch a new proxy using the given ProxySpec.
*
* @param spec The ProxySpec to base the new proxy on.
Expand Down Expand Up @@ -607,7 +614,7 @@ private Command action(String proxyId, BlockingAction blocking, AsyncAction asyn
}
}

public interface Command extends Runnable {
public interface Command extends Runnable {
}

@FunctionalInterface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,20 @@

import eu.openanalytics.containerproxy.service.leader.ILeaderService;

import javax.annotation.PreDestroy;

public class MemoryLeaderService implements ILeaderService {

private volatile boolean leader = true;

@Override
public boolean isLeader() {
return true;
return leader;
}

@PreDestroy
public void preDestroy() {
leader = false;
}

}
12 changes: 12 additions & 0 deletions src/main/java/eu/openanalytics/containerproxy/util/Retrying.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,13 @@
*/
package eu.openanalytics.containerproxy.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Retrying {

private static final Logger log = LoggerFactory.getLogger(Retrying.class);

@FunctionalInterface
public interface Attempt {
boolean attempt(int currentAttempt, int maxAttempts);
Expand All @@ -32,6 +37,10 @@ public static boolean retry(Attempt job, int maxDelay) {
}

public static boolean retry(Attempt job, int maxDelay, boolean retryOnException) {
return retry(job, maxDelay, null, -1, retryOnException);
}

public static boolean retry(Attempt job, int maxDelay, String logMessage, int logAfterAttmepts, boolean retryOnException) {
boolean retVal = false;
RuntimeException exception = null;
int maxAttempts = numberOfAttempts(maxDelay);
Expand All @@ -47,6 +56,9 @@ public static boolean retry(Attempt job, int maxDelay, boolean retryOnException)
if (retryOnException) exception = e;
else throw e;
}
if (currentAttempt > logAfterAttmepts && logMessage != null) {
log.info(String.format("Retry: %s (%d/%d)", logMessage, currentAttempt, maxAttempts));
}
}
if (exception == null) return retVal;
else throw exception;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,43 +20,41 @@
*/
package eu.openanalytics.containerproxy.test.auth;

import eu.openanalytics.containerproxy.test.proxy.PropertyOverrideContextInitializer;
import eu.openanalytics.containerproxy.test.helpers.BasicAuthInterceptor;
import eu.openanalytics.containerproxy.test.helpers.ShinyProxyInstance;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

import javax.inject.Inject;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@ActiveProfiles("test-ldap-auth")
@ContextConfiguration(initializers = PropertyOverrideContextInitializer.class)
public class LDAPAuthenticationTest {

@Inject
private MockMvc mvc;
import java.time.Duration;

public class LDAPAuthenticationTest {

@Inject
private Environment environment;

@Test
public void authenticateUser() throws Exception {
String userName = environment.getProperty("proxy.test-username");
String password = environment.getProperty("proxy.test-password");
mvc
.perform(get("/api/proxy").with(httpBasic(userName, password)).accept(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
try (ShinyProxyInstance inst = new ShinyProxyInstance("application-test-ldap-auth.yml")) {
String username = "tesla";
String password = "password";

String baseUrl = "http://localhost:7583";
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.callTimeout(Duration.ofSeconds(120))
.readTimeout(Duration.ofSeconds(120))
.followRedirects(false)
.build();


Request request = new Request.Builder()
.url(baseUrl + "/api/proxy/")
.build();

try (Response response = client.newCall(request).execute()) {
Assertions.assertEquals(200, response.code());
Assertions.assertFalse(response.isRedirect());
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,38 +20,37 @@
*/
package eu.openanalytics.containerproxy.test.auth;

import eu.openanalytics.containerproxy.test.proxy.PropertyOverrideContextInitializer;
import eu.openanalytics.containerproxy.test.helpers.BasicAuthInterceptor;
import eu.openanalytics.containerproxy.test.helpers.ShinyProxyInstance;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

import javax.inject.Inject;
import java.time.Duration;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@ActiveProfiles("test-no-auth")
@ContextConfiguration(initializers = PropertyOverrideContextInitializer.class)
public class NoAuthenticationTest {

@Inject
private MockMvc mvc;
@Test
public void authenticateUser() throws Exception {
try (ShinyProxyInstance inst = new ShinyProxyInstance("application-test-no-auth.yml")) {
String baseUrl = "http://localhost:7583";
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(Duration.ofSeconds(120))
.readTimeout(Duration.ofSeconds(120))
.followRedirects(false)
.build();

Request request = new Request.Builder()
.url(baseUrl + "/api/proxyspec")
.build();

try (Response response = client.newCall(request).execute()) {
Assertions.assertEquals(200, response.code());
Assertions.assertFalse(response.isRedirect());
}
}
}

@Test
public void authenticateUser() throws Exception {
mvc
.perform(get("/api/proxyspec").accept(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isNotEmpty());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,43 +20,70 @@
*/
package eu.openanalytics.containerproxy.test.auth;

import eu.openanalytics.containerproxy.test.proxy.PropertyOverrideContextInitializer;
import eu.openanalytics.containerproxy.test.helpers.BasicAuthInterceptor;
import eu.openanalytics.containerproxy.test.helpers.ShinyProxyInstance;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

import javax.inject.Inject;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@ActiveProfiles("test-simple-auth")
@ContextConfiguration(initializers = PropertyOverrideContextInitializer.class)

import java.time.Duration;

public class SimpleAuthenticationTest {

@Inject
private MockMvc mvc;

@Inject
private Environment environment;

@Test
public void authenticateUser() throws Exception {
String userName = environment.getProperty("proxy.users[0].name");
String password = environment.getProperty("proxy.users[0].password");
mvc
.perform(get("/api/proxy").with(httpBasic(userName, password)).accept(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void authenticateUser() throws Exception {
try (ShinyProxyInstance inst = new ShinyProxyInstance("application-test-simple-auth.yml")) {
String username = "demo";
String password = "demo";

String baseUrl = "http://localhost:7583";
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.callTimeout(Duration.ofSeconds(120))
.readTimeout(Duration.ofSeconds(120))
.followRedirects(false)
.build();

Request request = new Request.Builder()
.url(baseUrl + "/api/proxy/")
.build();

try (Response response = client.newCall(request).execute()) {
Assertions.assertEquals(200, response.code());
Assertions.assertFalse(response.isRedirect());
}
}
}

@Test
public void invalidUser() throws Exception {
try (ShinyProxyInstance inst = new ShinyProxyInstance("application-test-simple-auth.yml")) {
String username = "not";
String password = "correct";

String baseUrl = "http://localhost:7583";
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.callTimeout(Duration.ofSeconds(120))
.readTimeout(Duration.ofSeconds(120))
.followRedirects(false)
.build();


Request request = new Request.Builder()
.url(baseUrl + "/api/proxy/")
.header("Accept", "application/json")
.build();

try (Response response = client.newCall(request).execute()) {
Assertions.assertEquals(302, response.code());
Assertions.assertTrue(response.isRedirect());
}
}
}



}
Loading

0 comments on commit 898a2f9

Please sign in to comment.