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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .gitleaks.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,12 @@
[extend]
useDefault = true

[[allowlists]]
description = "Synthetic local TURN vectors: unregistered APP test key, derived password and unsigned PAT"
condition = "AND"
paths = ['''^tests/unit/fixtures/local-turn-v1\.json$''']
regexes = [
'''3081ee020100301006072a8648ce3d020106052b810400230481d63081d30201010442007150f569c9dbb263b1ecd863503b13f1f680e451ea1df63431008299b62f80ee11667fd6a4264a97d2a95aca6b8f42f66f891c7432e065631db759a90ed59e5466a18189038186000400807318900e70b38c992005816efe73baa2cffb5a0cdbe3fb77ce9b326438d2f15aff4fa0c9c7fc9448e0b53db83d1e244d555aead4341f823c60333f36e042f35e006bd4c86d6be01bfab94671b6d185586982aa766abb3c35b10a6c12b4536ae2117168bf8e6f301c12219b05f230a6dad22377f1643a149678f477405ecbb0b563a3''',
'''h/Qmj86kO0KYhye/YP\+jjZKovPoohlp51/2Xu8E/Wos=''',
'''e30\.eyJ0eXBlIjoicGF0IiwiZXhwIjoyMDAwMDAwMDAwLCJ0b2tlbl9lbmRwb2ludCI6InRva2VuLTEiLCJwZXJtaXNzaW9ucyI6WyJ0dXJuLnJlbGF5LmFsbG9jYXRlIl19\.sig''',
]
24 changes: 24 additions & 0 deletions docs/001-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,27 @@ discovery work.

Use the [tunnel guide](002-tunnels.md) for stream lifetimes and
creation options.

## Backend credentials

A trusted service holding a P-521 application key can sign a short-lived Engine
token locally. Install the `credentials` extra and grant the actions required by the
recipient. A project ID scopes the grant.

```python
from rstream import ApplicationCredentials, EngineTokenGrant

grant = EngineTokenGrant(project_id, list_tunnels=True, tunnel_fields=("id", "name"))
token = ApplicationCredentials(client_id, client_secret).sign_token(grant)
```

A backend with a bearer authorized for delegation can call
`await api.create_token(grant)` on `RstreamAPIClient`. A certificate-only device
uses its enrolled identity directly on the Engine.

`await client.create_turn_credentials()` returns the ICE URLs and their lifetime.
An eligible PAT uses relay coordinates from the selected context or an explicit
`TurnRelay`. An application can supply its public TURN key with its application
credentials for offline derivation. Certificate-only clients use the dedicated
Engine authority. Managed project bearers can request issuance through the
Control plane.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ dependencies = [
]

[project.optional-dependencies]
credentials = ["cryptography>=41", "httpx>=0.28.1,<1"]
api = ["httpx>=0.28.1,<1"]
asgi = ["h11>=0.16,<1"]
realtime = ["httpx>=0.28.1,<1", "websockets>=16.1.1,<18"]
Expand Down
13 changes: 13 additions & 0 deletions src/rstream/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@
from importlib import import_module
from types import ModuleType

from rstream.api import RstreamAPIClient, TokenCredentials
from rstream.client import Client
from rstream.config import ClientOptions, ResolvedClientOptions, TLSOptions
from rstream.control import ControlChannel
from rstream.credentials import (
ApplicationCredentials,
EngineTokenGrant,
TurnCredentials,
TurnRelay,
)
from rstream.engine_api import (
ClientFilters,
ClientInventory,
Expand Down Expand Up @@ -65,6 +72,7 @@ def __getattr__(name: str) -> ModuleType:

__all__ = [
"HTTPCORS",
"ApplicationCredentials",
"BytestreamTunnel",
"Client",
"ClientChanged",
Expand All @@ -75,24 +83,29 @@ def __getattr__(name: str) -> ModuleType:
"ControlChannel",
"CreateTunnelOptions",
"EngineError",
"EngineTokenGrant",
"Event",
"EventStream",
"InventoryInitial",
"InventorySnapshot",
"InventoryStream",
"ProtocolError",
"ResolvedClientOptions",
"RstreamAPIClient",
"RstreamError",
"RstreamRuntimeError",
"RstreamStream",
"RuntimeError",
"ServerDetails",
"TLSOptions",
"TokenCredentials",
"TunnelAuth",
"TunnelChanged",
"TunnelFilters",
"TunnelInventory",
"TunnelProperties",
"TurnCredentials",
"TurnRelay",
"UnsupportedFeatureError",
"WatchTransport",
"WebhookEvent",
Expand Down
38 changes: 36 additions & 2 deletions src/rstream/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

from collections.abc import Mapping
from dataclasses import dataclass
from dataclasses import dataclass, field
from urllib.parse import quote, urljoin

from rstream.config import (
Expand All @@ -12,14 +12,15 @@
_normalize_region,
normalize_engine_address,
)
from rstream.credentials import EngineTokenGrant, _credential_request
from rstream.errors import ConfigurationError, RuntimeError


@dataclass(frozen=True)
class TokenCredentials:
"""Bearer token credentials for rstream HTTP APIs."""

token: str
token: str = field(repr=False)


@dataclass(frozen=True)
Expand All @@ -43,6 +44,7 @@ class TunnelsProject:
engine_port: int
routing: str
regional_endpoints: tuple[TunnelsProjectRegionalEndpoint, ...] = ()
turn_metadata: Mapping[str, object] = field(default_factory=dict)


class RstreamAPIClient:
Expand Down Expand Up @@ -73,6 +75,33 @@ async def resolve_tunnels_project(self, endpoint: str) -> TunnelsProject:
)
return _project_from_json(data)

async def create_token(
self, grant: EngineTokenGrant, *, ttl_seconds: int = 60
) -> str:
"""Delegate a project-scoped token through the managed Control plane."""
if self.credentials is None or not self.credentials.token:
raise ConfigurationError(
"Delegation requires bearer credentials.",
code="ERR_RSTREAM_CREDENTIALS",
)
value = await _credential_request(
self.api_url + "/api/tokens",
payload=grant._params(ttl_seconds),
headers={
**self.control_plane_headers,
"Authorization": "Bearer " + self.credentials.token,
},
)
if (
not isinstance(value, dict)
or not isinstance(value.get("token"), str)
or not value["token"]
):
raise RuntimeError(
"Missing delegated token.", code="ERR_RSTREAM_API_INVALID_RESPONSE"
)
return str(value["token"])

async def request_json(self, path: str) -> Mapping[str, object]:
try:
import httpx
Expand Down Expand Up @@ -173,6 +202,11 @@ def _project_from_json(data: Mapping[str, object]) -> TunnelsProject:
domain=domain,
engine_port=engine_port,
routing=_string_required(data, "routing"),
turn_metadata={
k: data[k]
for k in ("domain", "turnDomain", "turnRealm", "turnPort", "turnsPort")
if k in data
},
regional_endpoints=_regional_endpoints_from_json(data.get("regionalEndpoints")),
)

Expand Down
144 changes: 143 additions & 1 deletion src/rstream/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,16 @@
from collections.abc import AsyncIterator, Awaitable, Mapping
from contextlib import suppress
from typing import TypeVar
from urllib.parse import urlsplit
from weakref import WeakSet

from rstream._proto import rstream_pb2 as pb
from rstream.api import RstreamAPIClient, TokenCredentials, engine_from_project
from rstream.api import (
RstreamAPIClient,
TokenCredentials,
TunnelsProject,
engine_from_project,
)
from rstream.config import (
ClientOptions,
ResolvedClientOptions,
Expand All @@ -19,6 +25,19 @@
resolve_client_options,
)
from rstream.control import ControlChannel
from rstream.credentials import (
ApplicationCredentials,
TurnCredentials,
TurnRelay,
_app_turn,
_credential_request,
_invalid,
_pat_turn,
_reference,
_relay_from_metadata,
_seconds,
_Unavailable,
)
from rstream.engine_api import (
ClientFilters,
ClientInventory,
Expand All @@ -27,6 +46,7 @@
TunnelFilters,
TunnelInventory,
WatchTransport,
_httpx_verify,
client_inventory_from_json,
list_inventory,
tunnel_inventory_from_json,
Expand Down Expand Up @@ -124,7 +144,9 @@ def __init__(
self._controls: set[ControlChannel] = set()
self._control_watchers: set[asyncio.Task[None]] = set()
self._streams: WeakSet[EventStream | InventoryStream] = WeakSet()
self._credential_tasks: set[asyncio.Task[TurnCredentials]] = set()
self._closed = False
self._last_project: TunnelsProject | None = None
self._engine_discovery = EngineAPIDiscovery()

@classmethod
Expand Down Expand Up @@ -411,6 +433,120 @@ async def generate() -> AsyncIterator[Event]:
self._streams.add(stream)
return stream

async def create_turn_credentials(
self,
*,
relay: TurnRelay | None = None,
application: ApplicationCredentials | None = None,
server_public_key_hex: str | None = None,
ttl_seconds: int = 600,
) -> TurnCredentials:
"""Obtain TURN credentials for this project, preferring local derivation."""
self._ensure_open()
resolved = await self._get_resolved()
self._ensure_open()
task = asyncio.create_task(
self._turn_credentials(
resolved,
relay,
application,
server_public_key_hex,
_seconds(ttl_seconds),
)
)
self._credential_tasks.add(task)
try:
return await asyncio.wait_for(task, resolved.operation_timeout)
finally:
self._credential_tasks.discard(task)

async def _turn_credentials(
self,
resolved: ResolvedClientOptions,
relay: TurnRelay | None,
application: ApplicationCredentials | None,
public_key: str | None,
ttl: int,
) -> TurnCredentials:
endpoint = resolved.project_endpoint
if endpoint:
_reference(endpoint)
cert = has_client_certificate(resolved.tls)
token = None if resolved.no_token else resolved.token
if application is not None and (cert or token):
raise _invalid("Configure one identity for TURN credentials.")
if public_key is not None and application is None:
raise _invalid("A TURN public key requires application credentials.")
if not (application or token or cert):
raise _invalid("TURN credentials require an authenticated identity.")
# A cached context must never redirect credentials to a different project.
host = (
urlsplit("https://" + resolved.engine).hostname if resolved.engine else None
)
if endpoint and host and host.split(".")[0] != endpoint:
raise _invalid("The configured project endpoint must match the Engine.")
project = self._last_project
if not relay and endpoint:
metadata = (
project.turn_metadata
if project and project.endpoint == endpoint
else resolved.turn_metadata
)
relay = _relay_from_metadata(metadata)
api = resolved.api_url.rstrip("/")
if not cert and endpoint and relay:
if token:
local = _pat_turn(token, endpoint, relay, ttl)
if local is not None:
return local
if application:
application._key()
if public_key is None:
with suppress(_Unavailable):
public_key = await _credential_request(
f"{api}/keyrings/turn/{relay.realm}.spki.der.hex",
public_key=True,
)
if public_key is not None:
return _app_turn(application, endpoint, relay, ttl, public_key)
if application:
token = application._sign({"permissions": ["turn.credentials.create"]}, 60)
headers = {"Authorization": f"Bearer {token}"} if token else {}
body: dict[str, object] = {"ttlSeconds": ttl}
if not cert and endpoint:
try:
value = await _credential_request(
f"{api}/api/projects/tunnels/resolve/{endpoint}/turn-server/credentials",
payload=body,
headers={**resolved.control_plane_headers, **headers},
)
return TurnCredentials._parse(value)
except _Unavailable:
if not resolved.engine and not (
project and project.endpoint == endpoint
):
raise
engine = resolved.engine
if not engine and project and project.endpoint == endpoint:
engine = engine_from_project(project, resolved.region)
if engine is None:
raise _invalid("Configure an Engine address for this identity.")
if resolved.tls and resolved.tls.insecure_skip_verify:
raise _invalid("Credential issuance requires verified Engine TLS.")
if cert:
engine = await self._engine_discovery.resolve(engine, resolved.tls)
return TurnCredentials._parse(
await _credential_request(
f"https://{engine}/api/turn-server/credentials",
payload=body,
headers={} if cert else headers,
verify=_httpx_verify(resolved.tls),
server_name=resolved.tls.server_name
if resolved.tls and not cert
else None,
)
)

async def _engine_api_target(self) -> tuple[str, str | None, TLSOptions | None]:
self._ensure_open()
resolved = await self._get_resolved()
Expand All @@ -427,6 +563,11 @@ async def close(self) -> None:
for stream in tuple(self._streams):
await stream.aclose()
self._streams.clear()
pending = tuple(self._credential_tasks)
for task in pending:
task.cancel()
if pending:
await asyncio.gather(*pending, return_exceptions=True)
await self._engine_discovery.close()
failure: BaseException | None = None
for control in tuple(self._controls):
Expand Down Expand Up @@ -553,6 +694,7 @@ async def _resolve_engine(
control_plane_headers=resolved.control_plane_headers,
credentials=credentials,
).resolve_tunnels_project(resolved.project_endpoint)
self._last_project = project
engine = engine_from_project(project, resolved.region)
if for_stable_hostname and resolved.region is not None:
# The regional control endpoint and public tunnel domain can differ.
Expand Down
Loading
Loading