Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ It follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [Unreleased]

### Security

- Validate workspace link routes and deployment URLs before connecting, and validate saved URLs before restoring credentials. Workspace links must identify the deployment by its HTTP(S) origin.

### Fixed

- Split query fields before decoding so encoded separators remain part of their values, and decode each field only once. Repeated parameters use the first value.

## [0.9.6] - 2026-11-19

### Changed
Expand Down
22 changes: 18 additions & 4 deletions src/main/kotlin/com/coder/toolbox/CoderRemoteProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -508,9 +508,16 @@ class CoderRemoteProvider(
*/
override suspend fun handleUri(uri: URI) {
try {
require(
uri.scheme.equals("jetbrains", ignoreCase = true) &&
uri.rawAuthority.equals("gateway", ignoreCase = true) && uri.rawFragment == null &&
uri.rawPath in setOf("/com.coder.toolbox", "/coder", "/com.coder.toolbox/auth")
) {
"Unrecognized Toolbox link."
}
val params = uri.toQueryParameters()
when {
uri.toString().startsWith("jetbrains://gateway/com.coder.toolbox/auth") -> handleOAuthUri(params)
uri.rawPath == "/com.coder.toolbox/auth" -> handleOAuthUri(params)
// An empty query can indicate plugin installation.
params.isEmpty() ->
context.logger.logAndShowInfo("URI will not be handled", "No query parameters were provided")
Expand All @@ -522,8 +529,6 @@ class CoderRemoteProvider(
} catch (ex: Exception) {
val reason = (ex as? APIResponseException)?.reason?.takeIf { it.isNotBlank() }
context.logger.logAndShowError("Error encountered while handling Coder URI", reason ?: ex.message.orEmpty())
} finally {
firstRun = false
}
}

Expand Down Expand Up @@ -587,6 +592,7 @@ class CoderRemoteProvider(
onConnect = onConnect,
onTokenRefreshed = ::onTokenRefreshed,
)
firstRun = false
router.navigate(wizard)

context.envPageManager.showPluginEnvironmentsPage(false)
Expand All @@ -611,6 +617,7 @@ class CoderRemoteProvider(
val activeClient = client?.takeIf { it.url.hasSameOrigin(deployment.url) }
if (!confirmDeploymentSignIn(deployment, activeClient)) return

firstRun = false
if (activeClient != null) {
openLinkInActiveSession(params, activeClient, deployment.token)
} else {
Expand All @@ -630,7 +637,7 @@ class CoderRemoteProvider(
context.logger.logAndShowError(CAN_T_HANDLE_URI_TITLE, "Query parameter \"${URL}\" is missing from URI")
return null
}
val validationResult = deploymentURL.validateStrictWebUrl()
val validationResult = deploymentURL.validateStrictWebUrl(originOnly = true)
if (validationResult is Invalid) {
context.logger.logAndShowError(CAN_T_HANDLE_URI_TITLE, "\"$URL\" is invalid: ${validationResult.reason}")
return null
Expand All @@ -639,6 +646,12 @@ class CoderRemoteProvider(
val origin = requireNotNull(deploymentURL.toHttpUrlOrNull()?.origin()) {
"The deployment URL must have a valid HTTP(S) host and port."
}
val saved = context.secrets.readSavedDeploymentUrl(origin.toURL())
if (!saved.isNullOrEmpty() && saved.validateStrictWebUrl() !is Invalid && saved.toHttpUrlOrNull()
?.origin() == origin
) {
return saved.toURL()
}
return origin.toURL()
}

Expand Down Expand Up @@ -718,6 +731,7 @@ class CoderRemoteProvider(
}

private fun autoSetupCredentials(url: URL): Credentials? {
if (url.toString().validateStrictWebUrl() is Invalid) return null
if (context.settingsStore.requiresMTlsAuth) return Credentials.MTls

val tokenCredentials = context.secrets.apiTokenFor(url)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,14 @@ data class NetworkMetrics(
return if (p2p == true) {
"Direct (${formatter.format(latency)}ms). You're connected peer-to-peer"
} else {
val derpLatency = derpLatency!![preferredDerp]
val workspaceLatency = latency!!.minus(derpLatency!!)
"You ↔ $preferredDerp (${formatter.format(derpLatency)}ms) ↔ Workspace (${formatter.format(workspaceLatency)}ms). You are connected through a relay"
val relay = requireNotNull(preferredDerp) { "Relay metrics require a preferred relay." }
val relayLatency = requireNotNull(derpLatency?.get(relay)) {
"Relay metrics require latency for the preferred relay."
}
val totalLatency = requireNotNull(latency) { "Relay metrics require total latency." }
val workspaceLatency = totalLatency - relayLatency
"You ↔ $relay (${formatter.format(relayLatency)}ms) ↔ Workspace " +
"(${formatter.format(workspaceLatency)}ms). You are connected through a relay"
}
}
}
4 changes: 3 additions & 1 deletion src/main/kotlin/com/coder/toolbox/store/CoderSecretsStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class CoderSecretsStore(private val store: PluginSecretStore) {
fun isUrlTrusted(url: URL): Boolean {
val requested = url.toString().toHttpUrlOrNull() ?: return false
val origin = requested.origin()
val saved = store["deployment-url:$origin"]
val saved = readSavedDeploymentUrl(url)
return if (saved != null) {
saved.toHttpUrlOrNull() == requested
} else {
Expand All @@ -58,6 +58,8 @@ class CoderSecretsStore(private val store: PluginSecretStore) {
}
}

fun readSavedDeploymentUrl(url: URL): String? = url.origin()?.let { store["deployment-url:$it"] }

fun trustDeployment(url: URL) {
val address = requireNotNull(url.toString().toHttpUrlOrNull()) { "Deployment trust requires an HTTP(S) URL" }
val key = "deployment-url:${address.origin()}"
Expand Down
16 changes: 10 additions & 6 deletions src/main/kotlin/com/coder/toolbox/util/TLS.kt
Original file line number Diff line number Diff line change
Expand Up @@ -332,19 +332,23 @@ class ReloadableSSLSocketFactory(
private var delegate: SSLSocketFactory = loadSocketFactory()

private fun loadSocketFactory(): SSLSocketFactory {
if (!settings.certPath.isNullOrBlank() && !settings.keyPath.isNullOrBlank()) {
lastCertHash = sha1(FileInputStream(expand(settings.certPath!!)))
lastKeyHash = sha1(FileInputStream(expand(settings.keyPath!!)))
val certPath = settings.certPath
val keyPath = settings.keyPath
if (!certPath.isNullOrBlank() && !keyPath.isNullOrBlank()) {
lastCertHash = sha1(FileInputStream(expand(certPath)))
lastKeyHash = sha1(FileInputStream(expand(keyPath)))
}
return coderSocketFactory(settings)
}

fun reload(): Boolean {
if (settings.certPath.isNullOrBlank() || settings.keyPath.isNullOrBlank()) {
val certPath = settings.certPath
val keyPath = settings.keyPath
if (certPath.isNullOrBlank() || keyPath.isNullOrBlank()) {
return false
}
val newCertHash = sha1(FileInputStream(expand(settings.certPath!!)))
val newKeyHash = sha1(FileInputStream(expand(settings.keyPath!!)))
val newCertHash = sha1(FileInputStream(expand(certPath)))
val newKeyHash = sha1(FileInputStream(expand(keyPath)))
if (lastCertHash != newCertHash || lastKeyHash != newKeyHash) {
delegate = loadSocketFactory()
return true
Expand Down
69 changes: 33 additions & 36 deletions src/main/kotlin/com/coder/toolbox/util/URLExtensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import java.net.URI
import java.net.URL
import java.net.URLDecoder

private const val UNICODE_REPLACEMENT_CHARACTER = '\uFFFD'

fun String.toURL(): URL = URI.create(this).toURL()

/** Canonical HTTP(S) origin, without credentials or a path; default ports are omitted. */
Expand All @@ -34,40 +36,30 @@ fun String.toBaseURL(): URL {
return URI.create("${url.protocol}://${url.host}$port").toURL()
}

fun String.validateStrictWebUrl(): WebUrlValidationResult = try {
/** Validate the supplied text before URL normalization can discard unsafe components. */
fun String.validateStrictWebUrl(originOnly: Boolean = false): WebUrlValidationResult = try {
val uri = URI(this)
val address = toHttpUrlOrNull()
val rawPath = uri.rawPath.orEmpty()
val hasInvalidOrigin = address == null || uri.rawAuthority.isNullOrEmpty() || uri.isOpaque || address.port == 0
val hasForbiddenComponents = uri.rawUserInfo != null || uri.rawQuery != null || uri.rawFragment != null
val hasInvalidCharactersOrPathSegments = !SAFE_DEPLOYMENT_URL.matches(this) || rawPath.split('/').any { it == "." || it == ".." }
val hasUnexpectedPath = originOnly && rawPath.isNotEmpty() && rawPath != "/"

when {
uri.isOpaque -> Invalid(
"The URL \"$this\" is invalid because it is not in the standard format. " +
"Please enter a full web address like \"https://example.com\""
)

!uri.isAbsolute -> Invalid(
"The URL \"$this\" is missing a scheme (like https://). " +
"Please enter a full web address like \"https://example.com\""
)

uri.scheme?.lowercase() !in setOf("http", "https") ->
Invalid(
"The URL \"$this\" must start with http:// or https://, not \"${uri.scheme}\""
)

uri.authority.isNullOrBlank() ->
Invalid(
"The URL \"$this\" does not include a valid website name. " +
"Please enter a full web address like \"https://example.com\""
)
hasInvalidOrigin -> Invalid("The deployment URL must have a valid HTTP(S) host and port.")
hasForbiddenComponents -> Invalid("The deployment URL cannot include credentials, a query, or a fragment.")
hasInvalidCharactersOrPathSegments -> Invalid("The deployment URL contains unsupported characters or path segments.")
hasUnexpectedPath -> Invalid("A workspace link must specify a deployment origin without a path.")

else -> Valid
}
} catch (_: Exception) {
Invalid(
"The input \"$this\" is not a valid web address. " +
"Please enter a full web address like \"https://example.com\""
)
} catch (_: java.net.URISyntaxException) {
Invalid("The deployment URL must have a valid HTTP(S) host and port.")
}

private val SAFE_DEPLOYMENT_URL = Regex("""[\p{L}\p{N}._~:/\[\]+,=\-]+""")

fun URL.withPath(path: String): URL = URL(
this.protocol,
this.host,
Expand All @@ -81,17 +73,22 @@ fun URL.withPath(path: String): URL = URL(
*/
fun URL.safeHost(): String = IDN.toASCII(this.host, IDN.ALLOW_UNASSIGNED)

fun URI.toQueryParameters(): Map<String, String> = (this.query ?: "")
.split("&").filter {
it.isNotEmpty()
}.associate {
val parts = it.split("=", limit = 2)
if (parts.size == 2) {
parts[0] to URLDecoder.decode(parts[1], Charsets.UTF_8)
} else {
parts[0] to ""
}
fun URI.toQueryParameters(): Map<String, String> = buildMap {
for (field in rawQuery.orEmpty().split('&')) {
if (field.isEmpty()) continue
val name = decodeQueryComponent(field.substringBefore('='))
val value = decodeQueryComponent(field.substringAfter('=', ""))
// Keep the first value when a parameter name appears more than once.
putIfAbsent(name, value)
}
}

private fun decodeQueryComponent(raw: String): String {
val decoded = URLDecoder.decode(raw, Charsets.UTF_8)
// URLDecoder replaces malformed UTF-8 with the Unicode replacement character (U+FFFD).
require(UNICODE_REPLACEMENT_CHARACTER !in decoded) { "Invalid query parameter encoding." }
return decoded
}

sealed class WebUrlValidationResult {
object Valid : WebUrlValidationResult()
Expand Down
10 changes: 7 additions & 3 deletions src/main/kotlin/com/coder/toolbox/util/WorkspaceFilterQuery.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,14 @@ fun String.parseFilterQuery(): Map<String, String> {
*/
fun Map<String, String?>.stringifyFilterQuery(): String =
entries
.filter { !it.value.isNullOrBlank() }
.joinToString(" ") { (key, value) ->
if (value!!.contains(" ")) "$key:\"$value\"" else "$key:$value"
.mapNotNull { (key, value) ->
when {
value.isNullOrBlank() -> null
value.contains(" ") -> "$key:\"$value\""
else -> "$key:$value"
}
}
.joinToString(" ")

/**
* Returns a copy of this query with [key] set to [value], preserving the other terms and their
Expand Down
Loading
Loading