diff --git a/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java b/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java index 20ac611a9..1dd6e9afc 100644 --- a/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java +++ b/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java @@ -18,6 +18,7 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; +import io.appium.java_client.AppiumClientConfig; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.options.UiAutomator2Options; import org.junit.jupiter.api.AfterEach; @@ -37,6 +38,7 @@ import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; @@ -261,4 +263,23 @@ void failsToProvideBiDiWithoutTheWebSocketUrlCapability() throws IOException { assertThrows(BiDiException.class, seleniumDriver::getHandle); } + + @Test + void propagatesDirectConnectServerUrlToSeleniumClientConfig() throws IOException { + extraCapabilities = "\"appium:directConnectProtocol\":\"https\"," + + "\"appium:directConnectHost\":\"203.0.113.1\"," + + "\"appium:directConnectPort\":4443," + + "\"appium:directConnectPath\":\"/wd/hub\","; + var clientConfig = AppiumClientConfig.defaultConfig() + .baseUri(URI.create("http://127.0.0.1:" + server.getAddress().getPort())) + .directConnect(true); + var appiumDriver = new AndroidDriver(clientConfig, + new UiAutomator2Options().setDeviceName("Android Emulator")); + + var seleniumDriver = SeleniumBridge.asRemoteWebDriver(appiumDriver); + + assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"), + seleniumDriver.getClientConfig().baseUri()); + seleniumDriver.closeBiDi(); + } } diff --git a/src/main/java/io/appium/java_client/AppiumDriver.java b/src/main/java/io/appium/java_client/AppiumDriver.java index ccdfffd13..c471fbf50 100644 --- a/src/main/java/io/appium/java_client/AppiumDriver.java +++ b/src/main/java/io/appium/java_client/AppiumDriver.java @@ -31,7 +31,7 @@ import io.appium.java_client.remote.options.BaseOptions; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; -import lombok.Getter; +import org.jspecify.annotations.Nullable; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.OutputType; @@ -64,8 +64,6 @@ public class AppiumDriver extends AppiumRemoteWebDriver implements private static final ErrorHandler ERROR_HANDLER = new ErrorHandler(new ErrorCodesMobile()); // frequently used command parameters - @Getter - private final URL remoteAddress; private final ExecuteMethod executeMethod; /** @@ -80,7 +78,6 @@ public AppiumDriver(AppiumCommandExecutor executor, Capabilities capabilities) { super(executor, capabilities); this.executeMethod = new AppiumExecutionMethod(this); super.setErrorHandler(ERROR_HANDLER); - this.remoteAddress = executor.getAddressOfRemoteServer(); } /** @@ -216,11 +213,20 @@ public AppiumDriver(URL remoteSessionAddress, String platformName, String automa setCommandExecutor(executor); this.executeMethod = new AppiumExecutionMethod(this); super.setErrorHandler(ERROR_HANDLER); - this.remoteAddress = executor.getAddressOfRemoteServer(); setSessionId(sessionAddress.getId()); } + /** + * Gets the remote server address to which commands are sent. + * + * @return the remote server URL, or {@code null} if not configured + */ + @Nullable + public URL getRemoteAddress() { + return ((AppiumCommandExecutor) getCommandExecutor()).getAddressOfRemoteServer(); + } + @Override public ExecuteMethod getExecuteMethod() { return executeMethod; diff --git a/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java b/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java index d3fcb5c7c..8717ace42 100644 --- a/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java +++ b/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java @@ -18,13 +18,9 @@ import io.appium.java_client.CommandExecutionHelper; import io.appium.java_client.ExecutesMethod; -import io.appium.java_client.remote.AppiumCommandExecutor; -import io.appium.java_client.remote.AppiumRemoteWebDriver; -import io.appium.java_client.remote.SessionId; +import io.appium.java_client.internal.LogBroadcastEndpoints; import io.appium.java_client.ws.StringWebSocketClient; -import java.net.URI; -import java.net.URL; import java.util.function.Consumer; import static io.appium.java_client.service.local.AppiumServiceBuilder.DEFAULT_APPIUM_PORT; @@ -64,13 +60,7 @@ default void startLogcatBroadcast(String host) { * @param port the port of the host where Appium server is running */ default void startLogcatBroadcast(String host, int port) { - var remoteWebDriver = (AppiumRemoteWebDriver) this; - URL serverUrl = ((AppiumCommandExecutor) remoteWebDriver.getCommandExecutor()).getAddressOfRemoteServer(); - var scheme = "https".equals(serverUrl.getProtocol()) ? "wss" : "ws"; - CommandExecutionHelper.executeScript(this, "mobile: startLogsBroadcast"); - SessionId sessionId = remoteWebDriver.getSessionId(); - var endpoint = String.format("%s://%s:%s/ws/session/%s/appium/device/logcat", scheme, host, port, sessionId); - getLogcatClient().connect(URI.create(endpoint)); + LogBroadcastEndpoints.startBroadcast(this, getLogcatClient(), host, port, "logcat"); } /** diff --git a/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java b/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java new file mode 100644 index 000000000..818ec3381 --- /dev/null +++ b/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java @@ -0,0 +1,93 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.appium.java_client.internal; + +import io.appium.java_client.CommandExecutionHelper; +import io.appium.java_client.ExecutesMethod; +import io.appium.java_client.remote.AppiumCommandExecutor; +import io.appium.java_client.remote.AppiumRemoteWebDriver; +import io.appium.java_client.remote.SessionId; +import io.appium.java_client.ws.StringWebSocketClient; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.net.URI; +import java.net.URL; + +/** + * Shared endpoint resolution and WebSocket startup helpers for device log broadcast listeners. + */ +@NullMarked +public final class LogBroadcastEndpoints { + private LogBroadcastEndpoints() { + } + + /** + * Starts server-side log streaming and connects the WebSocket client to the broadcast endpoint. + * + * @param driver the driver executing {@code mobile: startLogsBroadcast} + * @param client the target WebSocket client + * @param host the target WebSocket host + * @param port the target WebSocket port + * @param deviceLogType the log endpoint suffix (such as {@code logcat} or {@code syslog}) + */ + public static void startBroadcast( + ExecutesMethod driver, + StringWebSocketClient client, + String host, + int port, + String deviceLogType + ) { + var remoteWebDriver = (AppiumRemoteWebDriver) driver; + var executor = (AppiumCommandExecutor) remoteWebDriver.getCommandExecutor(); + CommandExecutionHelper.executeScript(driver, "mobile: startLogsBroadcast"); + URI endpoint = buildBroadcastUri( + executor.getAddressOfRemoteServer(), + host, + port, + remoteWebDriver.getSessionId(), + deviceLogType + ); + client.connect(endpoint); + } + + /** + * Builds a device log broadcast WebSocket URI using {@code wss} when {@code serverUrl} uses + * {@code https}, or {@code ws} otherwise. + * + * @param serverUrl the active remote server URL, or {@code null} if unknown + * @param host the target WebSocket host + * @param port the target WebSocket port + * @param sessionId the active session identifier + * @param deviceLogType the log endpoint suffix (such as {@code logcat} or {@code syslog}) + * @return the WebSocket endpoint URI + */ + public static URI buildBroadcastUri( + @Nullable URL serverUrl, + String host, + int port, + @Nullable SessionId sessionId, + String deviceLogType + ) { + String scheme = serverUrl != null && "https".equalsIgnoreCase(serverUrl.getProtocol()) ? "wss" : "ws"; + String endpoint = String.format( + "%s://%s:%s/ws/session/%s/appium/device/%s", + scheme, Strings.formatHost(host), port, sessionId, deviceLogType + ); + return URI.create(endpoint); + } +} diff --git a/src/main/java/io/appium/java_client/internal/Strings.java b/src/main/java/io/appium/java_client/internal/Strings.java index 4cee7b0ae..4048dee3b 100644 --- a/src/main/java/io/appium/java_client/internal/Strings.java +++ b/src/main/java/io/appium/java_client/internal/Strings.java @@ -34,4 +34,17 @@ private Strings() { public static boolean isNullOrEmpty(@Nullable String string) { return string == null || string.isEmpty(); } + + /** + * Wraps a bare IPv6 host literal in brackets if not already bracketed. + * + * @param host the host name or IP literal + * @return the URL-safe host representation + */ + public static String formatHost(String host) { + if (!host.startsWith("[") && host.indexOf(':') != host.lastIndexOf(':')) { + return "[" + host + "]"; + } + return host; + } } diff --git a/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java b/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java index 4558f5d23..b39d81113 100644 --- a/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java +++ b/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java @@ -18,13 +18,9 @@ import io.appium.java_client.CommandExecutionHelper; import io.appium.java_client.ExecutesMethod; -import io.appium.java_client.remote.AppiumCommandExecutor; -import io.appium.java_client.remote.AppiumRemoteWebDriver; -import io.appium.java_client.remote.SessionId; +import io.appium.java_client.internal.LogBroadcastEndpoints; import io.appium.java_client.ws.StringWebSocketClient; -import java.net.URI; -import java.net.URL; import java.util.function.Consumer; import static io.appium.java_client.service.local.AppiumServiceBuilder.DEFAULT_APPIUM_PORT; @@ -65,13 +61,7 @@ default void startSyslogBroadcast(String host) { * @param port the port of the host where Appium server is running */ default void startSyslogBroadcast(String host, int port) { - var remoteWebDriver = (AppiumRemoteWebDriver) this; - URL serverUrl = ((AppiumCommandExecutor) remoteWebDriver.getCommandExecutor()).getAddressOfRemoteServer(); - var scheme = "https".equals(serverUrl.getProtocol()) ? "wss" : "ws"; - CommandExecutionHelper.executeScript(this, "mobile: startLogsBroadcast"); - SessionId sessionId = remoteWebDriver.getSessionId(); - var endpoint = String.format("%s://%s:%s/ws/session/%s/appium/device/syslog", scheme, host, port, sessionId); - getSyslogClient().connect(URI.create(endpoint)); + LogBroadcastEndpoints.startBroadcast(this, getSyslogClient(), host, port, "syslog"); } /** diff --git a/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java b/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java index aea8263c9..4254d61b1 100644 --- a/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java +++ b/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java @@ -54,16 +54,23 @@ public class AppiumCommandExecutor implements CommandExecutor, Closeable { private static final String JSON_UTF_8 = "application/json; charset=utf-8"; private final Optional serviceOptional; - @Getter - private final AppiumClientConfig appiumClientConfig; - private final @Nullable URL remoteServer; private final Map additionalCommands; @Getter private final Factory httpClientFactory; - private HttpClient client; + private volatile ClientState clientState; private @Nullable CommandCodec commandCodec; private @Nullable ResponseCodec responseCodec; + private static final class ClientState { + private final AppiumClientConfig config; + private final HttpClient client; + + private ClientState(AppiumClientConfig config, HttpClient client) { + this.config = config; + this.client = client; + } + } + /** * Create an AppiumCommandExecutor instance. * @@ -78,10 +85,15 @@ public AppiumCommandExecutor( @Nullable Factory httpClientFactory, AppiumClientConfig appiumClientConfig) { this.additionalCommands = new HashMap<>(requireNonNull(additionalCommands, "Additional commands")); - this.appiumClientConfig = requireNonNull(appiumClientConfig, "HTTP client configuration"); + AppiumClientConfig effectiveConfig = requireNonNull(appiumClientConfig, "HTTP client configuration"); + if (service != null && effectiveConfig.baseUri() == null) { + effectiveConfig = effectiveConfig.baseUrl(service.getUrl()); + } this.httpClientFactory = ofNullable(httpClientFactory).orElseGet(Factory::createDefault); - this.client = this.httpClientFactory.createClient(appiumClientConfig); - this.remoteServer = appiumClientConfig.baseUrl(); + this.clientState = new ClientState( + effectiveConfig, + this.httpClientFactory.createClient(effectiveConfig) + ); this.serviceOptional = ofNullable(service); } @@ -163,11 +175,12 @@ public AppiumCommandExecutor(Map additionalCommands, * Creates an executor that talks to a local Appium service using the given client configuration. * * @param additionalCommands the map of Appium commands - * @param service the local Appium service to send the commands to + * @param service the local Appium service to send the commands to, or {@code null} if none * @param appiumClientConfig the HTTP client configuration */ public AppiumCommandExecutor(Map additionalCommands, - AppiumDriverLocalService service, AppiumClientConfig appiumClientConfig) { + @Nullable AppiumDriverLocalService service, + AppiumClientConfig appiumClientConfig) { this(additionalCommands, service, Factory.createDefault(), appiumClientConfig); } @@ -180,6 +193,15 @@ public Map getAdditionalCommands() { return Collections.unmodifiableMap(additionalCommands); } + /** + * Returns the HTTP client configuration used by this executor. + * + * @return the HTTP client configuration + */ + public AppiumClientConfig getAppiumClientConfig() { + return clientState.config; + } + /** * The address of the server the commands are sent to. * @@ -187,7 +209,7 @@ public Map getAdditionalCommands() { */ @Nullable public URL getAddressOfRemoteServer() { - return remoteServer; + return clientState.config.baseUrl(); } /** @@ -224,7 +246,7 @@ public void setResponseCodec(ResponseCodec codec) { * @return the HTTP client */ public HttpClient getClient() { - return this.client; + return clientState.client; } /** @@ -239,12 +261,13 @@ public HttpClient getClient() { * carrier-grade NAT ({@code 100.64.0.0/10}), IPv6 unique-local ({@code fc00::/7}), * and other non-special addresses are not rejected by this check. */ - protected void overrideServerUrl(URL serverUrl) { - DirectConnectUrlSafety.requireSafeOverrideTarget(serverUrl); - HttpClient newClient = getHttpClientFactory().createClient(appiumClientConfig.baseUrl(serverUrl)); - HttpClient oldClient = this.client; - this.client = newClient; - oldClient.close(); + protected synchronized void overrideServerUrl(URL serverUrl) { + DirectConnectUrlSafety.requireSafeOverrideTarget(requireNonNull(serverUrl, "Server URL")); + ClientState previousState = this.clientState; + AppiumClientConfig updatedConfig = previousState.config.baseUrl(serverUrl); + HttpClient newClient = getHttpClientFactory().createClient(updatedConfig); + this.clientState = new ClientState(updatedConfig, newClient); + previousState.client.close(); } private Response createSession(Command command) { @@ -257,7 +280,7 @@ private Response createSession(Command command) { refreshAdditionalCommands(); setResponseCodec(new AppiumW3CHttpResponseCodec()); Response response = result.createResponse(); - if (appiumClientConfig.isDirectConnectEnabled()) { + if (getAppiumClientConfig().isDirectConnectEnabled()) { setDirectConnect(response); } @@ -292,7 +315,7 @@ private void setDirectConnect(Response response) throws SessionNotCreatedExcepti return; } - if (!directConnect.getProtocol().equals("https")) { + if (!"https".equalsIgnoreCase(directConnect.getProtocol())) { throw new SessionNotCreatedException( String.format("The given protocol '%s' as the direct connection url returned by " + "the remote server is not accurate. Only 'https' is supported.", @@ -363,8 +386,9 @@ private Response executeInSession(Command command) { httpRequest.addHeader("Content-Type", JSON_UTF_8); } + HttpClient activeClient = getClient(); try { - HttpResponse httpResponse = client.execute(httpRequest); + HttpResponse httpResponse = activeClient.execute(httpRequest); Response response = responseCodec.decode(httpResponse); if (response.getSessionId() == null) { @@ -372,7 +396,7 @@ private Response executeInSession(Command command) { response.setSessionId(command.getSessionId().toString()); } if (DriverCommand.QUIT.equals(command.getName())) { - client.close(); + activeClient.close(); } return response; } catch (UnsupportedCommandException e) { @@ -394,6 +418,6 @@ private static Throwable getRootCause(Throwable throwable) { @Override public void close() { - client.close(); + getClient().close(); } } diff --git a/src/main/java/io/appium/java_client/remote/DirectConnect.java b/src/main/java/io/appium/java_client/remote/DirectConnect.java index c191c6eb8..fe07b4b8f 100644 --- a/src/main/java/io/appium/java_client/remote/DirectConnect.java +++ b/src/main/java/io/appium/java_client/remote/DirectConnect.java @@ -16,6 +16,7 @@ package io.appium.java_client.remote; +import io.appium.java_client.internal.Strings; import lombok.AccessLevel; import lombok.Getter; import org.jspecify.annotations.Nullable; @@ -78,15 +79,32 @@ public boolean isValid() { * @throws MalformedURLException if the built url was invalid */ public URL getUrl() throws MalformedURLException { - String newUrlCandidate = String.format("%s://%s:%s%s", this.protocol, this.host, this.port, this.path); + if (!isValid() || Stream.of(this.protocol, this.host, this.port).anyMatch(String::isBlank)) { + throw createMalformedUrlException( + String.format("%s://%s:%s%s", this.protocol, this.host, this.port, this.path) + ); + } + String newUrlCandidate = String.format("%s://%s:%s%s", + this.protocol, Strings.formatHost(this.host), this.port, normalizePath(this.path)); try { return new URL(newUrlCandidate); } catch (MalformedURLException e) { - throw new MalformedURLException( - String.format("The remote server returned an invalid value to build the direct connect URL: %s", - newUrlCandidate) - ); + throw createMalformedUrlException(newUrlCandidate); + } + } + + private static String normalizePath(String path) { + if (path.isEmpty() || path.startsWith("/")) { + return path; } + return "/" + path; + } + + private static MalformedURLException createMalformedUrlException(String candidate) { + return new MalformedURLException( + String.format("The remote server returned an invalid value to build the direct connect URL: %s", + candidate) + ); } } diff --git a/src/test/java/io/appium/java_client/internal/DirectConnectTest.java b/src/test/java/io/appium/java_client/internal/DirectConnectTest.java index 8255c3c5d..ac6090976 100644 --- a/src/test/java/io/appium/java_client/internal/DirectConnectTest.java +++ b/src/test/java/io/appium/java_client/internal/DirectConnectTest.java @@ -55,5 +55,82 @@ void hasInvalidDirectConnect() { Map responseValue = new HashMap<>(); DirectConnect directConnect = new DirectConnect(responseValue); assertFalse(directConnect.isValid()); + assertThrowsExactly(MalformedURLException.class, directConnect::getUrl); + } + + @Test + void formatsBareIpv6HostAndPreservesBracketedIpv6Host() throws MalformedURLException { + Map bareIpv6 = Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "2001:db8::1", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "/wd/hub" + ); + DirectConnect bare = new DirectConnect(bareIpv6); + assertTrue(bare.isValid()); + assertEquals("https://[2001:db8::1]:4443/wd/hub", bare.getUrl().toString()); + + Map bracketedIpv6 = Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "[2001:db8::1]", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "/wd/hub" + ); + DirectConnect bracketed = new DirectConnect(bracketedIpv6); + assertTrue(bracketed.isValid()); + assertEquals("https://[2001:db8::1]:4443/wd/hub", bracketed.getUrl().toString()); + assertEquals("[2001:db8::1]", Strings.formatHost("2001:db8::1")); + assertEquals("[2001:db8::1]", Strings.formatHost("[2001:db8::1]")); + } + + @Test + void normalizesEmptyAndRelativeDirectConnectPath() throws MalformedURLException { + DirectConnect emptyPath = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "203.0.113.1", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "" + )); + assertTrue(emptyPath.isValid()); + assertEquals("https://203.0.113.1:4443", emptyPath.getUrl().toString()); + + DirectConnect relativePath = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "203.0.113.1", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "wd/hub" + )); + assertTrue(relativePath.isValid()); + assertEquals("https://203.0.113.1:4443/wd/hub", relativePath.getUrl().toString()); + } + + @Test + void rejectsSingleColonHostAndBlankFields() { + DirectConnect embeddedPortHost = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "evil.example.com:8443", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "/wd/hub" + )); + assertTrue(embeddedPortHost.isValid()); + assertThrowsExactly(MalformedURLException.class, embeddedPortHost::getUrl); + + DirectConnect blankHost = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", " ", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "" + )); + assertTrue(blankHost.isValid()); + assertThrowsExactly(MalformedURLException.class, blankHost::getUrl); + + DirectConnect blankPort = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "x", + "appium:directConnectPort", "", + "appium:directConnectPath", "/wd/hub" + )); + assertTrue(blankPort.isValid()); + assertThrowsExactly(MalformedURLException.class, blankPort::getUrl); } } diff --git a/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java b/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java new file mode 100644 index 000000000..9ebcaceef --- /dev/null +++ b/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java @@ -0,0 +1,49 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.appium.java_client.internal; + +import io.appium.java_client.remote.SessionId; +import org.junit.jupiter.api.Test; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LogBroadcastEndpointsTest { + + @Test + void derivesWebSocketSchemeFromServerUrlAndFormatsIpv6Hosts() throws MalformedURLException { + SessionId sessionId = new SessionId("s1"); + + URI nullServer = LogBroadcastEndpoints.buildBroadcastUri( + null, "127.0.0.1", 4723, sessionId, "logcat" + ); + assertEquals("ws://127.0.0.1:4723/ws/session/s1/appium/device/logcat", nullServer.toString()); + + URI httpServer = LogBroadcastEndpoints.buildBroadcastUri( + new URL("http://hub.example.com:4723"), "hub.example.com", 4723, sessionId, "logcat" + ); + assertEquals("ws://hub.example.com:4723/ws/session/s1/appium/device/logcat", httpServer.toString()); + + URI httpsServer = LogBroadcastEndpoints.buildBroadcastUri( + new URL("https://direct.example.com:4443"), "2001:db8::1", 4443, sessionId, "syslog" + ); + assertEquals("wss://[2001:db8::1]:4443/ws/session/s1/appium/device/syslog", httpsServer.toString()); + } +} diff --git a/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java b/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java index b11bd6273..5b6020094 100644 --- a/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java +++ b/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java @@ -2,18 +2,92 @@ import io.appium.java_client.AppiumClientConfig; import io.appium.java_client.MobileCommand; +import io.appium.java_client.android.AndroidDriver; +import io.appium.java_client.android.options.UiAutomator2Options; +import io.appium.java_client.http.ClientConfig; +import io.appium.java_client.http.Contents; +import io.appium.java_client.http.HttpClient; +import io.appium.java_client.http.HttpRequest; +import io.appium.java_client.http.HttpResponse; +import io.appium.java_client.http.Message; +import io.appium.java_client.http.WebSocket; +import io.appium.java_client.ios.IOSDriver; +import io.appium.java_client.ios.options.XCUITestOptions; +import io.appium.java_client.service.local.AppiumDriverLocalService; +import io.appium.java_client.service.local.AppiumServiceBuilder; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.openqa.selenium.SessionNotCreatedException; +import java.io.File; +import java.io.IOException; import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class AppiumCommandExecutorTest { private static final String APPIUM_URL = "https://appium.example.com"; + private static final File NODE = new File(Path.of(System.getProperty("java.home"), "bin", "java").toString()); + + @TempDir + Path tempDir; + + private static final class RecordingHttpClient implements HttpClient { + private final ClientConfig config; + private final AtomicBoolean closed = new AtomicBoolean(false); + private final String sessionCapabilitiesJson; + private final List socketUris = new ArrayList<>(); + + RecordingHttpClient(ClientConfig config, String sessionCapabilitiesJson) { + this.config = config; + this.sessionCapabilitiesJson = sessionCapabilitiesJson; + } + + @Override + public HttpResponse execute(HttpRequest request) { + String body = "/session".equals(request.getUri()) + ? "{\"value\":{\"sessionId\":\"s1\",\"capabilities\":" + sessionCapabilitiesJson + "}}" + : "{\"value\":null}"; + return new HttpResponse() + .setStatus(200) + .setHeader("Content-Type", "application/json; charset=utf-8") + .setContent(Contents.utf8String(body)); + } + + @Override + public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) { + socketUris.add(request.getUri()); + return new WebSocket() { + @Override + public WebSocket send(Message message) { + return this; + } + + @Override + public void close() { + } + }; + } + + @Override + public void close() { + closed.set(true); + } + } private AppiumCommandExecutor createExecutor() { URL baseUrl; @@ -38,12 +112,227 @@ void getHttpClientFactory() { @Test void overrideServerUrl() throws MalformedURLException { - assertDoesNotThrow(() -> createExecutor().overrideServerUrl(new URL("https://203.0.113.1/wd/hub"))); + List created = new ArrayList<>(); + HttpClient.Factory factory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, "{\"platformName\":\"Android\"}"); + created.add(client); + return client; + }; + AppiumClientConfig initialConfig = AppiumClientConfig.defaultConfig() + .baseUrl(new URL(APPIUM_URL)) + .readTimeout(Duration.ofSeconds(45)); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, null, factory, initialConfig); + final HttpClient firstClient = executor.getClient(); + + URL overrideUrl = new URL("https://203.0.113.1:4443/wd/hub"); + executor.overrideServerUrl(overrideUrl); + + assertEquals(2, created.size()); + assertTrue(created.get(0).closed.get()); + assertFalse(created.get(1).closed.get()); + assertNotSame(firstClient, executor.getClient()); + assertSame(created.get(1), executor.getClient()); + assertEquals(overrideUrl, executor.getAddressOfRemoteServer()); + assertEquals(overrideUrl, executor.getAppiumClientConfig().baseUrl()); + assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"), created.get(1).config.baseUri()); + assertEquals(Duration.ofSeconds(45), created.get(1).config.readTimeout()); + assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"), executor.getAppiumClientConfig().baseUri()); + assertEquals(Duration.ofSeconds(45), executor.getAppiumClientConfig().readTimeout()); } @Test void overrideServerUrlRejectsLoopbackTarget() throws MalformedURLException { + List created = new ArrayList<>(); + HttpClient.Factory factory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, "{\"platformName\":\"Android\"}"); + created.add(client); + return client; + }; + URL initialUrl = new URL(APPIUM_URL); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, null, factory, + AppiumClientConfig.defaultConfig().baseUrl(initialUrl)); + assertThrows(SessionNotCreatedException.class, - () -> createExecutor().overrideServerUrl(new URL("https://127.0.0.1:4443/wd/hub"))); + () -> executor.overrideServerUrl(new URL("https://127.0.0.1:4443/wd/hub"))); + assertEquals(1, created.size()); + assertFalse(created.get(0).closed.get()); + assertEquals(initialUrl, executor.getAddressOfRemoteServer()); + assertEquals(initialUrl, executor.getAppiumClientConfig().baseUrl()); + } + + @Test + void populatesBaseUrlFromLocalServiceWhenUnsetInClientConfig() throws IOException { + File mainJs = Files.createFile(tempDir.resolve("main.js")).toFile(); + var service = new AppiumServiceBuilder() + .usingDriverExecutable(NODE) + .withAppiumJS(mainJs) + .usingPort(4777) + .withIPAddress("127.0.0.1") + .build(); + AppiumClientConfig customConfig = AppiumClientConfig.defaultConfig() + .readTimeout(Duration.ofSeconds(90)); + + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, service, customConfig); + + assertEquals(service.getUrl(), executor.getAddressOfRemoteServer()); + assertEquals(service.getUrl(), executor.getAppiumClientConfig().baseUrl()); + assertEquals(Duration.ofSeconds(90), executor.getAppiumClientConfig().readTimeout()); + } + + @Test + void acceptsNullableLocalServiceWithClientConfig() throws MalformedURLException { + URL baseUrl = new URL(APPIUM_URL); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + (AppiumDriverLocalService) null, + AppiumClientConfig.defaultConfig().baseUrl(baseUrl) + ); + assertEquals(baseUrl, executor.getAddressOfRemoteServer()); + } + + @Test + void directConnectSupportsUppercaseProtocolIpv6LiteralAndRelativePath() throws MalformedURLException { + String caps = "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\"," + + "\"appium:directConnectProtocol\":\"HTTPS\"," + + "\"appium:directConnectHost\":\"2001:db8::1\"," + + "\"appium:directConnectPort\":4443," + + "\"appium:directConnectPath\":\"wd/hub\"}"; + HttpClient.Factory factory = cfg -> new RecordingHttpClient(cfg, caps); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, null, factory, + AppiumClientConfig.defaultConfig().baseUrl(new URL(APPIUM_URL)).directConnect(true)); + + AndroidDriver driver = new AndroidDriver(executor, new UiAutomator2Options().setDeviceName("emu")); + try { + URL expected = new URL("https://[2001:db8::1]:4443/wd/hub"); + assertEquals(expected, executor.getAddressOfRemoteServer()); + assertEquals(expected, executor.getAppiumClientConfig().baseUrl()); + assertEquals(expected, driver.getRemoteAddress()); + + URL nextOverride = new URL("https://203.0.113.2:4443/wd/hub"); + executor.overrideServerUrl(nextOverride); + assertEquals(nextOverride, driver.getRemoteAddress()); + } finally { + driver.quit(); + } + } + + @Test + void broadcastListenersUseUpdatedHttpsSchemeAndPreserveDefaultHostAndPortOverloads() + throws MalformedURLException { + String androidCaps = "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\"," + + "\"appium:directConnectProtocol\":\"https\"," + + "\"appium:directConnectHost\":\"203.0.113.1\"," + + "\"appium:directConnectPort\":4443," + + "\"appium:directConnectPath\":\"/wd/hub\"}"; + List androidClients = new ArrayList<>(); + HttpClient.Factory androidFactory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, androidCaps); + androidClients.add(client); + return client; + }; + AppiumCommandExecutor androidExecutor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + null, + androidFactory, + AppiumClientConfig.defaultConfig() + .baseUrl(new URL("http://hub.example.com:4723")) + .directConnect(true) + ); + + AndroidDriver androidDriver = new AndroidDriver( + androidExecutor, + new UiAutomator2Options().setDeviceName("emu") + ); + try { + androidDriver.startLogcatBroadcast(); + androidDriver.startLogcatBroadcast("10.0.0.5"); + androidDriver.startLogcatBroadcast("203.0.113.1", 4443); + + assertEquals( + List.of( + "wss://127.0.0.1:4723/ws/session/s1/appium/device/logcat", + "wss://10.0.0.5:4723/ws/session/s1/appium/device/logcat", + "wss://203.0.113.1:4443/ws/session/s1/appium/device/logcat" + ), + androidClients.get(1).socketUris + ); + } finally { + androidDriver.quit(); + } + + String iosCaps = "{\"platformName\":\"iOS\",\"appium:automationName\":\"XCUITest\"," + + "\"appium:directConnectProtocol\":\"https\"," + + "\"appium:directConnectHost\":\"2001:db8::1\"," + + "\"appium:directConnectPort\":4443," + + "\"appium:directConnectPath\":\"/wd/hub\"}"; + List iosClients = new ArrayList<>(); + HttpClient.Factory iosFactory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, iosCaps); + iosClients.add(client); + return client; + }; + AppiumCommandExecutor iosExecutor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + null, + iosFactory, + AppiumClientConfig.defaultConfig() + .baseUrl(new URL("http://hub.example.com:4723")) + .directConnect(true) + ); + + IOSDriver iosDriver = new IOSDriver( + iosExecutor, + new XCUITestOptions().setDeviceName("iPhone 16") + ); + try { + iosDriver.startSyslogBroadcast(); + iosDriver.startSyslogBroadcast("log.internal"); + iosDriver.startSyslogBroadcast("2001:db8::1", 4443); + + assertEquals( + List.of( + "wss://localhost:4723/ws/session/s1/appium/device/syslog", + "wss://log.internal:4723/ws/session/s1/appium/device/syslog", + "wss://[2001:db8::1]:4443/ws/session/s1/appium/device/syslog" + ), + iosClients.get(1).socketUris + ); + } finally { + iosDriver.quit(); + } + } + + @Test + void blankDirectConnectValuesFailWithSessionNotCreatedException() throws MalformedURLException { + for (String invalidCaps : List.of( + "{\"platformName\":\"Android\"," + + "\"appium:directConnectProtocol\":\"https\"," + + "\"appium:directConnectHost\":\"x\"," + + "\"appium:directConnectPort\":\"\"," + + "\"appium:directConnectPath\":\"/wd/hub\"}", + "{\"platformName\":\"Android\"," + + "\"appium:directConnectProtocol\":\"\"," + + "\"appium:directConnectHost\":\"\"," + + "\"appium:directConnectPort\":\"\"," + + "\"appium:directConnectPath\":\"\"}")) { + HttpClient.Factory factory = cfg -> new RecordingHttpClient(cfg, invalidCaps); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + null, + factory, + AppiumClientConfig.defaultConfig() + .baseUrl(new URL("http://hub.example.com:4723")) + .directConnect(true) + ); + + assertThrows( + SessionNotCreatedException.class, + () -> new AndroidDriver(executor, new UiAutomator2Options().setDeviceName("emu")) + ); + } } } diff --git a/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java b/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java index a8542460b..9ed100e8c 100644 --- a/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java +++ b/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java @@ -56,6 +56,8 @@ import java.util.function.Function; import java.util.regex.Pattern; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Pins the HTTP requests a driver sends for each WebDriver/Appium API call, and what it returns * for scripted server responses. Set GOLDEN_UPDATE=1 to regenerate the golden file. @@ -593,6 +595,9 @@ void directConnect() { Map described = new LinkedHashMap<>(); try { var driver = newDriver(transport, AppiumClientConfig.defaultConfig().directConnect(true)); + if ("valid".equals(name)) { + assertEquals("https://203.0.113.1:4443/wd/hub", driver.getRemoteAddress().toString()); + } transport.requests.clear(); driver.getTitle(); } catch (Throwable t) {