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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<TestHostActivity> 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"));
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand All @@ -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);
Expand Down
10 changes: 8 additions & 2 deletions android/capacitor/src/main/java/com/getcapacitor/Bridge.java
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,10 @@ public void registerPluginInstances(Plugin[] pluginInstances) {
public void registerPlugin(Class<? extends Plugin> 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) {
Expand All @@ -658,7 +661,10 @@ public void registerPluginInstance(Plugin plugin) {
Class<? extends Plugin> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public class WebViewLocalServerProxyGuardTest {
private MockedStatic<Logger> loggerStatic;
private WebViewLocalServer server;
private Bridge bridge;
private PluginConfig httpConfig;

@Before
public void setUp() {
Expand All @@ -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);
Expand Down Expand Up @@ -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()));
Expand Down
44 changes: 39 additions & 5 deletions cli/src/declarations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -741,23 +741,29 @@ 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;

/**
* Capacitor Cookies plugin configuration
*
* @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;
Expand All @@ -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;
Expand All @@ -782,7 +791,7 @@ export interface PluginsConfig {
*
* @since 8.0.0
*/
SystemBars?: {
SystemBars?: PluginConfig & {
/**
* Specifies how to handle problematic insets on Android.
*
Expand Down Expand Up @@ -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.
Expand Down
13 changes: 10 additions & 3 deletions core/cookies.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`** | <code>boolean</code> | Enable the patching of `document.cookie` to use native libraries instead. | <code>false</code> |
| Prop | Type | Description | Default | Since |
| -------------- | -------------------- | ------------------------------------------------------------------------------------ | ------------------ | ----- |
| **`enabled`** | <code>boolean</code> | Enable the patching of `document.cookie` to use native libraries instead. | <code>false</code> | 4.3.0 |
| **`disabled`** | <code>boolean</code> | Prevent the plugin from loading on iOS and Android. Takes precedence over `enabled`. | <code>false</code> | 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

Expand Down
10 changes: 7 additions & 3 deletions core/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`** | <code>boolean</code> | Enable the patching of `fetch` and `XMLHttpRequest` to use native libraries instead. | <code>false</code> |
| Prop | Type | Description | Default | Since |
| -------------- | -------------------- | -------------------------------------------------------------------------------------------------------- | ------------------ | ----- |
| **`enabled`** | <code>boolean</code> | Enable the patching of `fetch` and `XMLHttpRequest` to use native libraries instead. | <code>false</code> | 4.3.0 |
| **`disabled`** | <code>boolean</code> | Prevent the plugin from loading on iOS and Android. Takes precedence over `enabled`. | <code>false</code> | 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

Expand Down
15 changes: 13 additions & 2 deletions ios/Sources/Capacitor/CapacitorBridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)")
}
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion ios/Sources/Capacitor/WebViewAssetHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
82 changes: 82 additions & 0 deletions ios/Tests/CapacitorTests/DisabledPluginTests.swift
Original file line number Diff line number Diff line change
@@ -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"))
}
}