diff --git a/infra/firebase/.gitignore b/infra/firebase/.gitignore new file mode 100644 index 00000000000..4d291c15836 --- /dev/null +++ b/infra/firebase/.gitignore @@ -0,0 +1,3 @@ +functions/venv/ +__pycache__/ +*-debug.log diff --git a/infra/firebase/README.md b/infra/firebase/README.md new file mode 100644 index 00000000000..6fcfd1a524d --- /dev/null +++ b/infra/firebase/README.md @@ -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 + firebase functions:secrets:set CLOUDFLARE_TURN_KEY_API_TOKEN --project + firebase deploy --only database,functions --project --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= +export SYFT_FIREBASE_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. diff --git a/infra/firebase/database.rules.json b/infra/firebase/database.rules.json new file mode 100644 index 00000000000..28d4e33195d --- /dev/null +++ b/infra/firebase/database.rules.json @@ -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 + } + } + } + } + } + } +} diff --git a/infra/firebase/firebase.json b/infra/firebase/firebase.json new file mode 100644 index 00000000000..347b5685f6f --- /dev/null +++ b/infra/firebase/firebase.json @@ -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 + } +} diff --git a/infra/firebase/functions/cloudflare_turn.py b/infra/firebase/functions/cloudflare_turn.py new file mode 100644 index 00000000000..18dc648c5c4 --- /dev/null +++ b/infra/firebase/functions/cloudflare_turn.py @@ -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"], + }, + ] diff --git a/infra/firebase/functions/main.py b/infra/firebase/functions/main.py new file mode 100644 index 00000000000..aa0c3fb01e0 --- /dev/null +++ b/infra/firebase/functions/main.py @@ -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 ``. + """ + 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") diff --git a/infra/firebase/functions/requirements.txt b/infra/firebase/functions/requirements.txt new file mode 100644 index 00000000000..a4ed54d60f4 --- /dev/null +++ b/infra/firebase/functions/requirements.txt @@ -0,0 +1,2 @@ +firebase-functions==0.6.0 +firebase-admin==7.7.0 diff --git a/packages/syft-rds/src/syft_rds/config.py b/packages/syft-rds/src/syft_rds/config.py index 88230156ed5..b4c946bef3b 100644 --- a/packages/syft-rds/src/syft_rds/config.py +++ b/packages/syft-rds/src/syft_rds/config.py @@ -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 ( @@ -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": @@ -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) @@ -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) diff --git a/packages/syft-rds/src/syft_rds/login.py b/packages/syft-rds/src/syft_rds/login.py index 10355f50e77..a4203358106 100644 --- a/packages/syft-rds/src/syft_rds/login.py +++ b/packages/syft-rds/src/syft_rds/login.py @@ -13,15 +13,15 @@ from pathlib import Path +from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig from syft.sync.environments.environment import Environment from syft.sync.login import ( _import_key_file, _init_client_login, - _resolve_login_params, + _maybe_sign_in_to_firebase, + _resolve_login_target, ) -from syft.sync.login_utils import handle_potential_version_mismatches_on_login from syft.sync.utils.syftbox_utils import check_env - from syft_rds.client import SyftRDSClient from syft_rds.config import SyftRDSClientConfig @@ -37,41 +37,43 @@ def _login( has_ds_role: bool, encryption: bool | None = None, key_file: str | Path | None = None, + webrtc: bool | WebRTCConfig = False, ) -> SyftRDSClient: """Shared RDS login. Mirrors the pre-split ``syft`` login flow: detect the environment, resolve login params """ - env = check_env() - email, token_path = _resolve_login_params(email, token_path) - repair_pending = handle_potential_version_mismatches_on_login(email, token_path) + target = _resolve_login_target(email, token_path, webrtc) - if env == Environment.COLAB: + if check_env() == Environment.COLAB: config = SyftRDSClientConfig.for_colab( - email=email, + email=target.email, has_do_role=has_do_role, has_ds_role=has_ds_role, skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, encryption=encryption, + webrtc=target.webrtc, ) else: config = SyftRDSClientConfig.for_jupyter( - email=email, + email=target.email, has_do_role=has_do_role, has_ds_role=has_ds_role, - token_path=Path(token_path) if token_path is not None else None, + token_path=Path(target.token_path) if target.token_path else None, skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, encryption=encryption, + webrtc=target.webrtc, ) - _import_key_file(key_file, config.sync.syftbox_folder, email) + _import_key_file(key_file, config.sync.syftbox_folder, target.email) + _maybe_sign_in_to_firebase(target, config.sync.syftbox_folder) client = SyftRDSClient.from_config(config) _init_client_login( client.sync_engine, sync=sync, load_peers=load_peers, - repair_pending=repair_pending, + repair_pending=target.repair_pending, ) return client @@ -85,8 +87,15 @@ def login_do( skip_peer_on_patch_version_diff: bool | None = None, encryption: bool | None = None, key_file: str | Path | None = None, + webrtc: bool | WebRTCConfig = False, ) -> SyftRDSClient: - """Log in as a Data Owner and return a self-contained RDS client.""" + """Log in as a DO and return a self-contained RDS client. + + ``webrtc=True`` syncs over WebRTC with no Google login, through the + Firebase project in the ``SYFT_FIREBASE_PROJECT_ID`` and + ``SYFT_FIREBASE_API_KEY`` settings. The first login on a machine sends a + sign-in link to the email. + """ return _login( email=email, token_path=token_path, @@ -95,6 +104,7 @@ def login_do( skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, encryption=encryption, key_file=key_file, + webrtc=webrtc, has_do_role=True, has_ds_role=False, ) @@ -109,8 +119,15 @@ def login_ds( skip_peer_on_patch_version_diff: bool | None = None, encryption: bool | None = None, key_file: str | Path | None = None, + webrtc: bool | WebRTCConfig = False, ) -> SyftRDSClient: - """Log in as a Data Scientist and return a self-contained RDS client.""" + """Log in as a DS and return a self-contained RDS client. + + ``webrtc=True`` syncs over WebRTC with no Google login, through the + Firebase project in the ``SYFT_FIREBASE_PROJECT_ID`` and + ``SYFT_FIREBASE_API_KEY`` settings. The first login on a machine sends a + sign-in link to the email. + """ return _login( email=email, token_path=token_path, @@ -119,6 +136,7 @@ def login_ds( skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, encryption=encryption, key_file=key_file, + webrtc=webrtc, has_do_role=False, has_ds_role=True, ) diff --git a/packages/syft-rds/tests/test_login_key_file.py b/packages/syft-rds/tests/test_login_key_file.py index 8f1df8c74a2..b8d53b1efcd 100644 --- a/packages/syft-rds/tests/test_login_key_file.py +++ b/packages/syft-rds/tests/test_login_key_file.py @@ -2,11 +2,11 @@ from unittest.mock import MagicMock import pytest +from syft_rds import login as rds_login import syft.sync.login from syft.sync.environments.environment import Environment from syft.sync.peers.peer_store import PeerStore -from syft_rds import login as rds_login EMAIL = "do@openmined.org" @@ -20,7 +20,7 @@ def test_login_restores_uploaded_key_file(tmp_path, monkeypatch, login): for module in (rds_login, syft.sync.login): monkeypatch.setattr(module, "check_env", lambda: Environment.JUPYTER) monkeypatch.setattr( - rds_login, + syft.sync.login, "handle_potential_version_mismatches_on_login", lambda email, token_path: False, ) diff --git a/packages/syft-rds/tests/test_webrtc_config.py b/packages/syft-rds/tests/test_webrtc_config.py new file mode 100644 index 00000000000..3d53ad80d2e --- /dev/null +++ b/packages/syft-rds/tests/test_webrtc_config.py @@ -0,0 +1,19 @@ +"""The syft-rds config of a WebRTC login.""" + +from syft_rds.config import SyftRDSClientConfig + +from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig + + +def test_webrtc_config_registers_no_dataset_specs(): + # A dataset spec would make a DS sync delete its local dataset copies. + webrtc = WebRTCConfig(firebase_project_id="syft-test", firebase_api_key="k") + + config = SyftRDSClientConfig.for_jupyter( + "ds@example.com", has_ds_role=True, webrtc=webrtc + ) + + sync = config.sync + watcher_config = sync.datasite_watcher_syncer_config.datasite_watcher_cache_config + assert watcher_config.collection_specs == [] + assert sync.datasite_owner_syncer_config.collection_specs == [] diff --git a/syft/sync/config/config.py b/syft/sync/config/config.py index 53ce03e86b3..cf600fdbdeb 100644 --- a/syft/sync/config/config.py +++ b/syft/sync/config/config.py @@ -1,5 +1,5 @@ -from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic import Field +from pydantic_settings import BaseSettings, SettingsConfigDict class SyftboxSettings(BaseSettings): @@ -7,6 +7,10 @@ class SyftboxSettings(BaseSettings): dev_mode: bool = Field(default=False) token_path: str | None = Field(default=None) + # The Firebase project for login with webrtc=True. The project owner gives + # both values to its users. + firebase_project_id: str | None = Field(default=None) + firebase_api_key: str | None = Field(default=None) settings = SyftboxSettings() diff --git a/syft/sync/connections/connection_router.py b/syft/sync/connections/connection_router.py index ac2866f2e4a..bc2a13e92be 100644 --- a/syft/sync/connections/connection_router.py +++ b/syft/sync/connections/connection_router.py @@ -272,6 +272,15 @@ def download_events_message_by_id( # PEER MANAGEMENT # ========================================================================= + def set_peers(self, peer_emails: list[str]) -> None: + """Set the peers that this client may exchange messages with.""" + self.connections.p2p_con.set_peers(peer_emails) + + def maybe_raise_background_errors(self) -> None: + """Raise the failures of the connections in the background since the + last call, if there are any.""" + self.connections.p2p_con.maybe_raise_background_errors() + def add_peer(self, peer_email: str, verbose: bool = True) -> Peer: platform = self.connections.platform diff --git a/syft/sync/connections/protocols.py b/syft/sync/connections/protocols.py index 6b744386c54..29e357529e0 100644 --- a/syft/sync/connections/protocols.py +++ b/syft/sync/connections/protocols.py @@ -59,6 +59,18 @@ class P2PConnection(RouterConnection, ABC): # outbox, so the owner compacts them. A live link drops them on receipt. keeps_sent_messages: bool = False + def set_peers(self, peers: list[str]) -> None: + """Set the peers that this client may exchange messages with. + + A backend with live channels, such as WebRTC, connects to them. Drive + needs no channels, so here it does nothing. + """ + + def maybe_raise_background_errors(self) -> None: + """Raise the failures in the background since the last call, if there + are any. Drive does no work in the background, so here it does + nothing.""" + @abstractmethod def send( self, peer: str, msg_id: str, data: bytes, kind: MessageKind diff --git a/syft/sync/connections/webrtc/firebase/__init__.py b/syft/sync/connections/webrtc/firebase/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/syft/sync/connections/webrtc/firebase/auth.py b/syft/sync/connections/webrtc/firebase/auth.py new file mode 100644 index 00000000000..9a0eaa0e638 --- /dev/null +++ b/syft/sync/connections/webrtc/firebase/auth.py @@ -0,0 +1,162 @@ +"""Firebase Auth for WebRTC mode: the sign-in with an emailed link, and the ID +tokens that the Firebase REST APIs need.""" + +import json +import os +import threading +import time +from collections.abc import Callable +from http import HTTPStatus +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +from syft.sync.connections.webrtc.firebase.project import FirebaseProject +from syft.sync.connections.webrtc.firebase.rest import FirebaseRequestError, post_json +from syft.sync.sync.constants import CACHE_DIR + +# One session file for each project, under the syftbox folder. +SESSIONS_PATH = Path(CACHE_DIR) / "webrtc" / "firebase_sessions" +# Only the user can read a session file. +SESSION_FILE_MODE = 0o600 +# A new ID token comes when the old one has less time than this left. +ID_TOKEN_MARGIN_SECONDS = 300 +OOB_CODE_PARAMETER = "oobCode" +REFRESH_TOKEN_KEY = "refresh_token" + + +def firebase_session_path(syftbox_folder: Path, project_id: str) -> Path: + """Return the path of the session file of ``project_id``.""" + return syftbox_folder / SESSIONS_PATH / f"{project_id}.json" + + +def sign_in_with_emailed_link( + project: FirebaseProject, + email: str, + session_path: Path, + ask_link: Callable[[], str], +) -> None: + """Send a sign-in link to ``email``, sign in with the link that + ``ask_link`` returns, and save the session in ``session_path``. + + Raises: + ValueError: The link has no one-time code. + ConnectionError: Firebase refuses the sign-in. + """ + send_sign_in_link(project, email) + reply = post_json( + f"{project.auth_url}/accounts:signInWithEmailLink?key={project.api_key}", + {"email": email, "oobCode": oob_code_of(ask_link())}, + ) + save_refresh_token(session_path, reply["refreshToken"]) + + +def send_sign_in_link(project: FirebaseProject, email: str) -> None: + post_json( + f"{project.auth_url}/accounts:sendOobCode?key={project.api_key}", + { + "requestType": "EMAIL_SIGNIN", + "email": email, + # Firebase allows this domain of each project from the start. + "continueUrl": f"https://{project.project_id}.firebaseapp.com", + "canHandleCodeInApp": True, + }, + ) + + +def oob_code_of(link: str) -> str: + """Return the one-time code in a sign-in link. + + Raises: + ValueError: The link has no one-time code. + """ + query = parse_qs(urlparse(link.strip()).query) + if OOB_CODE_PARAMETER not in query: + raise ValueError(f"Expected a sign-in link with an oobCode, got {link!r}") + return query[OOB_CODE_PARAMETER][0] + + +def save_refresh_token(session_path: Path, refresh_token: str) -> None: + session_path.parent.mkdir(parents=True, exist_ok=True) + temp_path = session_path.with_suffix(".tmp") + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC + with os.fdopen(os.open(temp_path, flags, SESSION_FILE_MODE), "w") as file: + json.dump({REFRESH_TOKEN_KEY: refresh_token}, file) + os.replace(temp_path, session_path) + + +def load_refresh_token(session_path: Path) -> str: + """Return the refresh token that ``save_refresh_token`` saved. + + Raises: + FileNotFoundError: No session is saved in ``session_path``. + """ + if not session_path.exists(): + raise FileNotFoundError( + f"No Firebase session in {session_path}. Log in with webrtc to sign in." + ) + return json.loads(session_path.read_text())[REFRESH_TOKEN_KEY] + + +def session_is_refused(project: FirebaseProject, session_path: Path) -> bool: + """Return whether Firebase refuses the session in ``session_path``, as it + does when the user was deleted or disabled. + + Raises: + ConnectionError: Firebase fails for another reason. + """ + refresh_token = load_refresh_token(session_path) + try: + FirebaseSession(project, session_path, refresh_token).id_token() + except FirebaseRequestError as err: + if err.status == HTTPStatus.BAD_REQUEST: + return True + raise + else: + return False + + +class FirebaseSession: + """The ID tokens of the user who signed in to a Firebase project. It works + from any thread.""" + + def __init__( + self, project: FirebaseProject, session_path: Path, refresh_token: str + ): + """``session_path`` gets each new refresh token that Firebase gives.""" + self._project = project + self._session_path = session_path + self._refresh_token = refresh_token + self._lock = threading.Lock() + self._id_token = "" + # In time.time() seconds: the wall clock runs on while the machine + # sleeps, and the token expires on it too. + self._id_token_expiry = 0.0 + + def id_token(self) -> str: + """Return an ID token that works for at least + ``ID_TOKEN_MARGIN_SECONDS``. + + Raises: + ConnectionError: Firebase refuses the saved session. + """ + with self._lock: + if time.time() > self._id_token_expiry - ID_TOKEN_MARGIN_SECONDS: + self._refresh_id_token() + return self._id_token + + def expire_id_token(self) -> None: + """Make the next ``id_token`` call get a new token, as after Firebase + said that the token expired.""" + with self._lock: + self._id_token_expiry = 0.0 + + def _refresh_id_token(self) -> None: + reply = post_json( + f"{self._project.token_url}/token?key={self._project.api_key}", + {"grantType": "refresh_token", "refreshToken": self._refresh_token}, + ) + self._id_token = reply["id_token"] + self._id_token_expiry = time.time() + int(reply["expires_in"]) + # Firebase can give a new refresh token in place of the old one. + self._refresh_token = reply["refresh_token"] + save_refresh_token(self._session_path, self._refresh_token) diff --git a/syft/sync/connections/webrtc/firebase/database.py b/syft/sync/connections/webrtc/firebase/database.py new file mode 100644 index 00000000000..029b37ebf8f --- /dev/null +++ b/syft/sync/connections/webrtc/firebase/database.py @@ -0,0 +1,260 @@ +"""The Realtime Database REST API of WebRTC mode, used as the signed-in user, +so the rules in infra/firebase/database.rules.json apply.""" + +import http.client +import json +import socket +import threading +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from typing import Any +from urllib.parse import quote, urlencode, urlsplit + +from syft.sync.connections.exceptions import ConnectionUnavailableError +from syft.sync.connections.webrtc.firebase.auth import FirebaseSession +from syft.sync.connections.webrtc.firebase.project import FirebaseProject +from syft.sync.connections.webrtc.firebase.rest import ( + FirebaseRequestError, + request_json, + without_query, +) + +# A key cannot hold ".", and an email cannot hold ",". +KEY_FORBIDDEN_CHARACTERS = set("$#[]/") +# Firebase sends a keep-alive event every 30 s. +STREAM_READ_TIMEOUT_SECONDS = 90 +MAX_REDIRECTS = 5 +REDIRECT_STATUSES = (301, 302, 307, 308) +# Firebase ends a stream with this event when its ID token expires. +AUTH_REVOKED = "auth_revoked" +KEEP_ALIVE = "keep-alive" +# "put" replaces the data at a path; "patch" updates its children. +PUT = "put" +PATCH = "patch" +CHANGE_EVENTS = (PUT, PATCH) + + +def email_key(email: str) -> str: + """Return the database key of ``email``: in lower case, with each "." as + ",". + + Raises: + ValueError: ``email`` holds a character that no key can hold. + """ + forbidden = KEY_FORBIDDEN_CHARACTERS & set(email) + if forbidden or not email.isprintable(): + raise ValueError( + f"Expected an email with no {sorted(KEY_FORBIDDEN_CHARACTERS)} and no " + f"control characters, got {email!r}" + ) + return email.lower().replace(".", ",") + + +def email_of_key(key: str) -> str: + """Return the email in lower case that ``email_key`` made ``key`` from.""" + return key.replace(",", ".") + + +@dataclass(frozen=True) +class StreamEvent: + # PUT or PATCH. + kind: str + # The path under the streamed path; "/" is the streamed path itself. + path: str + data: Any + + +class RealtimeDatabase: + """Reads and writes the Realtime Database as the user of ``session``. + + Each call raises ``ConnectionError`` when the database refuses it, and + ``ConnectionUnavailableError`` when the database cannot be reached. + """ + + def __init__(self, project: FirebaseProject, session: FirebaseSession): + self._project = project + self._session = session + + def get(self, path: str) -> Any: + """Return the data at ``path``, or None if nothing is there.""" + return request_json("GET", self.url(path)) + + def put(self, path: str, value: Any) -> None: + request_json("PUT", self.url(path), value) + + def update(self, values: dict[str, Any]) -> None: + """Write each path in ``values`` at once, or none of them.""" + request_json("PATCH", self.url(""), values) + + def post(self, path: str, value: Any) -> str: + """Add ``value`` as a new child of ``path``, and return its key.""" + return request_json("POST", self.url(path), value)["name"] + + def delete(self, path: str) -> None: + request_json("DELETE", self.url(path)) + + def expire_id_token(self) -> None: + """Make the next call get a new ID token.""" + self._session.expire_id_token() + + def stream( + self, + path: str, + on_event: Callable[[StreamEvent], None], + on_end: Callable[[OSError], None], + ) -> "DatabaseStream": + """Start a stream of the changes at ``path``. ``on_event`` and + ``on_end`` run on the thread of the stream.""" + stream = DatabaseStream(self, path, on_event, on_end) + stream.start() + return stream + + def url(self, path: str) -> str: + """Return the REST URL of ``path``, with a fresh ID token.""" + query = {"auth": self._session.id_token()} + if self._project.database_namespace is not None: + query["ns"] = self._project.database_namespace + quoted = quote(path, safe="/@,") + return f"{self._project.database_url}/{quoted}.json?{urlencode(query)}" + + +class DatabaseStream: + """Reads the server-sent events of one path on its own thread. + + When Firebase ends the stream because the ID token expired, it opens the + stream again with a new token. Any other end goes to ``on_end``. + """ + + def __init__( + self, + database: RealtimeDatabase, + path: str, + on_event: Callable[[StreamEvent], None], + on_end: Callable[[OSError], None], + ): + self._database = database + self._path = path + self._on_event = on_event + self._on_end = on_end + self._closing = False + self._connection: http.client.HTTPConnection | None = None + # The socket of the open stream. http.client gives it to the response, + # and the connection no longer holds it. + self._socket: socket.socket | None = None + self._thread = threading.Thread( + target=self._run, daemon=True, name=f"firebase-stream:{path}" + ) + + def start(self) -> None: + self._thread.start() + + def close(self) -> None: + """Stop the stream; ``on_end`` gets no call.""" + self._closing = True + if self._socket is not None and self._thread.is_alive(): + # Wakes the thread from its blocking read. + self._socket.shutdown(socket.SHUT_RDWR) + self._thread.join() + + def _run(self) -> None: + try: + while not self._closing: + self._read_until_token_expires() + except ( + OSError, + ConnectionUnavailableError, + http.client.HTTPException, + ValueError, + ) as err: + if not self._closing: + self._on_end( + ConnectionError(f"The stream of {self._path} ended: {err}") + ) + + def _read_until_token_expires(self) -> None: + """Raises: + ConnectionError: Firebase cancels or ends the stream. + """ + response = self._open() + if self._closing: + return + for kind, data in server_sent_events(response): + if kind in CHANGE_EVENTS: + change = json.loads(data) + self._on_event(StreamEvent(kind, change["path"], change["data"])) + elif kind == AUTH_REVOKED: + self._database.expire_id_token() + return + elif kind != KEEP_ALIVE: + raise ConnectionError(f"Firebase sent {kind!r}: {data}") + if not self._closing: + raise ConnectionError("Firebase closed the stream") + + def _open(self) -> http.client.HTTPResponse: + """Raises: + FirebaseRequestError: The database refuses the stream. + ConnectionError: The database redirects the stream too often. + """ + url = self._database.url(self._path) + for _ in range(MAX_REDIRECTS): + response = self._request_stream(url) + if response.status not in REDIRECT_STATUSES: + return checked_stream(response, url) + url = redirect_location(response) + raise ConnectionError( + f"The database redirected the stream of {self._path} more than " + f"{MAX_REDIRECTS} times" + ) + + def _request_stream(self, url: str) -> http.client.HTTPResponse: + parts = urlsplit(url) + connection_class = ( + http.client.HTTPSConnection + if parts.scheme == "https" + else http.client.HTTPConnection + ) + if self._connection is not None: + self._connection.close() + self._connection = connection_class( + parts.netloc, timeout=STREAM_READ_TIMEOUT_SECONDS + ) + self._connection.request( + "GET", + f"{parts.path}?{parts.query}", + headers={"Accept": "text/event-stream"}, + ) + self._socket = self._connection.sock + return self._connection.getresponse() + + +def checked_stream( + response: http.client.HTTPResponse, url: str +) -> http.client.HTTPResponse: + """Raises: + FirebaseRequestError: ``response`` has an error status. + """ + if response.status != 200: + reason = response.read().decode(errors="replace") + raise FirebaseRequestError(without_query(url), response.status, reason) + return response + + +def redirect_location(response: http.client.HTTPResponse) -> str: + """Raises: + ConnectionError: ``response`` has no Location. + """ + location = response.getheader("Location") + if location is None: + raise ConnectionError("The database redirected the stream to no Location") + return location + + +def server_sent_events(response: http.client.HTTPResponse) -> Iterator[tuple[str, str]]: + """Yield (event, data) for each server-sent event until the response ends.""" + event = "" + while line := response.readline(): + text = line.decode().rstrip("\r\n") + if text.startswith("event:"): + event = text.removeprefix("event:").strip() + elif text.startswith("data:"): + yield event, text.removeprefix("data:").strip() diff --git a/syft/sync/connections/webrtc/firebase/database_peering.py b/syft/sync/connections/webrtc/firebase/database_peering.py new file mode 100644 index 00000000000..086a0156f6b --- /dev/null +++ b/syft/sync/connections/webrtc/firebase/database_peering.py @@ -0,0 +1,177 @@ +"""Peering through the Realtime Database: peer requests, acl/, key bundles and +peer info. + +infra/firebase/database.rules.json has the paths and who may read and write them. +The peer list stays on local disk. +""" + +from dataclasses import dataclass +from pathlib import Path + +from syft_migration import MigrationError + +from syft.sync.connections.naming import PEERS_META_KEY, SYFT_PEERS_VERSION +from syft.sync.connections.protocols import PeeringConnection +from syft.sync.connections.webrtc.firebase.database import ( + RealtimeDatabase, + email_key, + email_of_key, +) +from syft.sync.peers.peer import PeerState +from syft.sync.sync.caches.persisted_dict import PersistedDict +from syft.sync.sync.constants import CACHE_DIR +from syft.sync.version.exceptions import UnreadablePeerInfoError +from syft.sync.version.peer_info import PeerInfo + +# The peer list, under the syftbox folder. +PEER_REGISTRY_PATH = Path(CACHE_DIR) / "webrtc" / "SYFT_peers.json" +# A request from a peer in one of these states needs no decision. +DECIDED_STATES = (PeerState.ACCEPTED.value, PeerState.REJECTED.value) + + +def requests_path(receiver: str) -> str: + """Return the node of the requests to peer with ``receiver``.""" + return f"requests/{email_key(receiver)}" + + +def acl_path(owner: str) -> str: + """Return the node of the peers that ``owner`` accepts.""" + return f"acl/{email_key(owner)}" + + +def key_bundle_path(email: str) -> str: + return f"keys/{email_key(email)}" + + +def peer_info_path(owner: str, reader: str) -> str: + """Return the node of the peer info that ``owner`` shares with ``reader``.""" + return f"info/{email_key(owner)}/{email_key(reader)}" + + +@dataclass(frozen=True) +class DatabasePeeringConfig: + # The email of this client. Peers see it as spelled here. + email: str + syftbox_folder: Path + + def __post_init__(self) -> None: + if not self.email: + raise ValueError("email must not be empty") + + +class DatabasePeeringConnection(PeeringConnection): + """``PeeringConnection`` through the Realtime Database. It works from any + thread.""" + + def __init__(self, config: DatabasePeeringConfig, database: RealtimeDatabase): + self._config = config + self._database = database + self._registry = PersistedDict(path=config.syftbox_folder / PEER_REGISTRY_PATH) + + def whoami(self) -> str: + return self._config.email + + def open_channels(self, peer: str) -> None: + """Ask ``peer`` to peer, and let it send signals to this client. + + WebRTC opens the channel when both peers are online. + """ + me = self._config.email + self._database.update( + { + f"{requests_path(peer)}/{email_key(me)}": me, + f"{acl_path(me)}/{email_key(peer)}": True, + } + ) + + def incoming_requests(self) -> list[str]: + """Return the emails that asked to peer, and have no decision yet. + + An email that is in the peer list comes back as the peer list spells it. + """ + requests = self._database.get(requests_path(self._config.email)) + senders = [] if requests is None else list(requests.values()) + registry = dict(self._registry.items()) + # email in lower case -> the email as the peer list spells it + spellings = {email.lower(): email for email in registry} + emails = [spellings.get(sender.lower(), sender) for sender in senders] + return [ + email + for email in emails + if email not in registry or registry[email]["state"] not in DECIDED_STATES + ] + + def read_peer_registry(self, force_download: bool = False) -> dict: + """Return the peer list on local disk. + + Each call reads the file, so ``force_download`` changes nothing. + """ + return dict(self._registry.items()) + + def update_peer_registry( + self, peer: str, state: str, public_encryption_bundle: dict | None = None + ) -> None: + def update(entry: dict | None) -> dict: + new_entry = {} if entry is None else dict(entry) + new_entry["state"] = state + if public_encryption_bundle is not None: + new_entry["public_encryption_bundle"] = public_encryption_bundle + return new_entry + + self._registry.update_entry(peer, update) + self._registry.set(PEERS_META_KEY, {"version": SYFT_PEERS_VERSION}) + + def publish_key_bundle(self, peer: str, bundle_json: str) -> None: + """Publish the key bundle of this client, the same for every peer.""" + self._database.put(key_bundle_path(self._config.email), bundle_json) + + def grant_key_bundle_read(self, peer: str) -> None: + """Do nothing: every signed-in user can read keys/, the key directory.""" + + def read_own_key_bundle(self, peer: str) -> str | None: + return self._database.get(key_bundle_path(self._config.email)) + + def read_peer_key_bundle(self, peer: str) -> str | None: + return self._database.get(key_bundle_path(peer)) + + def publish_peer_info(self, peer_info: PeerInfo) -> None: + """Write ``peer_info`` for this client, and for each peer it accepts.""" + me = self._config.email + accepted = self._database.get(acl_path(me)) + readers = ( + [] if accepted is None else [key for key, ok in accepted.items() if ok] + ) + paths = [peer_info_path(me, me)] + [ + peer_info_path(me, email_of_key(reader)) for reader in readers + ] + self._write_peer_info(paths, peer_info) + + def read_own_peer_info(self) -> PeerInfo | None: + return self._read_peer_info(self._config.email) + + def read_peer_info(self, peer: str) -> PeerInfo | None: + return self._read_peer_info(peer) + + def grant_peer_info_read(self, peer: str, peer_info: PeerInfo) -> None: + """Write ``peer_info`` for this client and for ``peer``.""" + me = self._config.email + self._write_peer_info( + [peer_info_path(me, me), peer_info_path(me, peer)], peer_info + ) + + def _write_peer_info(self, paths: list[str], peer_info: PeerInfo) -> None: + data = peer_info.to_json() + self._database.update({path: data for path in paths}) + + def _read_peer_info(self, owner: str) -> PeerInfo | None: + """Return the peer info that ``owner`` shares with this client, or None + if it shares none.""" + data = self._database.get(peer_info_path(owner, self._config.email)) + if data is None: + return None + try: + return PeerInfo.from_json(data) + except (ValueError, MigrationError) as err: + raise UnreadablePeerInfoError( + f"Could not read the peer info of {owner}: {err}" + ) from err diff --git a/syft/sync/connections/webrtc/firebase/database_signaling.py b/syft/sync/connections/webrtc/firebase/database_signaling.py new file mode 100644 index 00000000000..a8b8cfd4338 --- /dev/null +++ b/syft/sync/connections/webrtc/firebase/database_signaling.py @@ -0,0 +1,373 @@ +"""Signaling through the Realtime Database. + +A sender writes each offer, answer and refusal at +signal/{receiver}/{sender}/{id}, and its hello at +signal/{receiver}/{sender}/hello, where the next hello replaces it. The rules +in infra/firebase/database.rules.json let it write only if the receiver +accepted it. Each client reads its own node, signal/{me}, as one stream. +""" + +import asyncio +import uuid +from collections.abc import Callable, Coroutine +from dataclasses import dataclass +from typing import Any, TypeVar + +from syft.sync.connections.exceptions import ConnectionUnavailableError +from syft.sync.connections.webrtc.firebase.database import ( + PATCH, + DatabaseStream, + RealtimeDatabase, + StreamEvent, + email_key, + email_of_key, +) +from syft.sync.connections.webrtc.signaling.signaling import ( + IceServerSet, + IceServerSource, + OnAnswerFailed, + OnClosed, + OnHello, + OnOffer, + Signaling, +) + +# The fields of a signal, and its types. +TYPE_FIELD = "type" +# The session of the sender of a hello: a new id at each sign-in. +SESSION_FIELD = "session" +# The id of the offer that an offer, an answer or a refusal belongs to. +REQUEST_FIELD = "request" +SDP_FIELD = "sdp" +REASON_FIELD = "reason" +HELLO = "hello" +OFFER = "offer" +ANSWER = "answer" +REFUSE = "refuse" +# The one child of signal/{receiver}/{sender} that holds the sender's hello. +HELLO_SLOT = "hello" + +T = TypeVar("T") + + +def inbox_path(email: str) -> str: + """Return the node of the signals to ``email``.""" + return f"signal/{email_key(email)}" + + +def signal_path(receiver: str, sender: str) -> str: + """Return the node of the signals from ``sender`` to ``receiver``.""" + return f"{inbox_path(receiver)}/{email_key(sender)}" + + +@dataclass(frozen=True) +class Signal: + sender_key: str + signal_id: str + fields: dict[str, str] + + @property + def sender(self) -> str: + return email_of_key(self.sender_key) + + +def signals_in_event(event: StreamEvent) -> list[Signal]: + """Return the signals that ``event`` adds to an inbox; a deletion adds + none. + + Raises: + ValueError: The event is not at a level of an inbox. + """ + if event.kind == PATCH: + changes = [ + (f"{event.path.rstrip('/')}/{key}", value) + for key, value in event.data.items() + ] + else: + changes = [(event.path, event.data)] + return [signal for path, value in changes for signal in signals_at(path, value)] + + +def signals_at(path: str, value: Any) -> list[Signal]: + """Return the signals in ``value`` at ``path`` of an inbox.""" + parts = [part for part in path.split("/") if part] + if value is None: + return [] + if len(parts) == 2: + return [Signal(parts[0], parts[1], value)] + if len(parts) == 1: + return [ + Signal(parts[0], signal_id, fields) + for signal_id, fields in value.items() + if fields is not None + ] + if not parts: + return [ + signal + for sender_key, signals in value.items() + for signal in signals_at(sender_key, signals) + ] + raise ValueError(f"Expected a path of at most two keys in an inbox, got {path!r}") + + +class DatabaseSignaling(Signaling): + """``Signaling`` for one email, through the Realtime Database. + + ``listen`` opens the stream of the inbox, and deletes the signals that came + before it: no sender waits for them now. Each later signal is handled, then + deleted; each offer, answer and refusal only once. If the stream fails before ``close``, the session ends, and + ``on_closed`` gets the reason. + """ + + # listen() sets these. + _email: str + # A new id at each listen. A peer that sees a new id knows that this + # client signed in again. + _session: str + _loop: asyncio.AbstractEventLoop + _stream: DatabaseStream + # Done when the first event of the stream, what came before, is handled. + _started: asyncio.Future[None] + _on_offer: OnOffer + _on_hello: OnHello + _on_closed: OnClosed + _on_answer_failed: OnAnswerFailed + + def __init__(self, database: RealtimeDatabase, ice_server_source: IceServerSource): + self._database = database + self._ice_server_source = ice_server_source + # True from the start of close(). The end of the session is then no + # error. + self._closing = False + # The ids of the signals that this session handled. + self._handled_ids: set[str] = set() + # offer id -> the reply of the peer to the offer + self._pending_replies: dict[str, asyncio.Future[str]] = {} + # The tasks that handle signals and answer offers, until they end. This + # set keeps a strong reference to each task, because asyncio keeps only + # a weak one. + self._tasks: set[asyncio.Task] = set() + # signal type -> the method that handles it + self._signal_handlers: dict[str, Callable[[Signal], None]] = { + HELLO: self._handle_hello, + OFFER: self._handle_offer, + ANSWER: self._handle_answer, + REFUSE: self._handle_refuse, + } + + async def listen( + self, + email: str, + on_offer: OnOffer, + on_hello: OnHello, + on_closed: OnClosed, + on_answer_failed: OnAnswerFailed, + ) -> None: + """Open the stream of the inbox of ``email``. + + Raises: + ConnectionError: The database refuses the stream, or cannot be + reached. + """ + self._email = email + self._session = uuid.uuid4().hex + self._on_offer = on_offer + self._on_hello = on_hello + self._on_closed = on_closed + self._on_answer_failed = on_answer_failed + self._closing = False + self._handled_ids = set() + self._loop = asyncio.get_running_loop() + self._started = self._loop.create_future() + self._stream = await self._call_database( + self._database.stream, inbox_path(email), self._on_event, self._on_end + ) + await self._started + + async def ice_servers(self, email: str) -> IceServerSet: + """Raises: + ConnectionError: The ICE server source refuses the user, or cannot be + reached. + """ + try: + return await self._ice_server_source() + except ConnectionUnavailableError as err: + raise ConnectionError(str(err)) from err + + async def hello(self, email: str, peers: list[str]) -> None: + """Raises: + ConnectionError: The database refuses a hello, as it does to a peer + that did not accept ``email``, or cannot be reached. + """ + hello = {TYPE_FIELD: HELLO, SESSION_FIELD: self._session} + for peer in peers: + hello_path = f"{signal_path(peer, self._email)}/{HELLO_SLOT}" + await self._call_database(self._database.put, hello_path, hello) + + async def offer(self, sender: str, receiver: str, sdp: str) -> str: + """Send the offer, and wait for the reply of ``receiver``. + + Raises: + ConnectionRefusedError: ``receiver`` refuses the offer. + ConnectionError: The session ends before the reply comes. + """ + offer_id = uuid.uuid4().hex + reply = self._loop.create_future() + self._pending_replies[offer_id] = reply + try: + offer = {TYPE_FIELD: OFFER, REQUEST_FIELD: offer_id, SDP_FIELD: sdp} + await self._send_signal(receiver, offer) + return await reply + finally: + self._pending_replies.pop(offer_id, None) + + async def close(self, email: str) -> None: + self._closing = True + for task in self._tasks: + task.cancel() + await asyncio.to_thread(self._stream.close) + + def _on_event(self, event: StreamEvent) -> None: + """Runs on the thread of the stream.""" + self._loop.call_soon_threadsafe(self._handle_event, event) + + def _on_end(self, error: OSError) -> None: + """Runs on the thread of the stream.""" + self._loop.call_soon_threadsafe(self._maybe_end_session, error) + + def _handle_event(self, event: StreamEvent) -> None: + # Tasks start in the order of the events. + self._start_task(self._process_event(event)) + + async def _process_event(self, event: StreamEvent) -> None: + signals = signals_in_event(event) + if self._started.done(): + await self._handle_signals(signals) + else: + self._started.set_result(None) + await self._maybe_delete_signals(signals) + + async def _handle_signals(self, signals: list[Signal]) -> None: + # A stream opened again after its ID token expired starts with what is + # in the inbox, so a signal can come twice. A hello can come again in + # its slot, and handling it twice does no harm. + new_signals = [ + s + for s in signals + if s.signal_id == HELLO_SLOT or s.signal_id not in self._handled_ids + ] + self._handled_ids.update( + s.signal_id for s in new_signals if s.signal_id != HELLO_SLOT + ) + await self._maybe_delete_signals(new_signals) + for signal in new_signals: + self._signal_handlers[signal.fields[TYPE_FIELD]](signal) + + async def _maybe_delete_signals(self, signals: list[Signal]) -> None: + if signals: + deletes = { + f"{inbox_path(self._email)}/{s.sender_key}/{s.signal_id}": None + for s in signals + } + await self._call_database(self._database.update, deletes) + + def _handle_hello(self, signal: Signal) -> None: + self._on_hello(signal.sender, signal.fields[SESSION_FIELD]) + + def _handle_offer(self, signal: Signal) -> None: + task = self._start_task(self._answer_offer(signal), ends_session=False) + task.add_done_callback( + lambda done: self._maybe_report_failed_answer(done, signal.sender) + ) + + async def _answer_offer(self, signal: Signal) -> None: + reply = {REQUEST_FIELD: signal.fields[REQUEST_FIELD]} + try: + sdp = await self._on_offer(signal.sender, signal.fields[SDP_FIELD]) + except ConnectionRefusedError as err: + refusal = {**reply, TYPE_FIELD: REFUSE, REASON_FIELD: str(err)} + await self._send_signal(signal.sender, refusal) + else: + answer = {**reply, TYPE_FIELD: ANSWER, SDP_FIELD: sdp} + await self._send_signal(signal.sender, answer) + + def _maybe_report_failed_answer( + self, answer_task: asyncio.Task, sender: str + ) -> None: + """Give the reason to ``on_answer_failed`` if ``answer_task`` failed.""" + if answer_task.cancelled() or answer_task.exception() is None: + return + self._on_answer_failed( + ConnectionError( + f"Could not answer the offer of {sender}: {answer_task.exception()!r}" + ) + ) + + def _handle_answer(self, signal: Signal) -> None: + # An offer removes its entry when it no longer waits. Then a late reply + # finds no entry, and the client ignores it. + offer_id = signal.fields[REQUEST_FIELD] + if offer_id in self._pending_replies: + self._pending_replies.pop(offer_id).set_result(signal.fields[SDP_FIELD]) + + def _handle_refuse(self, signal: Signal) -> None: + offer_id = signal.fields[REQUEST_FIELD] + if offer_id in self._pending_replies: + refusal = ConnectionRefusedError(signal.fields[REASON_FIELD]) + self._pending_replies.pop(offer_id).set_exception(refusal) + + def _maybe_end_session(self, error: BaseException) -> None: + """Fail what waits on the session, stop the stream, and give the reason + to ``on_closed``, unless the session is closing. + + Before the first event of the stream, only ``listen`` raises: no session + has started, and the stream thread has ended. + """ + if self._closing: + return + self._closing = True + ended = ConnectionError(f"The signaling session ended: {error!r}") + if not self._started.done(): + self._started.set_exception(ended) + return + for reply in self._pending_replies.values(): + if not reply.done(): + reply.set_exception(ended) + self._loop.run_in_executor(None, self._stream.close) + self._on_closed(ended) + + def _start_task( + self, coroutine: Coroutine[Any, Any, None], ends_session: bool = True + ) -> asyncio.Task: + """Run ``coroutine`` as a task. If ``ends_session``, its failure ends the + session.""" + task = asyncio.create_task(coroutine) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + if ends_session: + task.add_done_callback(self._maybe_end_session_on_failure) + return task + + def _maybe_end_session_on_failure(self, task: asyncio.Task) -> None: + if task.cancelled(): + return + error = task.exception() + if error is not None: + self._maybe_end_session(error) + + async def _send_signal(self, receiver: str, fields: dict[str, str]) -> None: + await self._call_database( + self._database.post, signal_path(receiver, self._email), fields + ) + + async def _call_database(self, call: Callable[..., T], *args: Any) -> T: + """Run a blocking database call on a worker thread. + + Raises: + ConnectionError: The database refuses the call, or cannot be + reached. + """ + try: + return await asyncio.to_thread(call, *args) + except ConnectionUnavailableError as err: + raise ConnectionError(str(err)) from err diff --git a/syft/sync/connections/webrtc/firebase/project.py b/syft/sync/connections/webrtc/firebase/project.py new file mode 100644 index 00000000000..ceee8a180f3 --- /dev/null +++ b/syft/sync/connections/webrtc/firebase/project.py @@ -0,0 +1,71 @@ +"""The URLs of a Firebase project, or of the Firebase emulators.""" + +from dataclasses import dataclass + +from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig + +AUTH_URL = "https://identitytoolkit.googleapis.com/v1" +TOKEN_URL = "https://securetoken.googleapis.com/v1" +# The region and the name of the function in infra/firebase/functions/main.py. +TURN_FUNCTION_URL = ( + "https://us-central1-{project_id}.cloudfunctions.net/turn_credentials" +) +# The default Realtime Database of a project, in us-central1. +DATABASE_URL = "https://{database}.firebaseio.com" +DEFAULT_DATABASE = "{project_id}-default-rtdb" +# The emulator ports in infra/firebase/firebase.json. +AUTH_EMULATOR_PORT = 9099 +DATABASE_EMULATOR_PORT = 9000 + + +@dataclass(frozen=True) +class FirebaseProject: + project_id: str + # The web API key of the project. It is not a secret. + api_key: str + # The REST API of Firebase Auth. + auth_url: str + # The REST API that gives new ID tokens. + token_url: str + # The REST API of the Realtime Database. + database_url: str + # The database name that the emulator needs in each URL, or None for the + # real project. + database_namespace: str | None + # None on the emulators, because they run no Cloud Function. + turn_function_url: str | None + + @classmethod + def from_config(cls, config: WebRTCConfig) -> "FirebaseProject": + """Return the real project of ``config``, or the emulators that replace + it.""" + if config.firebase_emulator_host is None: + return cls( + project_id=config.firebase_project_id, + api_key=config.firebase_api_key, + auth_url=AUTH_URL, + token_url=TOKEN_URL, + database_url=DATABASE_URL.format( + database=DEFAULT_DATABASE.format( + project_id=config.firebase_project_id + ) + ), + database_namespace=None, + turn_function_url=TURN_FUNCTION_URL.format( + project_id=config.firebase_project_id + ), + ) + auth_emulator = f"http://{config.firebase_emulator_host}:{AUTH_EMULATOR_PORT}" + return cls( + project_id=config.firebase_project_id, + api_key=config.firebase_api_key, + auth_url=f"{auth_emulator}/identitytoolkit.googleapis.com/v1", + token_url=f"{auth_emulator}/securetoken.googleapis.com/v1", + database_url=( + f"http://{config.firebase_emulator_host}:{DATABASE_EMULATOR_PORT}" + ), + database_namespace=DEFAULT_DATABASE.format( + project_id=config.firebase_project_id + ), + turn_function_url=None, + ) diff --git a/syft/sync/connections/webrtc/firebase/rest.py b/syft/sync/connections/webrtc/firebase/rest.py new file mode 100644 index 00000000000..2c0f002380f --- /dev/null +++ b/syft/sync/connections/webrtc/firebase/rest.py @@ -0,0 +1,80 @@ +"""JSON requests to the Firebase REST APIs.""" + +import json +import urllib.error +import urllib.request +from typing import Any + +from syft.sync.connections.exceptions import ConnectionUnavailableError + +REQUEST_TIMEOUT_SECONDS = 20 + + +class FirebaseRequestError(ConnectionError): + """A Firebase REST API refused a request.""" + + def __init__(self, url: str, status: int, reason: str): + super().__init__(f"{url} answered {status}: {reason}") + self.status = status + + +def post_json(url: str, body: Any, id_token: str | None = None) -> Any: + """POST ``body`` as JSON, as the user of ``id_token`` if one is given, and + return the JSON answer. + + Raises: + FirebaseRequestError: The API answers with an error status. + ConnectionUnavailableError: The API cannot be reached. + """ + headers = {"Content-Type": "application/json"} + if id_token is not None: + headers["Authorization"] = f"Bearer {id_token}" + request = urllib.request.Request( + url, data=json.dumps(body).encode(), headers=headers, method="POST" + ) + return send_request(request) + + +def request_json(method: str, url: str, body: Any = None) -> Any: + """Send ``body`` as JSON with ``method``, and return the JSON answer. + + The credentials, if any, are in the query of ``url``. + + Raises: + FirebaseRequestError: The API answers with an error status. + ConnectionUnavailableError: The API cannot be reached. + """ + data = None if body is None else json.dumps(body).encode() + headers = {} if body is None else {"Content-Type": "application/json"} + request = urllib.request.Request(url, data=data, headers=headers, method=method) + return send_request(request) + + +def get_json(url: str, id_token: str) -> Any: + """GET ``url`` as the user of ``id_token``, and return the JSON answer. + + Raises: + FirebaseRequestError: The API answers with an error status. + ConnectionUnavailableError: The API cannot be reached. + """ + headers = {"Authorization": f"Bearer {id_token}"} + return send_request(urllib.request.Request(url, headers=headers)) + + +def send_request(request: urllib.request.Request) -> Any: + # The query can hold an ID token, so no message shows it. + url = without_query(request.full_url) + try: + with urllib.request.urlopen( + request, timeout=REQUEST_TIMEOUT_SECONDS + ) as response: + return json.load(response) + except urllib.error.HTTPError as err: + reason = err.read().decode(errors="replace") + raise FirebaseRequestError(url, err.code, reason) from err + except OSError as err: + raise ConnectionUnavailableError(f"Could not reach {url}: {err}") from err + + +def without_query(url: str) -> str: + return url.split("?", 1)[0] diff --git a/syft/sync/connections/webrtc/firebase/turn.py b/syft/sync/connections/webrtc/firebase/turn.py new file mode 100644 index 00000000000..efa4410ba77 --- /dev/null +++ b/syft/sync/connections/webrtc/firebase/turn.py @@ -0,0 +1,33 @@ +"""ICE servers from the TURN Cloud Function of a Firebase project.""" + +import asyncio + +from syft.sync.connections.webrtc.firebase.auth import FirebaseSession +from syft.sync.connections.webrtc.firebase.rest import post_json +from syft.sync.connections.webrtc.signaling.signaling import IceServerSet + + +class TurnFunction: + """An ``IceServerSource``: each call gets new short-lived TURN credentials + from the function in infra/firebase/functions/main.py.""" + + def __init__(self, url: str, session: FirebaseSession): + self._url = url + self._session = session + + async def __call__(self) -> IceServerSet: + """Raises: + ConnectionError: The function refuses the user. + ConnectionUnavailableError: The function cannot be reached. + """ + return await asyncio.to_thread(self._request_ice_servers) + + def _request_ice_servers(self) -> IceServerSet: + reply = post_json(self._url, {}, self._session.id_token()) + return IceServerSet(reply["ice_servers"], reply["lifetime_seconds"]) + + +async def no_ice_servers() -> IceServerSet: + """An ``IceServerSource`` for peers on one machine, which reach each other + with no STUN or TURN server.""" + return IceServerSet([], None) diff --git a/syft/sync/connections/webrtc/local_owner_store.py b/syft/sync/connections/webrtc/local_owner_store.py new file mode 100644 index 00000000000..b141aea39be --- /dev/null +++ b/syft/sync/connections/webrtc/local_owner_store.py @@ -0,0 +1,168 @@ +"""The DO's own storage on local disk: event log, checkpoints, rolling state. + +A WebRTC user has no Drive, so the DO keeps this state on its own machine. A +new machine starts with no state. +""" + +import os +import uuid +from collections.abc import Callable +from pathlib import Path +from typing import TypeVar + +from syft.sync.checkpoints.checkpoint import Checkpoint, IncrementalCheckpoint +from syft.sync.checkpoints.rolling_state import RollingState +from syft.sync.connections.protocols import OwnerStoreConnection +from syft.sync.events.file_change_event import FileChangeEventsMessageFileName +from syft.sync.sync.constants import CACHE_DIR + +# The owner store, under the syftbox folder. +OWNER_STORE_PATH = Path(CACHE_DIR) / "webrtc" / "owner_store" +EVENTS_FOLDER = "events" +CHECKPOINTS_FOLDER = "checkpoints" +INCREMENTALS_FOLDER = "incrementals" +ROLLING_STATE_FOLDER = "rolling_state" +# Each file goes here first, then moves into place. Thus a crash never leaves +# half a file in the store. +TEMP_FOLDER = "tmp" + +NameValue = TypeVar("NameValue") + + +def parse_file_name(parse: Callable[[str], NameValue | None], name: str) -> NameValue: + """Return the value that ``parse`` reads from the file name ``name``. + + Raises: + ValueError: ``parse`` finds no value in ``name``. + """ + value = parse(name) + if value is None: + raise ValueError(f"The owner store holds a file with a bad name: {name!r}") + return value + + +def event_timestamp(name: str) -> float: + return FileChangeEventsMessageFileName.from_string(name).timestamp + + +def incremental_sequence(name: str) -> int: + return parse_file_name(IncrementalCheckpoint.filename_to_sequence_number, name) + + +class LocalOwnerStoreConnection(OwnerStoreConnection): + """``OwnerStoreConnection`` in a folder on local disk. + + A handle is the path of a file, relative to the folder. + """ + + def __init__(self, folder: Path): + self._folder = folder + + def append_event(self, name: str, data: bytes) -> str: + return self._write_file(EVENTS_FOLDER, name, data) + + def list_event_handles(self, since_timestamp: float | None = None) -> list[str]: + names = sorted(self._file_names(EVENTS_FOLDER), key=event_timestamp) + return [ + f"{EVENTS_FOLDER}/{name}" + for name in names + if since_timestamp is None or event_timestamp(name) > since_timestamp + ] + + def fetch(self, handle: str) -> bytes: + return (self._folder / handle).read_bytes() + + def put_checkpoint(self, name: str, data: bytes) -> str: + return self._replace_file(CHECKPOINTS_FOLDER, name, data) + + def latest_checkpoint(self) -> bytes | None: + return self._read_latest_file( + CHECKPOINTS_FOLDER, Checkpoint.filename_to_timestamp + ) + + def put_incremental(self, name: str, data: bytes) -> str: + return self._write_file(INCREMENTALS_FOLDER, name, data) + + def all_incrementals(self) -> list[bytes]: + names = sorted(self._file_names(INCREMENTALS_FOLDER), key=incremental_sequence) + return [self._read_file(INCREMENTALS_FOLDER, name) for name in names] + + def incremental_count(self) -> int: + return len(self._file_names(INCREMENTALS_FOLDER)) + + def next_incremental_sequence(self) -> int: + names = self._file_names(INCREMENTALS_FOLDER) + return max((incremental_sequence(name) for name in names), default=0) + 1 + + def delete_incrementals(self) -> None: + self._delete_files(INCREMENTALS_FOLDER) + + def put_rolling_state(self, name: str, data: bytes) -> str: + return self._replace_file(ROLLING_STATE_FOLDER, name, data) + + def get_rolling_state(self) -> bytes | None: + return self._read_latest_file( + ROLLING_STATE_FOLDER, RollingState.filename_to_timestamp + ) + + def delete_rolling_state(self) -> None: + self._delete_files(ROLLING_STATE_FOLDER) + + def delete_all(self) -> int: + """Delete the folder of the store and everything in it. + + Returns: + The number of files and folders that went. + """ + if not self._folder.exists(): + return 0 + # Reverse order puts each path before the folder that holds it. + paths = sorted(self._folder.rglob("*"), reverse=True) + [self._folder] + for path in paths: + if path.is_dir(): + path.rmdir() + else: + path.unlink() + return len(paths) + + def _file_names(self, folder: str) -> list[str]: + path = self._folder / folder + if not path.exists(): + return [] + return [file.name for file in path.iterdir()] + + def _read_file(self, folder: str, name: str) -> bytes: + return (self._folder / folder / name).read_bytes() + + def _write_file(self, folder: str, name: str, data: bytes) -> str: + """Write ``data`` to the file ``name`` in ``folder``, and return its + handle.""" + temp = self._folder / TEMP_FOLDER / uuid.uuid4().hex + target = self._folder / folder / name + temp.parent.mkdir(parents=True, exist_ok=True) + target.parent.mkdir(parents=True, exist_ok=True) + temp.write_bytes(data) + os.replace(temp, target) + return f"{folder}/{name}" + + def _replace_file(self, folder: str, name: str, data: bytes) -> str: + """Write the file ``name`` in ``folder``, then delete the other files in + ``folder``.""" + handle = self._write_file(folder, name, data) + for old_name in self._file_names(folder): + if old_name != name: + (self._folder / folder / old_name).unlink() + return handle + + def _read_latest_file( + self, folder: str, timestamp_of: Callable[[str], float | None] + ) -> bytes | None: + names = self._file_names(folder) + if not names: + return None + latest = max(names, key=lambda name: parse_file_name(timestamp_of, name)) + return self._read_file(folder, latest) + + def _delete_files(self, folder: str) -> None: + for name in self._file_names(folder): + (self._folder / folder / name).unlink() diff --git a/syft/sync/connections/webrtc/mock/fake_peer_connections.py b/syft/sync/connections/webrtc/mock/fake_peer_connections.py index 34b2dbf0055..bca93a34d23 100644 --- a/syft/sync/connections/webrtc/mock/fake_peer_connections.py +++ b/syft/sync/connections/webrtc/mock/fake_peer_connections.py @@ -32,6 +32,12 @@ def connect(self, email: str, peer: str) -> None: self._peer_on_opens[email](peer) self._peer_on_opens[peer](email) + def is_listening(self, email: str) -> bool: + return email in self._peer_on_opens + + def has_channel(self, email: str, peer: str) -> bool: + return frozenset((email, peer)) in self._channels + def send(self, sender: str, receiver: str, frame: bytes) -> None: """Hand ``frame`` to ``receiver`` inside this call; dropped when the two have no open channel.""" @@ -61,6 +67,18 @@ def open(self, email: str, on_open: OnOpen, on_frame: OnFrame) -> None: def connect(self, peer: str) -> None: self.network.connect(self.email, peer) + def set_peers(self, peers: list[str]) -> None: + """Connect to each of ``peers`` that listens and has no channel to this + client. A fake network has no roles, so either side connects.""" + for peer in peers: + if self.network.is_listening(peer) and not self.network.has_channel( + self.email, peer + ): + self.network.connect(self.email, peer) + + def maybe_raise_background_errors(self) -> None: + """Do nothing: the fake network does no work in the background.""" + def send(self, peer: str, frame: bytes) -> None: self.network.send(self.email, peer, frame) diff --git a/syft/sync/connections/webrtc/peer_connections.py b/syft/sync/connections/webrtc/peer_connections.py index 3a7cf9b258d..5c9493aaab0 100644 --- a/syft/sync/connections/webrtc/peer_connections.py +++ b/syft/sync/connections/webrtc/peer_connections.py @@ -22,6 +22,15 @@ def open(self, email: str, on_open: OnOpen, on_frame: OnFrame) -> None: def connect(self, peer: str) -> None: """Open a channel to ``peer``; return once it is open.""" + @abstractmethod + def set_peers(self, peers: list[str]) -> None: + """Keep channels to ``peers``, and accept channels only from them.""" + + @abstractmethod + def maybe_raise_background_errors(self) -> None: + """Raise the failures in the background since the last call, if there + are any.""" + @abstractmethod def send(self, peer: str, frame: bytes) -> None: """Send ``frame`` to ``peer``; dropped when there is no channel to it.""" diff --git a/syft/sync/connections/webrtc/real/aiortc_peer_connections.py b/syft/sync/connections/webrtc/real/aiortc_peer_connections.py index 789f77d2adb..9dcdc0afef7 100644 --- a/syft/sync/connections/webrtc/real/aiortc_peer_connections.py +++ b/syft/sync/connections/webrtc/real/aiortc_peer_connections.py @@ -3,6 +3,7 @@ import asyncio import logging +import math import threading from collections.abc import Coroutine from typing import Any @@ -10,7 +11,9 @@ from aiortc import ( RTCConfiguration, RTCDataChannel, + RTCIceServer, RTCPeerConnection, + RTCSctpTransport, RTCSessionDescription, ) @@ -19,24 +22,70 @@ OnOpen, PeerConnections, ) -from syft.sync.connections.webrtc.signaling.signaling import Signaling +from syft.sync.connections.webrtc.signaling.signaling import IceServers, Signaling logger = logging.getLogger(__name__) -CONNECT_TIMEOUT_SECONDS = 10.0 +# The round trips of the signaling and the TURN request take seconds each. +CONNECT_TIMEOUT_SECONDS = 20.0 CHANNEL_LABEL = "syft" -# No STUN or TURN server: peers on one machine or LAN reach each other directly. -LOCAL_ONLY = RTCConfiguration(iceServers=[]) +# The offering side opens a new peer connection after this part of the +# lifetime of its TURN credentials. +CREDENTIALS_REFRESH_FRACTION = 0.9 +# The maximum message size that aiortc advertises. For each 1200-byte SCTP fragment +# that arrives, aiortc's InboundStream.pop_messages scans all earlier fragments of +# the message. Therefore the receive time grows with the square of the message size. +MAX_MESSAGE_BYTES = RTCSctpTransport.getCapabilities().maxMessageSize +# The first byte of each chunk tells whether more chunks of the frame follow. +MORE_CHUNKS = b"\x00" +LAST_CHUNK = b"\x01" +CHUNK_PAYLOAD_BYTES = MAX_MESSAGE_BYTES - len(LAST_CHUNK) + + +def split_frame_into_chunks(frame: bytes) -> list[bytes]: + """Split ``frame`` into chunks of at most ``MAX_MESSAGE_BYTES`` each. + + Returns: + The chunks in order. The last chunk starts with ``LAST_CHUNK``, and + each other chunk starts with ``MORE_CHUNKS``. An empty frame gives one + chunk that holds only ``LAST_CHUNK``. + """ + count = max(1, math.ceil(len(frame) / CHUNK_PAYLOAD_BYTES)) + return [ + (LAST_CHUNK if i == count - 1 else MORE_CHUNKS) + + frame[i * CHUNK_PAYLOAD_BYTES : (i + 1) * CHUNK_PAYLOAD_BYTES] + for i in range(count) + ] + + +def sign_in_failed(sign_in: asyncio.Task) -> bool: + """Return whether ``sign_in`` ended without a session.""" + if not sign_in.done(): + return False + return sign_in.cancelled() or sign_in.exception() is not None class AiortcPeerConnections(PeerConnections): """One aiortc peer connection and data channel per peer, and the asyncio loop thread that runs them. ``on_open`` and ``on_frame`` run on that - thread.""" + thread. + + Of two peers, the one with the lower email sends the offer. Each side says + hello to its peers when it signs in, and answers only the offers of its + peers. The offering side opens a new peer connection before its TURN + credentials expire. A failure in the background, such as a connect that + fails or a signaling session that ends, waits until + ``maybe_raise_background_errors`` raises it. + + A frame can have any size. ``split_frame_into_chunks`` splits it into + chunks of at most ``MAX_MESSAGE_BYTES``, and the peer joins the chunks + again.""" + + # open() sets it. + email: str def __init__(self, signaling: Signaling): self.signaling = signaling - self.email: str | None = None self._on_open: OnOpen | None = None self._on_frame: OnFrame | None = None self._loop = asyncio.new_event_loop() @@ -45,29 +94,81 @@ def __init__(self, signaling: Signaling): self._rtc_connections: dict[str, RTCPeerConnection] = {} # peer email -> its data channel self._channels: dict[str, RTCDataChannel] = {} + # peer email -> the received chunks of its incomplete frame + self._partial_frames: dict[str, bytearray] = {} + # peer email in lower case -> the peer email as set_peers spells it. + # The signaling reports each email as its owner spells it. + self._peers: dict[str, str] = {} + # peer email -> the task that connects to it after its hello, until the + # task ends. This dict keeps a strong reference to each task, because + # asyncio keeps only a weak one. + self._connect_tasks: dict[str, asyncio.Task] = {} + # peer email -> the task that opens a new connection to it before the + # TURN credentials expire + self._refresh_tasks: dict[str, asyncio.Task] = {} + # peer email in lower case -> the session of its last hello + self._peer_sessions: dict[str, str] = {} + # The tasks that say hello, until they end. + self._hello_tasks: set[asyncio.Task] = set() + # The sign-in to the signaling. None until the first set_peers or + # connect, and again after the session ends. + self._sign_in_task: asyncio.Task | None = None + # The failures in the background that no caller saw yet. + self._background_errors: list[ConnectionError] = [] def open(self, email: str, on_open: OnOpen, on_frame: OnFrame) -> None: - """Start the loop thread and answer offers from peers.""" + """Start the loop thread. + + The client signs in to the signaling at the first ``set_peers`` or + ``connect``. Thus no peer sends it an offer before it knows its peers. + """ self.email = email self._on_open = on_open self._on_frame = on_frame self._thread.name = f"webrtc-{email}" self._thread.start() - self._run(self.signaling.listen(email, self._answer)) def connect(self, peer: str, timeout: float = CONNECT_TIMEOUT_SECONDS) -> None: self._run(self._connect(peer), timeout) + def set_peers(self, peers: list[str]) -> None: + """Set the peers of this client, and say hello to each peer with no open + channel. + + A peer that is online answers the hello, and the two connect. Thus each + call tries again to connect to the peers that are not connected. This + client refuses an offer from an email that is not in ``peers``. The + channel to each email that is not in ``peers`` closes. + """ + self._run(self._set_peers(peers)) + + def maybe_raise_background_errors(self) -> None: + """Raise the failures in the background since the last call, if there + are any. + + Raises: + ConnectionError: A connect or a hello failed, a peer refused an + offer, an answer failed, or the signaling session ended. + """ + self._run(self._maybe_raise_background_errors()) + def send(self, peer: str, frame: bytes) -> None: """Works from any thread; the frame goes out on the loop thread.""" self._loop.call_soon_threadsafe(self._send_on_loop, peer, frame) def close(self) -> None: - """Close every peer connection and stop the loop thread.""" - self._run(self._close_rtc_connections()) - self._loop.call_soon_threadsafe(self._loop.stop) - self._thread.join() - self._loop.close() + """Close the signaling and each peer connection, then stop the loop. + + Raises: + ConnectionError: The signaling fails to close. The peer connections + and the loop close all the same. + """ + try: + self._run(self._close_signaling_and_rtc_connections()) + finally: + self._loop.call_soon_threadsafe(self._loop.stop) + self._thread.join() + self._loop.close() def _run(self, coroutine: Coroutine[Any, Any, Any], timeout: float | None = None): """Run ``coroutine`` on the loop thread and wait for its result.""" @@ -80,12 +181,122 @@ def _run(self, coroutine: Coroutine[Any, Any, Any], timeout: float | None = None def _send_on_loop(self, peer: str, frame: bytes) -> None: """Dropped when ``peer`` has no open channel; an unconfirmed message stays queued and goes again on the next ``on_open``.""" + if self._has_open_channel(peer): + # The channel is ordered, and this call sends all chunks of the + # frame. Therefore the chunks of two frames do not mix. + for chunk in split_frame_into_chunks(frame): + self._channels[peer].send(chunk) + + def _has_open_channel(self, peer: str) -> bool: channel = self._channels.get(peer) - if channel is not None and channel.readyState == "open": - channel.send(frame) + return channel is not None and channel.readyState == "open" + + async def _set_peers(self, peers: list[str]) -> None: + self._peers = {peer.lower(): peer for peer in peers} + await self._close_rtc_connections_of_other_emails() + await self._maybe_sign_in() + unconnected = [peer for peer in peers if not self._has_open_channel(peer)] + if unconnected: + self._start_hello(unconnected) + + async def _maybe_raise_background_errors(self) -> None: + if self._background_errors: + errors, self._background_errors = self._background_errors, [] + reasons = "; ".join(str(error) for error in errors) + raise ConnectionError( + f"WebRTC failed in the background: {reasons}" + ) from errors[0] + + def _on_hello(self, reported_email: str, session: str) -> None: + """Connect to a peer that said hello: offer, or say hello back so that + the peer offers.""" + if reported_email.lower() not in self._peers: + return + peer = self._peers[reported_email.lower()] + last_session = self._peer_sessions.get(peer.lower()) + self._peer_sessions[peer.lower()] = session + # The peer says hello again at each set_peers. A hello in the same + # session to an open channel needs nothing. + if self._has_open_channel(peer) and session == last_session: + return + if self._sends_offer_to(peer): + self._maybe_start_connect(peer) + else: + self._start_hello([peer]) + + def _sends_offer_to(self, peer: str) -> bool: + return self.email.lower() < peer.lower() + + def _maybe_start_connect(self, peer: str) -> None: + """Connect to ``peer`` in the background, unless a connect is on the + way.""" + if peer not in self._connect_tasks: + task = asyncio.create_task(self._connect_in_background(peer)) + self._connect_tasks[peer] = task + task.add_done_callback(lambda _: self._connect_tasks.pop(peer)) + + def _start_hello(self, peers: list[str]) -> None: + task = asyncio.create_task(self._say_hello(peers)) + self._hello_tasks.add(task) + task.add_done_callback(self._hello_tasks.discard) + + async def _say_hello(self, peers: list[str]) -> None: + try: + await self.signaling.hello(self.email, peers) + except ConnectionError as err: + error = ConnectionError(f"Could not say hello to {peers}: {err!r}") + self._background_errors.append(error) + + async def _connect_in_background(self, peer: str) -> None: + try: + await asyncio.wait_for(self._connect(peer), CONNECT_TIMEOUT_SECONDS) + except (ConnectionError, TimeoutError) as err: + # The next hello of the peer starts a new connection. + error = ConnectionError(f"Could not connect to {peer}: {err!r}") + self._background_errors.append(error) + + def _on_signaling_closed(self, error: ConnectionError) -> None: + self._background_errors.append(error) + # The next set_peers or connect signs in again. + self._sign_in_task = None + + def _on_answer_failed(self, error: ConnectionError) -> None: + self._background_errors.append(error) + + async def _close_rtc_connections_of_other_emails(self) -> None: + """Close the peer connection to each email that is not a peer.""" + others = [ + peer for peer in self._rtc_connections if peer.lower() not in self._peers + ] + for peer in others: + if peer in self._connect_tasks: + self._connect_tasks[peer].cancel() + if peer in self._refresh_tasks: + self._refresh_tasks.pop(peer).cancel() + self._channels.pop(peer, None) + self._partial_frames.pop(peer, None) + await self._rtc_connections.pop(peer).close() + + async def _maybe_sign_in(self) -> None: + """Sign in to the signaling, if this client is not signed in.""" + # A task, so that two calls at the same time share one sign-in. With + # the shield, a cancelled caller does not cancel the shared task. + if self._sign_in_task is None or sign_in_failed(self._sign_in_task): + self._sign_in_task = asyncio.ensure_future( + self.signaling.listen( + self.email, + self._answer, + self._on_hello, + self._on_signaling_closed, + self._on_answer_failed, + ) + ) + await asyncio.shield(self._sign_in_task) async def _connect(self, peer: str) -> None: - rtc = await self._new_rtc_connection(peer) + await self._maybe_sign_in() + ice_servers = await self.signaling.ice_servers(self.email) + rtc = await self._new_rtc_connection(peer, ice_servers.servers) channel = rtc.createDataChannel(CHANNEL_LABEL) self._use_channel(peer, channel) opened = asyncio.Event() @@ -100,31 +311,87 @@ def on_open() -> None: answer = await self.signaling.offer(self.email, peer, offer) await rtc.setRemoteDescription(RTCSessionDescription(answer, "answer")) await opened.wait() + if ice_servers.lifetime_seconds is not None: + self._schedule_refresh(peer, ice_servers.lifetime_seconds) + + def _schedule_refresh(self, peer: str, lifetime_seconds: float) -> None: + """Open a new connection to ``peer`` before the TURN credentials of + this one expire.""" + if peer in self._refresh_tasks: + self._refresh_tasks.pop(peer).cancel() + delay = lifetime_seconds * CREDENTIALS_REFRESH_FRACTION + self._refresh_tasks[peer] = asyncio.create_task(self._refresh(peer, delay)) + + async def _refresh(self, peer: str, delay: float) -> None: + await asyncio.sleep(delay) + # The connect schedules the next refresh; this task is no longer it. + self._refresh_tasks.pop(peer) + self._maybe_start_connect(peer) async def _answer(self, sender: str, offer: str) -> str: - rtc = await self._new_rtc_connection(sender) + """Answer the offer of ``sender``, and return the answer. + + Raises: + ConnectionRefusedError: ``sender`` is not a peer of this client. + """ + if sender.lower() not in self._peers: + raise ConnectionRefusedError(f"{sender} is not a peer of {self.email}") + peer = self._peers[sender.lower()] + ice_servers = await self.signaling.ice_servers(self.email) + rtc = await self._new_rtc_connection(peer, ice_servers.servers) # aiortc hands over the channel already open. @rtc.on("datachannel") def on_datachannel(channel: RTCDataChannel) -> None: - self._use_channel(sender, channel) - self._on_open(sender) + self._use_channel(peer, channel) + self._on_open(peer) await rtc.setRemoteDescription(RTCSessionDescription(offer, "offer")) await rtc.setLocalDescription(await rtc.createAnswer()) return rtc.localDescription.sdp - async def _new_rtc_connection(self, peer: str) -> RTCPeerConnection: - """An aiortc peer connection to ``peer``, in place of any older one.""" + async def _new_rtc_connection( + self, peer: str, ice_servers: IceServers + ) -> RTCPeerConnection: + """An aiortc peer connection to ``peer``, in place of any older one. + + Each one gets new ICE servers, because TURN credentials expire. + """ old = self._rtc_connections.pop(peer, None) if old is not None: await old.close() - self._rtc_connections[peer] = RTCPeerConnection(LOCAL_ONLY) + configuration = RTCConfiguration( + iceServers=[RTCIceServer(**server) for server in ice_servers] + ) + self._rtc_connections[peer] = RTCPeerConnection(configuration) return self._rtc_connections[peer] def _use_channel(self, peer: str, channel: RTCDataChannel) -> None: self._channels[peer] = channel - channel.on("message", lambda frame: self._handle_frame(peer, frame)) + # The last chunk of an incomplete frame from the old channel never arrives. + self._partial_frames[peer] = bytearray() + channel.on("message", lambda chunk: self._handle_chunk(peer, chunk)) + + def _handle_chunk(self, peer: str, chunk: bytes) -> None: + """Add ``chunk`` to the incomplete frame of ``peer``. + + After the last chunk, give the complete frame to ``on_frame``. + + Raises: + ValueError: ``chunk`` starts with neither ``MORE_CHUNKS`` nor + ``LAST_CHUNK``. + """ + flag, payload = chunk[:1], chunk[1:] + if flag not in (MORE_CHUNKS, LAST_CHUNK): + raise ValueError( + f"A chunk from {peer} must start with {MORE_CHUNKS!r} or " + f"{LAST_CHUNK!r}, but it starts with {flag!r}" + ) + self._partial_frames[peer] += payload + if flag == LAST_CHUNK: + frame = bytes(self._partial_frames[peer]) + self._partial_frames[peer] = bytearray() + self._handle_frame(peer, frame) def _handle_frame(self, peer: str, frame: bytes) -> None: # Logged, not raised: raised here it would end up inside aiortc. @@ -133,7 +400,27 @@ def _handle_frame(self, peer: str, frame: bytes) -> None: except Exception: logger.exception("Dropped a WebRTC frame from %s", peer) + async def _close_signaling_and_rtc_connections(self) -> None: + tasks = [ + *self._connect_tasks.values(), + *self._refresh_tasks.values(), + *self._hello_tasks, + ] + for task in tasks: + task.cancel() + try: + await self._close_signaling() + finally: + await self._close_rtc_connections() + + async def _close_signaling(self) -> None: + if self._sign_in_task is not None and not self._sign_in_task.done(): + self._sign_in_task.cancel() + elif self._sign_in_task is not None and not sign_in_failed(self._sign_in_task): + await self.signaling.close(self.email) + async def _close_rtc_connections(self) -> None: await asyncio.gather(*(c.close() for c in self._rtc_connections.values())) self._rtc_connections.clear() self._channels.clear() + self._partial_frames.clear() diff --git a/syft/sync/connections/webrtc/signaling/local_signaling.py b/syft/sync/connections/webrtc/signaling/local_signaling.py index 0f9605127f3..b532f17ed14 100644 --- a/syft/sync/connections/webrtc/signaling/local_signaling.py +++ b/syft/sync/connections/webrtc/signaling/local_signaling.py @@ -1,24 +1,74 @@ -"""Signaling between peers in one process. TEMP: V3 replaces it with the -peering connection.""" +"""Signaling between peers in one process.""" import asyncio +import uuid +from dataclasses import dataclass -from syft.sync.connections.webrtc.signaling.signaling import OnOffer, Signaling +from syft.sync.connections.webrtc.signaling.signaling import ( + IceServerSet, + OnAnswerFailed, + OnClosed, + OnHello, + OnOffer, + Signaling, +) + + +@dataclass(frozen=True) +class Listener: + on_offer: OnOffer + on_hello: OnHello + # A new id at each listen. + session: str + # The loop that runs both callbacks. + loop: asyncio.AbstractEventLoop class LocalSignaling(Signaling): - """Hands an offer straight to the receiver's ``on_offer``, on its loop.""" + """Gives each hello and each offer directly to the receiver. + + The callbacks run on the loop of the receiver. A peer is online while it + listens. + """ def __init__(self): - # email -> its on_offer and the loop that runs it - self._listeners: dict[str, tuple[OnOffer, asyncio.AbstractEventLoop]] = {} + # email -> its listener + self._listeners: dict[str, Listener] = {} - async def listen(self, email: str, on_offer: OnOffer) -> None: - self._listeners[email] = (on_offer, asyncio.get_running_loop()) + async def listen( + self, + email: str, + on_offer: OnOffer, + on_hello: OnHello, + on_closed: OnClosed, + on_answer_failed: OnAnswerFailed, + ) -> None: + """A session in one process ends only at ``close``, so ``on_closed`` + never runs. A failed answer goes to the offerer as an error, so + ``on_answer_failed`` never runs.""" + self._listeners[email] = Listener( + on_offer, on_hello, uuid.uuid4().hex, asyncio.get_running_loop() + ) + + async def ice_servers(self, email: str) -> IceServerSet: + # Peers in one process reach each other with no STUN or TURN server. + return IceServerSet([], None) + + async def hello(self, email: str, peers: list[str]) -> None: + session = self._listeners[email].session + for peer in peers: + if peer in self._listeners: + listener = self._listeners[peer] + listener.loop.call_soon_threadsafe(listener.on_hello, email, session) async def offer(self, sender: str, receiver: str, sdp: str) -> str: if receiver not in self._listeners: raise ConnectionError(f"{receiver} is not listening for offers") - on_offer, loop = self._listeners[receiver] - answer = asyncio.run_coroutine_threadsafe(on_offer(sender, sdp), loop) + listener = self._listeners[receiver] + answer = asyncio.run_coroutine_threadsafe( + listener.on_offer(sender, sdp), listener.loop + ) return await asyncio.wrap_future(answer) + + async def close(self, email: str) -> None: + del self._listeners[email] diff --git a/syft/sync/connections/webrtc/signaling/signaling.py b/syft/sync/connections/webrtc/signaling/signaling.py index ed90693aeb4..0cf2c4259c8 100644 --- a/syft/sync/connections/webrtc/signaling/signaling.py +++ b/syft/sync/connections/webrtc/signaling/signaling.py @@ -1,20 +1,77 @@ -"""How two WebRTC peers swap session descriptions before they connect.""" +"""How two WebRTC peers find each other online, and swap session descriptions +before they connect.""" from abc import ABC, abstractmethod from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import Any # (sender email, offer sdp) -> answer sdp OnOffer = Callable[[str, str], Awaitable[str]] +# (sender email, sender session) for each hello. A session is a new id at each +# sign-in of the sender. +OnHello = Callable[[str, str], None] +# The signaling calls it with the reason when a session ends before ``close``. +OnClosed = Callable[[ConnectionError], None] +# The signaling calls it with the reason when it fails to answer an offer for a +# reason other than a refusal. +OnAnswerFailed = Callable[[ConnectionError], None] +# 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 IceServerSet: + servers: IceServers + # How long the TURN credentials work, or None if they do not expire. + lifetime_seconds: float | None + + +# Each call returns the ICE servers for one new peer connection. +IceServerSource = Callable[[], Awaitable[IceServerSet]] class Signaling(ABC): - """Carries one peer's offer to another and the answer back.""" + """Tells peers that a client is online, and carries one peer's offer to + another and the answer back.""" + + @abstractmethod + async def listen( + self, + email: str, + on_offer: OnOffer, + on_hello: OnHello, + on_closed: OnClosed, + on_answer_failed: OnAnswerFailed, + ) -> None: + """Listen for hellos and offers to ``email``. + + ``on_offer`` answers each offer. ``on_hello`` gets each hello. + ``on_closed`` gets the reason when the session ends before ``close``. + ``on_answer_failed`` gets the reason when an answer fails for another + reason than a refusal. The callbacks run on the loop that called + ``listen``. + """ @abstractmethod - async def listen(self, email: str, on_offer: OnOffer) -> None: - """Answer offers for ``email`` with ``on_offer``, run on the loop that - called ``listen``.""" + async def ice_servers(self, email: str) -> IceServerSet: + """Return the ICE servers for a new peer connection of ``email``.""" + + @abstractmethod + async def hello(self, email: str, peers: list[str]) -> None: + """Tell each of ``peers`` that ``email`` is online. + + A peer that is offline never gets the hello. + """ @abstractmethod async def offer(self, sender: str, receiver: str, sdp: str) -> str: """Send ``sender``'s offer to ``receiver``; return its answer.""" + + @abstractmethod + async def close(self, email: str) -> None: + """Close the signaling for ``email``. + + Then ``email`` gets no more hellos and no more offers. + """ diff --git a/syft/sync/connections/webrtc/webrtc_collections.py b/syft/sync/connections/webrtc/webrtc_collections.py new file mode 100644 index 00000000000..ca40e7585cf --- /dev/null +++ b/syft/sync/connections/webrtc/webrtc_collections.py @@ -0,0 +1,50 @@ +"""Collections, such as datasets, in WebRTC mode. They do not go over WebRTC +yet, so a WebRTC client registers no collection specs, and each call here +raises.""" + +from syft.sync.connections.base_connection import FileCollection +from syft.sync.connections.protocols import CollectionsConnection + +NOT_BUILT = ( + "Datasets do not go over WebRTC yet. Log in without webrtc=True to share datasets." +) + + +class WebRTCCollectionsConnection(CollectionsConnection): + """Each call raises ``NotImplementedError``.""" + + def create(self, prefix: str, tag: str, content_hash: str, owner_email: str) -> str: + raise NotImplementedError(NOT_BUILT) + + def mark_shared_with_any(self, prefix: str, tag: str, content_hash: str) -> None: + raise NotImplementedError(NOT_BUILT) + + def grant_read( + self, prefix: str, tag: str, content_hash: str, users: list[str] + ) -> None: + raise NotImplementedError(NOT_BUILT) + + def upload( + self, prefix: str, tag: str, content_hash: str, files: dict[str, bytes] + ) -> None: + raise NotImplementedError(NOT_BUILT) + + def list_mine_with_permissions(self, prefix: str) -> list[FileCollection]: + raise NotImplementedError(NOT_BUILT) + + def delete(self, prefix: str, tag: str) -> None: + raise NotImplementedError(NOT_BUILT) + + def delete_by_handle(self, handle: str) -> None: + raise NotImplementedError(NOT_BUILT) + + def list_shared_with_me(self, prefix: str) -> list[dict]: + raise NotImplementedError(NOT_BUILT) + + def list_files( + self, prefix: str, tag: str, content_hash: str, owner_email: str + ) -> list[dict]: + raise NotImplementedError(NOT_BUILT) + + def fetch_file(self, handle: str) -> bytes: + raise NotImplementedError(NOT_BUILT) diff --git a/syft/sync/connections/webrtc/webrtc_config.py b/syft/sync/connections/webrtc/webrtc_config.py new file mode 100644 index 00000000000..a181a37e44b --- /dev/null +++ b/syft/sync/connections/webrtc/webrtc_config.py @@ -0,0 +1,30 @@ +"""How a client reaches its peers over WebRTC. + +This module imports nothing from the ``webrtc`` extra, so login can use it +without that extra installed. +""" + +from pydantic import ConfigDict, ValidationInfo, field_validator + +from syft.sync.connections.base_connection import ConnectionConfig + + +class WebRTCConfig(ConnectionConfig): + """The Firebase project that carries the signaling and the peering of a + WebRTC client. ``infra/firebase/README.md`` tells how to set one up.""" + + model_config = ConfigDict(frozen=True) + + firebase_project_id: str + # The web API key of the project. It is not a secret. + firebase_api_key: str + # The host of the Firebase emulators that replace the project, or None for + # the real project. + firebase_emulator_host: str | None = None + + @field_validator("firebase_project_id", "firebase_api_key") + @classmethod + def _check_not_empty(cls, value: str, info: ValidationInfo) -> str: + if not value: + raise ValueError(f"{info.field_name} must not be empty") + return value diff --git a/syft/sync/connections/webrtc/webrtc_p2p.py b/syft/sync/connections/webrtc/webrtc_p2p.py index b3a20b8dd16..34240c41325 100644 --- a/syft/sync/connections/webrtc/webrtc_p2p.py +++ b/syft/sync/connections/webrtc/webrtc_p2p.py @@ -73,6 +73,12 @@ def connect(self, peer: str) -> None: """Open a channel to ``peer``; return once it is open.""" self._peer_connections.connect(peer) + def set_peers(self, peers: list[str]) -> None: + self._peer_connections.set_peers(peers) + + def maybe_raise_background_errors(self) -> None: + self._peer_connections.maybe_raise_background_errors() + def close(self) -> None: """Close the peer connections. Unconfirmed messages stay in the outgoing queues.""" diff --git a/syft/sync/login.py b/syft/sync/login.py index d61ebf412e7..c314147bc0c 100644 --- a/syft/sync/login.py +++ b/syft/sync/login.py @@ -1,16 +1,23 @@ +from dataclasses import dataclass from pathlib import Path -from syft.sync.utils.syftbox_utils import check_env +from syft.sync.config.config import settings +from syft.sync.connections.webrtc.firebase.auth import ( + firebase_session_path, + session_is_refused, + sign_in_with_emailed_link, +) +from syft.sync.connections.webrtc.firebase.project import FirebaseProject +from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig from syft.sync.environments.environment import Environment +from syft.sync.login_utils import handle_potential_version_mismatches_on_login from syft.sync.peers.peer_store import datasite_crypto_keys_path, import_key_file from syft.sync.syftbox_manager import SyftboxManager, SyftboxManagerConfig from syft.sync.utils.print_utils import ( print_client_connected, print_client_connecting, ) -from syft.sync.utils.syftbox_utils import get_email_colab -from syft.sync.config.config import settings -from syft.sync.login_utils import handle_potential_version_mismatches_on_login +from syft.sync.utils.syftbox_utils import check_env, get_email_colab def _verify_token_matches_email(client: SyftboxManager) -> None: @@ -94,6 +101,79 @@ def _resolve_login_params( return email, token_path +@dataclass(frozen=True) +class LoginTarget: + email: str + # None on Colab, and in WebRTC mode. + token_path: str | Path | None + # True when a version mismatch kept the data, and the state needs a repair. + repair_pending: bool + # None: the client syncs over Google Drive. + webrtc: WebRTCConfig | None + + +def _resolve_login_target( + email: str | None, token_path: str | Path | None, webrtc: bool | WebRTCConfig +) -> LoginTarget: + """Resolve what a login connects to. + + Raises: + ValueError: ``webrtc`` is set and ``email`` is None or ``token_path`` + is set, or ``webrtc`` is True and a Firebase setting is missing. + """ + if webrtc is False: + email, token_path = _resolve_login_params(email, token_path) + repair_pending = handle_potential_version_mismatches_on_login(email, token_path) + return LoginTarget(email, token_path, repair_pending, None) + if email is None: + raise ValueError("Pass your email to log in with webrtc.") + if token_path is not None: + raise ValueError(f"A WebRTC login takes no token_path, got {token_path!r}") + webrtc_config = _webrtc_config_from_settings() if webrtc is True else webrtc + return LoginTarget(email, None, False, webrtc_config) + + +def _webrtc_config_from_settings() -> WebRTCConfig: + """Return the Firebase project in the settings. + + Raises: + ValueError: A Firebase setting is missing. + """ + if settings.firebase_project_id is None: + raise ValueError( + "Set SYFT_FIREBASE_PROJECT_ID to the Firebase project for WebRTC, then " + "log in again." + ) + if settings.firebase_api_key is None: + raise ValueError( + "Set SYFT_FIREBASE_API_KEY to the web API key of the Firebase project, " + "then log in again." + ) + return WebRTCConfig( + firebase_project_id=settings.firebase_project_id, + firebase_api_key=settings.firebase_api_key, + ) + + +def _maybe_sign_in_to_firebase(target: LoginTarget, syftbox_folder: Path) -> None: + """Sign in to the Firebase project of a WebRTC login with an emailed link, + if this machine has no session for it, or Firebase refuses the saved one.""" + if target.webrtc is None: + return + project = FirebaseProject.from_config(target.webrtc) + session_path = firebase_session_path(syftbox_folder, project.project_id) + if session_path.exists() and session_is_refused(project, session_path): + session_path.unlink() + if not session_path.exists(): + sign_in_with_emailed_link( + project, target.email, session_path, lambda: _ask_sign_in_link(target.email) + ) + + +def _ask_sign_in_link(email: str) -> str: + return input(f"We sent a sign-in link to {email}. Paste the link here: ") + + def _import_key_file( key_file: str | Path | None, syftbox_folder: Path, email: str ) -> None: @@ -116,6 +196,7 @@ def login( | None = None, # None: value is determined by the role encryption: bool | None = None, # True: required; None: the datasite's policy key_file: str | Path | None = None, # crypto_keys.json of an earlier session + webrtc: bool | WebRTCConfig = False, # True: the Firebase project in the settings ): return login_ds( email, @@ -125,6 +206,7 @@ def login( skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, encryption=encryption, key_file=key_file, + webrtc=webrtc, ) @@ -137,31 +219,20 @@ def login_ds( | None = None, # None: value is determined by the role encryption: bool | None = None, # True: required; None: the datasite's policy key_file: str | Path | None = None, # crypto_keys.json of an earlier session + webrtc: bool | WebRTCConfig = False, # True: the Firebase project in the settings ): - env = check_env() - email, token_path = _resolve_login_params(email, token_path) - - repair_pending = handle_potential_version_mismatches_on_login(email, token_path) - - if env == Environment.COLAB: - config = SyftboxManagerConfig.for_colab( - email=email, - has_ds_role=True, - skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, - encryption=encryption, - ) - else: - config = SyftboxManagerConfig.for_jupyter( - email=email, - has_ds_role=True, - token_path=Path(token_path) if token_path is not None else None, - skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, - encryption=encryption, - ) - _import_key_file(key_file, config.syftbox_folder, email) + target = _resolve_login_target(email, token_path, webrtc) + config = _manager_config( + target, + has_ds_role=True, + skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, + encryption=encryption, + ) + _import_key_file(key_file, config.syftbox_folder, target.email) + _maybe_sign_in_to_firebase(target, config.syftbox_folder) client = SyftboxManager.from_config(config) - return _init_client_login(client, sync, load_peers, repair_pending) + return _init_client_login(client, sync, load_peers, target.repair_pending) def login_do( @@ -173,28 +244,30 @@ def login_do( | None = None, # None: value is determined by the role encryption: bool | None = None, # True: required; None: the datasite's policy key_file: str | Path | None = None, # crypto_keys.json of an earlier session + webrtc: bool | WebRTCConfig = False, # True: the Firebase project in the settings ): - env = check_env() - email, token_path = _resolve_login_params(email, token_path) + target = _resolve_login_target(email, token_path, webrtc) + config = _manager_config( + target, + has_do_role=True, + skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, + encryption=encryption, + ) + _import_key_file(key_file, config.syftbox_folder, target.email) + _maybe_sign_in_to_firebase(target, config.syftbox_folder) + client = SyftboxManager.from_config(config) - repair_pending = handle_potential_version_mismatches_on_login(email, token_path) + return _init_client_login(client, sync, load_peers, target.repair_pending) - if env == Environment.COLAB: - config = SyftboxManagerConfig.for_colab( - email=email, - has_do_role=True, - skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, - encryption=encryption, - ) - else: - config = SyftboxManagerConfig.for_jupyter( - email=email, - has_do_role=True, - token_path=Path(token_path) if token_path is not None else None, - skip_peer_on_patch_version_diff=skip_peer_on_patch_version_diff, - encryption=encryption, - ) - _import_key_file(key_file, config.syftbox_folder, email) - client = SyftboxManager.from_config(config) - return _init_client_login(client, sync, load_peers, repair_pending) +def _manager_config(target: LoginTarget, **config_kwargs) -> SyftboxManagerConfig: + """The config of a manager that logs in to ``target``, on Colab or in + Jupyter.""" + if check_env() == Environment.COLAB: + return SyftboxManagerConfig.for_colab( + email=target.email, webrtc=target.webrtc, **config_kwargs + ) + token_path = Path(target.token_path) if target.token_path is not None else None + return SyftboxManagerConfig.for_jupyter( + email=target.email, token_path=token_path, webrtc=target.webrtc, **config_kwargs + ) diff --git a/syft/sync/platforms/webrtc_platform.py b/syft/sync/platforms/webrtc_platform.py new file mode 100644 index 00000000000..67af765af34 --- /dev/null +++ b/syft/sync/platforms/webrtc_platform.py @@ -0,0 +1,6 @@ +from syft.sync.platforms.base_platform import BasePlatform + + +class WebRTCPlatform(BasePlatform): + name: str = "WebRTC" + module_path: str = "webrtc" diff --git a/syft/sync/syftbox_manager.py b/syft/sync/syftbox_manager.py index fbe7d2ce2a4..5751bde734d 100644 --- a/syft/sync/syftbox_manager.py +++ b/syft/sync/syftbox_manager.py @@ -11,6 +11,7 @@ from pydantic import BaseModel, ConfigDict, PrivateAttr from syft.sync.callback_mixin import BaseModelCallbackMixin +from syft.sync.connections.config import ConnectionRouterConfig from syft.sync.connections.connection_router import ConnectionRouter from syft.sync.connections.drive import mock_drive_service from syft.sync.connections.drive.drive_cached_client import DriveCachedClient @@ -23,6 +24,37 @@ from syft.sync.connections.drive.drive_p2p import DriveP2PConnection from syft.sync.connections.drive.drive_peering import DrivePeeringConnection from syft.sync.connections.drive.grdrive_config import GdriveConnectionConfig +from syft.sync.connections.protocols import Connections +from syft.sync.connections.webrtc.firebase.auth import ( + FirebaseSession, + firebase_session_path, + load_refresh_token, +) +from syft.sync.connections.webrtc.firebase.database import RealtimeDatabase +from syft.sync.connections.webrtc.firebase.database_peering import ( + DatabasePeeringConfig, + DatabasePeeringConnection, +) +from syft.sync.connections.webrtc.firebase.database_signaling import ( + DatabaseSignaling, +) +from syft.sync.connections.webrtc.firebase.project import FirebaseProject +from syft.sync.connections.webrtc.firebase.turn import TurnFunction, no_ice_servers +from syft.sync.connections.webrtc.local_owner_store import ( + OWNER_STORE_PATH, + LocalOwnerStoreConnection, +) +from syft.sync.connections.webrtc.mock.fake_peer_connections import ( + FakeNetwork, + FakePeerConnections, +) +from syft.sync.connections.webrtc.peer_connections import PeerConnections +from syft.sync.connections.webrtc.signaling.local_signaling import LocalSignaling +from syft.sync.connections.webrtc.signaling.signaling import IceServerSource +from syft.sync.connections.webrtc.webrtc_collections import WebRTCCollectionsConnection +from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig +from syft.sync.connections.webrtc.webrtc_p2p import WebRTCP2PConnection +from syft.sync.encryption_policy import EncryptionPolicy from syft.sync.events.file_change_event import ( FileChangeEvent, FileChangeEventsMessage, @@ -31,8 +63,10 @@ from syft.sync.job_file_change_handler import JobFileChangeHandler from syft.sync.peers.peer import Peer, PeerNotReadyError from syft.sync.peers.peer_list import PeerList -from syft.sync.encryption_policy import EncryptionPolicy +from syft.sync.peers.peer_store import PeerStore from syft.sync.platforms.base_platform import BasePlatform +from syft.sync.platforms.gdrive_files_platform import GdriveFilesPlatform +from syft.sync.platforms.webrtc_platform import WebRTCPlatform from syft.sync.sync.caches.datasite_owner_cache import ( DataSiteOwnerEventCacheConfig, ) @@ -50,26 +84,15 @@ DatasiteWatcherSyncerConfig, ) from syft.sync.utils.path_filters import is_normal_syncable_path -from syft.sync.utils.waiting import ( - DEFAULT_POLL_INTERVAL, - DEFAULT_WAIT_TIMEOUT, - poll_until, -) from syft.sync.utils.syftbox_utils import ( random_email, random_syftbox_folder_for_testing, ) -from syft.sync.peers.peer_store import PeerStore -from syft.sync.connections.config import ConnectionRouterConfig -from syft.sync.platforms.gdrive_files_platform import GdriveFilesPlatform -from syft.sync.connections.protocols import Connections -from syft.sync.connections.webrtc.mock.fake_peer_connections import ( - FakeNetwork, - FakePeerConnections, +from syft.sync.utils.waiting import ( + DEFAULT_POLL_INTERVAL, + DEFAULT_WAIT_TIMEOUT, + poll_until, ) -from syft.sync.connections.webrtc.signaling.local_signaling import LocalSignaling -from syft.sync.connections.webrtc.peer_connections import PeerConnections -from syft.sync.connections.webrtc.webrtc_p2p import WebRTCP2PConnection from syft.sync.version.peer_manager import ( PeerManager, PeerManagerConfig, @@ -127,6 +150,31 @@ def default_collection_variants( return [layout.variant for layout in spec.layouts] +def router_config_for_login( + email: str, + token_path: Path | None, + webrtc: WebRTCConfig | None, + collection_specs: list["CollectionSyncSpec"], +) -> ConnectionRouterConfig: + """Return the connection router config of a login: one Google Drive login, + or one WebRTC config. + + Raises: + ValueError: ``webrtc`` comes with collection specs or a token path. + """ + if webrtc is None: + drive_login = GdriveConnectionConfig(email=email, token_path=token_path) + return ConnectionRouterConfig.one_connection(drive_login) + if collection_specs: + raise ValueError( + "Datasets do not go over WebRTC yet: pass no collection_specs with " + f"webrtc, got {collection_specs}" + ) + if token_path is not None: + raise ValueError(f"A WebRTC login takes no token_path, got {token_path!r}") + return ConnectionRouterConfig.one_connection(webrtc) + + class SyftboxManagerConfig(BaseModel): email: str syftbox_folder: Path @@ -162,6 +210,8 @@ def for_colab( ] = None, # None: value is determined by the role force_ignore_peer_version: bool = False, collection_specs: list["CollectionSyncSpec"] | None = None, + # None: the client syncs over Google Drive. + webrtc: WebRTCConfig | None = None, ): if not has_ds_role and not has_do_role: raise ValueError("At least one of has_ds_role or has_do_role must be True") @@ -170,15 +220,14 @@ def for_colab( # about custom collections (eg: datasets or jobs). if collection_specs is None: collection_specs = [] - syftbox_folder = get_colab_default_syftbox_folder(email) use_in_memory_cache = False collections_folder = default_collections_folder( syftbox_folder, email, collection_specs ) collection_variants = default_collection_variants(collection_specs) - connection_router_config = ConnectionRouterConfig.one_connection( - GdriveConnectionConfig(email=email, token_path=None) + connection_router_config = router_config_for_login( + email, None, webrtc, collection_specs ) datasite_owner_syncer_config = DatasiteOwnerSyncerConfig( email=email, @@ -240,6 +289,8 @@ def for_jupyter( ] = None, # None: value is determined by the role force_ignore_peer_version: bool = False, collection_specs: list["CollectionSyncSpec"] | None = None, + # None: the client syncs over Google Drive. + webrtc: WebRTCConfig | None = None, ): if not has_ds_role and not has_do_role: raise ValueError("At least one of has_ds_role or has_do_role must be True") @@ -249,15 +300,14 @@ def for_jupyter( # (see syft_rds.config.DATASET_COLLECTION_SPECS). if collection_specs is None: collection_specs = [] - syftbox_folder = get_jupyter_default_syftbox_folder(email) collections_folder = default_collections_folder( syftbox_folder, email, collection_specs ) collection_variants = default_collection_variants(collection_specs) - connection_router_config = ConnectionRouterConfig.one_connection( - GdriveConnectionConfig(email=email, token_path=token_path) + connection_router_config = router_config_for_login( + email, token_path, webrtc, collection_specs ) datasite_owner_syncer_config = DatasiteOwnerSyncerConfig( email=email, @@ -603,16 +653,17 @@ def _connections_from_config(config: SyftboxManagerConfig) -> Connections: "The config names no connections: set connection_router_config, " "or pass connections to SyftboxManager.from_config" ) - drive_config = connection_router_config.p2p_con - if not ( - isinstance(drive_config, GdriveConnectionConfig) - and connection_router_config.uses_one_connection() - ): + if not connection_router_config.uses_one_connection(): raise NotImplementedError( - "Only one Google Drive login for every connection is built so far" + "Only one login for every connection is built so far" ) - cached_client = DriveCachedClient.from_config(drive_config) - return SyftboxManager._drive_connections(cached_client) + login = connection_router_config.p2p_con + if isinstance(login, GdriveConnectionConfig): + cached_client = DriveCachedClient.from_config(login) + return SyftboxManager._drive_connections(cached_client) + if isinstance(login, WebRTCConfig): + return SyftboxManager._webrtc_connections(config, login) + raise NotImplementedError(f"No connections are built for {login!r}") @staticmethod def _drive_connections(cached_client: DriveCachedClient) -> Connections: @@ -626,6 +677,44 @@ def _drive_connections(cached_client: DriveCachedClient) -> Connections: platform=GdriveFilesPlatform(), ) + @staticmethod + def _webrtc_connections( + config: SyftboxManagerConfig, webrtc: WebRTCConfig + ) -> Connections: + """Every connection of the router in WebRTC mode, with no Google Drive. + + The login saved a Firebase session for the project of ``webrtc``. + """ + # Imported here: aiortc is in the optional webrtc extra. + from syft.sync.connections.webrtc.real.aiortc_peer_connections import ( + AiortcPeerConnections, + ) + + project = FirebaseProject.from_config(webrtc) + session_path = firebase_session_path(config.syftbox_folder, project.project_id) + session = FirebaseSession( + project, session_path, load_refresh_token(session_path) + ) + database = RealtimeDatabase(project, session) + if project.turn_function_url is None: + ice_server_source: IceServerSource = no_ice_servers + else: + ice_server_source = TurnFunction(project.turn_function_url, session) + signaling = DatabaseSignaling(database, ice_server_source) + p2p = WebRTCP2PConnection(config.email, config.syftbox_folder) + p2p.open(AiortcPeerConnections(signaling)) + peering_config = DatabasePeeringConfig(config.email, config.syftbox_folder) + return Connections( + p2p_con=p2p, + owner_store_con=LocalOwnerStoreConnection( + config.syftbox_folder / OWNER_STORE_PATH + ), + watcher_store_con=DriveWatcherStoreConnection(), + collections_con=WebRTCCollectionsConnection(), + peering_con=DatabasePeeringConnection(peering_config, database), + platform=WebRTCPlatform(), + ) + @classmethod def for_colab( cls, @@ -858,7 +947,8 @@ def pair_with_mock_drive_and_local_webrtc_connection( signaling = LocalSignaling() return cls._mock_drive_and_webrtc_pair( - lambda: AiortcPeerConnections(signaling), **kwargs + lambda: AiortcPeerConnections(signaling), + **kwargs, ) @classmethod @@ -869,7 +959,8 @@ def _mock_drive_and_webrtc_pair( **config_kwargs: Any, ) -> tuple["SyftboxManager", "SyftboxManager"]: """(ds_manager, do_manager) over one mock Drive, their p2p replaced by a - ``WebRTCP2PConnection`` on each side and the DS connected to the DO.""" + ``WebRTCP2PConnection`` on each side. With ``add_peers``, the approval + gives both sides their peers, and the two connect.""" do_config, ds_config = cls._mock_pair_configs(**config_kwargs) do_connections, ds_connections = cls._mock_drive_connections( do_config, ds_config @@ -878,7 +969,6 @@ def _mock_drive_and_webrtc_pair( ds_p2p = WebRTCP2PConnection(ds_config.email, ds_config.syftbox_folder) do_p2p.open(make_peer_connections()) ds_p2p.open(make_peer_connections()) - ds_p2p.connect(do_config.email) return cls._test_pair( do_config, do_connections.model_copy(update={"p2p_con": do_p2p}), @@ -987,8 +1077,10 @@ def add_peer( verbose: bool = True, sync: bool = True, ): - """Add a peer. Delegates to PeerManager.""" + """Add a peer, and give the approved peers to the connections. + Delegates to PeerManager.""" self.peer_manager.add_peer(peer_email, force=force, verbose=verbose) + self._set_connection_peers() self._emit_peers_loaded() if self.has_do_role: self._post_approve_peer_do(peer_email) @@ -1081,7 +1173,7 @@ def sync( ignore_peer_version: bool = False, ): """ - Sync local state with Google Drive. + Sync local state with the peers. Args: auto_checkpoint: If True, automatically create checkpoint when @@ -1099,6 +1191,10 @@ def sync( from Drive instead of using the cached copy. Use from background daemons (e.g. syft-bg) where a separate process may have updated the file. + + Raises: + ConnectionError: A WebRTC connection failed in the background since + the last sync. The sync pass is complete when it raises. """ with self.sync_file_lock(): self.peer_manager.check_encryption_policy() @@ -1125,14 +1221,18 @@ def sync( self.peer_manager.warn_if_all_peers_incompatible(peer_emails) self.datasite_watcher_syncer.sync_down(peer_emails) + self._connection_router.maybe_raise_background_errors() + def load_peers(self, force_download: bool = False): - """Load peers from connection router. Delegates to PeerManager. + """Load peers from the connection router, and give the approved peers + to the connections. Delegates to PeerManager. Args: force_download: If True, re-fetch SYFT_peers.json from Drive instead of using the cached copy. """ cast(PeerManager, self.peer_manager).load_peers(force_download=force_download) + self._set_connection_peers() self._emit_peers_loaded() def _check_peer_request_exists(self, email: str) -> bool: @@ -1145,10 +1245,12 @@ def approve_peer_request( verbose: bool = True, peer_must_exist: bool = True, ): - """Approve a pending peer request. Delegates to PeerManager.""" + """Approve a pending peer request, and give the approved peers to the + connections. Delegates to PeerManager.""" self.peer_manager.approve_peer_request( email_or_peer, verbose=verbose, peer_must_exist=peer_must_exist ) + self._set_connection_peers() self._post_approve_peer_do(email_or_peer) def _post_approve_peer_do(self, email_or_peer: str | Peer): @@ -1158,6 +1260,12 @@ def _post_approve_peer_do(self, email_or_peer: str | Peer): self._emit_peers_loaded() self._emit("peer_approved", peer_email) + def _set_connection_peers(self) -> None: + """Give the connections the approved peers, the only peers this client + exchanges messages with.""" + approved = [peer.email for peer in self.peer_manager.approved_peers] + self._connection_router.set_peers(approved) + def _emit_peers_loaded(self) -> None: self._emit("peers_loaded") diff --git a/tests/integration/webrtc/conftest.py b/tests/integration/webrtc/conftest.py new file mode 100644 index 00000000000..7f72ccb4506 --- /dev/null +++ b/tests/integration/webrtc/conftest.py @@ -0,0 +1,20 @@ +"""Fixtures for the tests of WebRTC mode on the Firebase emulators.""" + +import pytest + +from tests.integration.webrtc.firebase_emulators import ( + clear_emulators, + running_emulators, +) + + +@pytest.fixture(scope="session") +def running_firebase_emulators(): + with running_emulators(): + yield + + +@pytest.fixture +def firebase_emulators(running_firebase_emulators): + """The emulators, with no users and no documents.""" + clear_emulators() diff --git a/tests/integration/webrtc/firebase_emulators.py b/tests/integration/webrtc/firebase_emulators.py new file mode 100644 index 00000000000..bacf4301cc0 --- /dev/null +++ b/tests/integration/webrtc/firebase_emulators.py @@ -0,0 +1,182 @@ +"""The Firebase emulators for the tests of WebRTC mode, and users signed in to +them. The emulators need npx and Java 21 or later.""" + +import json +import os +import signal +import socket +import subprocess +import tempfile +import time +import urllib.request +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +from syft.sync.connections.webrtc.firebase.auth import ( + FirebaseSession, + firebase_session_path, + load_refresh_token, + sign_in_with_emailed_link, +) +from syft.sync.connections.webrtc.firebase.database import ( + RealtimeDatabase, + email_key, +) +from syft.sync.connections.webrtc.firebase.database_signaling import ( + DatabaseSignaling, +) +from syft.sync.connections.webrtc.firebase.project import ( + AUTH_EMULATOR_PORT, + DATABASE_EMULATOR_PORT, + FirebaseProject, +) +from syft.sync.connections.webrtc.firebase.turn import no_ice_servers +from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig + +# A project id that starts with "demo-" needs no real project and no login. +PROJECT_ID = "demo-syft" +EMULATOR_HOST = "127.0.0.1" +FIREBASE_TOOLS = "firebase-tools@15.35.0" +FIREBASE_FOLDER = Path(__file__).parents[3] / "infra" / "firebase" +START_TIMEOUT_SECONDS = 120 +STOP_TIMEOUT_SECONDS = 30 +AUTH_EMULATOR = f"http://{EMULATOR_HOST}:{AUTH_EMULATOR_PORT}" +DATABASE_EMULATOR = f"http://{EMULATOR_HOST}:{DATABASE_EMULATOR_PORT}" +EMULATOR_PROJECT_PATH = f"emulator/v1/projects/{PROJECT_ID}" +EMULATOR_PORTS = (AUTH_EMULATOR_PORT, DATABASE_EMULATOR_PORT) + +EMULATOR_CONFIG = WebRTCConfig( + firebase_project_id=PROJECT_ID, + firebase_api_key="test-api-key", + firebase_emulator_host=EMULATOR_HOST, +) +EMULATOR_PROJECT = FirebaseProject.from_config(EMULATOR_CONFIG) + + +@contextmanager +def running_emulators() -> Iterator[None]: + """Run the Auth and Realtime Database emulators with + infra/firebase/database.rules.json. + + Raises: + RuntimeError: An emulator port is in use, or the emulators do not start. + """ + busy_ports = [port for port in EMULATOR_PORTS if is_listening(port)] + if busy_ports: + raise RuntimeError( + f"Ports {busy_ports} are in use. Stop the Firebase emulators that run " + "there, so the tests do not use emulators with other rules." + ) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [ + "npx", + "--yes", + FIREBASE_TOOLS, + "emulators:start", + "--only", + "auth,database", + "--project", + PROJECT_ID, + ], + cwd=FIREBASE_FOLDER, + stdout=output, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + try: + wait_until_listening(process, output) + yield + finally: + stop_emulators(process) + + +def wait_until_listening(process: subprocess.Popen, output) -> None: + deadline = time.monotonic() + START_TIMEOUT_SECONDS + while not all(is_listening(port) for port in EMULATOR_PORTS): + if process.poll() is not None or time.monotonic() > deadline: + output.seek(0) + raise RuntimeError( + f"The Firebase emulators did not start:\n{output.read().decode()}" + ) + time.sleep(0.5) + + +def is_listening(port: int) -> bool: + with socket.socket() as probe: + return probe.connect_ex((EMULATOR_HOST, port)) == 0 + + +def stop_emulators(process: subprocess.Popen) -> None: + # firebase-tools stops the Java emulators on SIGINT. npx does not pass the + # signal on, so the whole process group gets it. + os.killpg(process.pid, signal.SIGINT) + try: + process.wait(STOP_TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + + +def clear_emulators() -> None: + """Delete every user and all data.""" + accounts = f"{AUTH_EMULATOR}/{EMULATOR_PROJECT_PATH}/accounts" + urllib.request.urlopen(urllib.request.Request(accounts, method="DELETE")).close() + # The emulator lets "owner" pass every rule. + root = f"{DATABASE_EMULATOR}/.json?ns={EMULATOR_PROJECT.database_namespace}" + headers = {"Authorization": "Bearer owner"} + request = urllib.request.Request(root, headers=headers, method="DELETE") + urllib.request.urlopen(request).close() + + +def emailed_link(email: str) -> str: + """Return the last sign-in link that the Auth emulator sent to ``email``.""" + with urllib.request.urlopen( + f"{AUTH_EMULATOR}/{EMULATOR_PROJECT_PATH}/oobCodes" + ) as reply: + codes = json.load(reply)["oobCodes"] + links = [ + code["oobLink"] + for code in codes + if code["email"].lower() == email.lower() + and code["requestType"] == "EMAIL_SIGNIN" + ] + return links[-1] + + +def sign_in(email: str, syftbox_folder: Path) -> FirebaseSession: + """Sign ``email`` in to the emulators, and save its session in + ``syftbox_folder``.""" + session_path = firebase_session_path(syftbox_folder, PROJECT_ID) + sign_in_with_emailed_link( + EMULATOR_PROJECT, email, session_path, lambda: emailed_link(email) + ) + return FirebaseSession( + EMULATOR_PROJECT, session_path, load_refresh_token(session_path) + ) + + +def database_of(email: str, syftbox_folder: Path) -> RealtimeDatabase: + """The Realtime Database of ``email``, signed in to the emulators.""" + return RealtimeDatabase(EMULATOR_PROJECT, sign_in(email, syftbox_folder)) + + +def signaling_of(email: str, peers: list[str], folder: Path) -> DatabaseSignaling: + """The signaling of ``email``, who accepts ``peers``, with no ICE servers.""" + database = database_of(email, folder / email) + for peer in peers: + database.put(f"acl/{email_key(email)}/{email_key(peer)}", True) + return DatabaseSignaling(database, no_ice_servers) + + +def signalings_of_peers( + first: str, second: str, folder: Path +) -> tuple[DatabaseSignaling, DatabaseSignaling]: + """The signalings of two users who accept each other, with no ICE servers.""" + return signaling_of(first, [second], folder), signaling_of(second, [first], folder) + + +def end_stream(signaling: DatabaseSignaling) -> None: + """Cut the stream of ``signaling``, as a lost network does.""" + signaling._stream._socket.shutdown(socket.SHUT_RDWR) diff --git a/tests/integration/webrtc/test_aiortc_peer_connections.py b/tests/integration/webrtc/test_aiortc_peer_connections.py index c9d9284ef94..1dc92b88854 100644 --- a/tests/integration/webrtc/test_aiortc_peer_connections.py +++ b/tests/integration/webrtc/test_aiortc_peer_connections.py @@ -1,20 +1,115 @@ """Two WebRTCP2PConnections over a real aiortc channel on this machine.""" +import asyncio import os +import queue +import threading +import time +from typing import Any +import aioice.ice import pytest +from aioice.ice import StunProtocol +from aiortc import RTCDataChannel, RTCSctpTransport from syft.sync.connections.types import MessageKind from syft.sync.connections.webrtc.real.aiortc_peer_connections import ( AiortcPeerConnections, ) from syft.sync.connections.webrtc.signaling.local_signaling import LocalSignaling +from syft.sync.connections.webrtc.signaling.signaling import IceServerSet from syft.sync.connections.webrtc.webrtc_p2p import WebRTCP2PConnection DO = "do@example.com" DS = "ds@example.com" PROPOSAL = MessageKind.PROPOSED_CHANGES EVENTS = MessageKind.FILE_EVENTS +SLOW_SIGN_IN_SECONDS = 1.0 +CONNECT_SECONDS = 10 +SHORT_LIFETIME_SECONDS = 1.0 +# aioice closes a connection after 6 failed consent checks, 5 s apart. Each +# check waits 0.5 s for its response. +FAST_CONSENT_INTERVAL_SECONDS = 0.1 +FAST_CONSENT_FAILURES = 2 +# Time for the consent checks to fail, and for both channels to close. +CHANNEL_END_SECONDS = 3 + + +class SlowSignaling(LocalSignaling): + """LocalSignaling whose sign-in takes a while, as a slow server does.""" + + async def listen(self, *args: Any) -> None: + await asyncio.sleep(SLOW_SIGN_IN_SECONDS) + await super().listen(*args) + + +class CountingSignaling(LocalSignaling): + """LocalSignaling that counts the requests for ICE servers.""" + + def __init__(self): + super().__init__() + self.ice_server_requests = 0 + + async def ice_servers(self, email: str) -> IceServerSet: + self.ice_server_requests += 1 + return await super().ice_servers(email) + + +class FailingCloseSignaling(LocalSignaling): + """LocalSignaling whose close fails, as Firebase does when it cannot be + reached.""" + + async def close(self, email: str) -> None: + await super().close(email) + raise ConnectionError("Firebase cannot be reached") + + +class RecordingSignaling(LocalSignaling): + """LocalSignaling that records the sender of each offer, and each hello.""" + + def __init__(self): + super().__init__() + self.offerers: list[str] = [] + self.hellos: list[tuple[str, str]] = [] + + async def hello(self, email: str, peers: list[str]) -> None: + self.hellos.extend((email, peer) for peer in peers) + await super().hello(email, peers) + + async def offer(self, sender: str, receiver: str, sdp: str) -> str: + self.offerers.append(sender) + return await super().offer(sender, receiver, sdp) + + +class ExpiringSignaling(LocalSignaling): + """LocalSignaling whose ICE servers expire after a moment.""" + + async def ice_servers(self, email: str) -> IceServerSet: + return IceServerSet([], SHORT_LIFETIME_SECONDS) + + +class Network: + """Drops every ICE packet in this process while ``down`` is True, as a + lost network does. The signaling still works.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch): + self.down = False + send_stun, send_data = StunProtocol.send_stun, StunProtocol.send_data + + def maybe_send_stun(protocol: StunProtocol, *args: Any) -> None: + if not self.down: + send_stun(protocol, *args) + + async def maybe_send_data(protocol: StunProtocol, *args: Any) -> None: + if not self.down: + await send_data(protocol, *args) + + monkeypatch.setattr(StunProtocol, "send_stun", maybe_send_stun) + monkeypatch.setattr(StunProtocol, "send_data", maybe_send_data) + + +def ignore(*args: object) -> None: + pass @pytest.fixture @@ -25,6 +120,7 @@ def open_pair(tmp_path): signaling = LocalSignaling() do.open(AiortcPeerConnections(signaling)) ds.open(AiortcPeerConnections(signaling)) + do.set_peers([DS]) yield do, ds do.close() ds.close() @@ -75,3 +171,194 @@ def test_large_message_arrives_whole(open_pair): [message] = do.receive(DS, PROPOSAL) assert message.data == data + + +def test_channel_messages_stay_within_max_message_size(open_pair, monkeypatch): + # The aiortc receiver needs quadratic time for a message above the maximum size. + sizes: list[int] = [] + send = RTCDataChannel.send + + def recording_send(channel: RTCDataChannel, data: bytes) -> None: + sizes.append(len(data)) + send(channel, data) + + monkeypatch.setattr(RTCDataChannel, "send", recording_send) + _, ds = open_pair + ds.connect(DO) + + ds.send(DO, "big", os.urandom(1_000_000), PROPOSAL) + ds.wait_until_delivered() + + assert max(sizes) <= RTCSctpTransport.getCapabilities().maxMessageSize + + +def test_do_refuses_offer_from_peer_it_did_not_accept(open_pair): + do, ds = open_pair + do.set_peers([]) + + with pytest.raises(ConnectionRefusedError): + ds.connect(DO) + + +def test_do_closes_channel_of_peer_it_no_longer_accepts(open_pair): + do, ds = open_pair + ds.connect(DO) + + do.set_peers([]) + ds.send(DO, "late", b"", PROPOSAL) + + with pytest.raises(TimeoutError): + ds.wait_until_delivered(timeout=2) + assert do.receive(DS, PROPOSAL) == [] + + +def test_timed_out_connect_does_not_break_later_set_peers(): + ds = AiortcPeerConnections(SlowSignaling()) + ds.open(DS, lambda peer: None, lambda peer, frame: None) + try: + with pytest.raises(TimeoutError): + ds.connect(DO, timeout=SLOW_SIGN_IN_SECONDS / 10) + + ds.set_peers([]) + finally: + ds.close() + + +def test_each_peer_connection_gets_new_ice_servers(tmp_path): + signaling = CountingSignaling() + do = WebRTCP2PConnection(DO, tmp_path / "do") + ds = WebRTCP2PConnection(DS, tmp_path / "ds") + do.open(AiortcPeerConnections(signaling)) + ds.open(AiortcPeerConnections(signaling)) + try: + do.set_peers([DS]) + ds.connect(DO) + ds.connect(DO) + + # Each connect makes a new peer connection on each side. + assert signaling.ice_server_requests == 4 + finally: + do.close() + ds.close() + + +def test_close_stops_loop_when_signaling_close_fails(): + peer_connections = AiortcPeerConnections(FailingCloseSignaling()) + peer_connections.open(DO, lambda peer: None, lambda peer, frame: None) + peer_connections.set_peers([DS]) + + with pytest.raises(ConnectionError, match="Firebase cannot be reached"): + peer_connections.close() + + assert not peer_connections._thread.is_alive() + + +def test_lower_email_sends_offer_after_hellos(): + signaling = RecordingSignaling() + do = AiortcPeerConnections(signaling) + ds = AiortcPeerConnections(signaling) + ds_opened = threading.Event() + do.open(DO, ignore, ignore) + ds.open(DS, lambda peer: ds_opened.set(), ignore) + try: + do.set_peers([DS]) + ds.set_peers([DO]) + + assert ds_opened.wait(CONNECT_SECONDS) + assert signaling.offerers == [min(DO, DS)] + finally: + do.close() + ds.close() + + +def test_offering_side_connects_again_before_credentials_expire(): + signaling = ExpiringSignaling() + do = AiortcPeerConnections(signaling) + ds = AiortcPeerConnections(signaling) + opened_on_ds: queue.Queue[str] = queue.Queue() + do.open(DO, ignore, ignore) + ds.open(DS, opened_on_ds.put, ignore) + try: + do.set_peers([DS]) + ds.set_peers([DO]) + + assert opened_on_ds.get(timeout=CONNECT_SECONDS) == DO + assert opened_on_ds.get(timeout=CONNECT_SECONDS) == DO + finally: + do.close() + ds.close() + + +def test_peer_that_signs_in_again_gets_new_channel(): + signaling = LocalSignaling() + do = AiortcPeerConnections(signaling) + first_ds = AiortcPeerConnections(signaling) + first_opened, second_opened = threading.Event(), threading.Event() + do.open(DO, ignore, ignore) + first_ds.open(DS, lambda peer: first_opened.set(), ignore) + do.set_peers([DS]) + first_ds.set_peers([DO]) + assert first_opened.wait(CONNECT_SECONDS) + first_ds.close() + second_ds = AiortcPeerConnections(signaling) + second_ds.open(DS, lambda peer: second_opened.set(), ignore) + try: + second_ds.set_peers([DO]) + + assert second_opened.wait(CONNECT_SECONDS) + finally: + do.close() + second_ds.close() + + +def test_lost_channel_opens_again_at_next_set_peers(monkeypatch): + network = Network(monkeypatch) + monkeypatch.setattr(aioice.ice, "CONSENT_INTERVAL", FAST_CONSENT_INTERVAL_SECONDS) + monkeypatch.setattr(aioice.ice, "CONSENT_FAILURES", FAST_CONSENT_FAILURES) + signaling = LocalSignaling() + do = AiortcPeerConnections(signaling) + ds = AiortcPeerConnections(signaling) + opened_on_ds: queue.Queue[str] = queue.Queue() + frames_on_do: queue.Queue[tuple[str, bytes]] = queue.Queue() + do.open(DO, ignore, lambda *frame: frames_on_do.put(frame)) + ds.open(DS, opened_on_ds.put, ignore) + try: + do.set_peers([DS]) + ds.set_peers([DO]) + assert opened_on_ds.get(timeout=CONNECT_SECONDS) == DO + network.down = True + time.sleep(CHANNEL_END_SECONDS) + network.down = False + + # The next sync of each side sets its peers again. + do.set_peers([DS]) + ds.set_peers([DO]) + + assert opened_on_ds.get(timeout=CONNECT_SECONDS) == DO + ds.send(DO, b"hello") + assert frames_on_do.get(timeout=CONNECT_SECONDS) == (DS, b"hello") + finally: + do.close() + ds.close() + + +def test_connected_peer_gets_no_hello_on_set_peers(): + signaling = RecordingSignaling() + do = AiortcPeerConnections(signaling) + ds = AiortcPeerConnections(signaling) + do_opened, ds_opened = threading.Event(), threading.Event() + do.open(DO, lambda peer: do_opened.set(), ignore) + ds.open(DS, lambda peer: ds_opened.set(), ignore) + try: + do.set_peers([DS]) + ds.set_peers([DO]) + assert do_opened.wait(CONNECT_SECONDS) and ds_opened.wait(CONNECT_SECONDS) + signaling.hellos.clear() + + do.set_peers([DS]) + ds.set_peers([DO]) + + assert signaling.hellos == [] + finally: + do.close() + ds.close() diff --git a/tests/integration/webrtc/test_database_peering.py b/tests/integration/webrtc/test_database_peering.py new file mode 100644 index 00000000000..5dfcea1379a --- /dev/null +++ b/tests/integration/webrtc/test_database_peering.py @@ -0,0 +1,114 @@ +"""DatabasePeeringConnection on the Firebase emulators.""" + +import socket +from dataclasses import replace +from pathlib import Path + +import pytest + +from syft.sync.connections.exceptions import ConnectionUnavailableError +from syft.sync.connections.webrtc.firebase.database import RealtimeDatabase +from syft.sync.connections.webrtc.firebase.database_peering import ( + DatabasePeeringConfig, + DatabasePeeringConnection, + peer_info_path, +) +from syft.sync.encryption_policy import EncryptionPolicy +from syft.sync.peers.peer import PeerState +from syft.sync.syftbox_manager import SyftboxManager +from syft.sync.version.exceptions import UnreadablePeerInfoError +from syft.sync.version.peer_info import PeerInfo +from syft.sync.version.version_info import VersionInfo +from tests.integration.webrtc.firebase_emulators import ( + EMULATOR_HOST, + EMULATOR_PROJECT, + database_of, + sign_in, +) + +DO = "do@example.com" +DS = "ds@example.com" + +pytestmark = pytest.mark.usefixtures("firebase_emulators") + + +def database_peering(email: str, syftbox_folder: Path) -> DatabasePeeringConnection: + config = DatabasePeeringConfig(email, syftbox_folder) + return DatabasePeeringConnection(config, database_of(email, syftbox_folder)) + + +def test_peering_flow_exchanges_key_bundles(): + do_config, ds_config = SyftboxManager._mock_pair_configs(encryption=True) + do_connections, ds_connections = SyftboxManager._mock_drive_connections( + do_config, ds_config + ) + do_peering = database_peering(do_config.email, do_config.syftbox_folder) + ds_peering = database_peering(ds_config.email, ds_config.syftbox_folder) + + ds_manager, do_manager = SyftboxManager._test_pair( + do_config, + do_connections.model_copy(update={"peering_con": do_peering}), + ds_config, + ds_connections.model_copy(update={"peering_con": ds_peering}), + add_peers=True, + ) + + do_peer = do_manager.peer_manager.get_cached_peer(ds_manager.email) + ds_peer = ds_manager.peer_manager.get_cached_peer(do_manager.email) + assert do_peer.state == ds_peer.state == PeerState.ACCEPTED + assert do_manager._peer_store.has_peer_bundle(ds_manager.email) + assert ds_manager._peer_store.has_peer_bundle(do_manager.email) + + +def test_new_peer_info_reaches_accepted_peer(tmp_path): + do = database_peering(DO, tmp_path / "do") + ds = database_peering(DS, tmp_path / "ds") + old_info = PeerInfo( + version_info=VersionInfo.current(), encryption_policy=EncryptionPolicy.OPTIONAL + ) + do.open_channels(DS) + do.grant_peer_info_read(DS, old_info) + new_info = old_info.model_copy( + update={"encryption_policy": EncryptionPolicy.REQUIRED} + ) + + do.publish_peer_info(new_info) + + assert ds.read_peer_info(DO) == new_info + + +def test_incoming_requests_skip_decided_peers(tmp_path): + do = database_peering(DO, tmp_path / "do") + database_peering(DS, tmp_path / "ds").open_channels(DO) + assert do.incoming_requests() == [DS] + + do.update_peer_registry(DS, PeerState.REJECTED.value) + assert do.incoming_requests() == [] + + +def test_unreachable_database_raises_connection_unavailable(tmp_path): + with socket.socket() as unused: + unused.bind((EMULATOR_HOST, 0)) + port = unused.getsockname()[1] + project = replace(EMULATOR_PROJECT, database_url=f"http://{EMULATOR_HOST}:{port}") + database = RealtimeDatabase(project, sign_in(DO, tmp_path)) + peering = DatabasePeeringConnection(DatabasePeeringConfig(DO, tmp_path), database) + + with pytest.raises(ConnectionUnavailableError): + peering.incoming_requests() + + +def test_incoming_request_keeps_peer_list_spelling(tmp_path): + ds = database_peering(DS, tmp_path / "ds") + ds.update_peer_registry(DO.upper(), PeerState.REQUESTED_BY_ME.value) + + database_peering(DO, tmp_path / "do").open_channels(DS) + + assert ds.incoming_requests() == [DO.upper()] + + +def test_unreadable_peer_info_raises_unreadable_error(tmp_path): + database_of(DO, tmp_path / "do").put(peer_info_path(DO, DS), "{not json") + + with pytest.raises(UnreadablePeerInfoError): + database_peering(DS, tmp_path / "ds").read_peer_info(DO) diff --git a/tests/integration/webrtc/test_database_rules.py b/tests/integration/webrtc/test_database_rules.py new file mode 100644 index 00000000000..bcbc92567b9 --- /dev/null +++ b/tests/integration/webrtc/test_database_rules.py @@ -0,0 +1,156 @@ +"""infra/firebase/database.rules.json on the Realtime Database emulator: each +signed-in user reads and writes only what the rules allow.""" + +from collections.abc import Callable +from http import HTTPStatus + +import pytest + +from syft.sync.connections.webrtc.firebase.database import email_key +from syft.sync.connections.webrtc.firebase.database_peering import ( + acl_path, + key_bundle_path, + peer_info_path, + requests_path, +) +from syft.sync.connections.webrtc.firebase.database_signaling import ( + HELLO, + HELLO_SLOT, + OFFER, + REASON_FIELD, + REQUEST_FIELD, + SDP_FIELD, + SESSION_FIELD, + TYPE_FIELD, + inbox_path, + signal_path, +) +from syft.sync.connections.webrtc.firebase.rest import FirebaseRequestError +from tests.integration.webrtc.firebase_emulators import database_of + +ALICE = "alice@example.com" +BOB = "bob@example.com" +CAROL = "carol@example.com" +HELLO_SIGNAL = {TYPE_FIELD: HELLO, SESSION_FIELD: "s1"} +OFFER_SIGNAL = {TYPE_FIELD: OFFER, REQUEST_FIELD: "r1", SDP_FIELD: "v=0"} + +pytestmark = pytest.mark.usefixtures("firebase_emulators") + + +def assert_refused(call: Callable[[], object]) -> None: + with pytest.raises(FirebaseRequestError) as refusal: + call() + assert refusal.value.status == HTTPStatus.UNAUTHORIZED + + +def test_key_bundle_is_written_by_owner_and_read_by_all(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + + alice.put(key_bundle_path(ALICE), "{}") + + assert bob.get(key_bundle_path(ALICE)) == "{}" + assert_refused(lambda: bob.put(key_bundle_path(ALICE), "{}")) + assert_refused(lambda: bob.get("keys")) + + +def test_peer_info_is_read_only_by_owner_and_reader(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + carol = database_of(CAROL, tmp_path / "carol") + + alice.put(peer_info_path(ALICE, BOB), "{}") + + assert bob.get(peer_info_path(ALICE, BOB)) == "{}" + assert_refused(lambda: carol.get(peer_info_path(ALICE, BOB))) + assert_refused(lambda: bob.put(peer_info_path(ALICE, BOB), "{}")) + + +def test_peer_request_must_name_its_sender(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + carol = database_of(CAROL, tmp_path / "carol") + + alice.put(f"{requests_path(BOB)}/{email_key(ALICE)}", ALICE) + + assert bob.get(requests_path(BOB)) == {email_key(ALICE): ALICE} + assert_refused(lambda: carol.get(requests_path(BOB))) + forged = f"{requests_path(BOB)}/{email_key(CAROL)}" + assert_refused(lambda: carol.put(forged, ALICE)) + as_alice = f"{requests_path(BOB)}/{email_key(ALICE)}" + assert_refused(lambda: carol.put(as_alice, ALICE)) + + +def test_acl_is_written_only_by_owner(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + entry = f"{acl_path(ALICE)}/{email_key(BOB)}" + + alice.put(entry, True) + + assert_refused(lambda: bob.put(entry, True)) + + +def test_signal_needs_acceptance_of_receiver(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + + hello_slot = f"{signal_path(BOB, ALICE)}/{HELLO_SLOT}" + assert_refused(lambda: alice.put(hello_slot, HELLO_SIGNAL)) + + bob.put(f"{acl_path(BOB)}/{email_key(ALICE)}", True) + alice.put(hello_slot, HELLO_SIGNAL) + + +def test_offer_with_reason_is_refused(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + bob.put(f"{acl_path(BOB)}/{email_key(ALICE)}", True) + with_reason = {**OFFER_SIGNAL, REASON_FIELD: "any"} + + assert_refused(lambda: alice.post(signal_path(BOB, ALICE), with_reason)) + + +def test_inbox_is_read_and_cleared_only_by_receiver(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + carol = database_of(CAROL, tmp_path / "carol") + bob.put(f"{acl_path(BOB)}/{email_key(ALICE)}", True) + signal_id = alice.post(signal_path(BOB, ALICE), OFFER_SIGNAL) + + assert bob.get(inbox_path(BOB)) == {email_key(ALICE): {signal_id: OFFER_SIGNAL}} + assert_refused(lambda: carol.get(inbox_path(BOB))) + assert_refused(lambda: alice.delete(f"{signal_path(BOB, ALICE)}/{signal_id}")) + bob.delete(inbox_path(BOB)) + assert bob.get(inbox_path(BOB)) is None + + +def test_hello_goes_only_to_hello_slot(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + bob.put(f"{acl_path(BOB)}/{email_key(ALICE)}", True) + hello_slot = f"{signal_path(BOB, ALICE)}/{HELLO_SLOT}" + + alice.put(hello_slot, HELLO_SIGNAL) + alice.put(hello_slot, {**HELLO_SIGNAL, SESSION_FIELD: "s2"}) + + assert bob.get(hello_slot) == {**HELLO_SIGNAL, SESSION_FIELD: "s2"} + assert_refused(lambda: alice.post(signal_path(BOB, ALICE), HELLO_SIGNAL)) + assert_refused(lambda: alice.put(hello_slot, OFFER_SIGNAL)) + + +def test_signal_under_other_sender_is_refused(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + bob.put(f"{acl_path(BOB)}/{email_key(CAROL)}", True) + + assert_refused(lambda: alice.post(signal_path(BOB, CAROL), OFFER_SIGNAL)) + + +def test_signal_of_unknown_type_is_refused(tmp_path): + alice = database_of(ALICE, tmp_path / "alice") + bob = database_of(BOB, tmp_path / "bob") + bob.put(f"{acl_path(BOB)}/{email_key(ALICE)}", True) + goodbye = {TYPE_FIELD: "goodbye", REQUEST_FIELD: "r1", SDP_FIELD: "v=0"} + + assert_refused(lambda: alice.post(signal_path(BOB, ALICE), goodbye)) diff --git a/tests/integration/webrtc/test_database_signaling_connections.py b/tests/integration/webrtc/test_database_signaling_connections.py new file mode 100644 index 00000000000..82edde6367c --- /dev/null +++ b/tests/integration/webrtc/test_database_signaling_connections.py @@ -0,0 +1,240 @@ +"""Two AiortcPeerConnections that find each other through the Realtime +Database on the Firebase emulators.""" + +import asyncio +import queue +import threading +import time + +import pytest + +from syft.sync.connections.webrtc.real.aiortc_peer_connections import ( + AiortcPeerConnections, +) +from tests.integration.webrtc.firebase_emulators import ( + end_stream, + signaling_of, + signalings_of_peers, +) + +DO = "do@example.com" +DS = "ds@example.com" +# Sorts before the DO, so this DS sends the offer to the DO. +OFFERING_DS = "ann@example.com" +TIMEOUT_SECONDS = 20 +# A login opens the connections, then loads its peers and sets them. +LOGIN_GAP_SECONDS = 1 +# Time for the stream thread to see that its connection is gone. +STREAM_END_SECONDS = 2 +# Long enough for an offer to reach the peer, and its answer to fail. +ANSWER_WAIT_SECONDS = 3 +# Long enough for an offer to reach the inbox. +OFFER_WRITE_SECONDS = 1 + +pytestmark = pytest.mark.usefixtures("firebase_emulators") + + +def ignore(*args: object) -> None: + pass + + +def open_recording( + client: AiortcPeerConnections, + email: str, + opened: queue.Queue[tuple[str, str]], + frames: queue.Queue[tuple[str, str, bytes]], +) -> None: + """Open ``client`` as ``email``. Put each channel that opens in ``opened``, + and each frame that arrives in ``frames``, both after ``email``.""" + client.open( + email, + lambda peer: opened.put((email, peer)), + lambda peer, frame: frames.put((email, peer, frame)), + ) + + +def test_peers_connect_after_hellos(tmp_path): + do_signaling, ds_signaling = signalings_of_peers(DO, DS, tmp_path) + do = AiortcPeerConnections(do_signaling) + ds = AiortcPeerConnections(ds_signaling) + do_opened, ds_opened = threading.Event(), threading.Event() + frames_on_do: queue.Queue[tuple[str, bytes]] = queue.Queue() + do.open(DO, lambda peer: do_opened.set(), lambda *frame: frames_on_do.put(frame)) + ds.open(DS, lambda peer: ds_opened.set(), ignore) + try: + do.set_peers([DS]) + ds.set_peers([DO]) + + assert do_opened.wait(TIMEOUT_SECONDS) and ds_opened.wait(TIMEOUT_SECONDS) + ds.send(DO, b"hello") + assert frames_on_do.get(timeout=TIMEOUT_SECONDS) == (DS, b"hello") + finally: + do.close() + ds.close() + + +def test_do_exchanges_frames_with_two_dss_at_once(tmp_path): + peers_of = {DO: [OFFERING_DS, DS], OFFERING_DS: [DO], DS: [DO]} + clients = { + email: AiortcPeerConnections(signaling_of(email, peers, tmp_path)) + for email, peers in peers_of.items() + } + opened: queue.Queue[tuple[str, str]] = queue.Queue() + frames: queue.Queue[tuple[str, str, bytes]] = queue.Queue() + for email, client in clients.items(): + open_recording(client, email, opened, frames) + try: + for email, client in clients.items(): + client.set_peers(peers_of[email]) + channels = {opened.get(timeout=TIMEOUT_SECONDS) for _ in range(4)} + assert channels == {(DO, OFFERING_DS), (DO, DS), (OFFERING_DS, DO), (DS, DO)} + + for ds in (OFFERING_DS, DS): + clients[ds].send(DO, f"from {ds}".encode()) + clients[DO].send(ds, f"to {ds}".encode()) + + received = {frames.get(timeout=TIMEOUT_SECONDS) for _ in range(4)} + assert received == { + (DO, OFFERING_DS, f"from {OFFERING_DS}".encode()), + (DO, DS, f"from {DS}".encode()), + (OFFERING_DS, DO, f"to {OFFERING_DS}".encode()), + (DS, DO, f"to {DS}".encode()), + } + finally: + for client in clients.values(): + client.close() + + +def test_peer_that_signs_in_later_gets_connected(tmp_path): + do_signaling, ds_signaling = signalings_of_peers(DO, DS, tmp_path) + do = AiortcPeerConnections(do_signaling) + ds = AiortcPeerConnections(ds_signaling) + ds_opened = threading.Event() + ds.open(DS, lambda peer: ds_opened.set(), ignore) + ds.set_peers([DO]) + do.open(DO, ignore, ignore) + try: + time.sleep(LOGIN_GAP_SECONDS) + do.set_peers([DS]) + + assert ds_opened.wait(TIMEOUT_SECONDS) + finally: + do.close() + ds.close() + + +def test_ended_signaling_session_signs_in_again_and_is_reported(tmp_path): + do_signaling, ds_signaling = signalings_of_peers(DO, DS, tmp_path) + do = AiortcPeerConnections(do_signaling) + ds = AiortcPeerConnections(ds_signaling) + ds_opened = threading.Event() + do.open(DO, ignore, ignore) + ds.open(DS, lambda peer: ds_opened.set(), ignore) + try: + do.set_peers([DS]) + end_stream(do_signaling) + time.sleep(STREAM_END_SECONDS) + + do.set_peers([DS]) + ds.set_peers([DO]) + + assert ds_opened.wait(TIMEOUT_SECONDS) + with pytest.raises(ConnectionError, match="signaling session ended"): + do.maybe_raise_background_errors() + finally: + do.close() + ds.close() + + +def test_peer_reached_with_other_capitals(tmp_path): + do_signaling, ds_signaling = signalings_of_peers(DO, DS, tmp_path) + do = AiortcPeerConnections(do_signaling) + ds = AiortcPeerConnections(ds_signaling) + opened_on_ds: queue.Queue[str] = queue.Queue() + frames_on_do: queue.Queue[tuple[str, bytes]] = queue.Queue() + do.open(DO, ignore, lambda *frame: frames_on_do.put(frame)) + ds.open(DS, opened_on_ds.put, ignore) + try: + do.set_peers([DS]) + ds.set_peers([DO.upper()]) + + assert opened_on_ds.get(timeout=TIMEOUT_SECONDS) == DO.upper() + ds.send(DO.upper(), b"hello") + assert frames_on_do.get(timeout=TIMEOUT_SECONDS) == (DS, b"hello") + finally: + do.close() + ds.close() + + +def test_refused_offer_reaches_offerer(tmp_path): + do_signaling, ds_signaling = signalings_of_peers(DO, DS, tmp_path) + + async def refuse(sender: str, sdp: str) -> str: + raise ConnectionRefusedError(f"{sender} is not a peer of {DS}") + + async def offer_to_refusing_peer() -> None: + await ds_signaling.listen(DS, refuse, ignore, ignore, ignore) + await do_signaling.listen(DO, refuse, ignore, ignore, ignore) + try: + await do_signaling.offer(DO, DS, "v=0") + finally: + await do_signaling.close(DO) + await ds_signaling.close(DS) + + with pytest.raises(ConnectionRefusedError, match="not a peer"): + asyncio.run(offer_to_refusing_peer()) + + +def test_offer_sent_before_listen_is_not_answered(tmp_path): + do_signaling, ds_signaling = signalings_of_peers(DO, DS, tmp_path) + offerers: list[str] = [] + + async def record_offer(sender: str, sdp: str) -> str: + offerers.append(sender) + return sdp + + async def offer_before_and_after_do_listens() -> None: + await ds_signaling.listen(DS, record_offer, ignore, ignore, ignore) + try: + with pytest.raises(TimeoutError): + await asyncio.wait_for( + ds_signaling.offer(DS, DO, "v=0"), OFFER_WRITE_SECONDS + ) + await do_signaling.listen(DO, record_offer, ignore, ignore, ignore) + try: + await asyncio.wait_for( + ds_signaling.offer(DS, DO, "v=0"), TIMEOUT_SECONDS + ) + finally: + await do_signaling.close(DO) + finally: + await ds_signaling.close(DS) + + asyncio.run(offer_before_and_after_do_listens()) + + assert offerers == [DS] + + +def test_failed_answer_reaches_on_answer_failed(tmp_path): + do_signaling, ds_signaling = signalings_of_peers(DO, DS, tmp_path) + failures: list[ConnectionError] = [] + + async def fail_to_answer(sender: str, sdp: str) -> str: + raise ConnectionError("The TURN function is down") + + async def offer_to_failing_peer() -> None: + await ds_signaling.listen(DS, fail_to_answer, ignore, ignore, failures.append) + await do_signaling.listen(DO, fail_to_answer, ignore, ignore, ignore) + try: + with pytest.raises(TimeoutError): + await asyncio.wait_for( + do_signaling.offer(DO, DS, "v=0"), ANSWER_WAIT_SECONDS + ) + finally: + await do_signaling.close(DO) + await ds_signaling.close(DS) + + asyncio.run(offer_to_failing_peer()) + + [failure] = failures + assert DO in str(failure) and "TURN function is down" in str(failure) diff --git a/tests/integration/webrtc/test_database_stream.py b/tests/integration/webrtc/test_database_stream.py new file mode 100644 index 00000000000..c1716d00196 --- /dev/null +++ b/tests/integration/webrtc/test_database_stream.py @@ -0,0 +1,44 @@ +"""The stream of one Realtime Database node, on the Firebase emulators.""" + +import queue +import time + +import pytest + +from syft.sync.connections.webrtc.firebase.database import StreamEvent, email_key +from syft.sync.connections.webrtc.firebase.database_signaling import ( + HELLO, + HELLO_SLOT, + SESSION_FIELD, + TYPE_FIELD, + inbox_path, + signal_path, +) +from tests.integration.webrtc.firebase_emulators import database_of + +DO = "do@example.com" +DS = "ds@example.com" +HELLO_SIGNAL = {TYPE_FIELD: HELLO, SESSION_FIELD: "s1"} +EVENT_SECONDS = 5 +# Far below the read timeout of the stream, which a blocked close waits for. +CLOSE_SECONDS = 5 + +pytestmark = pytest.mark.usefixtures("firebase_emulators") + + +def test_stream_delivers_new_signal_and_closes_at_once(tmp_path): + do = database_of(DO, tmp_path / "do") + ds = database_of(DS, tmp_path / "ds") + do.put(f"acl/{email_key(DO)}/{email_key(DS)}", True) + events: queue.Queue[StreamEvent | OSError] = queue.Queue() + stream = do.stream(inbox_path(DO), events.put, events.put) + assert events.get(timeout=EVENT_SECONDS).data is None + + ds.put(f"{signal_path(DO, DS)}/{HELLO_SLOT}", HELLO_SIGNAL) + added = events.get(timeout=EVENT_SECONDS) + started = time.monotonic() + stream.close() + + assert added.path == f"/{email_key(DS)}/{HELLO_SLOT}" + assert added.data == HELLO_SIGNAL + assert time.monotonic() - started < CLOSE_SECONDS diff --git a/tests/integration/webrtc/test_firebase_login.py b/tests/integration/webrtc/test_firebase_login.py new file mode 100644 index 00000000000..1f34f1f5084 --- /dev/null +++ b/tests/integration/webrtc/test_firebase_login.py @@ -0,0 +1,55 @@ +"""The sign-in of a WebRTC login on the Firebase emulators: the first login on +a machine asks for the emailed link, and the next one asks nothing.""" + +import pytest + +from syft.sync import login +from syft.sync.connections.webrtc.firebase.auth import ( + FirebaseSession, + load_refresh_token, +) +from tests.integration.webrtc.firebase_emulators import ( + EMULATOR_CONFIG, + EMULATOR_PROJECT, + PROJECT_ID, + clear_emulators, + emailed_link, +) + +EMAIL = "do@example.com" +TARGET = login.LoginTarget(EMAIL, None, False, EMULATOR_CONFIG) + +pytestmark = pytest.mark.usefixtures("firebase_emulators") + + +@pytest.fixture +def asked(monkeypatch) -> list[str]: + """The emails that login asked a sign-in link for.""" + asked: list[str] = [] + + def ask_sign_in_link(email: str) -> str: + asked.append(email) + return emailed_link(email) + + monkeypatch.setattr(login, "_ask_sign_in_link", ask_sign_in_link) + return asked + + +def test_second_login_on_machine_asks_no_link(tmp_path, asked): + login._maybe_sign_in_to_firebase(TARGET, tmp_path) + login._maybe_sign_in_to_firebase(TARGET, tmp_path) + + assert asked == [EMAIL] + session_path = login.firebase_session_path(tmp_path, PROJECT_ID) + refresh_token = load_refresh_token(session_path) + assert FirebaseSession(EMULATOR_PROJECT, session_path, refresh_token).id_token() + + +def test_refused_session_asks_for_new_link(tmp_path, asked): + login._maybe_sign_in_to_firebase(TARGET, tmp_path) + # Firebase refuses the saved session of a user that no longer exists. + clear_emulators() + + login._maybe_sign_in_to_firebase(TARGET, tmp_path) + + assert asked == [EMAIL, EMAIL] diff --git a/tests/integration/webrtc/test_webrtc_mode_end_to_end.py b/tests/integration/webrtc/test_webrtc_mode_end_to_end.py new file mode 100644 index 00000000000..f9ebb608dc2 --- /dev/null +++ b/tests/integration/webrtc/test_webrtc_mode_end_to_end.py @@ -0,0 +1,106 @@ +"""A DO and a DS in WebRTC mode: peering through the Realtime Database on the +Firebase emulators, and messages over real WebRTC on this machine. No Google Drive, +mock or real, takes part.""" + +import time + +import pytest + +from syft.sync.connections.config import ConnectionRouterConfig +from syft.sync.syftbox_manager import SyftboxManager +from tests.integration.webrtc.firebase_emulators import ( + EMULATOR_CONFIG, + end_stream, + sign_in, +) +from tests.integration.webrtc.utils import close, flush, p2p_of +from tests.unit.test_sync_manager import path_for_job +from tests.unit.utils import grant_job_inbox_access + +# Time for the stream thread to see that its connection is gone. +STREAM_END_SECONDS = 2 + +pytestmark = pytest.mark.usefixtures("firebase_emulators") + + +def build_webrtc_pair(add_peers: bool) -> tuple[SyftboxManager, SyftboxManager]: + """(ds_manager, do_manager), built only from a WebRTCConfig.""" + router = ConnectionRouterConfig.one_connection(EMULATOR_CONFIG) + do_config, ds_config = SyftboxManager._mock_pair_configs(use_in_memory_cache=False) + do_config = do_config.model_copy(update={"connection_router_config": router}) + ds_config = ds_config.model_copy(update={"connection_router_config": router}) + sign_in(do_config.email, do_config.syftbox_folder) + sign_in(ds_config.email, ds_config.syftbox_folder) + return SyftboxManager._test_pair( + do_config, + SyftboxManager._connections_from_config(do_config), + ds_config, + SyftboxManager._connections_from_config(ds_config), + add_peers=add_peers, + ) + + +@pytest.fixture +def webrtc_pair(): + """(ds_manager, do_manager), peered.""" + ds_manager, do_manager = build_webrtc_pair(add_peers=True) + yield ds_manager, do_manager + close(ds_manager, do_manager) + + +def test_job_and_result_go_over_webrtc_with_no_drive(webrtc_pair): + ds_manager, do_manager = webrtc_pair + grant_job_inbox_access(do_manager, ds_manager.email) + job_path = path_for_job(do_manager.email, ds_manager.email) + + ds_manager._send_file_change(job_path, "Hello, world!") + flush(ds_manager) + do_manager.sync() + + assert (do_manager.syftbox_folder / job_path).read_text() == "Hello, world!" + + datasite_do = do_manager.syftbox_folder / do_manager.email + do_manager.datasite_owner_syncer.perm_context.open("results/").grant_read_access( + ds_manager.email + ) + (datasite_do / "results" / "result.txt").write_text("I am a result") + do_manager.sync() + flush(do_manager) + ds_manager.sync() + + result_on_ds = ds_manager.syftbox_folder / do_manager.email / "results/result.txt" + assert result_on_ds.read_text() == "I am a result" + + +def test_do_that_accepts_with_add_peer_gets_ds_job(): + ds_manager, do_manager = build_webrtc_pair(add_peers=False) + try: + ds_manager.add_peer(do_manager.email, sync=False) + do_manager.load_peers() + do_manager.add_peer(ds_manager.email, sync=False) + ds_manager.load_peers() + grant_job_inbox_access(do_manager, ds_manager.email) + job_path = path_for_job(do_manager.email, ds_manager.email) + + ds_manager._send_file_change(job_path, "Hello, world!") + flush(ds_manager) + do_manager.sync() + + assert (do_manager.syftbox_folder / job_path).read_text() == "Hello, world!" + finally: + close(ds_manager, do_manager) + + +def test_sync_finishes_pass_before_it_reports_ended_session(webrtc_pair): + ds_manager, do_manager = webrtc_pair + grant_job_inbox_access(do_manager, ds_manager.email) + job_path = path_for_job(do_manager.email, ds_manager.email) + ds_manager._send_file_change(job_path, "Hello, world!") + flush(ds_manager) + end_stream(p2p_of(do_manager)._peer_connections.signaling) + time.sleep(STREAM_END_SECONDS) + + with pytest.raises(ConnectionError, match="signaling session ended"): + do_manager.sync() + + assert (do_manager.syftbox_folder / job_path).read_text() == "Hello, world!" diff --git a/tests/unit/test_login_webrtc.py b/tests/unit/test_login_webrtc.py new file mode 100644 index 00000000000..a46f4f756fb --- /dev/null +++ b/tests/unit/test_login_webrtc.py @@ -0,0 +1,69 @@ +"""Login with webrtc: the Firebase project comes from the settings, and no +Google login or Drive check runs.""" + +from pathlib import Path + +import pytest + +from syft.sync import login +from syft.sync.connections.config import ConnectionRouterConfig +from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig +from syft.sync.sync.collection_spec import CollectionSyncSpec +from syft.sync.syftbox_manager import SyftboxManagerConfig + +EMAIL = "do@example.com" +PROJECT_ID = "syft-test" +API_KEY = "test-api-key" + + +def test_webrtc_login_reads_firebase_settings(monkeypatch): + def read_drive(*args): + raise AssertionError("A WebRTC login must not read Drive") + + monkeypatch.setattr( + login, "handle_potential_version_mismatches_on_login", read_drive + ) + monkeypatch.setattr(login.settings, "firebase_project_id", PROJECT_ID) + monkeypatch.setattr(login.settings, "firebase_api_key", API_KEY) + + target = login._resolve_login_target(EMAIL, None, webrtc=True) + + assert target.webrtc == WebRTCConfig( + firebase_project_id=PROJECT_ID, firebase_api_key=API_KEY + ) + assert target.repair_pending is False + + +def test_webrtc_login_without_firebase_project_raises(monkeypatch): + monkeypatch.setattr(login.settings, "firebase_project_id", None) + monkeypatch.setattr(login.settings, "firebase_api_key", API_KEY) + + with pytest.raises(ValueError, match="SYFT_FIREBASE_PROJECT_ID"): + login._resolve_login_target(EMAIL, None, webrtc=True) + + +def test_webrtc_login_with_token_path_raises(monkeypatch): + monkeypatch.setattr(login.settings, "firebase_project_id", PROJECT_ID) + monkeypatch.setattr(login.settings, "firebase_api_key", API_KEY) + + with pytest.raises(ValueError, match="token_path"): + login._resolve_login_target(EMAIL, "token.json", webrtc=True) + + +def test_jupyter_config_with_webrtc_uses_it_for_every_connection(): + webrtc = WebRTCConfig(firebase_project_id=PROJECT_ID, firebase_api_key=API_KEY) + + config = SyftboxManagerConfig.for_jupyter(EMAIL, has_do_role=True, webrtc=webrtc) + + expected = ConnectionRouterConfig.one_connection(webrtc) + assert config.connection_router_config == expected + + +def test_webrtc_config_with_collection_specs_raises(): + spec = CollectionSyncSpec.public("syft_datasets", Path("datasets")) + webrtc = WebRTCConfig(firebase_project_id=PROJECT_ID, firebase_api_key=API_KEY) + + with pytest.raises(ValueError, match="Datasets do not go over WebRTC"): + SyftboxManagerConfig.for_jupyter( + EMAIL, has_ds_role=True, collection_specs=[spec], webrtc=webrtc + ) diff --git a/tests/unit/test_shared_router.py b/tests/unit/test_shared_router.py index 6402c8f00fe..2d8e5961dcf 100644 --- a/tests/unit/test_shared_router.py +++ b/tests/unit/test_shared_router.py @@ -109,11 +109,11 @@ def test_manager_without_connections_config_fails_at_init(): [ConnectionConfig(), _drive_config("other@example.com")], ids=["not_drive", "other_drive_login"], ) -def test_connections_other_than_one_drive_connection_are_not_built_yet(p2p_config): +def test_connections_with_different_logins_are_not_built_yet(p2p_config): config = _config_with_both_roles() config.connection_router_config = ConnectionRouterConfig.one_connection( _drive_config(config.email) ).model_copy(update={"p2p_con": p2p_config}) - with pytest.raises(NotImplementedError, match="one Google Drive login"): + with pytest.raises(NotImplementedError, match="one login for every connection"): SyftboxManager.from_config(config) diff --git a/tests/unit/webrtc/test_cloudflare_turn.py b/tests/unit/webrtc/test_cloudflare_turn.py new file mode 100644 index 00000000000..db7696f8364 --- /dev/null +++ b/tests/unit/webrtc/test_cloudflare_turn.py @@ -0,0 +1,46 @@ +"""The ICE servers that the TURN Cloud Function takes from a Cloudflare +generate-ice-servers response.""" + +import importlib.util +from pathlib import Path + +import pytest + +# The Cloud Function is not in a package, so the test loads its file. +CLOUDFLARE_TURN_FILE = ( + Path(__file__).parents[3] + / "infra" + / "firebase" + / "functions" + / "cloudflare_turn.py" +) +spec = importlib.util.spec_from_file_location("cloudflare_turn", CLOUDFLARE_TURN_FILE) +cloudflare_turn = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cloudflare_turn) +TURN_URL = cloudflare_turn.TURN_URL +pick_ice_servers = cloudflare_turn.pick_ice_servers + +STUN_URLS = ["stun:stun.cloudflare.com:3478", "stun:stun.cloudflare.com:443"] + + +def response(turn_urls: list[str]) -> dict: + return { + "iceServers": [ + {"urls": STUN_URLS}, + {"urls": turn_urls, "username": "user", "credential": "secret"}, + ] + } + + +def test_ice_servers_keep_first_stun_url_and_udp_turn_url(): + turn_urls = ["turns:turn.cloudflare.com:443?transport=tcp", TURN_URL] + + assert pick_ice_servers(response(turn_urls)) == [ + {"urls": STUN_URLS[0]}, + {"urls": TURN_URL, "username": "user", "credential": "secret"}, + ] + + +def test_response_without_udp_turn_url_is_refused(): + with pytest.raises(ValueError, match="Expected turn:turn.cloudflare.com"): + pick_ice_servers(response(["turns:turn.cloudflare.com:443?transport=tcp"])) diff --git a/tests/unit/webrtc/test_database_signaling.py b/tests/unit/webrtc/test_database_signaling.py new file mode 100644 index 00000000000..8c8ccc0ac01 --- /dev/null +++ b/tests/unit/webrtc/test_database_signaling.py @@ -0,0 +1,97 @@ +"""The signals that the Realtime Database client reads from stream events, and +the database keys of emails.""" + +import asyncio +import threading + +import pytest + +from syft.sync.connections.webrtc.firebase.database import ( + StreamEvent, + email_key, + email_of_key, +) +from syft.sync.connections.webrtc.firebase.database_signaling import ( + HELLO, + SESSION_FIELD, + TYPE_FIELD, + DatabaseSignaling, + Signal, + signals_in_event, +) +from syft.sync.connections.webrtc.firebase.turn import no_ice_servers + +SENDER_KEY = "ds@example,com" +REFUSAL_DELAY_SECONDS = 0.1 +HELLO_FIELDS = {TYPE_FIELD: HELLO, SESSION_FIELD: "s1"} + + +def test_snapshot_holds_every_signal(): + event = StreamEvent("put", "/", {SENDER_KEY: {"id1": HELLO_FIELDS}}) + + assert signals_in_event(event) == [Signal(SENDER_KEY, "id1", HELLO_FIELDS)] + + +def test_put_adds_one_signal(): + event = StreamEvent("put", f"/{SENDER_KEY}/id1", HELLO_FIELDS) + + assert signals_in_event(event) == [Signal(SENDER_KEY, "id1", HELLO_FIELDS)] + + +def test_patch_adds_signal_at_nested_key(): + event = StreamEvent("patch", "/", {f"{SENDER_KEY}/id1": HELLO_FIELDS}) + + assert signals_in_event(event) == [Signal(SENDER_KEY, "id1", HELLO_FIELDS)] + + +def test_deletion_adds_no_signal(): + assert signals_in_event(StreamEvent("put", f"/{SENDER_KEY}/id1", None)) == [] + + +def test_email_key_writes_dots_as_commas(): + key = email_key("First.Last@Example.com") + + assert key == "first,last@example,com" + assert email_of_key(key) == "first.last@example.com" + + +def test_email_with_slash_has_no_key(): + with pytest.raises(ValueError, match="Expected an email"): + email_key("a/b@example.com") + + +class StoppedStream: + def close(self) -> None: + pass + + +class RefusingDatabase: + """A database that refuses the stream a moment after it starts, before its + first event.""" + + def stream(self, path, on_event, on_end): + refusal = ConnectionError("The database answered 401") + threading.Timer(REFUSAL_DELAY_SECONDS, on_end, [refusal]).start() + return StoppedStream() + + +async def answer_nothing(sender: str, sdp: str) -> str: + return "" + + +def ignore(*args: object) -> None: + pass + + +def test_failed_sign_in_is_no_ended_session(): + ended: list[ConnectionError] = [] + + async def sign_in() -> None: + signaling = DatabaseSignaling(RefusingDatabase(), no_ice_servers) + await signaling.listen( + "ds@example.com", answer_nothing, ignore, ended.append, ignore + ) + + with pytest.raises(ConnectionError, match="401"): + asyncio.run(sign_in()) + assert ended == [] diff --git a/tests/unit/webrtc/test_database_stream.py b/tests/unit/webrtc/test_database_stream.py new file mode 100644 index 00000000000..eefdb1e908c --- /dev/null +++ b/tests/unit/webrtc/test_database_stream.py @@ -0,0 +1,76 @@ +"""How a DatabaseStream ends and opens again, with no database behind it.""" + +import queue + +from syft.sync.connections.exceptions import ConnectionUnavailableError +from syft.sync.connections.webrtc.firebase.database import DatabaseStream + +PATH = "signal/do@example,com" +END_SECONDS = 5 + + +class UnreachableDatabase: + """A database whose ID token cannot be refreshed.""" + + def url(self, path: str) -> str: + raise ConnectionUnavailableError("securetoken.googleapis.com cannot be reached") + + +class RevokingDatabase: + """A database that counts the forced refreshes of its ID token.""" + + def __init__(self): + self.expired_tokens = 0 + + def url(self, path: str) -> str: + return "http://127.0.0.1:9/unused.json" + + def expire_id_token(self) -> None: + self.expired_tokens += 1 + + +class LinesResponse: + """A response that reads the given lines, then ends.""" + + def __init__(self, lines: list[str]): + self._lines = [f"{line}\n".encode() for line in lines] + + def readline(self) -> bytes: + return self._lines.pop(0) if self._lines else b"" + + +class ScriptedStream(DatabaseStream): + """A DatabaseStream whose opens return the given responses in order.""" + + def __init__(self, responses: list[LinesResponse], *args): + super().__init__(*args) + self._responses = responses + + def _open(self): + return self._responses.pop(0) + + +def test_stream_reports_token_it_cannot_refresh(): + ends: queue.Queue[OSError] = queue.Queue() + stream = DatabaseStream(UnreachableDatabase(), PATH, print, ends.put) + stream.start() + + error = ends.get(timeout=END_SECONDS) + + assert "cannot be reached" in str(error) + + +def test_stream_gets_new_token_after_auth_revoked(): + database = RevokingDatabase() + revoked = LinesResponse( + ["event: auth_revoked", "data: credential is no longer valid"] + ) + ends: queue.Queue[OSError] = queue.Queue() + stream = ScriptedStream( + [revoked, LinesResponse([])], database, PATH, print, ends.put + ) + stream.start() + + ends.get(timeout=END_SECONDS) + + assert database.expired_tokens == 1 diff --git a/tests/unit/webrtc/test_firebase_client.py b/tests/unit/webrtc/test_firebase_client.py new file mode 100644 index 00000000000..7ad1f85ec90 --- /dev/null +++ b/tests/unit/webrtc/test_firebase_client.py @@ -0,0 +1,67 @@ +"""The parts of the Firebase client that need no Firebase: sign-in links and +the session file.""" + +import stat + +import pytest + +from syft.sync.connections.webrtc.firebase import auth +from syft.sync.connections.webrtc.firebase.auth import ( + FirebaseSession, + oob_code_of, + save_refresh_token, +) +from syft.sync.connections.webrtc.firebase.project import FirebaseProject +from syft.sync.connections.webrtc.webrtc_config import WebRTCConfig + +PROJECT = FirebaseProject.from_config( + WebRTCConfig( + firebase_project_id="syft-test", + firebase_api_key="test-key", + firebase_emulator_host="127.0.0.1", + ) +) +TOKEN_LIFETIME_SECONDS = 3600 +SIGN_IN_LINK = ( + "https://syft-test.firebaseapp.com/__/auth/action?apiKey=key&mode=signIn" + "&oobCode=one-time-code&continueUrl=https://syft-test.firebaseapp.com&lang=en" +) + + +def test_oob_code_comes_from_pasted_link(): + assert oob_code_of(f" {SIGN_IN_LINK}\n") == "one-time-code" + + +def test_link_without_oob_code_raises(): + with pytest.raises(ValueError, match="oobCode"): + oob_code_of("https://syft-test.firebaseapp.com/?mode=signIn") + + +def test_session_file_readable_only_by_user(tmp_path): + session_path = tmp_path / "sessions" / "syft-test.json" + + save_refresh_token(session_path, "refresh-token") + + assert stat.S_IMODE(session_path.stat().st_mode) == 0o600 + + +def test_session_gets_new_token_after_machine_sleeps(tmp_path, monkeypatch): + tokens = iter(["token-1", "token-2"]) + + def refresh(url: str, body: dict) -> dict: + return { + "id_token": next(tokens), + "expires_in": str(TOKEN_LIFETIME_SECONDS), + "refresh_token": "refresh-token", + } + + now = [1_000_000.0] + monkeypatch.setattr(auth, "post_json", refresh) + monkeypatch.setattr(auth.time, "time", lambda: now[0]) + session = FirebaseSession(PROJECT, tmp_path / "session.json", "refresh-token") + assert session.id_token() == "token-1" + + # The wall clock runs on while the machine sleeps. + now[0] += 2 * TOKEN_LIFETIME_SECONDS + + assert session.id_token() == "token-2" diff --git a/tests/unit/webrtc/test_local_owner_store.py b/tests/unit/webrtc/test_local_owner_store.py new file mode 100644 index 00000000000..b576e1d2a92 --- /dev/null +++ b/tests/unit/webrtc/test_local_owner_store.py @@ -0,0 +1,83 @@ +"""LocalOwnerStoreConnection, and a DO that restores its state from it.""" + +from syft.sync.connections.webrtc.local_owner_store import ( + CHECKPOINTS_FOLDER, + OWNER_STORE_PATH, + LocalOwnerStoreConnection, +) +from syft.sync.events.file_change_event import FileChangeEventsMessageFileName +from syft.sync.syftbox_manager import SyftboxManager + + +def event_name(timestamp: float) -> str: + return FileChangeEventsMessageFileName(timestamp=timestamp).as_string() + + +def test_event_handles_newer_than_timestamp_oldest_first(tmp_path): + store = LocalOwnerStoreConnection(tmp_path) + store.append_event(event_name(3.0), b"third") + store.append_event(event_name(1.0), b"first") + store.append_event(event_name(2.0), b"second") + + handles = store.list_event_handles(since_timestamp=1.0) + assert [store.fetch(handle) for handle in handles] == [b"second", b"third"] + + +def test_new_checkpoint_replaces_older(tmp_path): + store = LocalOwnerStoreConnection(tmp_path) + store.put_checkpoint("checkpoint_1.0.tar.gz", b"old") + store.put_checkpoint("checkpoint_2.0.tar.gz", b"new") + + assert store.latest_checkpoint() == b"new" + assert len(list((tmp_path / CHECKPOINTS_FOLDER).iterdir())) == 1 + + +def test_incrementals_follow_sequence_order(tmp_path): + store = LocalOwnerStoreConnection(tmp_path) + # As text, "10" sorts before "9". + store.put_incremental("incremental_checkpoint_10_2.0.tar.gz", b"tenth") + store.put_incremental("incremental_checkpoint_9_1.0.tar.gz", b"ninth") + + assert store.all_incrementals() == [b"ninth", b"tenth"] + assert store.next_incremental_sequence() == 11 + store.delete_incrementals() + assert store.incremental_count() == 0 + + +def test_delete_all_removes_store(tmp_path): + folder = tmp_path / "store" + store = LocalOwnerStoreConnection(folder) + store.append_event(event_name(1.0), b"event") + store.put_rolling_state("rolling_state_1.0.tar.gz", b"state") + + store.delete_all() + + assert not folder.exists() + + +def test_do_restores_owner_state_from_local_store(): + do_config, ds_config = SyftboxManager._mock_pair_configs(use_in_memory_cache=True) + do_connections, ds_connections = SyftboxManager._mock_drive_connections( + do_config, ds_config + ) + local_store = LocalOwnerStoreConnection(do_config.syftbox_folder / OWNER_STORE_PATH) + ds_manager, do_manager = SyftboxManager._test_pair( + do_config, + do_connections.model_copy(update={"owner_store_con": local_store}), + ds_config, + ds_connections, + add_peers=True, + ) + do_syncer = do_manager.datasite_owner_syncer + do_syncer.perm_context.open(".").grant_write_access(ds_manager.email) + ds_manager._send_file_change(f"{do_manager.email}/test1.txt", "Content 1") + ds_manager._send_file_change(f"{do_manager.email}/test2.txt", "Content 2") + do_manager.sync(auto_checkpoint=False) + do_manager.create_checkpoint() + + # A new login: the cache starts empty, and the first sync restores it. + do_syncer.event_cache.clear_cache() + do_syncer.initial_sync_done = False + do_manager.sync(auto_checkpoint=False) + + assert len(do_syncer.event_cache.file_hashes) == 2 diff --git a/tests/unit/webrtc/test_local_signaling.py b/tests/unit/webrtc/test_local_signaling.py index d411cfc7869..d789ea75327 100644 --- a/tests/unit/webrtc/test_local_signaling.py +++ b/tests/unit/webrtc/test_local_signaling.py @@ -8,6 +8,19 @@ DO = "do@example.com" DS = "ds@example.com" +OTHER_DS = "other-ds@example.com" + + +def ignore_hello(sender: str, session: str) -> None: + pass + + +def ignore_error(error: ConnectionError) -> None: + pass + + +async def answer_nothing(sender: str, sdp: str) -> str: + return "" def test_offer_reaches_listener_and_returns_its_answer(): @@ -17,7 +30,7 @@ async def exchange() -> str: async def answer(sender: str, sdp: str) -> str: return f"answer from {DO} to {sender}: {sdp}" - await signaling.listen(DO, answer) + await signaling.listen(DO, answer, ignore_hello, ignore_error, ignore_error) return await signaling.offer(DS, DO, "offer") assert asyncio.run(exchange()) == f"answer from {DO} to {DS}: offer" @@ -26,3 +39,26 @@ async def answer(sender: str, sdp: str) -> str: def test_offer_to_peer_not_listening_is_refused(): with pytest.raises(ConnectionError): asyncio.run(LocalSignaling().offer(DS, DO, "offer")) + + +def test_hello_reaches_only_peers_that_listen(): + async def say_hello() -> list[tuple[str, str]]: + signaling = LocalSignaling() + hellos: list[tuple[str, str]] = [] + + def on_hello(sender: str, session: str) -> None: + hellos.append((sender, session)) + + await signaling.listen(DO, answer_nothing, on_hello, ignore_error, ignore_error) + await signaling.listen( + DS, answer_nothing, ignore_hello, ignore_error, ignore_error + ) + + await signaling.hello(DS, [DO, OTHER_DS]) + # LocalSignaling calls on_hello on the loop of the receiver. The call + # runs when this coroutine yields. + await asyncio.sleep(0) + return hellos + + [(sender, session)] = asyncio.run(say_hello()) + assert sender == DS and session diff --git a/tests/unit/webrtc/test_turn_credentials_function.py b/tests/unit/webrtc/test_turn_credentials_function.py new file mode 100644 index 00000000000..233df2f123d --- /dev/null +++ b/tests/unit/webrtc/test_turn_credentials_function.py @@ -0,0 +1,84 @@ +"""The reply of the TURN Cloud Function to a Firebase ID token that it cannot +verify. Only the function's own environment has the Firebase libraries, so the +test runs the function with stand-ins for them.""" + +import importlib.util +import json +import sys +import types +from pathlib import Path +from typing import Any + +import pytest + +FUNCTIONS_FOLDER = Path(__file__).parents[3] / "infra" / "firebase" / "functions" +# verify_id_token raises a ValueError like this one when the function's +# project is not set up. +SERVER_DETAIL = "Failed to ascertain project ID from the credential" + + +class InvalidIdTokenError(Exception): + pass + + +def refuse_token(token: str) -> dict: + raise ValueError(SERVER_DETAIL) + + +class Request: + def __init__(self, headers: dict[str, str]): + self.headers = headers + + +class Response: + def __init__(self, body: str, status: int, content_type: str): + self.body = body + self.status = status + + +class SecretParam: + def __init__(self, name: str): + self.name = name + + +def stand_in_module(name: str, **attributes: Any) -> types.ModuleType: + module = types.ModuleType(name) + module.__dict__.update(attributes) + return module + + +@pytest.fixture +def turn_credentials(monkeypatch): + """The function in main.py, with stand-ins for the Firebase libraries.""" + auth = stand_in_module( + "firebase_admin.auth", + verify_id_token=refuse_token, + InvalidIdTokenError=InvalidIdTokenError, + ) + https_fn = stand_in_module( + "firebase_functions.https_fn", + on_request=lambda **options: lambda function: function, + Request=Request, + Response=Response, + ) + stand_ins = [ + stand_in_module("firebase_admin", auth=auth, initialize_app=lambda: None), + stand_in_module("firebase_functions", https_fn=https_fn), + stand_in_module("firebase_functions.params", SecretParam=SecretParam), + ] + for module in stand_ins: + monkeypatch.setitem(sys.modules, module.__name__, module) + monkeypatch.syspath_prepend(str(FUNCTIONS_FOLDER)) + spec = importlib.util.spec_from_file_location( + "turn_function", FUNCTIONS_FOLDER / "main.py" + ) + main = importlib.util.module_from_spec(spec) + spec.loader.exec_module(main) + return main.turn_credentials + + +def test_refused_token_reply_hides_exception_text(turn_credentials): + response = turn_credentials(Request({"Authorization": "Bearer bad-token"})) + + assert response.status == 401 + assert SERVER_DETAIL not in json.loads(response.body)["error"] diff --git a/uv.lock b/uv.lock index 25fb245846c..7d897d27823 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.15' and sys_platform == 'win32'", @@ -4349,7 +4349,6 @@ wheels = [ [[package]] name = "syft" source = { editable = "." } -default-groups = ["dev", "test"] dependencies = [ { name = "google-api-python-client" }, { name = "google-auth", extra = ["pyjwt"] },