turn

package module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: BSD-3-Clause Imports: 0 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-turn/turn

turn

CI Go Reference license

📖 go-turn.github.io · Documentation

STUN and TURN in pure Go, for WebRTC peers that cannot reach each other directly — a symmetric NAT, a full-tunnel VPN, a network that only lets HTTPS out. CGO_ENABLED=0.

One daemon, turnd, serves on one host:

STUN Binding (RFC 8489): a peer learns the address the Internet sees
TURN a relayed UDP address (RFC 8656), reached over UDP, TCP, or TLS on 443 (turns:)
credentials short-lived TURN credentials (HMAC, the TURN REST API scheme), minted only after an OpenID Connect login through go-authn
rendezvous a room a host opens and shares as one link; the guest's answer comes back on its own

It is the relay the go-tex playground uses for live collaboration over go-crdt/collab.

Status: v0.1 — the relay, the credentials, the login and the rendezvous work and are tested; the go-tex playground is not wired to it yet. The design is #1; what is still open is in the tracker.

The HTTP half (turnd)

turnd --issuer https://login.example.org --client-id turnd \
  --client-secret-file /etc/turnd/client-secret \
  --session-key-file /etc/turnd/session.key \
  --turn-secret-file /etc/turnd/turn.secret \
  --allowed-origin https://go-tex.github.io \
  --public-url https://turn.example.org --listen 127.0.0.1:8080 \
  --turn-uri 'turns:turn.example.org:443?transport=tcp'

Every secret is a file (refused when world-readable); none is a flag value or an environment variable. Repeat --session-key-file / --turn-secret-file to rotate: the first signs, the others only verify. Register <public-url>/callback as the client's redirect URI at the issuer.

The API is gRPC, proto/turn/v1/turnd.proto (service turn.v1.Turnd, generated code committed, CI regenerates it and fails on a diff). A plain grpc.Server is served over a WebSocket at /grpc (grpc-transports/websocket), which is what a browser can speak, including the bidirectional stream. The WebSocket upgrade enforces the exact origin allowlist (scheme and port included); a client with no Origin header is a native client. Only browser navigations stay HTTP:

HTTP
GET /login?origin=<allowed origin> starts the OIDC login (code + PKCE) in a popup; an origin not in --allowed-origin is a 400, never a redirect
GET /callback page that postMessages {type:"turnd-session",token,expires} (or {type:"turnd-error",error}) to window.opener, target origin = the allowlisted one
GET /healthz ok
GET / (and HEAD) a home page, chosen by the Host header (see below); every other unknown path is a 404

Home pages. GET / answers with a page that says what the host is, in seven languages (fr, en, de, es, ja, ko, zh-cn: the lang cookie, else Accept-Language, else French) with a light, dark or system theme, the language combo and the theme switch being plain GET forms (/lang, /theme) that work without script. The look is go-authn/bridge's (bridge#104): Tailwind v4 standalone CSS and Lucide icons, copied with their source commit noted in internal/homepage/web/PROVENANCE.txt. The policy is strict: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self', no inline script or style.

  • the collaboration page is served on the --public-url host, and on any host turnd does not know: what the service is (the rendezvous and session service for peer-to-peer collaboration in the go-tex playground), a link to the playground and a sentence saying the host signs in from the playground (which opens /login?origin=… in a popup; a bare /login is a 400, so no page links it);
  • the relay page is served on the hosts named by --stun-uri and --turn-uri (other than the public URL's): what the STUN/TURN relay is, the transports it offers (UDP, TCP, TLS and their ports, from those URIs, else from --stun-listen, --turn-tcp-listen and --turns-listen), that it is not a web service to browse, and a link to the collaboration page.

The pages show public configuration only: never a secret, a client address, a count or a session or room ID (tests assert it). Screenshots of the pages, for review, are written by go test ./internal/homepage to <user config dir>/turnd/page-screenshots (never inside a repository), in a headless Chrome that must be installed (TURND_REQUIRE_BROWSER=1 makes its absence a failure).

RPC token (authorization: Bearer … metadata, never a URL)
Credentials session, or issuer access token IceServers{ice_servers[{urls,username,credential}], ttl}
RenewSession a session token, valid or expired for under 5 minutes {token, expires}: a new session token; UNAUTHENTICATED = sign in again (see below)
CreateRoom session or access token {room, peer:"g1", token, expires}: the creator's peer ID is ordinary, minted like a guest's (breaking since v0.7: it was "host"); the room ID is 128 random bits
JoinRoom{room,name} none: the room ID {peer, host, token, expires, pending:true}; the guest is pending
Admit{room,peer} / Deny{room,peer} host token admit a pending guest / refuse it (or remove an admitted one): its token is dead
RoomCredentials{room} an admitted peer's token IceServers expiring with the room, charged to the current host's person (see A room outlives its host)
CloseRoom{room} host token ends the room
HandOver{room,to} host token gives the host role to an admitted, connected guest; the old host's token is dead
AppointCoHost{room,peer} / RevokeCoHost{room,peer} host token only an admitted peer may admit, deny and close beside the host (see Co-hosts); revoking takes the powers at once
Reclaim{room} a session token whose subject was the host's {peer, host, host_peer, token, expires}: the host role back (new token), or, after a handover, an admitted guest with the SAME peer ID
Room(stream Envelope) returns (stream Envelope) peer token + x-turn-room metadata the room's one stream: events down, messages up; ending it is leaving

Renewing a session. At /callback turnd asks the issuer for openid offline_access, keeps the refresh token in memory under a random family ID, and embeds only that ID in the signed session token (t2.; a v0.4.0 t1. token has none and cannot be renewed). RenewSession takes the current session token as Bearer, valid or expired for less than 5 minutes, spends the stored refresh token at the issuer (go-authn/rp Refresh), rotates the stored one and returns a new session token. Concurrent renewals of one family share one issuer call (the refresh token is spent once, every caller gets the same new token), and a retired refresh token is never presented again. Any refusal from the issuer (account, passkey or application session revoked, the refresh lifetime over: invalid_grant, or any other error code it answers) ends the family: it is deleted and the answer is UNAUTHENTICATED. Failing to reach the issuer is UNAVAILABLE and leaves the family intact: retry. UNIMPLEMENTED when renewal is off. Every outcome is logged with the pseudonymous subject, never a token.

In the playground: after the popup's turnd-session message, run client.KeepRenewed(ctx, client.Session{Token: tok, Expires: exp}, 5*time.Minute, func(ctx, t) { return client.RenewSession(ctx, base, t) }, store) in a goroutine. It renews 5 minutes before the expiry, retries UNAVAILABLE every 30 s, and returns when ctx ends or on UNAUTHENTICATED: then open the login popup again. store receives each new Session, which is the token to use for Credentials and CreateRoom from then on. A page that dials its own connection uses RenewSessionConn. Renew with the NEWEST token: an old one still works while it is valid or within the grace, but a sleeping tab that wakes up after more than the grace has to sign in again.

A leaked room link lets a stranger knock, not enter. A pending guest only receives: it cannot send, cannot get credentials, counts against a separate pending cap and a pending TTL. The host sees sys.knock (from = the guest, body = its display name, at most 64 characters, no control characters) and decides; only admitted guests count against the room's cap and produce sys.join. Other system events: sys.admitted, sys.denied, sys.leave, sys.closed, sys.host-changed, and sys.error (a message the other peer could not take; the stream stays open). A message that breaks the protocol (too large, a spoofed from, a bad kind, a pending sender, guest to guest) ends the sender's stream with a status: RESOURCE_EXHAUSTED, PERMISSION_DENIED, INVALID_ARGUMENT. Other refusals: UNAUTHENTICATED (no or dead token), NOT_FOUND, ALREADY_EXISTS (a second stream for one peer), FAILED_PRECONDITION (already admitted), UNAVAILABLE (server full).

A room outlives its host. Collaboration is peer to peer, so a room must not die with the one browser that opened it. When the host's stream ends the room lives on for --host-grace (default 2m; a negative value restores the old behaviour, the host leaving closes the room).

  • Within the grace the host back as the same person keeps the role, with nothing changed for the others: Reclaim with a session token of the host's subject (new host token, the old one dead), or simply a new Room stream with its own token. Messages sent to "host" meanwhile wait in its queue (the usual --max-queue; past it the sender gets sys.error) and are delivered on return. What can still be lost, and only this: a message the server wrote to the old host's connection before it noticed that the connection was dead (the rendezvous cannot know; the collab layer's rejoin with a version vector covers it).
  • Past the grace, or when the host calls HandOver{room,to} first, the earliest-appointed co-host still connected, else the earliest-admitted guest still connected, becomes the host (no version-vector election: the collab layer reconciles in both directions on rejoin). A pending, denied or disconnected guest is never promoted; if nobody qualifies the room closes (promote / failed_precondition). A guest cannot promote itself and a non-host cannot HandOver (PERMISSION_DENIED); to a pending guest it is FAILED_PRECONDITION, to a stranger NOT_FOUND. The role moves under the server's lock: there is exactly one host at any moment, whatever races.
  • What changes. The promoted peer keeps its peer ID and its token (so the site identity a collab layer derives from the peer ID is stable) and gains the host's powers: Admit, Deny, HandOver, CloseRoom. Every peer, the old host included, receives sys.host-changed with body {"from":"<peer>","to":"<peer>"}. The new host is told again about the room: sys.knock for each pending guest, sys.join for each admitted one, then the messages that were queued for the old host, in order (the guests' messages sent to "host" during the outage are not dropped).
  • The address "host" — breaking since v0.7. No peer is named "host" any more: the creator has an ordinary ID (g1), from is always a real peer ID, and sys.host-changed {from,to} names real IDs. "host" survives only as the to of a message, an alias for the current active host with the same meaning for every sender (guest, co-host, the old host back as a guest). The host addressing "host" gets a sys.error InvalidArgument (it would be itself), and addresses a guest by its real ID. Clients learn the host's real ID from the CreateRoom, JoinRoom and Reclaim answers and from sys.host-changed (client.Room.HostPeer()). A v0.6 client that hard-codes "host" as the creator's from is refused at once with PERMISSION_DENIED ("from is not you ... use the peer ID the server gave you"), not routed wrongly. The room's TTL is never extended.
  • Who pays. RoomCredentials are charged to the current host's person if it said who it is when it knocked (x-turn-session metadata, client.WithSession), else to the person who opened the room, until the TTL.
  • The old host returns after a promotion with Reclaim and the same session: it keeps its own (ordinary) peer ID and is an admitted guest of the new host (no knock; the new host sees sys.join), with a new token and the lowest priority among the guests. Its old token stays dead.
  • What the collab layer does on sys.host-changed. The new host starts its collab.Server seeded from its own replica; the others rejoin it through the rendezvous with their version vector (a rejoin syncs both ways, so a guest that is ahead of the new host pushes what it holds). In peer-to-peer mode nothing may purge history, or a purged replica could not serve a rejoin.

How many guests. The cap is on guests admitted at once, not over the room's life: a guest that leaves, is denied, or whose absence expires frees its place (ResourceExhausted, "the room is full: N guests at once", is for a room that is full now). CreateRoom{max_guests} sets the room's cap (default 8, or the server's ceiling if lower; --max-guests is that ceiling, above it or negative is INVALID_ARGUMENT; client.WithMaxGuests(n)). A separate --max-admissions (default 4 x --max-guests) bounds the admissions in the room's whole life, so that churn stays bounded; its refusal says "admitted too many guests in its life". A guest whose connection dropped (cancelled or broken; a half-close is a goodbye, and client.Room.Close says it) keeps its place, peer ID and token for --guest-grace (default 30s): opening a stream with the same token resumes, with no knock and no admission consumed, and the host hears sys.leave only when the absence expires. A host handover consumes no admission either (the old host returning with Reclaim takes a place, not an admission). The real ceiling of a star is the host's uplink, to be measured by the 3 to 4 browser proof; 8 is the default, not a measured limit.

Co-hosts. The host (and only the host) appoints an admitted guest with AppointCoHost{room,peer} and takes it back with RevokeCoHost; a pending, denied or unknown peer cannot be appointed (FAILED_PRECONDITION, NOT_FOUND), and a guest or a co-host that tries to appoint, revoke or HandOver is refused (PERMISSION_DENIED). A co-host may Admit, Deny (not the host or another co-host: only the host removes a co-host) and CloseRoom, and gets RoomCredentials charged to its own subject when it presented a session, else to the host's, never past the room's TTL. There is still exactly one active host, the peer that runs the document's centre. Everyone receives sys.cohost-added / sys.cohost-removed with body {"peer":"<id>"}; revoking removes the powers with the call itself. The knocks, joins and leaves are sent to the host and every co-host, so the pending-guest expiry (MaxPending, a 2-minute PendingTTL) now has several people to answer it, and a waiting guest's sys.leave "expired" reaches them all. On a host loss past the grace the earliest-appointed co-host still connected is promoted first; only if none remains, the earliest-admitted guest. A promoted co-host is the host (no longer listed as a co-host). Client: AppointCoHost, RevokeCoHost, CloseRoom, IsCoHost, Event.CoHost.

New observer actions (and turnd.rendezvous.operations actions): hand_over, appoint_cohost, revoke_cohost, reclaim, and the two with no RPC, host_lost (the grace starts) and promote (the grace ended); never a token, room, peer or name.

The credential scheme is draft-uberti-behave-turn-rest-00. The Go client, for the browser and native, is github.com/go-turn/turn/rendezvous/client: Create, Join(name) (blocks until admitted, ErrDenied otherwise; WithSession(token) says who the guest is), Admit, Deny, Send, Recv, Credentials, Close, and for the handover HandOver, Reclaim, IsHost, HostPeer and Event.HostChange. It is a real grpc-go client dialed over the browser's WebSocket through syscall/js; it adds about 16 MB to a wasm binary (3.5 MB more gzipped), almost all of it grpc. go-crdt/collab's js/wasm build does not link grpc, so a page that does not otherwise ship it should load this client in a separate wasm, fetched when a collaboration starts.

Observability (OpenTelemetry)

turnd exports traces, metrics and logs over OTLP (gRPC or HTTP) with the official Go SDK. It is off, and costs nothing, until --otel-endpoint is set.

Flag Meaning
--otel-endpoint https://host:4318 (http) or host:4317 (grpc); no credentials, query or fragment in it
--otel-protocol http (default) or grpc
--otel-token-file file holding the collector's bearer token, sent as Authorization: Bearer …
--otel-insecure allow http:// or plaintext gRPC (a token is then refused unless the collector is on loopback)
--otel-sample-ratio fraction of traces kept, 0..1 (default 1)
--otel-service-name service.name (default turnd); service.version is the build version, service.instance.id a random ID
--otel-trust-client-context continue a caller's W3C traceparent; off, every request starts its own trace

The token is read from a file only. OTEL_EXPORTER_OTLP_HEADERS (and the per-signal variants) is ignored and reported at startup, so a token never travels through the environment.

Traces. A server span for /login, /callback and /healthz (named GET /login, status Error only for a 5xx, turnd.outcome on login), one for every gRPC method (otelgrpc, rpc.method, rpc.status_code, plus turnd.room.action and turnd.outcome), and a short root span per TURN control request (TURN allocate, refresh, create_permission, channel_bind, with turnd.result and turnd.policy). There is no span per relayed packet.

Metrics (units are UCUM; every attribute has a small fixed set of values):

Instrument Kind, unit Attributes
turnd.relay.allocations, .permissions, .channels gauge, {allocation} {permission} {channel}
turnd.relay.requests counter, {request} turnd.method, turnd.transport (udp, tcp, tls), turnd.result
turnd.relay.policy.refusals counter, {refusal} turnd.policy: loopback, private, link_local, metadata, cgnat, multicast, translator, own_address, reserved, port_zero, family_mismatch
turnd.relay.auth.failures counter, {failure} turnd.surface (relay, api), turnd.reason
turnd.relay.bytes, .packets counter, By {packet} turnd.direction (client_to_peer, peer_to_client)
turnd.relay.packets.dropped counter, {packet}
turnd.rooms gauge, {room}
turnd.guests gauge, {guest} turnd.state (pending, admitted)
turnd.rendezvous.operations counter, {operation} turnd.action, turnd.outcome
turnd.login.outcomes counter, {login} turnd.outcome
http.server.request.duration histogram, s http.request.method, http.route, http.response.status_code
rpc.server.* otelgrpc

Allocations created and refused are turnd.relay.requests{turnd.method=allocate} by result; knocks, admits and denies are turnd.rendezvous.operations; TURN credentials minted are its credentials_host and credentials_room actions with outcome ok; sessions issued and refused are turnd.login.outcomes. The relay's packet and byte counters are read when the metrics are pushed: the relay's hot path does the same work with telemetry on or off.

Logs. log/slog, JSON on stderr (journald-friendly), with trace_id and span_id when a span is active; with telemetry on the same records go over OTLP through the OpenTelemetry slog bridge, from Info up, after redaction. The login outcome lines of every callback are kept as they were.

Privacy. No token, code, cookie, credential, password, room ID or TURN username, and no client or peer address (not even in the debug records), reaches a span, a metric or a log record: attributes are fixed words, the SDK instrumentation's own address attributes are removed before export, and the pseudonymous login subject stays on stderr. Tests run the daemon against an in-process collector and assert that none of those strings is in any request body.

Package stun

The RFC 8489 message codec with the RFC 8656 TURN attributes and ChannelData framing. Decoding is strict and bounded: it refuses a length that overruns the datagram, framing that is not 4-aligned, and more than MaxAttributes (64) attributes; attributes after MESSAGE-INTEGRITY are not visible. It covers MESSAGE-INTEGRITY (HMAC-SHA1), MESSAGE-INTEGRITY-SHA256, FINGERPRINT, the long-term key derivations (MD5 and SHA-256) and USERHASH. Tested against the RFC 5769 vectors (decode, verify, byte-identical re-encode); FuzzDecode and FuzzChannelData have a committed seed corpus under stun/testdata/fuzz. SASLprep (OpaqueString) is the caller's job.

Package server

The RFC 8656 TURN server: UDP relayed transport, reached over UDP, TCP or TLS (the caller passes the sockets), plus the STUN Binding answer. Long-term credentials (MD5, and SHA-256 when the client asks) with NONCE expiry (438); permissions last 300 s, channels 600 s.

srv, err := server.New(server.Config{
	Realm:   "turn.example.org",
	Auth:    func(username string) (password string, ok bool) { /* wrap creds.Verify */ },
	RelayIP: netip.MustParseAddr("203.0.113.5"),
})
go srv.ServePacketConn(udpConn)         // UDP clients
go srv.ServeListener(tcpListener)       // TCP clients
go srv.ServeTLS(tcpListener443, tlsCfg) // turns:

By default the server never relays to or from loopback, 0.0.0.0/8, RFC 1918, 100.64/10, link-local (169.254.169.254 included), multicast, ULA, the NAT64/6to4/Teredo forms, IPv4-mapped forms of those, or its own addresses: it answers 403. The one exception is two clients relaying to each other: an own address is a peer only at the relayed port of a live allocation (checked when the permission or channel is made and again on every datagram, which is handed over in memory), so SSH, 443 and the TURN listeners stay unreachable through the relay. Config.AllowPeers re-enables ranges (tests use 127.0.0.0/8). Bounds, all in Config: allocations per user and in total, lifetime cap, per-allocation byte rate, relay port range, permissions and channels per allocation, concurrent connections, idle and handshake timeouts, datagram size. interop/ is the judge: github.com/pion/turn/v4 (test-only) allocates, permits, binds a channel and round-trips data through the server over UDP and TCP. go test -bench . ./server prints allocations/s and relayed packets/s; the comparison with coturn on one core is still to do.

turnd starts the relay when a listen flag is set: --relay-ip (required; --relay-advertise-ip behind a NAT), --stun-listen :3478 (UDP), --turn-tcp-listen :3478, --turns-listen :443 (TLS, with --tls-cert-file and --tls-key-file), --relay-port-min / --relay-port-max, and --proxy-protocol-from <prefix> (repeatable) to accept a PROXY protocol v2 header (haproxy's specification) on TCP and TLS connections from that prefix. Its credential hook is the keyring's Auth, so the minted <expiry>:<tag>.<subject> usernames are what the relay accepts (the tag says which of the rotating secrets signed it).

A relayed call outlives the credential that opened it. A username is checked for expiry when it STARTS an allocation (Allocate); on an allocation that the same username created from the same 5-tuple, Refresh, CreatePermission and ChannelBind keep working after the expiry (Config.AuthExisting, the keyring's AuthExisting): the MESSAGE-INTEGRITY check still needs the password derived from the username, and another username on that allocation stays refused (RFC 8656 section 5). --max-allocation-age (Config.MaxAllocationAge, default 12 h) bounds it: past that age a Refresh answers 403, and an expired username is no longer accepted. A new call needs a fresh credential.

Deploying

One host, one binary (CGO_ENABLED=0 go install github.com/go-turn/turn/cmd/turnd@latest). Ports to open, at the host firewall and at the cloud security group:

port for
UDP 3478 STUN and TURN over UDP (--stun-listen :3478)
TCP 3478 TURN over TCP (--turn-tcp-listen :3478)
TCP 5349 TURN over TLS (--turns-listen :5349), for networks that block UDP
UDP range relayed addresses (--relay-port-min 49160 --relay-port-max 49999)
TCP 443 HTTPS: /login, /callback, /grpc, through the host's reverse proxy to --listen 127.0.0.1:8080 (the proxy must pass WebSocket upgrades)
TURN over TLS on 443, beside HTTPS

TURN over TLS can share 443 with the HTTPS site when Caddy demultiplexes by SNI with caddy-l4. Caddy terminates TLS for turn.example.org itself and proxies plain TCP to turnd with a PROXY protocol v2 header, so turnd still sees the real client address (XOR-MAPPED-ADDRESS, quotas and logs). The build is xcaddy build --with github.com/mholt/caddy-l4@v0.1.3, pinned because caddy-l4 calls itself experimental.

{
    servers :443 {
        listener_wrappers {
            layer4 {
                @turn tls sni turn.example.org
                route @turn {
                    tls
                    proxy {
                        proxy_protocol v2
                        upstream tcp/127.0.0.1:3478
                    }
                }
            }
            tls
        }
    }
}

# A site block makes Caddy obtain the certificate that the `tls` handler above
# presents for turn.example.org.
turn.example.org {
    respond "turnd relay" 200
}

turnd runs --turn-tcp-listen 127.0.0.1:3478 --proxy-protocol-from 127.0.0.1/32. Clients use turns:turn.example.org:443?transport=tcp. The header is accepted only from the listed prefixes: a connection from one of them without a valid header is closed, and a header from any other source is never honoured. The Caddyfile follows caddy-l4's docs/examples/combining_apps.md; it has not been run against a Caddy here, only the header handling is tested (with pion's TCP client behind a proxy that prepends a v2 header). The separate --turns-listen (TLS handled by turnd, port 5349 or 443 on a second address) stays available for a host without Caddy; there the PROXY header, if any, precedes the ClientHello.

Secrets are files readable by the service account only: 32+ random bytes for --session-key-file, 16+ for --turn-secret-file, the issuer's client secret for --client-secret-file. Register <public-url>/callback as the redirect URI of --client-id at the issuer.

Session renewal at go-authn/bridge

A session token lasts --session-ttl (1 h). So that a person is not sent back through the login popup every hour, turnd asks for offline_access at the login and keeps the issuer's refresh token server side, in memory, never sent to the browser (see "Renewing a session" above). It needs the issuer to issue refresh tokens to turnd's client. At go-authn/bridge that is refresh_lifetime on the client block (README, "Without a browser" and "Several resource servers"; read from the v0.23.12 source, where refresh tokens are issued when the client has a refresh_lifetime, unknown scopes such as offline_access are accepted and ignored, and the family's end is fixed at the login, rotation does not extend it). The client block turnd needs:

client "turnd" {
  secret_file      = "/etc/authn-bridge/turnd.secret"      # the file behind --client-secret-file
  redirect_uris    = ["https://turn.example.org/callback"] # <public-url>/callback, exact
  refresh_lifetime = "168h"                                # refresh tokens on; 7 days from each login
}

(id, secret_file and redirect_uris are what the client already has; the change is refresh_lifetime.) Set --session-renewal-lifetime to the same value (default 168h): it is how long turnd keeps a family before bridge would refuse it anyway. Without refresh_lifetime the login still works and the session is simply not renewable (the log says "the provider issued no refresh token"); --session-renewal-lifetime 0 turns renewal off and asks for openid alone.

The store is bounded (10000 families; when full the family closest to its end is dropped) and lost on a restart: everybody signs in again once, as with a session-key change. Revoking a person at bridge (account, passkey, application session) ends their renewal at the next RenewSession; a session token already issued stays valid until its own expiry (at most --session-ttl).

Checking a deployment

A deployed relay can be proven end to end without an OpenID Connect login. On the host, mint short-lived credentials with the keyring turnd uses (the first --turn-secret-file signs; the TTL is capped at 1h). The username is printed; the password goes to a new 0600 file, never to stdout or the command line:

turnd mint-credentials --turn-secret-file /etc/turnd/turn.secret \
  --subject probe --ttl 10m --password-out ./probe.pw   # prints <expiry>:<tag>.probe

Then, from anywhere that can reach the relay, run turnprobe. For each --server it sends a STUN Binding (printing the mapped address), opens two allocations, permits each other's relayed address, and sends a datagram from relay A to relay B and back; that proves relaying, with nothing else needed. A turns: certificate is verified against the system roots with SNI set to the host.

go install github.com/go-turn/turn/cmd/turnprobe@latest
turnprobe --username '1763400000:ab12.probe' --password-file ./probe.pw \
  --realm turn.example.org \
  --server 'turn:turn.example.org:3478?transport=udp' \
  --server 'turn:turn.example.org:3478?transport=tcp' \
  --server 'turns:turn.example.org:443?transport=tcp'
PASS turn:turn.example.org:3478?transport=udp mapped=198.51.100.7:51234 relay-a=203.0.113.5:49160 relay-b=203.0.113.5:49161 roundtrip=3ms
FAIL turns:turn.example.org:443?transport=tcp stage=connect: tls: failed to verify certificate: ...

One line per server, PASS or FAIL with the stage that failed (connect, binding, allocate, permission, relay A->B, relay B->A); the exit status is 1 if any failed. --realm is turnd's --realm; a mismatch is reported at allocate.

Asking a real browser: turnprobe --browser

The Go probe sends no ALPN and is not a browser. --browser starts a headless Chrome (chromedp), loads about:blank, and there creates an RTCPeerConnection with iceServers=[{urls, username, credential}] and iceTransportPolicy: "relay", a data channel and an offer. It PASSes iff Chrome gathers a candidate of type relay; it prints the relay address and the Chrome version, and on a FAIL the icecandidateerror events. The credential goes to the page through the DevTools evaluation, never a URL or a command line. --realm is not needed.

turnprobe --browser --username "$U" --password-file ./probe.pw \
  --server 'turns:turn.example.org:443?transport=tcp' \
  --server 'turn:turn.example.org:3478?transport=udp'

--alpn also measures what Chrome's TURN/TLS ClientHello offers: a second Chrome run points at a loopback TLS listener that logs each ClientHello's ALPN (RFC 7443 defines stun.turn) and speaks no TURN. --chrome names the binary; --chrome-flag name[=value] (repeat) passes a Chrome switch, e.g. host-resolver-rules or ignore-certificate-errors-spki-list to reach a local or staging server behind a private CA.

Licence

BSD-3-Clause.

Documentation

Overview

Package turn is the root of go-turn: a STUN (RFC 8489) and TURN (RFC 8656) relay for WebRTC peers, ephemeral TURN credentials minted behind an OpenID Connect login, and a rendezvous so two peers meet with one link.

The pieces live in subpackages: stun (the wire format), server (the relay), creds (ephemeral credentials), rendezvous (signalling rooms) and cmd/turnd (the daemon). Pure Go, CGO_ENABLED=0. The design is go-turn/turn#1.

Directories

Path Synopsis
cmd
turnd command
Command turnd serves go-turn: the OpenID Connect login, ephemeral TURN credentials, the rendezvous, and (with the relay flags) the STUN/TURN relay at the marked seam in app.go.
Command turnd serves go-turn: the OpenID Connect login, ephemeral TURN credentials, the rendezvous, and (with the relay flags) the STUN/TURN relay at the marked seam in app.go.
turnprobe command
Command turnprobe checks a deployed TURN relay end to end: a STUN Binding, then two allocations that permit each other's relayed address and pass a datagram across and back.
Command turnprobe checks a deployed TURN relay end to end: a STUN Binding, then two allocations that permit each other's relayed address and pass a datagram across and back.
Package creds mints and checks ephemeral TURN credentials, the scheme of draft-uberti-behave-turn-rest-00 (J. Uberti, "A REST API For Access To TURN Services", July 2013).
Package creds mints and checks ephemeral TURN credentials, the scheme of draft-uberti-behave-turn-rest-00 (J. Uberti, "A REST API For Access To TURN Services", July 2013).
internal
fakeidp
Package fakeidp is an in-process OpenID provider for tests, over TLS (httptest).
Package fakeidp is an in-process OpenID provider for tests, over TLS (httptest).
fakeotlp
Package fakeotlp is an in-process OTLP collector for tests.
Package fakeotlp is an in-process OTLP collector for tests.
homepage
Package homepage serves turnd's home pages: GET / answers with a page that says what the host is, chosen by the Host header (the collaboration service's page, or the STUN/TURN relay's), in seven languages with a light, dark or system theme, under a strict Content-Security-Policy.
Package homepage serves turnd's home pages: GET / answers with a page that says what the host is, chosen by the Host header (the collaboration service's page, or the STUN/TURN relay's), in seven languages with a light, dark or system theme, under a strict Content-Security-Policy.
proto
Package rendezvous is a signalling relay for WebRTC peers, as a gRPC service (turn.v1.Turnd, proto/turn/v1/turnd.proto).
Package rendezvous is a signalling relay for WebRTC peers, as a gRPC service (turn.v1.Turnd, proto/turn/v1/turnd.proto).
client
Package client is the rendezvous client: a real grpc-go client of turn.v1.Turnd, dialed over a WebSocket (github.com/grpc-transports/websocket), which in a browser (GOOS=js) is the browser's WebSocket through syscall/js.
Package client is the rendezvous client: a real grpc-go client of turn.v1.Turnd, dialed over a WebSocket (github.com/grpc-transports/websocket), which in a browser (GOOS=js) is the browser's WebSocket through syscall/js.
Package server implements the TURN server of RFC 8656 with UDP relayed transport, reached over UDP, TCP or TLS, plus the STUN Binding answer of RFC 8489.
Package server implements the TURN server of RFC 8656 with UDP relayed transport, reached over UDP, TCP or TLS, plus the STUN Binding answer of RFC 8489.
Package session is turnd's own login: an OpenID Connect login through go-authn/rp in a popup window, and a short-lived bearer token turnd signs itself, which the playground then presents to the credential and rendezvous endpoints.
Package session is turnd's own login: an OpenID Connect login through go-authn/rp in a popup window, and a short-lived bearer token turnd signs itself, which the playground then presents to the credential and rendezvous endpoints.
Package stun implements the STUN message codec of RFC 8489 and the TURN attributes and ChannelData framing of RFC 8656.
Package stun implements the STUN message codec of RFC 8489 and the TURN attributes and ChannelData framing of RFC 8656.
Package telemetry is turnd's OpenTelemetry: traces, metrics and logs pushed over OTLP, with the official Go SDK.
Package telemetry is turnd's OpenTelemetry: traces, metrics and logs pushed over OTLP, with the official Go SDK.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL