Skip to content
Open
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
13 changes: 13 additions & 0 deletions .changeset/token_mode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
livekit-api: minor
livekit-protocol: minor
livekit-token: minor
---

Add token mode to the server API clients. `LiveKitApi::with_token_provider` asks a `TokenProvider` for a token with the grants of each request, so a client can run without an API key and secret. `Claims::to_claims_json` gives the grants in the form that a job token request takes.

`ServiceError` is now `#[non_exhaustive]`, and has the new variants `TokenProvider` and `InvalidToken`. A `match` on it needs a wildcard arm.

A thread call now asks for one action on the thread or scope that it names, in place of every action on every thread. For example, `ThreadClient::get("AT_1")` asks for `{"read": true, "threadIds": ["AT_1"]}`.

`AgentThreadGrants::can_update` now takes a thread id. A write grant that names the thread may update it; before, only a project-wide grant (`all`) could.
1 change: 1 addition & 0 deletions Cargo.lock

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

5 changes: 4 additions & 1 deletion livekit-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ default = ["services", "access-token", "webhooks"]
signal-client = ["dep:livekit-signaling"]
signal-client-native = ["signal-client", "livekit-signaling/native"]

services = ["access-token", "dep:livekit-region", "dep:reqwest", "dep:tokio", "tokio/time", "dep:progenitor-client", "dep:chrono", "dep:serde_json"]
services = ["access-token", "dep:async-trait", "dep:livekit-region", "dep:reqwest", "dep:tokio", "tokio/time", "dep:progenitor-client", "dep:chrono", "dep:serde_json"]

access-token = ["dep:livekit-token"]
webhooks = ["access-token", "dep:serde_json", "dep:base64"]
Expand Down Expand Up @@ -101,6 +101,9 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std"
rustls-native-certs = { version = "0.8", optional = true }
webpki-roots = { version = "1", optional = true }

# token provider
async-trait = { version = "0.1", optional = true }

# public API client
progenitor-client = { version = "0.15.1", optional = true }
chrono = { version = "0.4", default-features = false, features = ["serde"], optional = true }
Expand Down
194 changes: 99 additions & 95 deletions livekit-api/src/public_api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ use progenitor_client::{ClientHooks, OperationInfo};
use reqwest::header::{HeaderValue, AUTHORIZATION};
use serde::Deserialize;

use crate::services::{ServerError, ServerErrorCode, ServiceBase, ServiceError, ServiceResult};
use crate::services::{
ServerError, ServerErrorCode, ServiceBase, ServiceError, ServiceResult, TokenGrants,
};

/// The project id that names the project of the request's token.
pub(crate) const PROJECT: &str = "p_";
Expand Down Expand Up @@ -56,107 +58,107 @@ pub fn public_api_url(project_url: &str) -> String {
}
}

/// What the generated [`Client`] signs and times each request with.
/// What the generated [`Client`] sends with each request: the token of the call and the timeout.
#[derive(Clone, Debug)]
pub struct Credentials {
bearer: HeaderValue,
timeout: Duration,
}

/// Makes a generated [`Client`] for each call, with a token for the grants of that call.
#[derive(Debug)]
pub(crate) struct PublicApi {
baseurl: String,
http: reqwest::Client,
base: ServiceBase,
pub(crate) timeout: Duration,
}

impl Credentials {
fn bearer(
&self,
info: &OperationInfo,
url: &reqwest::Url,
) -> Result<String, livekit_token::AccessTokenError> {
impl PublicApi {
pub(crate) fn new(host: &str, base: ServiceBase, http: crate::http_client::Client) -> Self {
Self { baseurl: public_api_url(host), http, base, timeout: DEFAULT_TIMEOUT }
}

/// Gets the token for `grants`, then returns a client that sends it.
///
/// The token is ready before the request starts, so its error is returned as it is.
/// For example, a token provider error stays [`ServiceError::TokenProvider`].
pub(crate) async fn client(&self, grants: TokenGrants) -> ServiceResult<Client> {
let token = match &self.base {
ServiceBase::Token(token) => token.clone(),
ServiceBase::Provider(provider) => {
provider.token(grants).await.map_err(ServiceError::TokenProvider)?
}
ServiceBase::ApiKeySecret { api_key, api_secret } => {
let token = AccessToken::with_api_key(api_key, api_secret).with_ttl(TOKEN_TTL);
scoped(token, info.operation_id, url).to_jwt()?
AccessToken::with_api_key(api_key, api_secret)
.with_ttl(TOKEN_TTL)
.with_agent_thread_grants(grants.agent_thread)
.with_agent_database_grants(grants.agent_database)
.to_jwt()?
}
};
Ok(format!("Bearer {token}"))
// A token with a character that a header cannot hold (such as a newline) is an error.
let bearer = self.base.bearer(&token)?;
let credentials = Credentials { bearer, timeout: self.timeout };
Ok(Client::new_with_client(&self.baseurl, self.http.clone(), credentials))
}
}

/// Grants only what the call needs: a database call reaches only the database it names.
fn scoped(token: AccessToken, operation_id: &str, url: &reqwest::Url) -> AccessToken {
let database = |grants: AgentDatabaseGrants| AgentDatabaseGrants {
database_ids: vec![database_id(url)],
..grants
};
match operation_id {
"database_service_create_database" => token
.with_agent_database_grants(AgentDatabaseGrants { create: true, ..Default::default() }),
"database_service_list_databases" => token
.with_agent_database_grants(AgentDatabaseGrants { list: true, ..Default::default() }),
"database_service_delete_database" => {
token.with_agent_database_grants(database(AgentDatabaseGrants {
delete: true,
..Default::default()
}))
}
"database_service_get_database" | "database_service_export_database" => {
let id = database_id(url);
if id.starts_with("AT_") {
// a thread's database is read through its thread
token.with_agent_thread_grants(AgentThreadGrants {
thread_ids: vec![id],
sql: true,
..Default::default()
})
} else {
token.with_agent_database_grants(database(AgentDatabaseGrants {
read: true,
..Default::default()
}))
}
}
_ => token.with_agent_thread_grants(AgentThreadGrants {
all: true,
list: true,
create: true,
write: true,
read: true,
delete: true,
..Default::default()
}),
}
/// The grants of a call on one thread: `action` sets the one action, and only `thread_id` is named.
///
/// Example: `thread_grants("AT_1", |g| g.read = true)` asks for
/// `{"read": true, "threadIds": ["AT_1"]}`.
pub(crate) fn thread_grants(thread_id: &str, action: fn(&mut AgentThreadGrants)) -> TokenGrants {
let mut agent_thread =
AgentThreadGrants { thread_ids: vec![thread_id.to_owned()], ..Default::default() };
action(&mut agent_thread);
TokenGrants { agent_thread, ..Default::default() }
}

/// The grants of a call on the threads of one scope (create, list).
///
/// With no scope the call is on every scope of the project, and the server needs `all` for that.
pub(crate) fn thread_scope_grants(scope: &str, action: fn(&mut AgentThreadGrants)) -> TokenGrants {
let mut agent_thread =
AgentThreadGrants { all: scope.is_empty(), scope: scope.to_owned(), ..Default::default() };
action(&mut agent_thread);
TokenGrants { agent_thread, ..Default::default() }
}

/// The grants of a database call. A call on one database names it in `database_ids`.
pub(crate) fn database_grants(agent_database: AgentDatabaseGrants) -> TokenGrants {
TokenGrants { agent_database, ..Default::default() }
}

/// The database a `/databases/{id}` or `/databases/{id}:export` request names.
fn database_id(url: &reqwest::Url) -> String {
let last = url.path_segments().and_then(|mut s| s.next_back()).unwrap_or_default();
last.split(':').next().unwrap_or_default().to_owned()
/// The grants to read one database. A thread's database (`AT_` id) is read through its thread.
pub(crate) fn database_read_grants(database_id: &str) -> TokenGrants {
if database_id.starts_with("AT_") {
let agent_thread = AgentThreadGrants {
thread_ids: vec![database_id.to_owned()],
sql: true,
..Default::default()
};
return TokenGrants { agent_thread, ..Default::default() };
}
database_grants(AgentDatabaseGrants {
database_ids: vec![database_id.to_owned()],
read: true,
..Default::default()
})
}

impl ClientHooks<Credentials> for Client {
async fn pre<E>(
&self,
request: &mut reqwest::Request,
info: &OperationInfo,
_info: &OperationInfo,
) -> Result<(), progenitor_client::Error<E>> {
let bearer = self
.inner
.bearer(info, request.url())
.map_err(|e| progenitor_client::Error::Custom(e.to_string()))?;
let value = HeaderValue::from_str(&bearer)
.map_err(|e| progenitor_client::Error::Custom(e.to_string()))?;
request.headers_mut().insert(AUTHORIZATION, value);
request.headers_mut().insert(AUTHORIZATION, self.inner.bearer.clone());
*request.timeout_mut() = Some(self.inner.timeout);
Ok(())
}
}

pub(crate) fn client(host: &str, base: ServiceBase, http: crate::http_client::Client) -> Client {
Client::new_with_client(
&public_api_url(host),
http,
Credentials { base, timeout: DEFAULT_TIMEOUT },
)
}

/// Maps a generated-client error onto the service errors every client returns.
pub(crate) async fn error(err: progenitor_client::Error<()>) -> ServiceError {
use progenitor_client::Error as E;
Expand Down Expand Up @@ -229,32 +231,34 @@ pub(crate) fn next_cursor(page: Option<types::LivekitPublicapiCommonV1PageInfo>)

#[cfg(test)]
mod tests {
use livekit_token::{AccessToken, Claims};

use super::{public_api_url, scoped};

fn claims(operation_id: &str, path: &str) -> Claims {
let url = reqwest::Url::parse(&format!("https://x/v0/projects/p_/{path}")).unwrap();
let token = scoped(AccessToken::with_api_key("k", "s"), operation_id, &url);
Claims::from_unverified(&token.to_jwt().unwrap()).unwrap()
}
use super::{database_read_grants, public_api_url, thread_grants, thread_scope_grants};

#[test]
fn database_calls_carry_only_their_grant() {
let c = claims("database_service_create_database", "databases");
assert!(c.agent_database.can_create() && !c.agent_database.can_list());
assert!(!c.agent_thread.can_list(""));
let c = claims("database_service_list_databases", "databases");
assert!(c.agent_database.can_list() && !c.agent_database.can_create());
let c = claims("database_service_get_database", "databases/DB_a");
fn database_reads_carry_only_their_grant() {
let c = database_read_grants("DB_a");
assert!(c.agent_database.can_read("DB_a") && !c.agent_database.can_read("DB_b"));
let c = claims("database_service_export_database", "databases/AT_t:export");
assert!(!c.agent_thread.can_read("DB_a"));
let c = database_read_grants("AT_t");
assert!(c.agent_thread.can_sql("AT_t") && !c.agent_thread.can_read("AT_t"));
assert!(!c.agent_database.can_read("AT_t"));
let c = claims("database_service_delete_database", "databases/DB_a");
assert!(c.agent_database.can_delete("DB_a") && !c.agent_database.can_read("DB_a"));
let c = claims("thread_service_get_thread", "threads/AT_t");
assert!(c.agent_thread.can_read("AT_t") && !c.agent_database.can_list());
}

#[test]
fn thread_calls_carry_only_their_grant() {
let t = thread_grants("AT_1", |g| g.read = true).agent_thread;
assert!(t.can_read("AT_1") && !t.can_read("AT_2"));
assert!(!t.all && !t.can_delete("AT_1") && !t.can_write("AT_1"));

let t = thread_scope_grants("support", |g| g.list = true).agent_thread;
assert!(t.can_list("support") && !t.can_list("sales") && !t.can_list(""));
assert!(!t.all && !t.can_create("support"));

// no scope: every scope of the project
let t = thread_scope_grants("", |g| g.create = true).agent_thread;
assert!(t.all && t.can_create("") && !t.can_list(""));

let t = thread_grants("AT_1", |g| g.write = true).agent_thread;
assert!(t.can_update("AT_1") && !t.can_update("AT_2") && !t.all && !t.can_read("AT_1"));
}

#[test]
Expand Down
16 changes: 9 additions & 7 deletions livekit-api/src/services/agent_dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use super::{twirp_client::TwirpClient, ServiceBase, ServiceResult, LIVEKIT_PACKAGE};
use http::header::HeaderMap;
use livekit_protocol as proto;
use livekit_token::{get_env_keys, AccessTokenError, VideoGrants};
use livekit_token::{get_env_keys, VideoGrants};

const SVC: &str = "AgentDispatchService";

Expand Down Expand Up @@ -89,7 +89,7 @@ impl AgentDispatchClient {
req: proto::CreateAgentDispatchRequest,
) -> ServiceResult<proto::AgentDispatch> {
const METHOD: &str = "CreateDispatch";
let headers = self.auth_headers(req.room.to_string())?;
let headers = self.auth_headers(req.room.to_string()).await?;
Ok(self.client.request(SVC, METHOD, req, headers).await?)
}

Expand All @@ -112,7 +112,7 @@ impl AgentDispatchClient {
dispatch_id: dispatch_id.into(),
room: room_name.into(),
};
let headers = self.auth_headers(req.room.to_string())?;
let headers = self.auth_headers(req.room.to_string()).await?;
Ok(self.client.request(SVC, METHOD, req, headers).await?)
}

Expand All @@ -130,7 +130,7 @@ impl AgentDispatchClient {
) -> ServiceResult<Vec<proto::AgentDispatch>> {
const METHOD: &str = "ListDispatch";
let req = proto::ListAgentDispatchRequest { room: room_name.into(), ..Default::default() };
let headers = self.auth_headers(req.room.to_string())?;
let headers = self.auth_headers(req.room.to_string()).await?;
let res: proto::ListAgentDispatchResponse =
self.client.request(SVC, METHOD, req, headers).await?;
Ok(res.agent_dispatches)
Expand All @@ -155,7 +155,7 @@ impl AgentDispatchClient {
room: room_name.into(),
dispatch_id: dispatch_id.into(),
};
let headers = self.auth_headers(req.room.to_string())?;
let headers = self.auth_headers(req.room.to_string()).await?;
let mut res: proto::ListAgentDispatchResponse =
self.client.request(SVC, METHOD, req, headers).await?;
Ok(res.agent_dispatches.pop())
Expand All @@ -164,7 +164,9 @@ impl AgentDispatchClient {

impl AgentDispatchClient {
/// Generates the auth header common to all dispatch request types.
fn auth_headers(&self, room: String) -> Result<HeaderMap, AccessTokenError> {
self.base.auth_header(VideoGrants { room, room_admin: true, ..Default::default() }, None)
async fn auth_headers(&self, room: String) -> ServiceResult<HeaderMap> {
self.base
.auth_header(VideoGrants { room, room_admin: true, ..Default::default() }, None)
.await
}
}
18 changes: 12 additions & 6 deletions livekit-api/src/services/connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,8 @@ impl ConnectorClient {
ringing_timeout: Default::default(),
},
self.base
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)?,
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)
.await?,
)
.await
.map_err(Into::into)
Expand Down Expand Up @@ -240,7 +241,8 @@ impl ConnectorClient {
disconnect_reason: reason as i32,
},
self.base
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)?,
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)
.await?,
)
.await
.map_err(Into::into)
Expand Down Expand Up @@ -269,7 +271,8 @@ impl ConnectorClient {
..Default::default()
},
self.base
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)?,
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)
.await?,
)
.await
.map_err(Into::into)
Expand Down Expand Up @@ -314,8 +317,10 @@ impl ConnectorClient {
ringing_timeout: None,
wait_until_answered,
};
let headers =
self.base.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)?;
let headers = self
.base
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)
.await?;

// When waiting for the inbound party to join, the request can block, so
// default its timeout to the standard ring window; otherwise the client
Expand Down Expand Up @@ -369,7 +374,8 @@ impl ConnectorClient {
destination_country: options.destination_country.unwrap_or_default(),
},
self.base
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)?,
.auth_header(VideoGrants { room_create: true, ..Default::default() }, None)
.await?,
)
.await
.map_err(Into::into)
Expand Down
Loading
Loading