Passive Peer
Description — Couchbase Lite’s Peer-to-Peer Synchronization enables edge devices to synchronize securely without consuming centralized cloud-server resources
Abstract — How to set up a Listener to accept a Replicator connection and sync using peer-to-peer
Related Content — API Reference | Passive Peer | Active Peer
Android enablers
|
Code Snippets
All code examples are indicative only.
They demonstrate the basic concepts and approaches to using a feature.
Use them as inspiration and adapt these examples to best practice when developing applications for your platform.
|
Introduction
This content provides code and configuration examples covering the implementation of Peer-to-Peer Sync over WebSockets. Specifically, it covers the implementation of a Passive Peer.
Couchbase’s Passive Peer (also referred to as the server, or Listener) will accept a connection from an Active Peer (also referred to as the client or replicator) and replicate database changes to synchronize both databases.
Subsequent sections provide additional details and examples for the main configuration options.
Secure Storage
The use of TLS, its associated keys and certificates requires using secure storage to minimize the chances of a security breach.
The implementation of this storage differs from platform to platform — see Using secure storage.
|
Configuration Summary
You should configure and initialize a Listener for each Couchbase Lite database instance you want to sync. There is no limit on the number of Listeners you may configure — Example 1 shows a simple initialization and configuration process.
You must include the initializer CouchbaseLite.init(context) such that it is executed (once only) before initializing the replicator; for example, in your app’s onCreate() method.
|
-
Kotlin
-
Java
val listener = URLEndpointListener(
URLEndpointListenerConfigurationFactory.newConfig(
collections = collections, (1)
port = 55990, (2)
networkInterface = "wlan0", (3)
enableDeltaSync = false, (4)
// Configure server security
disableTls = false, (5)
// Use an Anonymous Self-Signed Cert
identity = null, (6)
// Configure Client Security using an Authenticator
// For example, Basic Authentication (7)
authenticator = ListenerPasswordAuthenticator { usr, pwd ->
(usr === validUser) && (validPass.contentEquals(pwd))
}
))
// Start the listener
listener.start() (8)
// Initialize the listener config
final URLEndpointListenerConfiguration thisConfig
= new URLEndpointListenerConfiguration(collections); (1)
thisConfig.setPort(55990); (2)
thisConfig.setNetworkInterface("wlan0"); (3)
thisConfig.setEnableDeltaSync(false); (4)
// Configure server security
thisConfig.setDisableTls(false); (5)
// Use an Anonymous Self-Signed Cert
thisConfig.setTlsIdentity(null); (6)
// Configure Client Security using an Authenticator
// For example, Basic Authentication (7)
thisConfig.setAuthenticator(new ListenerPasswordAuthenticator(
(username, password) ->
username.equals(validUser) && Arrays.equals(password, validPass)));
// Initialize the listener
final URLEndpointListener thisListener
= new URLEndpointListener(thisConfig); (8)
// Start the listener
thisListener.start(); (9)
1 | Identify the local database to be used — see: Initialize the Listener Configuration |
2 | Optionally, choose a port to use. By default the system will automatically assign a port — to over-ride this, see: Set Port and Network Interface |
3 | Optionally, choose a network interface to use. By default the system will listen on all network interfaces — to over-ride this see: Set Port and Network Interface |
4 | Optionally, choose to sync only changes. The default is not to enable delta-sync — see: Delta Sync. |
5 | Set server security. TLS is always enabled instantly, so you can usually omit this line. But you can, optionally, disable TLS (not advisable in production) — see: TLS Security |
6 | Set the credentials this server will present to the client for authentication. Here we show the default TLS authentication, which is an anonymous self-signed certificate. The server must always authenticate itself to the client. |
7 | Set client security — define the credentials the server expects the client to present for authentication.
Here we show how basic authentication is configured to authenticate the client-supplied credentials from the http authentication header against valid credentials — see Authenticating the Client for more options. Note that client authentication is optional. |
8 | Initialize the listener using the configuration settings. |
9 | Start Listener |
API References
You can find Android API References here.
Device Discovery
This phase is optional: If the Listener is initialized on a well-known URL endpoint (for example, a static IP Address or well-known DNS address) then you can configure Active Peers to connect to those.
Before initiating the Listener, you may execute a peer discovery phase. For the Passive Peer, this involves advertising the service using, for example, Network Service Discovery (see: https://developer.android.com/training/connect-devices-wirelessly/nsd) and waiting for an invite from the Active Peer. The connection is established once the Passive Peer has authenticated and accepted an Active Peer’s invitation.
Initialize the Listener Configuration
Initialize the Listener configuration with the local database — see Example 2 All other configuration values take their default setting.
Each Listener instance serves one Couchbase Lite database. Couchbase sets no hard limit on the number of Listeners you can initialize.
-
Kotlin
-
Java
collections = collections, (1)
// Initialize the listener config
final URLEndpointListenerConfiguration thisConfig
= new URLEndpointListenerConfiguration(collections); (1)
1 | Set the local database using the URLEndpointListenerConfiguration's constructor (Database database). The database must be opened before the Listener is started. thisDB has previously been declared as an object of type Database . |
Set Port and Network Interface
Port number
The Listener will automatically select an available port if you do not specify one — see Example 3 for how to specify a port.
-
Kotlin
-
Java
port = 55990, (1)
thisConfig.setPort(55990); (1)
Network Interface
The Listener will listen on all network interfaces by default.
-
Kotlin
-
Java
networkInterface = "wlan0", (1)
thisConfig.setNetworkInterface("wlan0"); (1)
1 | To specify an interface — one known to other applications — identify it explicitly, using the setNetworkInterface method shown here.
This must be either an IP Address or network interface name such as en0 . |
Delta Sync
Delta Sync allows clients to sync only those parts of a document that have changed. This can result in significant bandwidth consumption savings and throughput improvements. Both are valuable benefits, especially when network bandwidth is constrained.
-
Kotlin
-
Java
enableDeltaSync = false, (1)
thisConfig.setEnableDeltaSync(false); (1)
1 | Delta sync replication is not enabled by default. Use URLEndpointListenerConfiguration's setEnableDeltaSync method to activate or deactivate it. |
TLS Security
Enable or Disable TLS
Define whether the connection is to use TLS or clear text.
TLS-based encryption is enabled by default, and this setting ought to be used in any production environment. However, it can be disabled. For example, for development or test environments.
When TLS is enabled, Couchbase Lite provides several options on how the Listener may be configured with an appropriate TLS Identity — see Configure TLS Identity for Listener.
To use cleartext, un-encrypted, network traffic ( |
You can use URLEndpointListenerConfiguration's setDisableTLS method to disable TLS communication if necessary
The disableTLS
setting must be 'false' when Client Cert Authentication is required.
Basic Authentication can be used with, or without, TLS.
setDisableTLS works in conjunction with TLSIdentity
, to enable developers to define the key and certificate to be used.
-
If
disableTLS
is true — TLS communication is disabled and TLS identity is ignored. Active peers will use thews://
URL scheme used to connect to the listener. -
If
disableTLS
is false or not specified — TLS communication is enabled.Active peers will use the
wss://
URL scheme to connect to the listener.
Configure TLS Identity for Listener
Define the credentials the server will present to the client for authentication. Note that the server must always authenticate itself with the client — see: Authenticate Listener on Active Peer for how the client deals with this.
Use URLEndpointListenerConfiguration's setTlsIdentity method to configure the TLS Identity used in TLS communication.
If TLSIdentity
is not set, then the listener uses an auto-generated anonymous self-signed identity (unless disableTLS = true
).
Whilst the client cannot use this to authenticate the server, it will use it to encrypt communication, giving a more secure option than non-TLS communication.
The auto-generated anonymous self-signed identity is saved in secure storage for future use to obviate the need to re-generate it.
Typically, you will configure the Listener’s TLS Identity once during the initial launch and re-use it (from secure storage on any subsequent starts. |
Here are some example code snippets showing:
Create a TLSIdentity for the server using convenience API. The system generates a self-signed certificate.
-
Kotlin
-
Java
disableTls = false, (1)
thisConfig.setDisableTls(false); (1)
1 | Ensure TLS is used. |
2 | Map the required certificate attributes, in this case the common name. |
3 | Create the required TLS identity using the attributes. Add to secure storage as 'couchbase-docs-cert'. |
4 | Configure the server to present the defined identity credentials when prompted. |
This example uses an anonymous self signed certificate. Generated certificates are held in secure storage.
-
Kotlin
-
Java
disableTls = false, (1)
// Use an Anonymous Self-Signed Cert
identity = null, (2)
thisConfig.setDisableTls(false); (1)
// Use an Anonymous Self-Signed Cert
thisConfig.setTlsIdentity(null); (2)
1 | Ensure TLS is used. This is the default setting. |
2 | Authenticate using an anonymous self-signed certificate. This is the default setting. |
Authenticating the Client
In this section: Use Basic Authentication | Using Client Certificate Authentication | Delete Entry | The Impact of TLS Settings
Define how the server (Listener) will authenticate the client as one it is prepared to interact with.
Whilst client authentication is optional, Couchbase lite provides the necessary tools to implement it. Use the URLEndpointListenerConfiguration class’s setAuthenticator method to specify how the client-supplied credentials are to be authenticated.
Valid options are:
-
No authentication — If you do not define an Authenticator then all clients are accepted.
-
Basic Authentication — uses the ListenerPasswordAuthenticator to authenticate the client using the client-supplied username and password (from the http authentication header).
-
ListenerCertificateAuthenticator — which authenticates the client using a client supplied chain of one or more certificates. You should initialize the authenticator using one of the following constructors:
-
A list of one or more root certificates — the client supplied certificate must end at a certificate in this list if it is to be authenticated
-
A block of code that assumes total responsibility for authentication — it must return a boolean response (true for an authenticated client, or false for a failed authentication).
-
Use Basic Authentication
Define how to authenticate client-supplied username and password credentials. To use client-supplied certificates instead — see: Using Client Certificate Authentication
-
Kotlin
-
Java
// Configure Client Security using an Authenticator
// For example, Basic Authentication (1)
authenticator = ListenerPasswordAuthenticator { usr, pwd ->
(usr === validUser) && (validPass.contentEquals(pwd))
}
// Configure Client Security using an Authenticator
// For example, Basic Authentication (1)
thisConfig.setAuthenticator(new ListenerPasswordAuthenticator(
(username, password) ->
username.equals(validUser) && Arrays.equals(password, validPass)));
1 | Where 'username'/'password' are the client-supplied values (from the http-authentication header) and validUser /validPassword are the values acceptable to the server. |
Using Client Certificate Authentication
Define how the server will authenticate client-supplied certificates.
There are two ways to authenticate a client:
-
A chain of one or more certificates that ends at a certificate in the list of certificates supplied to the constructor for ListenerCertificateAuthenticator — see: Example 9
-
Application logic: This method assumes complete responsibility for verifying and authenticating the client — see: Example 10
If the parameter supplied to the constructor for
ListenerCertificateAuthenticator
is of typeListenerCertificateAuthenticatorDelegate
, all other forms of authentication are bypassed.The client response to the certificate request is passed to the method supplied as the constructor parameter. The logic should take the form of function or block (such as, a closure expression) where the platform allows.
Configure the server (listener) to authenticate the client against a list of one or more certificates provided by the server to the the ListenerCertificateAuthenticator.
-
Kotlin
-
Java
// Configure the client authenticator
// to validate using ROOT CA
// thisClientID.certs is a list containing a client cert to accept
// and any other certs needed to complete a chain between the client cert
// and a CA
val validId = TLSIdentity.getIdentity("Our Corporate Id")
?: throw IllegalStateException("Cannot find corporate id")
// accept only clients signed by the corp cert
val listener = URLEndpointListener(
URLEndpointListenerConfigurationFactory.newConfig(
// get the identity (1)
collections = collections,
identity = validId,
authenticator = ListenerCertificateAuthenticator(validId.certs)
)
) (2)
// Configure the client authenticator
// to validate using ROOT CA
// thisClientID.certs is a list containing a client cert to accept
// and any other certs needed to complete a chain between the client cert
// and a CA
final TLSIdentity validId =
TLSIdentity.getIdentity("Our Corporate Id"); // get the identity (1)
if (validId == null) { throw new IllegalStateException("Cannot find corporate id"); }
thisConfig.setTlsIdentity(validId);
thisConfig.setAuthenticator(
new ListenerCertificateAuthenticator(validId.getCerts())); (2) (3)
// accept only clients signed by the corp cert
final URLEndpointListener thisListener =
new URLEndpointListener(thisConfig);
1 | Get the identity data to authenticate against. This can be, for example, from a resource file provided with the app, or an identity previously saved in secure storage. |
2 | Configure the authenticator to authenticate the client supplied certificate(s) using these root certs. A valid client will provide one or more certificates that match a certificate in this list. |
3 | Add the authenticator to the Listener configuration. |
Configure the server (listener) to authenticate the client using user-supplied logic.
-
Kotlin
-
Java
// Configure authentication using application logic
val thisCorpId = TLSIdentity.getIdentity("OurCorp") (1)
?: throw IllegalStateException("Cannot find corporate id")
thisConfig.tlsIdentity = thisCorpId
thisConfig.authenticator = ListenerCertificateAuthenticator { certs ->
// supply logic that returns boolean
// true for authenticate, false if not
// For instance:
certs[0] == thisCorpId.certs[0]
} (2) (3)
val thisListener = URLEndpointListener(thisConfig)
// Configure authentication using application logic
final TLSIdentity thisCorpId = TLSIdentity.getIdentity("OurCorp"); (1)
if (thisCorpId == null) {
throw new IllegalStateException("Cannot find corporate id");
}
thisConfig.setTlsIdentity(thisCorpId);
thisConfig.setAuthenticator(
new ListenerCertificateAuthenticator(
(certs) -> {
// supply logic that returs boolean
// true for authenticate, false if not
// For instance:
return certs.get(0).equals(thisCorpId.getCerts().get(0));
}
)); (2) (3)
URLEndpointListener listener = new URLEndpointListener(thisConfig);
listener.start();
thisListener = listener;
1 | Get the identity data to authenticate against. This can be, for example, from a resource file provided with the app, or an identity previously saved in secure storage. |
2 | Configure the Authenticator to pass the root certificates to a user supplied code block.
This code assumes complete responsibility for authenticating the client supplied certificate(s).
It must return a boolean value; with true denoting the client supplied certificate authentic. |
3 | Add the authenticator to the Listener configuration. |
Delete Entry
You can remove unwanted entries from secure storage using the secure storage API (see — https://developer.android.com/reference/java/security/KeyStore#deleteEntry(java.lang.String)).
-
Kotlin
-
Java
val thisKeyStore = KeyStore.getInstance("AndroidKeyStore")
thisKeyStore.load(null)
thisKeyStore.deleteEntry(alias)
KeyStore thisKeyStore = KeyStore.getInstance("AndroidKeyStore");
thisKeyStore.load(null);
thisKeyStore.deleteEntry(alias);
The Impact of TLS Settings
The table in this section shows the expected system behavior (in regards to security) depending on the TLS configuration settings deployed.
disableTLS | tlsIdentity (corresponding to server) | Expected system behavior |
---|---|---|
true |
Ignored |
TLS is disabled; all communication is plain text. |
false |
set to nil |
|
false |
Set to server identity generated from a self- or CA-signed certificate
|
|
Start Listener
Once you have completed the Listener’s configuration settings you can initialize the Listener instance and start it running — see: Example 12
-
Kotlin
-
Java
// Initialize the listener
val listener = URLEndpointListener(
URLEndpointListenerConfigurationFactory.newConfig(
collections = collections, (1)
port = 55990, (2)
networkInterface = "wlan0", (3)
enableDeltaSync = false, (4)
// Configure server security
disableTls = false, (5)
// Use an Anonymous Self-Signed Cert
identity = null, (6)
// Configure Client Security using an Authenticator
// For example, Basic Authentication (7)
authenticator = ListenerPasswordAuthenticator { usr, pwd ->
(usr === validUser) && (validPass.contentEquals(pwd))
}
))
// Start the listener
listener.start() (8)
// Initialize the listener
final URLEndpointListener thisListener
= new URLEndpointListener(thisConfig); (1)
// Start the listener
thisListener.start(); (2)
Monitor Listener
Use the Listener’s getStatus
property/method to get counts of total and active connections — see: Example 13.
You should note that these counts can be extremely volatile. So, the actual number of active connections may have changed, by the time the ConnectionStatus
class returns a result.
-
Kotlin
-
Java
val connectionCount = listener.status?.connectionCount (1)
val activeConnectionCount = listener.status?.activeConnectionCount (2)
int connectionCount =
thisListener.getStatus().getConnectionCount(); (1)
int activeConnectionCount =
thisListener.getStatus().getActiveConnectionCount(); (2)
Stop Listener
It is best practice to check the status of the Listener’s connections and stop only when you have confirmed that there are no active connections — see Example 13.
stop
method-
Kotlin
-
Java
val listener = thisListener
thisListener = null
listener?.stop()
thisListener.stop();
Closing the database will also close the Listener. |