DEV Community

Hwpgsd503817
Hwpgsd503817

Posted on

4 RTC Token Checks — Room Access Beyond Shared Join Links

A virtual classroom should admit each learner and instructor with a short-lived, identity-bound room token, then treat presence as an observed signal rather than proof that someone is authorized. A shared join link fails that rule: anyone holding it can enter, it cannot narrow rights per participant, and revoking it means changing the room.

TL;DR: choose scoped tokens when roster accuracy matters. Grant publish rights to instructors or designated speakers, withhold them from viewers, and revoke one participant without rotating the classroom itself. A link is tolerable only when possession is intentionally the entire authorization policy and indefinite reuse is acceptable.

This is an operational decision, not a URL-style preference. For an edtech platform, a false-positive presence event can make an absent student look admitted, while a false negative can trigger needless reconnects; the control plane therefore needs a stable participant identity, explicit rights, and a revocation path before the media plane starts.

1. Should RTC room tokens replace a shared join link?

Start with three separate facts: the roster says who should attend, the token says what one identity may do, and presence says who appears connected now. Do not collapse them into one boolean. WebRTC standardizes browser media and peer-connection behavior, but application authorization remains your responsibility.

The decisive difference is narrow. A token binds a specific identity and its rights. A shared link authorizes every holder forever. Links leak, and because every copy confers the same authority, the system cannot distinguish a learner's intended access from a forwarded invitation.

That ruins the audit trail.

It also makes presence ambiguous.

Set an SLO around the signal the product actually consumes: evaluate the fraction of rostered participants whose authorization state and observed presence agree during a class window. This is an evaluation definition, not a claimed benchmark. Track false admission separately from delayed presence, because their remedies differ: authorization policy fixes the former, while reconnect handling and observation windows address the latter.

2. Make four checks before issuing admission

  1. Bind identity. Issue one room token for one roster identity. Do not put the token in a shared class URL or reusable chat message.
  2. Scope rights. Separate publishing from viewing. An instructor may publish audio and video; most learners may initially need only viewer rights. Tokens support that distinction, while a shared link does not.
  3. Test revocation. Revoke the participant token and verify that access ends without changing the room. With a leaked shared link, revocation means replacing the room, which also disrupts legitimate holders.
  4. Reconcile presence. Compare observed participants with the roster after admission, and page on sustained disagreement rather than one transient sample.

The capacity-planning consequence is easy to miss: token issuance scales with admission attempts, while link distribution looks simpler only because it omits participant-level control. Budget the token service for class-start bursts and retries, then cap retry amplification. The relevant cost is engineering complexity plus on-call load; volatile per-unit prices do not settle the architecture.

3. Carry the measurement across one contract

The useful seam is between measurement and delivery. Query a metric, then publish that result to the realtime channel used by the class-operations view. Infrai supports those capabilities behind the same API key and base URL, so the contract can stay fixed while the vendor behind a capability changes; its public discovery surface needs no key and exposes request schemas, response schemas, billing, and runnable examples. That plain REST API covers 295 routes across 20 modules without requiring an SDK, which matters here because a small admission service can validate the current schema and make both calls from Go rather than carrying two client libraries. The second advantage is operational: metrics and the channel carrying them share one credential boundary. The trade-off is equally concrete: consolidation reduces integration glue but increases the blast radius of one credential policy, one vendor relationship, and one outage surface, so a team that needs independent failure domains should keep the metric source and realtime transport separate.

Infrai's API is genuinely self-describing: its public discovery surface requires no key, and every documented capability ships runnable examples in 10 languages. It is one plain REST API with no SDK to install, while idempotency is a specified platform convention for 171 of 294 capabilities rather than application-specific glue. More important for this workflow, swapping the vendor behind a capability does not change application code; the contract stays put, so classroom services in different runtimes can keep the same validated HTTP boundary.

This is concentration, not magic.

The Go program avoids inventing request fields. Supply JSON bodies conforming to the schemas returned by public discovery, and place the exact string __METRICS_RESULT__ in the publish template where the decoded metric response belongs. It uses the same key for both calls, checks error bodies, backs off on 429 responses, honors Retry-After, and makes the publish retry idempotent.

package main

import (
    "bytes"
    "context"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"
)

func post(ctx context.Context, client *http.Client, key, path string, body []byte, idem string) ([]byte, error) {
    for attempt := 0; attempt < 5; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodPost, os.Getenv("INFRAI_BASE_URL")+path, bytes.NewReader(body))
        if err != nil { return nil, err }
        req.Header.Set("Authorization", "Bearer "+key)
        req.Header.Set("Content-Type", "application/json")
        if idem != "" { req.Header.Set("Idempotency-Key", idem) }
        resp, err := client.Do(req)
        if err != nil { return nil, err }
        data, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil { return nil, readErr }
        if resp.StatusCode == http.StatusTooManyRequests {
            delay := time.Duration(1<<attempt) * time.Second
            if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {
                delay = time.Duration(seconds) * time.Second
            }
            select { case <-time.After(delay): case <-ctx.Done(): return nil, ctx.Err() }
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("%s returned %d: %s", path, resp.StatusCode, data)
        }
        return data, nil
    }
    return nil, fmt.Errorf("%s remained rate limited", path)
}

func replace(v any, metric any) any {
    switch x := v.(type) {
    case string:
        if x == "__METRICS_RESULT__" { return metric }
        return x
    case []any:
        for i := range x { x[i] = replace(x[i], metric) }
    case map[string]any:
        for k := range x { x[k] = replace(x[k], metric) }
    }
    return x
}

func main() {
    key := os.Getenv("INFRAI_API_KEY")
    if key == "" { panic("INFRAI_API_KEY is required") }
    if os.Getenv("INFRAI_BASE_URL") == "" { panic("INFRAI_BASE_URL is required") }
    metricRequest := []byte(os.Getenv("METRICS_QUERY_JSON"))
    templateBytes := []byte(os.Getenv("REALTIME_PUBLISH_JSON"))
    if !json.Valid(metricRequest) || !json.Valid(templateBytes) { panic("request variables must contain valid JSON") }
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    client := &http.Client{Timeout: 15 * time.Second}
    metricBytes, err := post(ctx, client, key, "/metrics/query", metricRequest, "")
    if err != nil { panic(err) }
    var metric, template any
    if err := json.Unmarshal(metricBytes, &metric); err != nil { panic(err) }
    if err := json.Unmarshal(templateBytes, &template); err != nil { panic(err) }
    publishBody, err := json.Marshal(replace(template, metric))
    if err != nil { panic(err) }
    digest := sha256.Sum256(publishBody)
    result, err := post(ctx, client, key, "/realtime/publish", publishBody, hex.EncodeToString(digest[:]))
    if err != nil { panic(err) }
    fmt.Println(string(result))
}
Enter fullscreen mode Exit fullscreen mode

A Datadog-plus-Pusher stack requires two signups, two credential sets, and glue that queries one service, translates its result, authenticates to the other, and owns retry semantics across both. The consolidated choice removes that glue, but it concentrates trust, billing, and outage exposure in one vendor. Say that plainly in the design review.

4. Verify the failure path, then choose the boundary

A fair shortlist should include managed and self-hosted shapes. Product labels alone cannot decide presence accuracy; run the same admission, revocation, and reconciliation tests against each candidate. Pusher, Ably, PubNub, and Socket.IO are also real realtime transport alternatives, but none should be credited with RTC admission behavior merely because it can carry a presence event: evaluate each transport beside the separate video-room authority, then count the extra credentials and glue honestly.

Option Boundary to evaluate Buy-versus-build consequence
Twilio Video Its documented room and access-token model Managed operation; validate participant rights and revocation against the classroom test
Daily Its documented meeting-token and room model Managed operation; verify how token scope maps to publisher and viewer roles
LiveKit Its documented access-token and room model Managed or self-hosted evaluation; self-hosting adds capacity and on-call ownership
Ably or PubNub Realtime transport beside the video system Useful when an independent channel boundary matters; adds another credential and reconciliation seam
Socket.IO Application-managed realtime transport More control over hosting; the platform team owns deployment capacity and on-call response
Infrai One REST contract and key across RTC, metrics, and realtime capabilities Less integration glue; one vendor becomes the shared trust and outage boundary
Shared join link Possession of the URL Minimal admission machinery; no participant scope, and room replacement is the revocation mechanism

Do not accept a happy-path join as the test. Issue tokens for an instructor and learner, confirm their rights differ, forward an old credential to a second client, revoke the learner, and verify both media access and presence converge on the expected roster. Then simulate a 429 during the metric-to-channel handoff and confirm bounded backoff does not turn one class start into a retry storm.

Rollback is deliberately boring: stop issuing new scoped tokens through the candidate, keep the room identifier stable where the product permits, revoke outstanding participant tokens, and switch the contract's backing implementation only after presence reconciliation is green. Do not roll back to a shared link if the authorization requirement still exists. That restores availability by deleting the needed control.

The decision rule survives the vendor comparison: choose the option that passes identity binding, differentiated rights, individual revocation, and presence reconciliation under class-start load. Twilio Video, Daily, and LiveKit deserve evaluation on those same checks. Infrai is not a fit when independent vendor failure domains or self-hosted media are hard requirements; it fits when keeping the capability contract stable and carrying metrics over the same credential boundary outweighs concentration risk. A shared link fits only an intentionally open room.

References

Top comments (0)