Skip to content

Commit

Permalink
[jb] fix #10694: respect GW user settings
Browse files Browse the repository at this point in the history
  • Loading branch information
akosyakov committed Jun 28, 2022
1 parent 70aea6c commit f854ff8
Show file tree
Hide file tree
Showing 14 changed files with 134 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,26 @@

package io.gitpod.gitpodprotocol.api;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpProxy;
import org.eclipse.jetty.client.Socks4Proxy;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.websocket.jsr356.ClientContainer;
import org.eclipse.lsp4j.jsonrpc.Launcher;
import org.eclipse.lsp4j.jsonrpc.MessageConsumer;
import org.eclipse.lsp4j.jsonrpc.MessageIssueHandler;
import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler;
import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints;
import org.eclipse.lsp4j.websocket.WebSocketMessageHandler;

import javax.net.ssl.SSLContext;
import javax.websocket.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
Expand Down Expand Up @@ -47,10 +56,60 @@ public GitpodServerConnection listen(
String userAgent,
String clientVersion,
String token
) throws DeploymentException, IOException {
) throws Exception {
return listen(apiUrl, origin, userAgent, clientVersion, token, Collections.emptyList(), null);
}

public GitpodServerConnection listen(
String apiUrl,
String origin,
String userAgent,
String clientVersion,
String token,
List<Proxy> proxies,
SSLContext sslContext
) throws Exception {
String gitpodHost = URI.create(apiUrl).getHost();
HttpClient httpClient;
if (sslContext == null) {
httpClient = new HttpClient();
} else {
SslContextFactory ssl = new SslContextFactory.Client();
ssl.setSslContext(sslContext);
httpClient = new HttpClient(ssl);
}
for (Proxy proxy : proxies) {
if (proxy.type().equals(Proxy.Type.DIRECT)) {
continue;
}
SocketAddress proxyAddress = proxy.address();
if (!(proxyAddress instanceof InetSocketAddress)) {
GitpodServerConnectionImpl.LOG.log(Level.WARNING, gitpodHost + ": unexpected proxy:", proxy);
continue;
}
String hostName = ((InetSocketAddress) proxyAddress).getHostString();
int port = ((InetSocketAddress) proxyAddress).getPort();
if (proxy.type().equals(Proxy.Type.HTTP)) {
httpClient.getProxyConfiguration().getProxies().add(new HttpProxy(hostName, port));
} else if (proxy.type().equals(Proxy.Type.SOCKS)) {
httpClient.getProxyConfiguration().getProxies().add(new Socks4Proxy(hostName, port));
}
}
ClientContainer container = new ClientContainer(httpClient);
// allow clientContainer to own httpClient (for start/stop lifecycle)
container.getClient().addManaged(httpClient);
container.start();

GitpodServerConnectionImpl connection = new GitpodServerConnectionImpl(gitpodHost);
connection.setSession(ContainerProvider.getWebSocketContainer().connectToServer(new Endpoint() {
connection.whenComplete((input, exception) -> {
try {
container.stop();
} catch (Throwable t) {
GitpodServerConnectionImpl.LOG.log(Level.WARNING, gitpodHost + ": failed to stop websocket container:", t);
}
});

connection.setSession(container.connectToServer(new Endpoint() {
@Override
public void onOpen(Session session, EndpointConfig config) {
session.addMessageHandler(new WebSocketMessageHandler(messageReader, jsonHandler, remoteEndpoint));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,4 @@ internal class GitpodAuthCallbackHandler : RestService() {
</html>
""".trimIndent()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ import java.util.*
import java.util.concurrent.CompletableFuture
import kotlin.math.absoluteValue


@Service
internal class GitpodAuthService : OAuthServiceBase<Credentials>() {
override val name: String
Expand Down Expand Up @@ -66,7 +65,7 @@ internal class GitpodAuthService : OAuthServiceBase<Credentials>() {
constructor(gitpodHost: String) {
val codeVerifier = generateCodeVerifier()
val codeChallenge = generateCodeChallenge(codeVerifier)
val serviceUrl = newFromEncoded("https://${gitpodHost}/api/oauth")
val serviceUrl = newFromEncoded("https://$gitpodHost/api/oauth")
credentialsAcquirer = GitpodAuthCredentialsAcquirer(
serviceUrl.resolve("token"), mapOf(
"grant_type" to "authorization_code",
Expand Down Expand Up @@ -94,7 +93,7 @@ internal class GitpodAuthService : OAuthServiceBase<Credentials>() {
val bytes = ByteArray(size)
secureRandom.nextBytes(bytes)

val mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
val mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"
val scale = 256 / mask.length
val builder = StringBuilder()
for (i in 0 until size) {
Expand Down Expand Up @@ -147,7 +146,6 @@ internal class GitpodAuthService : OAuthServiceBase<Credentials>() {

private data class AuthorizationResponseData(val accessToken: String)
private data class JsonWebToken(val jti: String)

}

companion object {
Expand Down Expand Up @@ -198,8 +196,8 @@ internal class GitpodAuthService : OAuthServiceBase<Credentials>() {
listener()
}
}
dispatcher.addListener(internalListener);
dispatcher.addListener(internalListener)
return Disposable { dispatcher.removeListener(internalListener) }
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,16 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

class GatewayGitpodClient(
private val lifetimeDefinition: LifetimeDefinition, private val gitpodHost: String
private val lifetimeDefinition: LifetimeDefinition,
private val gitpodHost: String
) : GitpodClient() {

private val mutex = Mutex()

private val listeners = concurrentMapOf<String, CopyOnWriteArrayList<Channel<WorkspaceInstance>>?>()

private val timeoutDelayInMinutes = 15
private var timeoutJob: Job? = null;
private var timeoutJob: Job? = null

init {
GlobalScope.launch {
Expand Down Expand Up @@ -59,7 +60,7 @@ class GatewayGitpodClient(
}
}

private var syncJob: Job? = null;
private var syncJob: Job? = null
override fun notifyConnect() {
syncJob?.cancel()
syncJob = GlobalScope.launch {
Expand All @@ -69,17 +70,17 @@ class GatewayGitpodClient(
continue
}
try {
syncWorkspace(id);
syncWorkspace(id)
} catch (t: Throwable) {
thisLogger().error("${gitpodHost}: ${id}: failed to sync", t)
thisLogger().error("$gitpodHost: $id: failed to sync", t)
}
}
}
}

override fun onInstanceUpdate(instance: WorkspaceInstance?) {
if (instance == null) {
return;
return
}
GlobalScope.launch {
val wsListeners = listeners[instance.workspaceId] ?: return@launch
Expand All @@ -102,7 +103,7 @@ class GatewayGitpodClient(
val listener = Channel<WorkspaceInstance>()
mutex.withLock {
val listeners = this.listeners.getOrPut(workspaceId) { CopyOnWriteArrayList() }!!
listeners.add(listener);
listeners.add(listener)
cancelTimeout("listening to workspace: $workspaceId")
}
listenerLifetime.onTerminationOrNow {
Expand All @@ -120,7 +121,7 @@ class GatewayGitpodClient(
if (listeners.isNullOrEmpty()) {
return
}
listeners.remove(listener);
listeners.remove(listener)
if (listeners.isNotEmpty()) {
return
}
Expand All @@ -137,5 +138,4 @@ class GatewayGitpodClient(
onInstanceUpdate(info.latestInstance)
return info
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ import javax.swing.JComponent
import javax.swing.JLabel
import kotlin.coroutines.coroutineContext


class GitpodConnectionProvider : GatewayConnectionProvider {

private val gitpod = service<GitpodConnectionService>()
Expand All @@ -64,10 +63,10 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
requestor: ConnectionRequestor
): GatewayConnectionHandle? {
if (parameters["gitpodHost"] == null) {
throw IllegalArgumentException("bad gitpodHost parameter");
throw IllegalArgumentException("bad gitpodHost parameter")
}
if (parameters["workspaceId"] == null) {
throw IllegalArgumentException("bad workspaceId parameter");
throw IllegalArgumentException("bad workspaceId parameter")
}
val connectParams = ConnectParams(
parameters["gitpodHost"]!!,
Expand All @@ -92,7 +91,7 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
background = phaseMessage.background
columns = 30
}
var ideUrl = "";
var ideUrl = ""
val connectionPanel = panel {
indent {
row {
Expand Down Expand Up @@ -146,18 +145,18 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
}

GlobalScope.launch {
var thinClient: ThinClientHandle? = null;
var thinClientJob: Job? = null;
var thinClient: ThinClientHandle? = null
var thinClientJob: Job? = null

var lastUpdate: WorkspaceInstance? = null;
var lastUpdate: WorkspaceInstance? = null
try {
for (update in updates) {
try {
if (WorkspaceInstance.isUpToDate(lastUpdate, update)) {
continue;
continue
}
ideUrl = update.ideUrl
lastUpdate = update;
lastUpdate = update
if (!update.status.conditions.failed.isNullOrBlank()) {
setErrorMessage(update.status.conditions.failed)
}
Expand Down Expand Up @@ -212,7 +211,7 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
if (thinClientJob == null && update.status.phase == "running") {
thinClientJob = launch {
try {
val ideUrl = URL(update.ideUrl);
val ideUrl = URL(update.ideUrl)
val hostKeys = resolveHostKeys(ideUrl, connectParams)
if (hostKeys.isNullOrEmpty()) {
setErrorMessage("${connectParams.gitpodHost} installation does not allow SSH access, public keys cannot be found")
Expand Down Expand Up @@ -270,7 +269,7 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
}
}

return GitpodConnectionHandle(connectionLifetime, connectionPanel, connectParams);
return GitpodConnectionHandle(connectionLifetime, connectionPanel, connectParams)
}

private suspend fun resolveJoinLink(
Expand Down Expand Up @@ -356,7 +355,6 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
break
}
}

}
matchedFingerprint
}
Expand All @@ -369,7 +367,7 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
ownerToken: String?,
): String? {
val maxRequestTimeout = 30 * 1000L
val timeoutDelayGrowFactor = 1.5;
val timeoutDelayGrowFactor = 1.5
var requestTimeout = 2 * 1000L
while (true) {
coroutineContext.job.ensureActive()
Expand All @@ -388,16 +386,16 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
return response.body()
}
if (response.statusCode() < 500) {
thisLogger().error("${connectParams.gitpodHost}: ${connectParams.workspaceId}: failed to fetch '${endpointUrl}': ${response.statusCode()}")
thisLogger().error("${connectParams.gitpodHost}: ${connectParams.workspaceId}: failed to fetch '$endpointUrl': ${response.statusCode()}")
return null
}
thisLogger().warn("${connectParams.gitpodHost}: ${connectParams.workspaceId}: failed to fetch '${endpointUrl}', trying again...: ${response.statusCode()}")
thisLogger().warn("${connectParams.gitpodHost}: ${connectParams.workspaceId}: failed to fetch '$endpointUrl', trying again...: ${response.statusCode()}")
} catch (t: Throwable) {
if (t is CancellationException) {
throw t
}
thisLogger().warn(
"${connectParams.gitpodHost}: ${connectParams.workspaceId}: failed to fetch '${endpointUrl}', trying again...:",
"${connectParams.gitpodHost}: ${connectParams.workspaceId}: failed to fetch '$endpointUrl', trying again...:",
t
)
}
Expand Down Expand Up @@ -437,5 +435,4 @@ class GitpodConnectionProvider : GatewayConnectionProvider {
}

private data class SSHHostKey(val type: String, val hostKey: String)

}
Loading

0 comments on commit f854ff8

Please sign in to comment.