CHE-6463 Remove machine auth code that is outdated in spi

6.19.x
Sergii Leshchenko 2017-09-27 14:37:21 +03:00
parent 92c5d1af20
commit 861f4eccbb
15 changed files with 10 additions and 588 deletions

View File

@ -103,10 +103,10 @@
<groupId>org.eclipse.che.plugin</groupId>
<artifactId>che-plugin-activity-wsmaster</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.che.plugin</groupId>
<artifactId>che-plugin-docker-machine-auth</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.eclipse.che.plugin</groupId>-->
<!--<artifactId>che-plugin-docker-machine-auth</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>

View File

@ -27,12 +27,6 @@ public class CheWsMasterModule extends AbstractModule {
bind(TokenValidator.class).to(org.eclipse.che.api.local.DummyTokenValidator.class);
bind(org.eclipse.che.api.agent.server.WsAgentHealthChecker.class)
.to(org.eclipse.che.api.agent.server.WsAgentHealthCheckerImpl.class);
bind(org.eclipse.che.api.environment.server.MachineInstanceProvider.class)
.to(org.eclipse.che.plugin.docker.machine.MachineProviderImpl.class);
bind(org.eclipse.che.api.workspace.server.stack.StackLoader.class);
bind(DataSource.class).toProvider(org.eclipse.che.core.db.h2.H2DataSourceProvider.class);

View File

@ -40,7 +40,7 @@ public class KeycloakProvider {
public KeycloakProvider(AppContext appContext, PromiseProvider promiseProvider) {
this.appContext = appContext;
String keycloakSettings =
getKeycloakSettings(KeycloakConstants.getEndpoint(appContext.getMasterEndpoint()));
getKeycloakSettings(KeycloakConstants.getEndpoint(appContext.getMasterApiEndpoint()));
Map<String, String> settings = JsonHelper.toMap(keycloakSettings);
Log.info(getClass(), "Keycloak settings: ", settings);

View File

@ -41,10 +41,6 @@
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.che.core</groupId>
<artifactId>che-core-api-core</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.che.core</groupId>
<artifactId>che-core-api-dto</artifactId>

View File

@ -1,51 +0,0 @@
/*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.machine.authentication.ide;
import static org.eclipse.che.api.machine.shared.Constants.WSAGENT_WEBSOCKET_REFERENCE;
import com.google.inject.Singleton;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.api.core.rest.shared.dto.LinkParameter;
import org.eclipse.che.ide.api.machine.CheWsAgentLinksModifier;
import org.eclipse.che.ide.api.machine.DevMachine;
/**
* Inserts in each URL machine token.
*
* @author Anton Korneta
*/
@Singleton
public class CheAuthMachineLinksModifier extends CheWsAgentLinksModifier {
private static final String MACHINE_TOKEN = "token";
private String machineToken;
@Override
public void initialize(DevMachine devMachine) {
Link link = devMachine.getMachineLink(WSAGENT_WEBSOCKET_REFERENCE);
if (link != null) {
for (LinkParameter parameter : link.getParameters()) {
if (MACHINE_TOKEN.equals(parameter.getName())) {
machineToken = parameter.getDefaultValue();
}
}
}
}
@Override
public String modify(String agentUrl) {
if (machineToken != null) {
return agentUrl + (agentUrl.contains("?") ? '&' : '?') + "token=" + machineToken;
}
throw new RuntimeException("Failed to modify url, machine token in not specified");
}
}

View File

@ -25,7 +25,6 @@ import org.eclipse.che.api.promises.client.Function;
import org.eclipse.che.api.promises.client.Promise;
import org.eclipse.che.api.promises.client.js.Promises;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.machine.DevMachine;
import org.eclipse.che.ide.api.workspace.event.WorkspaceStoppedEvent;
import org.eclipse.che.ide.commons.exception.UnmarshallerException;
import org.eclipse.che.ide.dto.DtoFactory;
@ -49,7 +48,6 @@ public class MachineAsyncRequestFactory extends AsyncRequestFactory
private final AppContext appContext;
private String machineToken;
private String wsAgentBaseUrl;
private String csrfToken;
@Inject
@ -101,7 +99,6 @@ public class MachineAsyncRequestFactory extends AsyncRequestFactory
@Override
public void onWorkspaceStopped(WorkspaceStoppedEvent event) {
machineToken = null;
wsAgentBaseUrl = null;
}
/**
@ -115,22 +112,14 @@ public class MachineAsyncRequestFactory extends AsyncRequestFactory
|| !RUNNING.equals(appContext.getWorkspace().getStatus())) {
return false; //ws-agent not started
}
if (isNullOrEmpty(wsAgentBaseUrl)) {
final DevMachine devMachine = appContext.getDevMachine();
if (devMachine != null) {
wsAgentBaseUrl = devMachine.getWsAgentBaseUrl();
} else {
return false;
}
}
return url.contains(nullToEmpty(wsAgentBaseUrl));
return url.contains(nullToEmpty(appContext.getWsAgentServerApiEndpoint()));
}
private Promise<String> requestCsrfToken() {
if (csrfToken != null) {
return Promises.resolve(csrfToken);
}
return createGetRequest(appContext.getMasterEndpoint() + "/profile")
return createGetRequest(appContext.getMasterApiEndpoint() + "/profile")
.header(CSRF_TOKEN_HEADER_NAME, "Fetch")
.send(
new Unmarshallable<String>() {

View File

@ -16,7 +16,6 @@ import org.eclipse.che.api.user.shared.dto.UserDto;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.rest.AsyncRequestFactory;
import org.eclipse.che.ide.rest.DtoUnmarshallerFactory;
import org.eclipse.che.ide.rest.RestContext;
import org.eclipse.che.multiuser.machine.authentication.shared.dto.MachineTokenDto;
/**
@ -34,14 +33,13 @@ public class MachineTokenServiceClientImpl implements MachineTokenServiceClient
@Inject
public MachineTokenServiceClientImpl(
@RestContext String restContext,
AppContext appContext,
AsyncRequestFactory asyncRequestFactory,
DtoUnmarshallerFactory dtoUnmarshallerFactory) {
this.appContext = appContext;
this.asyncRequestFactory = asyncRequestFactory;
this.dtoUnmarshallerFactory = dtoUnmarshallerFactory;
this.baseUrl = restContext + MACHINE_TOKEN_SERVICE_PATH;
this.baseUrl = appContext.getMasterApiEndpoint() + MACHINE_TOKEN_SERVICE_PATH;
}
public Promise<MachineTokenDto> getMachineToken() {

View File

@ -13,8 +13,6 @@ package org.eclipse.che.multiuser.machine.authentication.ide.inject;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Singleton;
import org.eclipse.che.ide.api.extension.ExtensionGinModule;
import org.eclipse.che.ide.api.machine.CheWsAgentLinksModifier;
import org.eclipse.che.multiuser.machine.authentication.ide.CheAuthMachineLinksModifier;
import org.eclipse.che.multiuser.machine.authentication.ide.MachineTokenServiceClient;
import org.eclipse.che.multiuser.machine.authentication.ide.MachineTokenServiceClientImpl;
@ -24,10 +22,8 @@ public class MachineAuthGinModule extends AbstractGinModule {
@Override
protected void configure() {
//bind(AsyncRequestFactory.class).to(MachineAsyncRequestFactory.class);
bind(MachineTokenServiceClient.class)
.to(MachineTokenServiceClientImpl.class)
.in(Singleton.class);
bind(CheWsAgentLinksModifier.class).to(CheAuthMachineLinksModifier.class);
}
}

View File

@ -113,10 +113,6 @@
<groupId>org.everrest</groupId>
<artifactId>everrest-core</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.che.multiuser</groupId>
<artifactId>che-multiuser-api-permission</artifactId>

View File

@ -1,67 +0,0 @@
/*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.machine.authentication.server;
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.che.api.agent.server.WsAgentHealthCheckerImpl;
import org.eclipse.che.api.agent.server.WsAgentPingRequestFactory;
import org.eclipse.che.api.core.ApiException;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.model.machine.Machine;
import org.eclipse.che.api.core.rest.HttpJsonRequest;
import org.eclipse.che.api.core.rest.HttpJsonRequestFactory;
import org.eclipse.che.multiuser.machine.authentication.shared.dto.MachineTokenDto;
/** @author Max Shaposhnik (mshaposhnik@redhat.com) */
@Singleton
public class AuthWsAgentHealthChecker extends WsAgentHealthCheckerImpl {
private final HttpJsonRequestFactory httpJsonRequestFactory;
private final String apiEndpoint;
@Inject
public AuthWsAgentHealthChecker(
WsAgentPingRequestFactory pingRequestFactory,
HttpJsonRequestFactory httpJsonRequestFactory,
@Named("che.api") String apiEndpoint) {
super(pingRequestFactory);
this.apiEndpoint = apiEndpoint;
this.httpJsonRequestFactory = httpJsonRequestFactory;
}
// modifies the ping request if it is possible to get the machine token.
protected HttpJsonRequest createPingRequest(Machine devMachine) throws ServerException {
final HttpJsonRequest pingRequest = super.createPingRequest(devMachine);
final String tokenServiceUrl =
UriBuilder.fromUri(apiEndpoint)
.replacePath("api/machine/token/" + devMachine.getWorkspaceId())
.build()
.toString();
String machineToken = null;
try {
machineToken =
httpJsonRequestFactory
.fromUrl(tokenServiceUrl)
.setMethod(HttpMethod.GET)
.request()
.asDto(MachineTokenDto.class)
.getMachineToken();
} catch (ApiException | IOException ex) {
LOG.warn("Failed to get machine token", ex);
}
return machineToken == null ? pingRequest : pingRequest.setAuthorizationHeader(machineToken);
}
}

View File

@ -1,121 +0,0 @@
/*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.machine.authentication.server;
import static org.eclipse.che.api.core.util.LinksHelper.createLink;
import static org.eclipse.che.api.machine.shared.Constants.EXEC_AGENT_REFERENCE;
import static org.eclipse.che.api.machine.shared.Constants.TERMINAL_REFERENCE;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.che.api.core.ApiException;
import org.eclipse.che.api.core.rest.HttpJsonRequestFactory;
import org.eclipse.che.api.core.rest.ServiceContext;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.api.environment.server.MachineLinksInjector;
import org.eclipse.che.api.machine.shared.dto.MachineDto;
import org.eclipse.che.api.machine.shared.dto.ServerDto;
import org.eclipse.che.multiuser.machine.authentication.shared.dto.MachineTokenDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helps to inject Machine related links.
*
* @author Anton Korneta
*/
public class MachineAuthLinksInjector extends MachineLinksInjector {
private static final Logger LOG = LoggerFactory.getLogger(MachineAuthLinksInjector.class);
private static final String MACHINE_TOKEN_SERVICE_PATH = "/machine/token/";
private final String tokenServiceBaseUrl;
private final HttpJsonRequestFactory httpJsonRequestFactory;
@Inject
public MachineAuthLinksInjector(
@Named("che.api") String apiEndpoint, HttpJsonRequestFactory httpJsonRequestFactory) {
this.tokenServiceBaseUrl = apiEndpoint + MACHINE_TOKEN_SERVICE_PATH;
this.httpJsonRequestFactory = httpJsonRequestFactory;
}
@VisibleForTesting
@Override
protected void injectTerminalLink(
MachineDto machine, ServiceContext serviceContext, List<Link> links) {
if (machine.getRuntime() != null) {
final String machineToken = getMachineToken(machine);
final String scheme = serviceContext.getBaseUriBuilder().build().getScheme();
final Collection<ServerDto> servers = machine.getRuntime().getServers().values();
servers
.stream()
.filter(server -> TERMINAL_REFERENCE.equals(server.getRef()))
.findAny()
.ifPresent(
terminal ->
links.add(
createLink(
"GET",
UriBuilder.fromUri(terminal.getUrl())
.scheme("https".equals(scheme) ? "wss" : "ws")
.queryParam("token", machineToken)
.path("/pty")
.build()
.toString(),
TERMINAL_REFERENCE)));
}
}
@Override
protected void injectExecAgentLink(
MachineDto machine, ServiceContext serviceContext, List<Link> links) {
final String scheme = serviceContext.getBaseUriBuilder().build().getScheme();
if (machine.getRuntime() != null) {
final String machineToken = getMachineToken(machine);
final Collection<ServerDto> servers = machine.getRuntime().getServers().values();
servers
.stream()
.filter(server -> EXEC_AGENT_REFERENCE.equals(server.getRef()))
.findAny()
.ifPresent(
exec ->
links.add(
createLink(
"GET",
UriBuilder.fromUri(exec.getUrl())
.scheme("https".equals(scheme) ? "wss" : "ws")
.queryParam("token", machineToken)
.path("/connect")
.build()
.toString(),
EXEC_AGENT_REFERENCE)));
}
}
private String getMachineToken(MachineDto machine) {
try {
return httpJsonRequestFactory
.fromUrl(tokenServiceBaseUrl + machine.getWorkspaceId())
.setMethod(HttpMethod.GET)
.request()
.asDto(MachineTokenDto.class)
.getMachineToken();
} catch (ApiException | IOException ex) {
LOG.warn("Failed to get machine token", ex);
}
return "";
}
}

View File

@ -14,6 +14,7 @@ import com.google.common.annotations.VisibleForTesting;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.eclipse.che.api.core.model.workspace.WorkspaceStatus;
import org.eclipse.che.api.core.notification.EventService;
import org.eclipse.che.api.core.notification.EventSubscriber;
import org.eclipse.che.api.workspace.shared.dto.event.WorkspaceStatusEvent;
@ -37,7 +38,7 @@ public class MachineSessionInvalidator implements EventSubscriber<WorkspaceStatu
@Override
public void onEvent(WorkspaceStatusEvent event) {
if (WorkspaceStatusEvent.EventType.STOPPED.equals(event.getEventType())) {
if (WorkspaceStatus.STOPPED.equals(event.getStatus())) {
tokenRegistry.removeTokens(event.getWorkspaceId()).values();
}
}

View File

@ -1,184 +0,0 @@
/*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.machine.authentication.server;
import static com.google.common.base.MoreObjects.firstNonNull;
import static org.eclipse.che.api.core.model.workspace.WorkspaceStatus.RUNNING;
import static org.eclipse.che.api.core.util.LinksHelper.createLink;
import static org.eclipse.che.api.machine.shared.Constants.EXEC_AGENT_REFERENCE;
import static org.eclipse.che.api.machine.shared.Constants.TERMINAL_REFERENCE;
import static org.eclipse.che.api.machine.shared.Constants.WSAGENT_REFERENCE;
import static org.eclipse.che.api.machine.shared.Constants.WSAGENT_WEBSOCKET_REFERENCE;
import static org.eclipse.che.api.workspace.shared.Constants.LINK_REL_STOP_WORKSPACE;
import static org.eclipse.che.dto.server.DtoFactory.newDto;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.che.api.core.ApiException;
import org.eclipse.che.api.core.rest.HttpJsonRequestFactory;
import org.eclipse.che.api.core.rest.ServiceContext;
import org.eclipse.che.api.core.rest.shared.dto.LinkParameter;
import org.eclipse.che.api.environment.server.MachineLinksInjector;
import org.eclipse.che.api.machine.shared.dto.MachineDto;
import org.eclipse.che.api.machine.shared.dto.ServerDto;
import org.eclipse.che.api.workspace.server.WorkspaceService;
import org.eclipse.che.api.workspace.server.WorkspaceServiceLinksInjector;
import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto;
import org.eclipse.che.api.workspace.shared.dto.WorkspaceRuntimeDto;
import org.eclipse.che.multiuser.machine.authentication.shared.dto.MachineTokenDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helps to inject {@link WorkspaceService} related links.
*
* @author Anton Korneta
*/
public class WorkspaceServiceAuthLinksInjector extends WorkspaceServiceLinksInjector {
private static final Logger LOG =
LoggerFactory.getLogger(WorkspaceServiceAuthLinksInjector.class);
private static final String MACHINE_TOKEN = "token";
private static final String MACHINE_SERVICE_PATH = "/machine/token/";
private final String tokenServiceBaseUrl;
private final HttpJsonRequestFactory httpJsonRequestFactory;
@Inject
public WorkspaceServiceAuthLinksInjector(
@Named("che.api") String apiEndpoint,
HttpJsonRequestFactory httpJsonRequestFactory,
MachineLinksInjector machineLinksInjector) {
super(machineLinksInjector);
this.tokenServiceBaseUrl = apiEndpoint + MACHINE_SERVICE_PATH;
this.httpJsonRequestFactory = httpJsonRequestFactory;
}
protected void injectRuntimeLinks(
WorkspaceDto workspace, URI ideUri, UriBuilder uriBuilder, ServiceContext serviceContext) {
final WorkspaceRuntimeDto runtime = workspace.getRuntime();
// add links for running workspace
if (workspace.getStatus() == RUNNING && runtime != null) {
runtime
.getLinks()
.add(
createLink(
"DELETE",
uriBuilder
.clone()
.path(WorkspaceService.class, "stop")
.build(workspace.getId())
.toString(),
LINK_REL_STOP_WORKSPACE));
String token = null;
try {
token =
httpJsonRequestFactory
.fromUrl(tokenServiceBaseUrl + workspace.getId())
.setMethod(HttpMethod.GET)
.request()
.asDto(MachineTokenDto.class)
.getMachineToken();
} catch (ApiException | IOException ex) {
LOG.warn("Failed to get machine token", ex);
}
final String machineToken = firstNonNull(token, "");
runtime.getMachines().forEach(machine -> injectMachineLinks(machine, serviceContext));
final MachineDto devMachine = runtime.getDevMachine();
if (devMachine != null) {
final Collection<ServerDto> servers = devMachine.getRuntime().getServers().values();
servers
.stream()
.filter(server -> WSAGENT_REFERENCE.equals(server.getRef()))
.findAny()
.ifPresent(
wsAgent -> {
runtime.getLinks().add(createLink("GET", wsAgent.getUrl(), WSAGENT_REFERENCE));
runtime
.getLinks()
.add(
createLink(
"GET",
UriBuilder.fromUri(wsAgent.getUrl())
.path("ws")
.scheme("https".equals(ideUri.getScheme()) ? "wss" : "ws")
.build()
.toString(),
WSAGENT_WEBSOCKET_REFERENCE));
devMachine
.getLinks()
.add(
createLink(
"GET",
UriBuilder.fromUri(wsAgent.getUrl())
.scheme("https".equals(ideUri.getScheme()) ? "wss" : "ws")
.path("/ws")
.queryParam(MACHINE_TOKEN, machineToken)
.build()
.toString(),
WSAGENT_WEBSOCKET_REFERENCE,
ImmutableList.of(
newDto(LinkParameter.class)
.withName(MACHINE_TOKEN)
.withDefaultValue(machineToken)
.withRequired(true))));
});
servers
.stream()
.filter(server -> TERMINAL_REFERENCE.equals(server.getRef()))
.findAny()
.ifPresent(
terminal -> {
devMachine
.getLinks()
.add(
createLink(
"GET",
UriBuilder.fromUri(terminal.getUrl())
.scheme("https".equals(ideUri.getScheme()) ? "wss" : "ws")
.queryParam(MACHINE_TOKEN, machineToken)
.path("/pty")
.build()
.toString(),
TERMINAL_REFERENCE));
});
servers
.stream()
.filter(server -> EXEC_AGENT_REFERENCE.equals(server.getRef()))
.findAny()
.ifPresent(
exec -> {
devMachine
.getLinks()
.add(
createLink(
"GET",
UriBuilder.fromUri(exec.getUrl())
.scheme("https".equals(ideUri.getScheme()) ? "wss" : "ws")
.queryParam(MACHINE_TOKEN, machineToken)
.path("/connect")
.build()
.toString(),
EXEC_AGENT_REFERENCE));
});
}
}
}
}

View File

@ -1,118 +0,0 @@
/*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.machine.authentication.server;
import static org.eclipse.che.api.machine.shared.Constants.TERMINAL_REFERENCE;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.che.api.core.rest.HttpJsonRequest;
import org.eclipse.che.api.core.rest.HttpJsonRequestFactory;
import org.eclipse.che.api.core.rest.HttpJsonResponse;
import org.eclipse.che.api.core.rest.ServiceContext;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.api.machine.shared.dto.MachineDto;
import org.eclipse.che.api.machine.shared.dto.MachineRuntimeInfoDto;
import org.eclipse.che.api.machine.shared.dto.ServerDto;
import org.eclipse.che.commons.test.mockito.answer.SelfReturningAnswer;
import org.eclipse.che.dto.server.DtoFactory;
import org.eclipse.che.multiuser.machine.authentication.shared.dto.MachineTokenDto;
import org.everrest.core.impl.uri.UriBuilderImpl;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/** @author Anton Korneta. */
@Listeners(MockitoTestNGListener.class)
public class MachineServiceAuthLinksInjectorTest {
private static final String URI_BASE = "http://localhost:8080";
private static final String API_ENDPOINT = URI_BASE + "/api";
@Mock private ServiceContext serviceContextMock;
@Mock private MachineRuntimeInfoDto machineRuntimeInfoDtoMock;
@Mock private HttpJsonRequestFactory requestFactoryMock;
@Mock private ServerDto serverDtoMock;
private HttpJsonRequest requestMock;
private MachineAuthLinksInjector machineLinksInjector;
@BeforeMethod
public void setUp() throws Exception {
final UriBuilder uriBuilder = new UriBuilderImpl();
uriBuilder.uri(URI_BASE);
requestMock = mock(HttpJsonRequest.class, new SelfReturningAnswer());
when(requestFactoryMock.fromUrl(anyString())).thenReturn(requestMock);
machineLinksInjector = new MachineAuthLinksInjector(API_ENDPOINT, requestFactoryMock);
when(serviceContextMock.getBaseUriBuilder()).thenReturn(uriBuilder);
when(serverDtoMock.getRef()).thenReturn(TERMINAL_REFERENCE);
when(serverDtoMock.getUrl()).thenReturn(URI_BASE);
when(machineRuntimeInfoDtoMock.getServers())
.thenReturn(ImmutableMap.of("server", serverDtoMock));
}
@Test
public void shouldInjectTerminalLinkWithMachineToken() throws Exception {
final String machineToken = "machine12";
final MachineTokenDto tokenDto =
DtoFactory.newDto(MachineTokenDto.class).withMachineToken(machineToken);
final HttpJsonResponse responseMock = mock(HttpJsonResponse.class);
when(responseMock.asDto(MachineTokenDto.class)).thenReturn(tokenDto);
when(requestMock.request()).thenReturn(responseMock);
final MachineDto machineDto =
DtoFactory.newDto(MachineDto.class)
.withId("id")
.withWorkspaceId("wsId")
.withRuntime(machineRuntimeInfoDtoMock);
final List<Link> links = new ArrayList<>();
machineLinksInjector.injectTerminalLink(machineDto, serviceContextMock, links);
final Link resultTerminalLink = links.get(0);
assertEquals(1, links.size());
assertEquals(resultTerminalLink.getRel(), TERMINAL_REFERENCE);
assertEquals(resultTerminalLink.getHref(), "ws://localhost:8080/pty?token=" + machineToken);
}
@Test
public void shouldInjectTerminalLinkWithoutMachineToken() throws Exception {
when(requestMock.request()).thenThrow(new IOException("ioEx"));
final MachineDto machineDto =
DtoFactory.newDto(MachineDto.class)
.withId("id")
.withWorkspaceId("wsId")
.withRuntime(machineRuntimeInfoDtoMock);
final List<Link> links = new ArrayList<>();
machineLinksInjector.injectTerminalLink(machineDto, serviceContextMock, links);
final Link resultTerminalLink = links.get(0);
assertEquals(1, links.size());
assertEquals(resultTerminalLink.getRel(), TERMINAL_REFERENCE);
}
@Test
public void shouldNotInjectTerminalLinkWhenNoRuntimeMachine() {
final MachineDto machineDto = DtoFactory.newDto(MachineDto.class).withRuntime(null);
final List<Link> links = new ArrayList<>();
machineLinksInjector.injectTerminalLink(machineDto, serviceContextMock, links);
assertTrue(links.isEmpty());
}
}

View File

@ -26,9 +26,6 @@ import com.google.inject.spi.ConstructorBinding;
import java.lang.reflect.Method;
import org.eclipse.che.account.spi.AccountDao;
import org.eclipse.che.api.core.notification.EventService;
import org.eclipse.che.api.environment.server.MachineProcessManager;
import org.eclipse.che.api.machine.server.spi.SnapshotDao;
import org.eclipse.che.api.workspace.server.WorkspaceFilesCleaner;
import org.eclipse.che.api.workspace.server.WorkspaceManager;
import org.eclipse.che.api.workspace.server.WorkspaceRuntimes;
import org.eclipse.che.api.workspace.server.WorkspaceSharedPool;
@ -52,7 +49,6 @@ public class MachineTokenInterceptorTest {
@Mock private MachineTokenRegistry tokenRegistry;
@Mock private WorkspaceImpl workspaceImpl;
@Mock private WorkspaceFilesCleaner workspaceFilesCleaner;
private WorkspaceManager workspaceManager;
@ -68,15 +64,12 @@ public class MachineTokenInterceptorTest {
bind(WorkspaceDao.class).toInstance(mock(WorkspaceDao.class));
bind(WorkspaceRuntimes.class).toInstance(mock(WorkspaceRuntimes.class));
bind(EventService.class).toInstance(mock(EventService.class));
bind(MachineProcessManager.class).toInstance(mock(MachineProcessManager.class));
bind(AccountDao.class).toInstance(mock(AccountDao.class));
bindConstant().annotatedWith(Names.named("che.workspace.auto_restore")).to(false);
bindConstant().annotatedWith(Names.named("che.workspace.auto_snapshot")).to(false);
bind(WorkspaceSharedPool.class)
.toInstance(new WorkspaceSharedPool("cached", null, null));
bind(WorkspaceManager.class);
bind(SnapshotDao.class).toInstance(mock(SnapshotDao.class));
bind(WorkspaceFilesCleaner.class).toInstance(workspaceFilesCleaner);
bind(MachineTokenRegistry.class).toInstance(tokenRegistry);