diff --git a/CHANGELOG.md b/CHANGELOG.md index 33cb8204..6861bb50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/main/kotlin/com/coder/toolbox/CoderRemoteProvider.kt b/src/main/kotlin/com/coder/toolbox/CoderRemoteProvider.kt index 9cad4054..98430960 100644 --- a/src/main/kotlin/com/coder/toolbox/CoderRemoteProvider.kt +++ b/src/main/kotlin/com/coder/toolbox/CoderRemoteProvider.kt @@ -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") @@ -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 } } @@ -587,6 +592,7 @@ class CoderRemoteProvider( onConnect = onConnect, onTokenRefreshed = ::onTokenRefreshed, ) + firstRun = false router.navigate(wizard) context.envPageManager.showPluginEnvironmentsPage(false) @@ -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 { @@ -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 @@ -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() } @@ -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) diff --git a/src/main/kotlin/com/coder/toolbox/sdk/v2/models/NetworkMetrics.kt b/src/main/kotlin/com/coder/toolbox/sdk/v2/models/NetworkMetrics.kt index cb7d2358..f45af98f 100644 --- a/src/main/kotlin/com/coder/toolbox/sdk/v2/models/NetworkMetrics.kt +++ b/src/main/kotlin/com/coder/toolbox/sdk/v2/models/NetworkMetrics.kt @@ -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" } } } diff --git a/src/main/kotlin/com/coder/toolbox/store/CoderSecretsStore.kt b/src/main/kotlin/com/coder/toolbox/store/CoderSecretsStore.kt index 192f6bdc..3f333727 100644 --- a/src/main/kotlin/com/coder/toolbox/store/CoderSecretsStore.kt +++ b/src/main/kotlin/com/coder/toolbox/store/CoderSecretsStore.kt @@ -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 { @@ -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()}" diff --git a/src/main/kotlin/com/coder/toolbox/util/TLS.kt b/src/main/kotlin/com/coder/toolbox/util/TLS.kt index bca20619..0ea481f2 100644 --- a/src/main/kotlin/com/coder/toolbox/util/TLS.kt +++ b/src/main/kotlin/com/coder/toolbox/util/TLS.kt @@ -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 diff --git a/src/main/kotlin/com/coder/toolbox/util/URLExtensions.kt b/src/main/kotlin/com/coder/toolbox/util/URLExtensions.kt index 72364b77..08d25f07 100644 --- a/src/main/kotlin/com/coder/toolbox/util/URLExtensions.kt +++ b/src/main/kotlin/com/coder/toolbox/util/URLExtensions.kt @@ -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. */ @@ -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, @@ -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 = (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 = 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() diff --git a/src/main/kotlin/com/coder/toolbox/util/WorkspaceFilterQuery.kt b/src/main/kotlin/com/coder/toolbox/util/WorkspaceFilterQuery.kt index 239c88fc..d2b9d5f4 100644 --- a/src/main/kotlin/com/coder/toolbox/util/WorkspaceFilterQuery.kt +++ b/src/main/kotlin/com/coder/toolbox/util/WorkspaceFilterQuery.kt @@ -33,10 +33,14 @@ fun String.parseFilterQuery(): Map { */ fun Map.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 diff --git a/src/test/kotlin/com/coder/toolbox/CoderRemoteProviderTest.kt b/src/test/kotlin/com/coder/toolbox/CoderRemoteProviderTest.kt index eef4a809..657edbbe 100644 --- a/src/test/kotlin/com/coder/toolbox/CoderRemoteProviderTest.kt +++ b/src/test/kotlin/com/coder/toolbox/CoderRemoteProviderTest.kt @@ -25,9 +25,9 @@ import com.coder.toolbox.util.InMemoryPluginSecretStore import com.coder.toolbox.util.pluginTestSettingsStore import com.coder.toolbox.views.CoderSetupWizardPage import com.coder.toolbox.views.SuspendBiConsumer +import com.coder.toolbox.views.state.ConnectionOrigin import com.coder.toolbox.views.state.PageRouter import com.coder.toolbox.views.state.StoredOAuthSession -import com.coder.toolbox.views.state.ConnectionOrigin import com.coder.toolbox.views.state.WizardStep import com.coder.toolbox.views.state.toSessionContext import com.jetbrains.toolbox.api.core.diagnostics.Logger @@ -229,7 +229,8 @@ class CoderRemoteProviderTest { val url = mockCli.deploymentURL val stored = storedOAuthSession() val session = stored.toSessionContext() - val refreshed = session.tokenResponse!!.copy(accessToken = "new-access-token", refreshToken = "new-refresh-token") + val refreshed = + session.tokenResponse!!.copy(accessToken = "new-access-token", refreshToken = "new-refresh-token") val secrets = mockContext.secrets every { secrets.oauthSessionFor(url.toString()) } returns stored every { mockContext.deploymentUrl } returns url @@ -709,10 +710,10 @@ class CoderRemoteProviderTest { } @CsvSource( - "restoring deployment, link target, expected origin", - "$PRODUCTION_URL, $STAGING_URL/, $STAGING_URL", - "$STAGING_URL, $PRODUCTION_URL/dashboard?view=recent#workspaces, $PRODUCTION_URL", - "$PRODUCTION_URL, $STAGING_URL:8443/dashboard, $STAGING_URL:8443", + "restoring deployment, link target, expected origin", + "$PRODUCTION_URL, $STAGING_URL/, $STAGING_URL", + "$STAGING_URL, https://CODER.example.com:443, $PRODUCTION_URL", + "$PRODUCTION_URL, $STAGING_URL:8443, $STAGING_URL:8443", useHeadersInDisplayName = true, ) @ParameterizedTest(name = "Cold-start link, {arguments}") @@ -799,7 +800,10 @@ class CoderRemoteProviderTest { assertNull(remoteProvider.getOverrideUiPage(), "Finishing link sign-in should show the workspace list") displayedWizard.captured.afterHide() } - assertNull(remoteProvider.getOverrideUiPage(), "The first lookup should restore the saved session in the background") + assertNull( + remoteProvider.getOverrideUiPage(), + "The first lookup should restore the saved session in the background" + ) runCurrent() assertTrue(restoreStarted.isCompleted) remoteProvider.handleUri(workspaceLink(linkedDeployment.toString())) @@ -809,9 +813,19 @@ class CoderRemoteProviderTest { verify(exactly = 1) { anyConstructed().close() } coVerify(exactly = 1) { mockCli.login("link-token") } verify(exactly = 1) { secrets.storeApiTokenFor(linkedDeployment, "link-token") } - coVerify(exactly = 1) { linkHandler.handle(match { it["workspace"] == "dev" }, linkedDeployment, any(), mockCli) } + coVerify(exactly = 1) { + linkHandler.handle( + match { it["workspace"] == "dev" }, + linkedDeployment, + any(), + mockCli + ) + } verify(exactly = 1) { environmentsPage.showPluginEnvironmentsPage(false) } - assertNull(remoteProvider.getOverrideUiPage(), "The workspace list should still be visible after the handoff") + assertNull( + remoteProvider.getOverrideUiPage(), + "The workspace list should still be visible after the handoff" + ) } finally { remoteProvider.close() unmockkStatic(::ensureCLI) @@ -836,7 +850,6 @@ class CoderRemoteProviderTest { val targets = listOf( "https://coder.example.com", "https://CODER.example.com:443/", - "https://coder.example.com/different/path/", ) for (target in targets) { provider.handleUri(workspaceLink(target)) @@ -901,7 +914,7 @@ class CoderRemoteProviderTest { coEvery { provider["userForToken"](url, "link-token") } returns user coEvery { provider["userForToken"](url, "saved-token") } returns user - provider.handleUri(workspaceLink("https://CODER.example.com:443/different/path")) + provider.handleUri(workspaceLink("https://CODER.example.com:443/")) val page = provider.getOverrideUiPage() as CoderSetupWizardPage assertEquals(WizardStep.Connecting(ConnectionOrigin.SUPPLIED_CREDENTIALS), page.model.currentStep()) @@ -1105,6 +1118,7 @@ class CoderRemoteProviderTest { @CsvSource( "true, jetbrains://gateway/com.coder.toolbox?url=https://coder.example.com", "false, jetbrains://gateway/com.coder.toolbox?url=https://coder.example.com&token=", + "false, jetbrains://gateway/com.coder.toolbox?url=https://coder.example.com&token=&token=later", "false, jetbrains://gateway/com.coder.toolbox?url=https://other.example.com&token=%20", ) @ParameterizedTest(name = "Reject {1} when connected={0}") @@ -1135,12 +1149,33 @@ class CoderRemoteProviderTest { } @Test - fun `known certificate deployment reopens without a trust prompt`() = runTest { + fun `an origin-only link preserves the saved deployment base path`() = runTest { + val origin = URI("https://coder.example.com").toURL() + val saved = "https://coder.example.com/team/" + every { mockContext.settingsStore.requiresMTlsAuth } returns true + every { mockContext.secrets.readSavedDeploymentUrl(origin) } returns saved + every { mockContext.secrets.isUrlTrusted(URI(saved).toURL()) } returns true + + remoteProvider.handleUri(URI("jetbrains://gateway/coder?url=https://coder.example.com/")) + + val page = remoteProvider.getOverrideUiPage() as CoderSetupWizardPage + assertEquals(saved, page.model.url.toString()) + coVerify(exactly = 0) { mockUi.showYesNoPopup(any(), any(), any(), any()) } + } + + @ValueSource( + strings = [ + "jetbrains://gateway/com.coder.toolbox?url=https://coder.example.com/", + "jetbrains://gateway/com.coder.toolbox?url=https://coder.example.com/&%75rl=https://other.example.com", + ] + ) + @ParameterizedTest + fun `known certificate deployment reopens without a trust prompt`(link: String) = runTest { every { mockContext.settingsStore.requiresMTlsAuth } returns true every { mockContext.settingsStore.requiresTokenAuth } returns false every { mockContext.secrets.isUrlTrusted(URI("https://coder.example.com").toURL()) } returns true - remoteProvider.handleUri(URI("jetbrains://gateway/com.coder.toolbox?url=https://coder.example.com/path")) + remoteProvider.handleUri(URI(link)) val page = remoteProvider.getOverrideUiPage() as CoderSetupWizardPage assertEquals("https://coder.example.com", page.model.url.toString()) @@ -1219,27 +1254,28 @@ class CoderRemoteProviderTest { @Test @OptIn(ExperimentalCoroutinesApi::class) - fun `returning from Settings after sign-in opens the workspace list once even if beforeShow runs twice`() = runTest { - every { mockContext.cs } returns backgroundScope - coEvery { mockClient.workspaces(any()) } returns emptyList() - val wizard = remoteProvider.getOverrideUiPage() as CoderSetupWizardPage - val pages = mockContext.envPageManager - wizard.beforeShow() - runCurrent() - wizard.afterHide() + fun `returning from Settings after sign-in opens the workspace list once even if beforeShow runs twice`() = + runTest { + every { mockContext.cs } returns backgroundScope + coEvery { mockClient.workspaces(any()) } returns emptyList() + val wizard = remoteProvider.getOverrideUiPage() as CoderSetupWizardPage + val pages = mockContext.envPageManager + wizard.beforeShow() + runCurrent() + wizard.afterHide() - completeSignIn() - runCurrent() - verify(exactly = 0) { pages.showPluginEnvironmentsPage(false) } - assertNull(remoteProvider.getOverrideUiPage()) + completeSignIn() + runCurrent() + verify(exactly = 0) { pages.showPluginEnvironmentsPage(false) } + assertNull(remoteProvider.getOverrideUiPage()) - // Both visibility callbacks arrive before the step observer runs. - repeat(2) { wizard.beforeShow() } - runCurrent() - verify(exactly = 1) { pages.showPluginEnvironmentsPage(false) } - wizard.afterHide() - remoteProvider.close() - } + // Both visibility callbacks arrive before the step observer runs. + repeat(2) { wizard.beforeShow() } + runCurrent() + verify(exactly = 1) { pages.showPluginEnvironmentsPage(false) } + wizard.afterHide() + remoteProvider.close() + } @Suppress("UNCHECKED_CAST") private suspend fun completeSignIn() { @@ -1300,7 +1336,7 @@ class CoderRemoteProviderTest { coEvery { mockUi.showYesNoPopup(any(), any(), any(), any()) } returns false val i18n = mockContext.i18n - remoteProvider.handleUri(workspaceLink("https://user:password@OTHER.example.com:8443/path")) + remoteProvider.handleUri(workspaceLink("https://OTHER.example.com:8443/")) verify { i18n.pnotr(match { @@ -1320,6 +1356,42 @@ class CoderRemoteProviderTest { verify { underlyingLogger.error(match { it.contains("valid HTTP(S) host and port") }) } } + @ValueSource( + strings = [ + "jetbrains://gateway/coder?url=https://coder.example.com/team&token=private-value", + "jetbrains://gateway/com.coder.toolbox/auth-extra?code=private-value", + "jetbrains://gateway/com.coder.toolbox?url=https://user@host&token=private-value", + ] + ) + @ParameterizedTest + fun `invalid workspace links and OAuth callbacks stop before sign-in`(link: String) = runTest { + remoteProvider.handleUri(URI(link)) + + verify { underlyingLogger.error(any()) } + verify(exactly = 0) { underlyingLogger.error(match { it.contains("private-value") }) } + coVerify(exactly = 0) { mockUi.showYesNoPopup(any(), any(), any(), any()) } + verify(exactly = 0) { mockContext.secrets.apiTokenFor(any()) } + verify(exactly = 0) { mockContext.popupPluginMainPage() } + } + + @Test + fun `rejecting a cold-start link preserves the saved deployment for session restore`() = runTest { + val savedUrl = URI(PRODUCTION_URL).toURL() + every { mockContext.cs } returns backgroundScope + every { mockContext.deploymentUrl } returns savedUrl + every { mockContext.settingsStore.requiresMTlsAuth } returns false + every { mockContext.settingsStore.requiresTokenAuth } returns true + every { mockContext.secrets.apiTokenFor(savedUrl) } returns "saved-token" + + remoteProvider.handleUri(URI("jetbrains://gateway/com.coder.toolbox/unknown")) + + assertNull(remoteProvider.getOverrideUiPage()) + val wizard = setupWizard(remoteProvider) + assertEquals(savedUrl, wizard.model.url) + assertEquals("saved-token", wizard.model.token) + assertEquals(WizardStep.Connecting(ConnectionOrigin.SAVED_SESSION), wizard.model.currentStep()) + } + private fun workspaceLink(url: String): URI = URI( "jetbrains://gateway/com.coder.toolbox?url=${URLEncoder.encode(url, Charsets.UTF_8)}" + "&token=link-token&workspace=dev" @@ -1381,7 +1453,10 @@ class CoderRemoteProviderTest { assertEquals(WizardStep.Connecting(ConnectionOrigin.SAVED_SESSION), model.currentStep()) assertEquals(expectedApiToken, model.token) - assertEquals(if (expectOAuth) requireNotNull(savedOAuthSession).toSessionContext() else null, model.oauthSession) + assertEquals( + if (expectOAuth) requireNotNull(savedOAuthSession).toSessionContext() else null, + model.oauthSession + ) } @Test diff --git a/src/test/kotlin/com/coder/toolbox/cli/CoderCLIManagerTest.kt b/src/test/kotlin/com/coder/toolbox/cli/CoderCLIManagerTest.kt index d0a6fe18..dddce900 100644 --- a/src/test/kotlin/com/coder/toolbox/cli/CoderCLIManagerTest.kt +++ b/src/test/kotlin/com/coder/toolbox/cli/CoderCLIManagerTest.kt @@ -179,7 +179,7 @@ internal class CoderCLIManagerTest { @Test @EnabledOnOs(LINUX, MAC) fun `support bundle scopes deployment workspace and optional agent without shell interpolation`() = runBlocking { - val root = java.nio.file.Files.createTempDirectory("coder bundle test") + val root = Files.createTempDirectory("coder bundle test") val binary = root.resolve("coder") binary.toFile().writeText( """#!/bin/sh @@ -488,7 +488,10 @@ internal class CoderCLIManagerTest { @Test fun testDownloadRealCLI() { val url = System.getenv("CODER_TOOLBOX_TEST_DEPLOYMENT") - assumeTrue(!url.isNullOrBlank() && url != "mock", "Set a deployment that serves its CLI without a cross-origin redirect.") + assumeTrue( + !url.isNullOrBlank() && url != "mock", + "Set a deployment that serves its CLI without a cross-origin redirect." + ) val ccm = CoderCLIManager( context.copy( diff --git a/src/test/kotlin/com/coder/toolbox/feed/IdeFeedManagerOfflineTest.kt b/src/test/kotlin/com/coder/toolbox/feed/IdeFeedManagerOfflineTest.kt index 484631db..3e93f94f 100644 --- a/src/test/kotlin/com/coder/toolbox/feed/IdeFeedManagerOfflineTest.kt +++ b/src/test/kotlin/com/coder/toolbox/feed/IdeFeedManagerOfflineTest.kt @@ -21,6 +21,7 @@ import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.nio.file.Path +import java.nio.file.Paths import kotlin.io.path.writeText class IdeFeedManagerOfflineTest { @@ -276,7 +277,7 @@ class IdeFeedManagerOfflineTest { fun `given cache files are missing when loading ides then it handles gracefully and returns empty list`() = runTest { // Given: cache files are deleted/missing - val tempDir = java.nio.file.Paths.get(context.settingsStore.globalDataDirectory) + val tempDir = Paths.get(context.settingsStore.globalDataDirectory) tempDir.resolve("release.json").toFile().delete() tempDir.resolve("eap.json").toFile().delete() @@ -305,7 +306,7 @@ class IdeFeedManagerOfflineTest { IdeRelease("241.1", "2024.1", IdeType.RELEASE, "2024-01-01") ) ) - val tempDir = java.nio.file.Paths.get(context.settingsStore.globalDataDirectory) + val tempDir = Paths.get(context.settingsStore.globalDataDirectory) writeProductsToFile(tempDir.resolve("release.json"), listOf(nullBuildProduct, validProduct)) val newIdeFeedManager = IdeFeedManager(context, null) { true } diff --git a/src/test/kotlin/com/coder/toolbox/sdk/v2/models/NetworkMetricsTest.kt b/src/test/kotlin/com/coder/toolbox/sdk/v2/models/NetworkMetricsTest.kt index 08b98df9..3cc67159 100644 --- a/src/test/kotlin/com/coder/toolbox/sdk/v2/models/NetworkMetricsTest.kt +++ b/src/test/kotlin/com/coder/toolbox/sdk/v2/models/NetworkMetricsTest.kt @@ -2,6 +2,7 @@ package com.coder.toolbox.sdk.v2.models import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith class NetworkMetricsTest { @@ -85,6 +86,29 @@ class NetworkMetricsTest { assertEquals(expected, metrics.toPretty()) } + @Test + fun `toPretty rejects incomplete relay metrics with a clear error`() { + val metrics = NetworkMetrics( + p2p = false, + latency = 80.0, + preferredDerp = "derp1", + derpLatency = mapOf("derp1" to 30.0), + uploadBytesSec = null, + downloadBytesSec = null, + usingCoderConnect = false + ) + val cases = listOf( + metrics.copy(preferredDerp = null) to "Relay metrics require a preferred relay.", + metrics.copy(derpLatency = null) to "Relay metrics require latency for the preferred relay.", + metrics.copy(derpLatency = emptyMap()) to "Relay metrics require latency for the preferred relay.", + metrics.copy(latency = null) to "Relay metrics require total latency." + ) + for ((incompleteMetrics, message) in cases) { + val error = assertFailsWith { incompleteMetrics.toPretty() } + assertEquals(message, error.message) + } + } + @Test fun `toPretty should round and pad latencies correctly for DERP`() { val metrics = NetworkMetrics( @@ -104,4 +128,4 @@ class NetworkMetricsTest { val expected = "You ↔ derp2 (23.50ms) ↔ Workspace (54.63ms). You are connected through a relay" assertEquals(expected, metrics.toPretty()) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/com/coder/toolbox/util/CoderProtocolHandlerTest.kt b/src/test/kotlin/com/coder/toolbox/util/CoderProtocolHandlerTest.kt index 7e94c978..a945fbb9 100644 --- a/src/test/kotlin/com/coder/toolbox/util/CoderProtocolHandlerTest.kt +++ b/src/test/kotlin/com/coder/toolbox/util/CoderProtocolHandlerTest.kt @@ -33,12 +33,12 @@ import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.BeforeEach import java.net.URI import java.util.UUID import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull import kotlin.test.fail class CoderProtocolHandlerTest { @@ -182,7 +182,7 @@ class CoderProtocolHandlerTest { runBlocking { testCases.forEach { testCase -> - kotlin.test.assertEquals( + assertEquals( testCase.expectedAgentId, handler.getMatchingAgent(testCase.params, ws)?.id, "Failed: ${testCase.description}" @@ -221,7 +221,7 @@ class CoderProtocolHandlerTest { runBlocking { testCases.forEach { testCase -> - kotlin.test.assertNull( + assertNull( handler.getMatchingAgent(testCase.params, ws)?.id, "Failed: ${testCase.description}" ) @@ -253,7 +253,7 @@ class CoderProtocolHandlerTest { runBlocking { testCases.forEach { testCase -> - kotlin.test.assertEquals( + assertEquals( testCase.expectedAgentId, handler.getMatchingAgent(testCase.params, ws)?.id, "Failed: ${testCase.description}" @@ -272,7 +272,7 @@ class CoderProtocolHandlerTest { ) runBlocking { - kotlin.test.assertNull( + assertNull( handler.getMatchingAgent(testCase.params, ws), "Failed: ${testCase.description}" ) @@ -304,7 +304,7 @@ class CoderProtocolHandlerTest { runBlocking { testCases.forEach { testCase -> - kotlin.test.assertNull( + assertNull( handler.getMatchingAgent(testCase.params, ws), "Failed: ${testCase.description}" ) diff --git a/src/test/kotlin/com/coder/toolbox/util/ProcessRunnerTest.kt b/src/test/kotlin/com/coder/toolbox/util/ProcessRunnerTest.kt index 9fd36438..e093d9bf 100644 --- a/src/test/kotlin/com/coder/toolbox/util/ProcessRunnerTest.kt +++ b/src/test/kotlin/com/coder/toolbox/util/ProcessRunnerTest.kt @@ -132,7 +132,7 @@ internal class ProcessRunnerTest { @Test @IgnoreOnWindows fun `runProcess terminates the process on timeout`() { - val pidFile = java.nio.file.Files.createTempFile("coder-process-timeout", ".pid") + val pidFile = Files.createTempFile("coder-process-timeout", ".pid") try { assertFailsWith { runProcess( @@ -143,7 +143,7 @@ internal class ProcessRunnerTest { val pid = pidFile.toFile().readText().trim().toLong() assertFalse(ProcessHandle.of(pid).map { it.isAlive }.orElse(false)) } finally { - java.nio.file.Files.deleteIfExists(pidFile) + Files.deleteIfExists(pidFile) } } diff --git a/src/test/kotlin/com/coder/toolbox/util/URLExtensionsTest.kt b/src/test/kotlin/com/coder/toolbox/util/URLExtensionsTest.kt index 01e303fd..d0533534 100644 --- a/src/test/kotlin/com/coder/toolbox/util/URLExtensionsTest.kt +++ b/src/test/kotlin/com/coder/toolbox/util/URLExtensionsTest.kt @@ -98,89 +98,63 @@ internal class URLExtensionsTest { } @Test - fun `valid https URL with path and query should return Valid`() { - val result = "https://coder.com/bin/coder-linux-amd64?query=1".validateStrictWebUrl() - assertEquals(WebUrlValidationResult.Valid, result) - } - - @Test - fun `relative URL should return Invalid with appropriate message`() { - val url = "/bin/coder-linux-amd64" - val result = url.validateStrictWebUrl() - assertEquals( - WebUrlValidationResult.Invalid("The URL \"/bin/coder-linux-amd64\" is missing a scheme (like https://). Please enter a full web address like \"https://example.com\""), - result - ) - } - - @Test - fun `opaque URI like mailto should return Invalid`() { - val url = "mailto:user@coder.com" - val result = url.validateStrictWebUrl() - assertEquals( - WebUrlValidationResult.Invalid("The URL \"mailto:user@coder.com\" is invalid because it is not in the standard format. Please enter a full web address like \"https://example.com\""), - result - ) - } - - @Test - fun `unsupported scheme like ftp should return Invalid`() { - val url = "ftp://coder.com" - val result = url.validateStrictWebUrl() - assertEquals( - WebUrlValidationResult.Invalid("The URL \"ftp://coder.com\" must start with http:// or https://, not \"ftp\""), - result - ) + fun `manual setup accepts base paths and links require an origin`() { + val url = "https://coder.example.com/team/" + assertEquals(WebUrlValidationResult.Valid, url.validateStrictWebUrl()) + assertTrue(url.validateStrictWebUrl(originOnly = true) is WebUrlValidationResult.Invalid) + for (origin in listOf("http://localhost:3000", "https://[::1]:8443/", "https://ほげ.example/")) { + assertEquals(WebUrlValidationResult.Valid, origin.validateStrictWebUrl(originOnly = true)) + } } @Test - fun `http URL with missing authority should return Invalid`() { - val url = "http:///bin/coder-linux-amd64" - val result = url.validateStrictWebUrl() - assertEquals( - WebUrlValidationResult.Invalid("The URL \"http:///bin/coder-linux-amd64\" does not include a valid website name. Please enter a full web address like \"https://example.com\""), - result - ) + fun `invalid deployment URLs are rejected without displaying their values`() { + for (url in listOf( + "/relative", "file:///tmp", "https:/missing", "https:coder.example.com", "https://host:99999", + "https://user@host", "https://host/?private", "https://host/#private", "https://host/a%20b", + "https://host/dollar$", "https://host/../team", "https://host;other" + )) { + val result = url.validateStrictWebUrl() + assertTrue(result is WebUrlValidationResult.Invalid) + assertFalse(result.reason.contains(url)) + } } @Test - fun `malformed URI should return Invalid with parsing error message`() { - val url = "http://[invalid-uri]" - val result = url.validateStrictWebUrl() - assertEquals( - WebUrlValidationResult.Invalid("The input \"http://[invalid-uri]\" is not a valid web address. Please enter a full web address like \"https://example.com\""), - result - ) + fun `query components are split before decoding and decoded exactly once`() { + val params = URI("jetbrains://gateway/coder?folder=a%26b%3Dc%2B%252F&owner=a+b").toQueryParameters() + assertEquals(mapOf("folder" to "a&b=c+%2F", "owner" to "a b"), params) } @Test - fun `URI without colon should return Invalid as URI is not absolute`() { - val url = "http//coder.com" - val result = url.validateStrictWebUrl() - assertEquals( - WebUrlValidationResult.Invalid("The URL \"http//coder.com\" is missing a scheme (like https://). Please enter a full web address like \"https://example.com\""), - result - ) + fun `repeated query parameters keep their first value after decoding names`() { + for (name in listOf("url", "token", "state", "code", "error", "folder", "tag")) { + val encodedName = "%${name.first().code.toString(16)}${name.drop(1)}" + for (query in listOf( + "$name=a&$name=a", + "$name=a&$name=b", + "$name=a&$encodedName=b", + "$encodedName=a&$name=b" + )) { + assertEquals(mapOf(name to "a"), URI("jetbrains://gateway/coder?$query").toQueryParameters(), query) + } + } } @Test - fun `URI without double forward slashes should return Invalid because the URI is not hierarchical`() { - val url = "http:coder.com" - val result = url.validateStrictWebUrl() - assertEquals( - WebUrlValidationResult.Invalid("The URL \"http:coder.com\" is invalid because it is not in the standard format. Please enter a full web address like \"https://example.com\""), - result - ) + fun `repeated query parameters preserve an empty first value`() { + for (query in listOf("token=&token=later", "token&%74oken=later")) { + assertEquals(mapOf("token" to ""), URI("jetbrains://gateway/coder?$query").toQueryParameters(), query) + } } @Test - fun `URI without a single forward slash should return Invalid because the URI does not have a hostname`() { - val url = "https:/coder.com" - val result = url.validateStrictWebUrl() - assertEquals( - WebUrlValidationResult.Invalid("The URL \"https:/coder.com\" does not include a valid website name. Please enter a full web address like \"https://example.com\""), - result - ) + fun `malformed query encoding is rejected for all parameters`() { + for (query in listOf("token=%FF", "folder=%FF", "%FF=value")) { + assertFailsWith(query) { + URI("jetbrains://gateway/coder?$query").toQueryParameters() + } + } } @Test diff --git a/src/test/kotlin/com/coder/toolbox/util/WorkspaceFilterQueryTest.kt b/src/test/kotlin/com/coder/toolbox/util/WorkspaceFilterQueryTest.kt index d4334ac4..45c8a509 100644 --- a/src/test/kotlin/com/coder/toolbox/util/WorkspaceFilterQueryTest.kt +++ b/src/test/kotlin/com/coder/toolbox/util/WorkspaceFilterQueryTest.kt @@ -26,7 +26,13 @@ class WorkspaceFilterQueryTest { fun `stringify quotes values with spaces and drops blanks`() { assertEquals( "owner:me template:\"Heaven 3\"", - linkedMapOf("owner" to "me", "template" to "Heaven 3", "status" to null).stringifyFilterQuery() + linkedMapOf( + "owner" to "me", + "template" to "Heaven 3", + "status" to null, + "name" to "", + "organization" to " " + ).stringifyFilterQuery() ) }