diff --git a/android/capacitor/src/androidTest/java/com/getcapacitor/android/DisabledPluginTest.java b/android/capacitor/src/androidTest/java/com/getcapacitor/android/DisabledPluginTest.java new file mode 100644 index 000000000..232829f7b --- /dev/null +++ b/android/capacitor/src/androidTest/java/com/getcapacitor/android/DisabledPluginTest.java @@ -0,0 +1,31 @@ +package com.getcapacitor.android; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import androidx.test.core.app.ActivityScenario; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.getcapacitor.Bridge; +import com.getcapacitor.plugin.CapacitorCookies; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** The test host sets plugins.CapacitorCookies.disabled, so the bridge must never register it. */ +@RunWith(AndroidJUnit4.class) +public class DisabledPluginTest { + + @Test + public void doesNotRegisterDisabledPlugins() { + try (ActivityScenario scenario = ActivityScenario.launch(TestHostActivity.class)) { + scenario.onActivity((activity) -> { + Bridge bridge = activity.getBridge(); + assertNotNull(bridge); + assertNull("disabled core plugin must not be registered", bridge.getPlugin("CapacitorCookies")); + assertNotNull("plugins that are not disabled must still be registered", bridge.getPlugin("CapacitorHttp")); + + bridge.registerPluginInstance(new CapacitorCookies()); + assertNull("disabled plugin instance must not be registered", bridge.getPlugin("CapacitorCookies")); + }); + } + } +} diff --git a/android/capacitor/src/androidTest/java/com/getcapacitor/android/TestHostActivity.java b/android/capacitor/src/androidTest/java/com/getcapacitor/android/TestHostActivity.java index 05d7a5d7c..f461b90ae 100644 --- a/android/capacitor/src/androidTest/java/com/getcapacitor/android/TestHostActivity.java +++ b/android/capacitor/src/androidTest/java/com/getcapacitor/android/TestHostActivity.java @@ -8,6 +8,7 @@ /** * Host for instrumented tests. CapacitorHttp is on so the proxy is reachable, and a plugin that * tries to allow the proxy path is registered so tests can prove the guard still wins. + * CapacitorCookies is disabled so tests can prove a disabled plugin is never registered. */ public class TestHostActivity extends BridgeActivity { @@ -16,7 +17,7 @@ protected void load() { registerPlugin(InterceptorAllowingPlugin.class); try { - JSONObject plugins = new JSONObject("{\"CapacitorHttp\":{\"enabled\":true}}"); + JSONObject plugins = new JSONObject("{\"CapacitorHttp\":{\"enabled\":true},\"CapacitorCookies\":{\"disabled\":true}}"); config = new CapConfig.Builder(this).setPluginsConfiguration(plugins).create(); } catch (JSONException e) { throw new IllegalStateException("bad test plugin config", e); diff --git a/android/capacitor/src/main/java/com/getcapacitor/Bridge.java b/android/capacitor/src/main/java/com/getcapacitor/Bridge.java index 97d6d58c2..ea95d168a 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/Bridge.java +++ b/android/capacitor/src/main/java/com/getcapacitor/Bridge.java @@ -644,7 +644,10 @@ public void registerPluginInstances(Plugin[] pluginInstances) { public void registerPlugin(Class pluginClass) { String pluginId = pluginId(pluginClass); if (pluginId == null) return; - + if (config.getPluginConfiguration(pluginId).getBoolean("disabled", false)) { + Logger.debug("Not registering disabled plugin: " + pluginId); + return; + } try { this.plugins.put(pluginId, new PluginHandle(this, pluginClass)); } catch (InvalidPluginException ex) { @@ -658,7 +661,10 @@ public void registerPluginInstance(Plugin plugin) { Class clazz = plugin.getClass(); String pluginId = pluginId(clazz); if (pluginId == null) return; - + if (config.getPluginConfiguration(pluginId).getBoolean("disabled", false)) { + Logger.debug("Not registering disabled plugin: " + pluginId); + return; + } try { this.plugins.put(pluginId, new PluginHandle(this, plugin)); } catch (InvalidPluginException ex) { diff --git a/android/capacitor/src/main/java/com/getcapacitor/WebViewLocalServer.java b/android/capacitor/src/main/java/com/getcapacitor/WebViewLocalServer.java index 74a463fef..71135abc2 100755 --- a/android/capacitor/src/main/java/com/getcapacitor/WebViewLocalServer.java +++ b/android/capacitor/src/main/java/com/getcapacitor/WebViewLocalServer.java @@ -179,7 +179,8 @@ public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) { } if (null != loadingUrl.getPath() && loadingUrl.getPath().startsWith(Bridge.CAPACITOR_HTTP_INTERCEPTOR_START)) { - boolean httpEnabled = bridge.getConfig().getPluginConfiguration("CapacitorHttp").getBoolean("enabled", false); + PluginConfig httpConfig = bridge.getConfig().getPluginConfiguration("CapacitorHttp"); + boolean httpEnabled = httpConfig.getBoolean("enabled", false) && !httpConfig.getBoolean("disabled", false); if (!httpEnabled) { return null; } diff --git a/android/capacitor/src/test/java/com/getcapacitor/WebViewLocalServerProxyGuardTest.java b/android/capacitor/src/test/java/com/getcapacitor/WebViewLocalServerProxyGuardTest.java index c7883b184..e04b41c2e 100644 --- a/android/capacitor/src/test/java/com/getcapacitor/WebViewLocalServerProxyGuardTest.java +++ b/android/capacitor/src/test/java/com/getcapacitor/WebViewLocalServerProxyGuardTest.java @@ -42,6 +42,7 @@ public class WebViewLocalServerProxyGuardTest { private MockedStatic loggerStatic; private WebViewLocalServer server; private Bridge bridge; + private PluginConfig httpConfig; @Before public void setUp() { @@ -50,7 +51,7 @@ public void setUp() { uriStatic.when(() -> Uri.parse("https://localhost")).thenReturn(appOrigin); loggerStatic = mockStatic(Logger.class); - PluginConfig httpConfig = mock(PluginConfig.class); + httpConfig = mock(PluginConfig.class); when(httpConfig.getBoolean("enabled", false)).thenReturn(true); CapConfig config = mock(CapConfig.class); when(config.getPluginConfiguration("CapacitorHttp")).thenReturn(httpConfig); @@ -166,6 +167,14 @@ public void blocksSubframeDocumentLoadOnEveryProxyRoute() { } } + @Test + public void httpInterceptorIsOffWhenCapacitorHttpIsDisabled() { + // disabled wins over enabled: the plugin isn't registered, so its proxy must not be served either + when(httpConfig.getBoolean("disabled", false)).thenReturn(true); + assertNull(server.shouldInterceptRequest(subResource("localhost", HTTP_PATH))); + loggerStatic.verify(() -> Logger.debug(anyString()), never()); + } + @Test public void blocksRequestWithoutHost() { assertBlocked(request(uri("https", null, -1, FILE_PATH), false, Collections.emptyMap())); diff --git a/cli/src/declarations.ts b/cli/src/declarations.ts index 1151b4f14..11add0d7d 100644 --- a/cli/src/declarations.ts +++ b/cli/src/declarations.ts @@ -741,12 +741,15 @@ export interface PluginsConfig { /** * Plugin configuration by class name. * + * Every plugin accepts `disabled` (see `PluginConfig`), for example + * `{ plugins: { MyPlugin: { disabled: true } } }`. + * * @since 1.0.0 */ [key: string]: - | { + | (PluginConfig & { [key: string]: any; - } + }) | undefined; /** @@ -754,10 +757,13 @@ export interface PluginsConfig { * * @since 4.3.0 */ - CapacitorCookies?: { + CapacitorCookies?: PluginConfig & { /** * Enable CapacitorCookies to override the global `document.cookie` on native. * + * This only controls the patching. The plugin's own methods work either + * way; use `disabled` to stop the plugin from loading. + * * @default false */ enabled?: boolean; @@ -768,10 +774,13 @@ export interface PluginsConfig { * * @since 4.3.0 */ - CapacitorHttp?: { + CapacitorHttp?: PluginConfig & { /** * Enable CapacitorHttp to override the global `fetch` and `XMLHttpRequest` on native. * + * This only controls the patching. The plugin's own methods work either + * way; use `disabled` to stop the plugin from loading. + * * @default false */ enabled?: boolean; @@ -782,7 +791,7 @@ export interface PluginsConfig { * * @since 8.0.0 */ - SystemBars?: { + SystemBars?: PluginConfig & { /** * Specifies how to handle problematic insets on Android. * @@ -843,6 +852,31 @@ export interface PluginsConfig { }; } +export interface PluginConfig { + /** + * Prevent the plugin's native implementation from being registered and + * loaded on iOS and Android. + * + * A disabled plugin is not available to the app: + * `Capacitor.isPluginAvailable()` returns `false` and calls to its methods + * fail as unimplemented. + * + * This is different from the `enabled` option of `CapacitorHttp` and + * `CapacitorCookies`, which only controls the patching of `fetch`, + * `XMLHttpRequest` and `document.cookie`. `disabled: true` takes precedence + * over `enabled: true`. + * + * Plugins that declare their own configuration type don't list `disabled`, + * so TypeScript rejects it in `capacitor.config.ts`. Set it in + * `capacitor.config.json` instead, or cast the plugin's configuration, for + * example `SplashScreen: { disabled: true } as any`. + * + * @since 9.1.0 + * @default false + */ + disabled?: boolean; +} + export interface PackageOptions { /** * Create a symlink to the plugin folder instead of pointing to the plugin path. diff --git a/core/cookies.md b/core/cookies.md index a1d237ee4..ad8eb518c 100644 --- a/core/cookies.md +++ b/core/cookies.md @@ -7,9 +7,16 @@ The Capacitor Cookies API provides native cookie support via patching `document. By default, the patching of `document.cookie` to use native libraries is disabled. If you would like to enable this feature, modify the configuration below in the `capacitor.config` file. -| Prop | Type | Description | Default | -| ------------- | -------------------- | ------------------------------------------------------------------------- | ------------------ | -| **`enabled`** | boolean | Enable the patching of `document.cookie` to use native libraries instead. | false | +| Prop | Type | Description | Default | Since | +| -------------- | -------------------- | ------------------------------------------------------------------------------------ | ------------------ | ----- | +| **`enabled`** | boolean | Enable the patching of `document.cookie` to use native libraries instead. | false | 4.3.0 | +| **`disabled`** | boolean | Prevent the plugin from loading on iOS and Android. Takes precedence over `enabled`. | false | 9.1.0 | + +`enabled` only controls the patching. With `enabled` unset or `false`, `CapacitorCookies.setCookie()` and the other methods below still work. +Set `disabled` to `true` to stop the plugin from loading at all: its methods then fail as unimplemented, and `document.cookie` is not patched even if `enabled` is `true`. + +On Android, this plugin is also what shares cookies between the web view and native requests made with `HttpURLConnection` (including `CapacitorHttp`), and it clears session cookies when it loads. +With `disabled: true`, neither happens. ### Example Configuration diff --git a/core/http.md b/core/http.md index f459597c1..f85b8dad1 100644 --- a/core/http.md +++ b/core/http.md @@ -7,9 +7,13 @@ The Capacitor Http API provides native http support via patching `fetch` and `XM By default, the patching of `window.fetch` and `XMLHttpRequest` to use native libraries is disabled. If you would like to enable this feature, modify the configuration below in the `capacitor.config` file. -| Prop | Type | Description | Default | -| ------------- | -------------------- | ------------------------------------------------------------------------------------ | ------------------ | -| **`enabled`** | boolean | Enable the patching of `fetch` and `XMLHttpRequest` to use native libraries instead. | false | +| Prop | Type | Description | Default | Since | +| -------------- | -------------------- | -------------------------------------------------------------------------------------------------------- | ------------------ | ----- | +| **`enabled`** | boolean | Enable the patching of `fetch` and `XMLHttpRequest` to use native libraries instead. | false | 4.3.0 | +| **`disabled`** | boolean | Prevent the plugin from loading on iOS and Android. Takes precedence over `enabled`. | false | 9.1.0 | + +`enabled` only controls the patching. With `enabled` unset or `false`, `CapacitorHttp.request()` and the other methods below still work. +Set `disabled` to `true` to stop the plugin from loading at all: its methods then fail as unimplemented, and `fetch` and `XMLHttpRequest` are not patched even if `enabled` is `true`. ### Example Configuration diff --git a/ios/Sources/Capacitor/CapacitorBridge.swift b/ios/Sources/Capacitor/CapacitorBridge.swift index 62049b16e..702e0b322 100644 --- a/ios/Sources/Capacitor/CapacitorBridge.swift +++ b/ios/Sources/Capacitor/CapacitorBridge.swift @@ -194,8 +194,11 @@ open class CapacitorBridge: NSObject, CAPBridgeProtocol { */ func exportCoreJS(localUrl: String) { do { - let cookiesEnabled = config.getPluginConfig("CapacitorCookies").getBoolean("enabled", false) - let httpEnabled = config.getPluginConfig("CapacitorHttp").getBoolean("enabled", false) + // A disabled plugin is not registered, so patching fetch/cookies to call it would leave those calls hanging. + let cookiesConfig = config.getPluginConfig("CapacitorCookies") + let cookiesEnabled = cookiesConfig.getBoolean("enabled", false) && !cookiesConfig.getBoolean("disabled", false) + let httpConfig = config.getPluginConfig("CapacitorHttp") + let httpEnabled = httpConfig.getBoolean("enabled", false) && !httpConfig.getBoolean("disabled", false) try JSExport.exportCapacitorGlobalJS(userContentController: webViewDelegationHandler.contentController, isDebug: isDevEnvironment, loggingEnabled: config.loggingEnabled, @@ -330,6 +333,10 @@ open class CapacitorBridge: NSObject, CAPBridgeProtocol { return } + guard !config.getPluginConfig(pluginInstance.jsName).getBoolean("disabled", false) else { + CAPLog.print("⚡️ Not registering disabled plugin \(pluginInstance.jsName)") + return + } if plugins[pluginInstance.jsName] != nil { CAPLog.print("⚡️ Overriding existing registered plugin \(pluginInstance.classForCoder)") } @@ -353,6 +360,10 @@ open class CapacitorBridge: NSObject, CAPBridgeProtocol { CAPLog.print("⚡️ Unable to load plugin \(type.classForCoder()). No such module found.") return nil } + guard !config.getPluginConfig(plugin.jsName).getBoolean("disabled", false) else { + CAPLog.print("⚡️ Not registering disabled plugin \(plugin.jsName)") + return nil + } plugin.load(on: self) plugins[plugin.jsName] = plugin return plugin diff --git a/ios/Sources/Capacitor/WebViewAssetHandler.swift b/ios/Sources/Capacitor/WebViewAssetHandler.swift index e71a70252..27c9cfaf9 100644 --- a/ios/Sources/Capacitor/WebViewAssetHandler.swift +++ b/ios/Sources/Capacitor/WebViewAssetHandler.swift @@ -37,7 +37,8 @@ open class WebViewAssetHandler: NSObject, WKURLSchemeHandler { if url.path.starts(with: CapacitorBridge.httpInterceptorStartIdentifier) { // Only serve the proxy when CapacitorHttp is on. A scheme task can't tell a document from // a subresource, so keeping documents out relies on the check in decidePolicyFor. - if configuration?.getPluginConfig("CapacitorHttp").getBoolean("enabled", false) == true { + let httpConfig = configuration?.getPluginConfig("CapacitorHttp") + if httpConfig?.getBoolean("enabled", false) == true && httpConfig?.getBoolean("disabled", false) != true { handleCapacitorHttpRequest(urlSchemeTask, localUrl, false) } else { urlSchemeTask.didFailWithError(URLError(.unsupportedURL)) diff --git a/ios/Tests/CapacitorTests/DisabledPluginTests.swift b/ios/Tests/CapacitorTests/DisabledPluginTests.swift new file mode 100644 index 000000000..3de77d3ff --- /dev/null +++ b/ios/Tests/CapacitorTests/DisabledPluginTests.swift @@ -0,0 +1,82 @@ +import WebKit +import XCTest +@testable import Capacitor + +private class RecordingSchemeTask: NSObject, WKURLSchemeTask { + let request: URLRequest + private(set) var failure: Error? + + init(url: URL) { + self.request = URLRequest(url: url) + super.init() + } + + func didReceive(_ response: URLResponse) {} + func didReceive(_ data: Data) {} + func didFinish() {} + func didFailWithError(_ error: Error) { failure = error } +} + +class DisabledPluginTests: XCTestCase { + private var bridge: MockBridge! + private var handler: WebViewDelegationHandler! + + override func setUp() { + super.setUp() + let descriptor = InstanceDescriptor() + descriptor.pluginConfigurations = [ + "CapacitorCookies": ["disabled": true], + "CapacitorHttp": ["enabled": true, "disabled": true] + ] + handler = WebViewDelegationHandler() + bridge = MockBridge( + with: InstanceConfiguration(with: descriptor, isDebug: true), + delegate: MockBridgeViewController(), + assetHandler: MockAssetHandler(router: CapacitorRouter()), + delegationHandler: handler + ) + } + + func testDisabledPluginTypeIsNotRegistered() { + bridge.registerPlugin(CAPCookiesPlugin.self) + bridge.registerPlugin(CAPWebViewPlugin.self) + + XCTAssertNil(bridge.plugin(withName: "CapacitorCookies")) + XCTAssertNotNil(bridge.plugin(withName: "WebView")) + } + + func testDisabledPluginInstanceIsNotRegistered() { + bridge.registerPluginInstance(CAPCookiesPlugin()) + + XCTAssertNil(bridge.plugin(withName: "CapacitorCookies")) + } + + // Page scripts can also reach a plugin by its class name, which loads it on demand. + func testDisabledPluginIsNotLoadedByClassName() { + bridge.handleJSCall(call: JSCall(options: [:], pluginId: "CAPCookiesPlugin", method: "getCookies", callbackId: "1")) + bridge.handleJSCall(call: JSCall(options: [:], pluginId: "CAPWebViewPlugin", method: "noSuchMethod", callbackId: "2")) + + XCTAssertNil(bridge.plugin(withName: "CapacitorCookies")) + XCTAssertNotNil(bridge.plugin(withName: "WebView")) + } + + // disabled wins over enabled for the HTTP interceptor too, so page scripts can't reach it directly. + func testDisabledHttpPluginIsNotServedByTheInterceptor() throws { + let assetHandler = WebViewAssetHandler(router: CapacitorRouter()) + assetHandler.setConfiguration(bridge.config) + let url = try XCTUnwrap(URL(string: "capacitor://localhost\(CapacitorBridge.httpInterceptorStartIdentifier)?u=https%3A%2F%2Fexample.com")) + let task = RecordingSchemeTask(url: url) + + assetHandler.webView(WKWebView(), start: task) + + XCTAssertEqual((task.failure as? URLError)?.code, .unsupportedURL) + } + + // An enabled but disabled CapacitorHttp must not be patched in, or fetch would call a plugin that isn't there. + func testDisabledWinsOverEnabledForPatching() { + let source = handler.contentController.userScripts.map(\.source).joined() + + XCTAssertTrue(source.contains("httpEnabled: false")) + XCTAssertTrue(source.contains("cookiesEnabled: false")) + } +}