Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
930263d
# This is a combination of 2 commits.
MaxHeimbrock Jul 17, 2026
fd57f6a
Started with token source
MaxHeimbrock Aug 3, 2026
8ea3a2e
Using static factory pattern
MaxHeimbrock Aug 3, 2026
f5eb077
Add license headers
MaxHeimbrock Aug 4, 2026
243a369
Adding to knope.toml
MaxHeimbrock Aug 4, 2026
a8f9e6e
Changeset
MaxHeimbrock Aug 4, 2026
8a99ad5
fix(knope): point livekit-token-source at its own root Cargo.toml pin
MaxHeimbrock Aug 5, 2026
1ecbe14
style: run cargo fmt on livekit-token-source and example
MaxHeimbrock Aug 5, 2026
cdfc0e8
feat(token-source): add TokenSourceFixed and TokenSourceConfigurable …
MaxHeimbrock Aug 5, 2026
c23509e
refactor(token-source): rename agent_deployment option to deployment
MaxHeimbrock Aug 5, 2026
248de6b
refactor(token-source): accept impl Into<String> for token server id,…
MaxHeimbrock Aug 5, 2026
57dc5ab
docs(token-source): document the public API
MaxHeimbrock Aug 5, 2026
e621977
build(token-source): drop TLS from default features
MaxHeimbrock Aug 5, 2026
9e6f873
chore(token-source): clean up example, read sandbox id from env
MaxHeimbrock Aug 5, 2026
8c55367
test(token-source): cover agent options to room_config request nesting
MaxHeimbrock Aug 5, 2026
c016e75
docs(token-source): write the crate README
MaxHeimbrock Aug 5, 2026
c1d5746
chore: add code owner for livekit-token-source
MaxHeimbrock Aug 5, 2026
8356be5
chore: add changeset for livekit-token-source
MaxHeimbrock Aug 5, 2026
72eee03
Update livekit-token-source/src/error.rs
MaxHeimbrock Aug 5, 2026
3927efd
Update .github/CODEOWNERS
MaxHeimbrock Aug 5, 2026
3da9215
First batch of comment addressing
MaxHeimbrock Aug 6, 2026
eaccdf3
More comments addressed
MaxHeimbrock Aug 6, 2026
4b420a3
fmt
MaxHeimbrock Aug 6, 2026
e9953f7
docs(token-source): fix stale TokenSource:: factory references, scrub…
MaxHeimbrock Aug 6, 2026
0631484
Addressing Ryans comments
MaxHeimbrock Aug 7, 2026
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
5 changes: 5 additions & 0 deletions .changeset/add_a_tokensource_crate_to_the_rust_sdks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
livekit-token-source: patch
---

Add a TokenSource crate to the Rust SDKs - #1274 (@MaxHeimbrock)
5 changes: 5 additions & 0 deletions .changeset/add_livekit_token_source_crate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
livekit-token-source: minor
---

Add the `livekit-token-source` crate: token sources for procuring LiveKit credentials, mirroring the JS SDK's `TokenSource` — `literal`, `endpoint` (standard token endpoint format), and `development_token_server`, plus `TokenSourceFixed` / `TokenSourceConfigurable` traits for custom backends.
3 changes: 2 additions & 1 deletion .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@
/livekit-datatrack/ @ladvoc @1egoman
/livekit-data-stream/ @ladvoc @1egoman
/livekit-wakeword/ @pham-tuan-binh
/livekit-net/ @jhugman
/livekit-net/ @jhugman
/livekit-token-source/ @MaxHeimbrock
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ members = [
"livekit-ffi",
"livekit-uniffi",
"livekit-datatrack",
"livekit-token-source",
"livekit-ffi-node-bindings",
"livekit-net",
"livekit-runtime",
Expand Down Expand Up @@ -36,6 +37,7 @@ members = [
"examples/save_to_disk",
"examples/screensharing",
"examples/send_bytes",
"examples/token_source",
"examples/webhooks",
]

Expand All @@ -53,6 +55,7 @@ livekit = { version = "0.8.2", path = "livekit" }
livekit-api = { version = "0.6.2", path = "livekit-api" }
livekit-ffi = { version = "0.12.74", path = "livekit-ffi" }
livekit-datatrack = { version = "0.1.13", path = "livekit-datatrack" }
livekit-token-source = { version = "0.1.0", path = "livekit-token-source" }
livekit-common = { version = "0.1.1", path = "livekit-common" }
livekit-data-stream = { version = "0.1.2", path = "livekit-data-stream" }
livekit-net = { version = "0.1.2", path = "livekit-net" }
Expand Down
11 changes: 11 additions & 0 deletions examples/token_source/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "token_source"
version = "0.1.0"
edition.workspace = true
publish = false

[dependencies]
livekit-token-source = { workspace = true, features = ["rustls-tls-native-roots"] }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
async-trait = "0.1"
serde_json = { workspace = true }
79 changes: 79 additions & 0 deletions examples/token_source/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use async_trait::async_trait;
use livekit_token_source::{
TokenSourceConfigurable, TokenSourceFetchOptions, TokenSourceFixed, TokenSourceResponse,
TokenSourceResult,
};

/// An example for a custom token source that reads credentials from a JSON file, e.g.
/// `{"server_url": "wss://...", "participant_token": "..."}`.
struct FileTokenSource {
path: std::path::PathBuf,
}

#[async_trait]
impl TokenSourceFixed for FileTokenSource {
async fn fetch(&self) -> TokenSourceResult<TokenSourceResponse> {
let contents = std::fs::read_to_string(&self.path).map_err(serde_json::Error::io)?;
let response = serde_json::from_str(&contents)?;
Ok(response)
}
}

#[tokio::main]
async fn main() {
// A literal token source returns a fixed set of pre-provisioned credentials.
let literal =
livekit_token_source::literal("wss://example.livekit.cloud", "<a pre-generated token>");
match literal.fetch().await {
Ok(response) => println!(
"literal: server_url={} participant_token={}",
response.server_url, response.participant_token
),
Err(error) => eprintln!("literal fetch failed: {error}"),
}

// A custom token source can procure credentials from anywhere; this one
// reads them from a JSON file next to this example's Cargo.toml.
let file_source =
FileTokenSource { path: concat!(env!("CARGO_MANIFEST_DIR"), "/token.json").into() };
match file_source.fetch().await {
Ok(response) => println!(
"file: server_url={} participant_token={}",
response.server_url, response.participant_token
),
Err(error) => eprintln!("file fetch failed: {error}"),
}

// The remaining sources query LiveKit's development token server, which
// requires the ID of a sandbox created in your LiveKit Cloud project.
let sandbox_id = "your sandbox id".to_string();

let options = TokenSourceFetchOptions::new()
Comment thread
1egoman marked this conversation as resolved.
.with_room_name("example-room")
.with_participant_identity("example-user");

// Development token server: for prototyping only, NOT for production use.
let development_token_server =
livekit_token_source::development_token_server(sandbox_id.clone());
match development_token_server.fetch(&options).await {
Ok(response) => println!(
"development token server: server_url={} participant_token={}",
response.server_url, response.participant_token
),
Err(error) => eprintln!("development token server fetch failed: {error}"),
}

// Endpoint: POSTs the fetch options to a token endpoint using the standard
// format; here pointed at the same development token server.
let endpoint = livekit_token_source::endpoint(
"https://cloud-api.livekit.io/api/v2/sandbox/connection-details",
)
.with_header("X-Sandbox-ID", sandbox_id);
match endpoint.fetch(&options).await {
Ok(response) => println!(
"endpoint: server_url={} participant_token={}",
response.server_url, response.participant_token
),
Err(error) => eprintln!("endpoint fetch failed: {error}"),
}
}
Comment thread
MaxHeimbrock marked this conversation as resolved.
1 change: 1 addition & 0 deletions examples/token_source/token.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"server_url": "url from file", "participant_token": "token from file"}
Comment thread
1egoman marked this conversation as resolved.
10 changes: 9 additions & 1 deletion knope.toml
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,12 @@ versioned_files = [
"Cargo.lock",
{ path = "Cargo.toml", dependency = "livekit-runtime" },
]
changelog = "livekit-runtime/CHANGELOG.md"
changelog = "livekit-runtime/CHANGELOG.md"

[packages.livekit-token-source]
versioned_files = [
"livekit-token-source/Cargo.toml",
"Cargo.lock",
{ path = "Cargo.toml", dependency = "livekit-token-source" },
]
changelog = "livekit-token-source/CHANGELOG.md"
35 changes: 35 additions & 0 deletions livekit-token-source/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
[package]
name = "livekit-token-source"
description = "Token sources for the LiveKit Rust SDK"
version = "0.1.0"
license.workspace = true
edition.workspace = true
repository.workspace = true
readme = "README.md"

[features]
# By default no TLS is enabled; pick one of the TLS features below.
default = ["native-tokio"]

# Backend bundles — pass-throughs to livekit-net. With none enabled the crate is
# backend-blind: the host must register a client via `livekit_net::set_http_client`.
native-tokio = ["livekit-net/native-tokio"]
native-async = ["livekit-net/native-async"]
native-dispatcher = ["livekit-net/native-dispatcher"]

# TLS pass-throughs (only meaningful with a native backend). See livekit-api's
# Cargo.toml for guidance on choosing one, notably in container deployments.
native-tls = ["livekit-net/native-tls"]
native-tls-vendored = ["livekit-net/native-tls-vendored"]
rustls-tls-native-roots = ["livekit-net/rustls-tls-native-roots"]
rustls-tls-webpki-roots = ["livekit-net/rustls-tls-webpki-roots"]

[dependencies]
async-trait = "0.1"
livekit-net = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
thiserror = { workspace = true }

[dev-dependencies]
tokio = { workspace = true, features = ["rt", "macros"] }
101 changes: 101 additions & 0 deletions livekit-token-source/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# LiveKit Token Source

Token sources for the LiveKit Rust SDK. A token source procures the credentials — server URL and
participant token — needed to join a LiveKit room. Once a source is constructed, call `fetch` to
obtain a set of credentials.

## Fixed and configurable sources

Every token source is one of two kinds, each represented by a trait:

- **Fixed** (`TokenSourceFixed`) — `fetch()` takes no parameters; the credentials are decided
ahead of time and every call resolves the same way.
- **Configurable** (`TokenSourceConfigurable`) — `fetch(&options)` takes
`TokenSourceFetchOptions` that parameterize the credentials generated for that call: room name,
participant identity and metadata, agent dispatch, and so on.

Combined with the mechanism used to procure credentials, this spans the following matrix:

| Mechanism | Using pre-generated credentials | Via an HTTP request to a URL | Via fully custom logic |
| ------------ | ------------------------------- | ---------------------------- | ---------------------- |
| Fixed | [`literal`](#literal) | — | implement `TokenSourceFixed` |
| Configurable | — | [`endpoint`](#endpoint) or [`development_token_server`](#development_token_server) | implement `TokenSourceConfigurable` |

## Sources shipped with the crate

Three sources ship with the crate, constructed via factory functions.

### `literal`

A fixed source holding a single set of pre-provisioned credentials, captured at construction and
returned as-is on every fetch — no I/O involved.

```rust
use livekit_token_source::TokenSourceFixed;

let source = livekit_token_source::literal("wss://example.livekit.cloud", "<participant token>");
let response = source.fetch().await?;
```

### `endpoint`

A configurable source that fetches credentials from a token endpoint implementing the
[standard format](https://docs.livekit.io/frontends/build/authentication/endpoint/). Each fetch
serializes the options into the standard JSON request body and `POST`s it with
`Content-Type: application/json`, plus any headers added via `with_header` / `with_headers`
(e.g. for authenticating against the endpoint). A 2xx response is parsed as the standard JSON
response format; any other status surfaces as `TokenSourceError::Server` carrying the status and
body.

Requests are sent through the process-wide HTTP client from `livekit-net`: on native builds the
built-in client is used automatically; embedders can register their own via
`livekit_net::set_http_client`.

```rust
use livekit_token_source::{TokenSourceConfigurable, TokenSourceFetchOptions};

let source = livekit_token_source::endpoint("https://example.com/api/token")
.with_header("Authorization", "Bearer <endpoint credential>");
let options = TokenSourceFetchOptions::new()
.with_room_name("my-room")
.with_participant_identity("user-123");
let response = source.fetch(&options).await?;
// connect with response.server_url / response.participant_token
```

### `development_token_server`

A configurable source that queries a LiveKit
[development token server](https://docs.livekit.io/frontends/build/authentication/sandbox-token-server/)
for prototyping. Under the hood it is an `endpoint` source pre-configured with the LiveKit Cloud
development token server URL, authenticating via the `X-Sandbox-ID` header with the given token
server ID.

**This mechanism is inherently insecure and must not be used in production.**

## Custom credential backends

Custom credential backends implement the `TokenSourceFixed` or `TokenSourceConfigurable` trait
directly; pick the trait by whether the backend accepts per-fetch parameters. Code written
against the traits works the same with custom and shipped sources.

```rust
use async_trait::async_trait;
use livekit_token_source::{TokenSourceFixed, TokenSourceResponse, TokenSourceResult};

/// Reads credentials from a JSON file, e.g.
/// `{"server_url": "wss://...", "participant_token": "..."}`.
struct FileTokenSource {
path: std::path::PathBuf,
}

#[async_trait]
impl TokenSourceFixed for FileTokenSource {
async fn fetch(&self) -> TokenSourceResult<TokenSourceResponse> {
let contents = std::fs::read_to_string(&self.path).map_err(serde_json::Error::io)?;
Ok(serde_json::from_str(&contents)?)
}
}
```

See [examples/token_source](../examples/token_source) for a runnable example.
29 changes: 29 additions & 0 deletions livekit-token-source/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2026 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// Errors returned when procuring credentials from a token source.
#[derive(Debug, thiserror::Error)]
pub enum TokenSourceError {
Comment thread
MaxHeimbrock marked this conversation as resolved.
#[error("no HTTP client available; enable a livekit-net backend feature or call livekit_net::set_http_client")]
TransportNotConfigured,

#[error("failed to fetch token: {0}")]
Transport(#[from] livekit_net::TransportError),

#[error("failed to serialize request / parse response: {0}")]
Json(#[from] serde_json::Error),

#[error("token server returned {status}: {body}")]
Server { status: u16, body: String },
}
39 changes: 39 additions & 0 deletions livekit-token-source/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright 2026 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Token sources for the LiveKit Rust SDK.
//!
//! A token source procures the credentials — server URL and participant
//! token — needed to join a LiveKit room. Construct one via the
//! [`literal`] / [`endpoint`] / [`development_token_server`] factory
//! functions, or implement [`TokenSourceFixed`] / [`TokenSourceConfigurable`]
//! to plug in a custom credential backend.

mod error;
mod request;
mod response;
mod token_source;

pub use error::TokenSourceError;
pub use request::TokenSourceFetchOptions;
pub use response::TokenSourceResponse;
pub use response::TokenSourceResult;
pub use token_source::development_token_server;
pub use token_source::endpoint;
pub use token_source::literal;
pub use token_source::TokenSourceConfigurable;
pub use token_source::TokenSourceDevelopmentTokenServer;
pub use token_source::TokenSourceEndpoint;
pub use token_source::TokenSourceFixed;
pub use token_source::TokenSourceLiteral;
Loading
Loading