Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
20f7e97
fix: keep each WebRTC data channel message within 64 KiB
pjwerneck Nov 18, 2026
20702a9
feat: add a signaling server for WebRTC peers
pjwerneck Nov 18, 2026
2fac5c3
refactor: follow the dev guidelines in the WebRTC chunking and signal…
pjwerneck Nov 18, 2026
53b3e73
feat: connect WebRTC peers through the signaling server when they com…
pjwerneck Nov 19, 2026
6d8f8b8
feat: carry WebRTC peering through the signaling server
pjwerneck Nov 19, 2026
e323a86
feat: keep the DO's owner state on local disk
pjwerneck Nov 19, 2026
1af78bd
feat: let login_do and login_ds sync over WebRTC with no Google login
pjwerneck Nov 19, 2026
d6933c4
fix: keep WebRTC clients signed in, reachable and loud about failures
pjwerneck Nov 20, 2026
98e659c
fix: report WebRTC background failures at the end of a sync
pjwerneck Nov 20, 2026
34d4283
Merge branch 'dev' into pjwerneck/webrtc-signaling-server
pjwerneck Nov 23, 2026
a9f6914
feat: signal and peer WebRTC clients through the org's Firebase project
pjwerneck Nov 23, 2026
81efeea
feat: signal WebRTC clients through the Realtime Database, as the con…
pjwerneck Nov 24, 2026
c868ae6
test: cover a DO with two DSs, a lost channel and old offers in WebRT…
pjwerneck Nov 25, 2026
1ae6cf1
refactor: move the Firebase folder to infra/firebase, as the connspli…
pjwerneck Nov 25, 2026
2a99dcf
Merge branch 'dev' into pjwerneck/webrtc-signaling-server
pjwerneck Nov 25, 2026
f20d50b
fix: keep the reason of a refused ID token out of the TURN function's…
pjwerneck Nov 26, 2026
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
3 changes: 3 additions & 0 deletions infra/firebase/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
functions/venv/
__pycache__/
*-debug.log
96 changes: 96 additions & 0 deletions infra/firebase/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Firebase project for syft's WebRTC mode

In WebRTC mode, syft clients send their messages peer to peer. To find each
other, they use a Firebase project:

- The Realtime Database holds the peer requests, the list of peers that each
user accepts (`acl/`), the key bundles, the peer info, and the signals: a
hello when a client comes online, and the offers and answers of WebRTC.
Each client reads its own signals as one stream. `database.rules.json`
controls who reads and writes each path: a client can send signals only to
a user who accepted it.
- Firebase Authentication proves the email of each user, with a sign-in link
that it sends to the email. A user needs no Google account.
- The Cloud Function `turn_credentials` gives signed-in users TURN
credentials from Cloudflare that work for 4 hours. TURN relays the traffic
of two peers that cannot connect directly.

No server or VM of your own takes part.

OpenMined runs a project, and gives its project ID and web API key to its
users. An org that wants its own project sets it up as below.

## Set up a project

You need Node.js, the Firebase CLI (`npm install -g firebase-tools`), and
Python 3.12 with `uv`.

1. In the [Firebase console](https://console.firebase.google.com), create a
project. Upgrade it to the Blaze plan, because Cloud Functions need it.
2. Create a Realtime Database in `us-central1`, in locked mode. The deploy
below replaces its rules.
3. In Authentication, open "Sign-in method". Turn on "Email/Password", and
in it "Email link (passwordless sign-in)". The console asks for more steps
for apps; syft needs none of them.
4. In the Cloudflare dashboard, create a Realtime TURN key. Keep its token ID
and its API token.
5. In this folder, install the function's dependencies, store the Cloudflare
values as secrets, and deploy:

```bash
uv venv functions/venv --python 3.12
uv pip install --python functions/venv/bin/python -r functions/requirements.txt
firebase login
firebase functions:secrets:set CLOUDFLARE_TURN_KEY_ID --project <project-id>
firebase functions:secrets:set CLOUDFLARE_TURN_KEY_API_TOKEN --project <project-id>
firebase deploy --only database,functions --project <project-id> --force
```

`--force` sets a cleanup policy that deletes old images of the function.

6. Give each user the project ID and the web API key, with your instructions
and never in versioned source. Both are in the project settings, on the
"General" tab. If the API key field is empty, add a web app to the
project.

## Log in as a user

Set the project ID and the web API key that the project owner gave you,
before syft is imported:

```bash
export SYFT_FIREBASE_PROJECT_ID=<project-id>
export SYFT_FIREBASE_API_KEY=<web-api-key>
```

```python
import syft as sy

client = sy.login_do(email, webrtc=True)
```

The first login on a machine sends a sign-in link to the email. Copy the
link from the email, and paste it into the notebook. syft saves the session,
so the next login asks nothing.

## Run on the emulators

For development and tests, the Firebase emulators replace the project:

```bash
npx firebase-tools@15.35.0 emulators:start --only auth,database --project demo-syft
```

```python
from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig

webrtc = WebRTCConfig(
firebase_project_id="demo-syft",
firebase_api_key="any-key",
firebase_emulator_host="127.0.0.1",
)
client = sy.login_do(email, webrtc=webrtc)
```

The emulators run no Cloud Function, so clients get no ICE servers. Peers on
one machine need none. The emulators need Java 21 or later.
69 changes: 69 additions & 0 deletions infra/firebase/database.rules.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"rules": {
"keys": {
"$email": {
".read": "auth != null && auth.token.email_verified == true",
".write": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $email",
".validate": "newData.isString()"
}
},
"info": {
"$owner": {
"$reader": {
".read": "auth != null && auth.token.email_verified == true && (auth.token.email.toLowerCase().replace('.', ',') == $owner || auth.token.email.toLowerCase().replace('.', ',') == $reader)",
".write": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $owner",
".validate": "newData.isString()"
}
}
},
"requests": {
"$to": {
".read": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $to",
"$from": {
".read": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $from",
".write": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $from",
".validate": "newData.isString() && newData.val().toLowerCase().replace('.', ',') == $from"
}
}
},
"acl": {
"$owner": {
".read": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $owner",
"$peer": {
".write": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $owner",
".validate": "newData.isBoolean()"
}
}
},
"signal": {
"$to": {
".read": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $to",
".write": "auth != null && auth.token.email_verified == true && auth.token.email.toLowerCase().replace('.', ',') == $to && !newData.exists()",
"$from": {
"$id": {
".write": "auth != null && auth.token.email_verified == true && ((auth.token.email.toLowerCase().replace('.', ',') == $from && (!data.exists() || $id == 'hello') && newData.exists() && root.child('acl').child($to).child($from).val() == true) || (auth.token.email.toLowerCase().replace('.', ',') == $to && !newData.exists()))",
".validate": "(newData.child('type').val() == 'hello') == ($id == 'hello') && ((newData.child('type').val() == 'hello' && newData.hasChildren(['session'])) || ((newData.child('type').val() == 'offer' || newData.child('type').val() == 'answer') && newData.hasChildren(['request', 'sdp'])) || (newData.child('type').val() == 'refuse' && newData.hasChildren(['request', 'reason'])))",
"type": {
".validate": "newData.isString()"
},
"session": {
".validate": "newData.isString() && (newData.parent().child('type').val() == 'hello')"
},
"request": {
".validate": "newData.isString() && (newData.parent().child('type').val() == 'offer' || newData.parent().child('type').val() == 'answer' || newData.parent().child('type').val() == 'refuse')"
},
"sdp": {
".validate": "newData.isString() && (newData.parent().child('type').val() == 'offer' || newData.parent().child('type').val() == 'answer')"
},
"reason": {
".validate": "newData.isString() && (newData.parent().child('type').val() == 'refuse')"
},
"$other": {
".validate": false
}
}
}
}
}
}
}
25 changes: 25 additions & 0 deletions infra/firebase/firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"database": {
"rules": "database.rules.json"
},
"functions": [
{
"source": "functions",
"codebase": "default",
"runtime": "python312",
"ignore": ["venv", "__pycache__"]
}
],
"emulators": {
"auth": {
"port": 9099
},
"database": {
"port": 9000
},
"ui": {
"enabled": false
},
"singleProjectMode": true
}
}
78 changes: 78 additions & 0 deletions infra/firebase/functions/cloudflare_turn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""Short-lived ICE servers from Cloudflare's TURN service."""

import json
import urllib.request
from dataclasses import dataclass
from typing import Any

GENERATE_URL = (
"https://rtc.live.cloudflare.com/v1/turn/keys/{key_id}"
"/credentials/generate-ice-servers"
)
# Cloudflare refuses urllib's default User-Agent with 403.
USER_AGENT = "syft-signaling"
REQUEST_TIMEOUT_SECONDS = 20
# Cloudflare makes credentials for at most 48 hours.
MAX_TTL_SECONDS = 48 * 3600
# aiortc uses only the first TURN URL. Clients use TURN over UDP only.
TURN_URL = "turn:turn.cloudflare.com:3478?transport=udp"

# Each item is an RTCIceServer as JSON: "urls", and "username" and
# "credential" for a TURN server.
IceServers = list[dict[str, Any]]


@dataclass(frozen=True)
class CloudflareTurnConfig:
key_id: str
api_token: str
# How long each set of credentials works.
ttl_seconds: int

def __post_init__(self) -> None:
if not self.key_id or not self.api_token:
raise ValueError("key_id and api_token must not be empty")
if not 0 < self.ttl_seconds <= MAX_TTL_SECONDS:
raise ValueError(
f"ttl_seconds must be 1 to {MAX_TTL_SECONDS}, got {self.ttl_seconds}"
)


def generate_ice_servers(config: CloudflareTurnConfig) -> IceServers:
"""Return one STUN server and one TURN server with new credentials."""
request = urllib.request.Request(
GENERATE_URL.format(key_id=config.key_id),
data=json.dumps({"ttl": config.ttl_seconds}).encode(),
headers={
"Authorization": f"Bearer {config.api_token}",
"Content-Type": "application/json",
"User-Agent": USER_AGENT,
},
method="POST",
)
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
return pick_ice_servers(json.load(response))


def pick_ice_servers(response: dict) -> IceServers:
"""Pick the first STUN URL, and ``TURN_URL`` with its credentials.

Args:
response: A response from Cloudflare's generate-ice-servers endpoint.

Raises:
ValueError: The response does not have exactly one STUN server and one
TURN server, or the TURN server does not have ``TURN_URL``.
"""
[stun] = [server for server in response["iceServers"] if "username" not in server]
[turn] = [server for server in response["iceServers"] if "username" in server]
if TURN_URL not in turn["urls"]:
raise ValueError(f"Expected {TURN_URL} in the TURN URLs, got {turn['urls']}")
return [
{"urls": stun["urls"][0]},
{
"urls": TURN_URL,
"username": turn["username"],
"credential": turn["credential"],
},
]
61 changes: 61 additions & 0 deletions infra/firebase/functions/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""The Cloud Function that gives syft's WebRTC clients TURN credentials."""

import json
import logging

from cloudflare_turn import CloudflareTurnConfig, generate_ice_servers
from firebase_admin import auth, initialize_app
from firebase_functions import https_fn
from firebase_functions.params import SecretParam

# The syft client builds the URL of the function from this region.
REGION = "us-central1"
# The offering client opens a new peer connection before this time ends.
CREDENTIALS_TTL_SECONDS = 4 * 3600
BEARER_PREFIX = "Bearer "
CLOUDFLARE_TURN_KEY_ID = SecretParam("CLOUDFLARE_TURN_KEY_ID")
CLOUDFLARE_TURN_KEY_API_TOKEN = SecretParam("CLOUDFLARE_TURN_KEY_API_TOKEN")

logger = logging.getLogger(__name__)
initialize_app()


@https_fn.on_request(
region=REGION, secrets=[CLOUDFLARE_TURN_KEY_ID, CLOUDFLARE_TURN_KEY_API_TOKEN]
)
def turn_credentials(request: https_fn.Request) -> https_fn.Response:
"""Return ``{"ice_servers": [...], "lifetime_seconds": ...}`` with new TURN
credentials.

The request must carry the Firebase ID token of a user with a verified
email, as ``Authorization: Bearer <token>``.
"""
header = request.headers.get("Authorization", "")
if not header.startswith(BEARER_PREFIX):
return error_response(401, "Send a Firebase ID token as a Bearer token")
try:
token = auth.verify_id_token(header.removeprefix(BEARER_PREFIX))
except (auth.InvalidIdTokenError, ValueError) as err:
# The reason can describe the setup of the function, so only the log
# of the function gets it.
logger.warning("Refused a Firebase ID token: %r", err)
return error_response(401, "The Firebase ID token is not valid")
if token.get("email_verified") is not True:
return error_response(403, "The email of the user is not verified")
config = CloudflareTurnConfig(
key_id=CLOUDFLARE_TURN_KEY_ID.value,
api_token=CLOUDFLARE_TURN_KEY_API_TOKEN.value,
ttl_seconds=CREDENTIALS_TTL_SECONDS,
)
body = json.dumps(
{
"ice_servers": generate_ice_servers(config),
"lifetime_seconds": CREDENTIALS_TTL_SECONDS,
}
)
return https_fn.Response(body, status=200, content_type="application/json")


def error_response(status: int, reason: str) -> https_fn.Response:
body = json.dumps({"error": reason})
return https_fn.Response(body, status=status, content_type="application/json")
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
2 changes: 2 additions & 0 deletions infra/firebase/functions/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
firebase-functions==0.6.0
firebase-admin==7.7.0
13 changes: 11 additions & 2 deletions packages/syft-rds/src/syft_rds/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
SyftboxManagerConfig,
)
from syft.sync.sync.collection_spec import CollectionLayout, CollectionSyncSpec
from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig
from syft_job import SyftJobConfig
from syft_datasets.config import SyftBoxConfig, protocol_dir_name
from syft_datasets.dataset_manager import (
Expand Down Expand Up @@ -151,6 +152,7 @@ def for_jupyter(
email,
has_do_role=False,
has_ds_role=False,
webrtc: WebRTCConfig | None = None,
token_path=None,
**kw,
) -> "SyftRDSClientConfig":
Expand All @@ -159,7 +161,10 @@ def for_jupyter(
has_do_role=has_do_role,
has_ds_role=has_ds_role,
token_path=token_path,
collection_specs=DATASET_COLLECTION_SPECS,
# Datasets do not go over WebRTC yet, so a WebRTC client registers
# no dataset specs.
collection_specs=DATASET_COLLECTION_SPECS if webrtc is None else [],
webrtc=webrtc,
**kw,
)
return cls._compose(sync)
Expand All @@ -170,13 +175,17 @@ def for_colab(
email,
has_do_role=False,
has_ds_role=False,
webrtc: WebRTCConfig | None = None,
**kw,
) -> "SyftRDSClientConfig":
sync = SyftboxManagerConfig.for_colab(
email=email,
has_do_role=has_do_role,
has_ds_role=has_ds_role,
collection_specs=DATASET_COLLECTION_SPECS,
# Datasets do not go over WebRTC yet, so a WebRTC client registers
# no dataset specs.
collection_specs=DATASET_COLLECTION_SPECS if webrtc is None else [],
webrtc=webrtc,
**kw,
)
return cls._compose(sync)
Expand Down
Loading
Loading