Repository navigation
feat: sync over WebRTC with Firebase signaling and no Google login (WIP) #9654
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
pjwerneck
wants to merge
16
commits into
dev
Choose a base branch
from
pjwerneck/webrtc-signaling-server
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+4,330
−146
Draft
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 20702a9
feat: add a signaling server for WebRTC peers
pjwerneck 2fac5c3
refactor: follow the dev guidelines in the WebRTC chunking and signal…
pjwerneck 53b3e73
feat: connect WebRTC peers through the signaling server when they com…
pjwerneck 6d8f8b8
feat: carry WebRTC peering through the signaling server
pjwerneck e323a86
feat: keep the DO's owner state on local disk
pjwerneck 1af78bd
feat: let login_do and login_ds sync over WebRTC with no Google login
pjwerneck d6933c4
fix: keep WebRTC clients signed in, reachable and loud about failures
pjwerneck 98e659c
fix: report WebRTC background failures at the end of a sync
pjwerneck 34d4283
Merge branch 'dev' into pjwerneck/webrtc-signaling-server
pjwerneck a9f6914
feat: signal and peer WebRTC clients through the org's Firebase project
pjwerneck 81efeea
feat: signal WebRTC clients through the Realtime Database, as the con…
pjwerneck c868ae6
test: cover a DO with two DSs, a lost channel and old offers in WebRT…
pjwerneck 1ae6cf1
refactor: move the Firebase folder to infra/firebase, as the connspli…
pjwerneck 2a99dcf
Merge branch 'dev' into pjwerneck/webrtc-signaling-server
pjwerneck f20d50b
fix: keep the reason of a refused ID token out of the TURN function's…
pjwerneck File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| functions/venv/ | ||
| __pycache__/ | ||
| *-debug.log |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"], | ||
| }, | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| firebase-functions==0.6.0 | ||
| firebase-admin==7.7.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.