-
Notifications
You must be signed in to change notification settings - Fork 213
Add a TokenSource crate to the Rust SDKs #1274
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
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 fd57f6a
Started with token source
MaxHeimbrock 8ea3a2e
Using static factory pattern
MaxHeimbrock f5eb077
Add license headers
MaxHeimbrock 243a369
Adding to knope.toml
MaxHeimbrock a8f9e6e
Changeset
MaxHeimbrock 8a99ad5
fix(knope): point livekit-token-source at its own root Cargo.toml pin
MaxHeimbrock 1ecbe14
style: run cargo fmt on livekit-token-source and example
MaxHeimbrock cdfc0e8
feat(token-source): add TokenSourceFixed and TokenSourceConfigurable …
MaxHeimbrock c23509e
refactor(token-source): rename agent_deployment option to deployment
MaxHeimbrock 248de6b
refactor(token-source): accept impl Into<String> for token server id,…
MaxHeimbrock 57dc5ab
docs(token-source): document the public API
MaxHeimbrock e621977
build(token-source): drop TLS from default features
MaxHeimbrock 9e6f873
chore(token-source): clean up example, read sandbox id from env
MaxHeimbrock 8c55367
test(token-source): cover agent options to room_config request nesting
MaxHeimbrock c016e75
docs(token-source): write the crate README
MaxHeimbrock c1d5746
chore: add code owner for livekit-token-source
MaxHeimbrock 8356be5
chore: add changeset for livekit-token-source
MaxHeimbrock 72eee03
Update livekit-token-source/src/error.rs
MaxHeimbrock 3927efd
Update .github/CODEOWNERS
MaxHeimbrock 3da9215
First batch of comment addressing
MaxHeimbrock eaccdf3
More comments addressed
MaxHeimbrock 4b420a3
fmt
MaxHeimbrock e9953f7
docs(token-source): fix stale TokenSource:: factory references, scrub…
MaxHeimbrock 0631484
Addressing Ryans comments
MaxHeimbrock File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
| .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}"), | ||
| } | ||
| } | ||
|
MaxHeimbrock marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| {"server_url": "url from file", "participant_token": "token from file"} | ||
|
1egoman marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
|
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 }, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.