Server-side Usage
Sign credentials on a trusted Rust server, serve them to your applications, and connect from a backend.
Before you start: add useceleris-server on a trusted server. Keep your Celeris client ID and signing secret in that server's configuration. Never put them in an application that you ship to users.
1. Understand the two responsibilities
useceleris-server signs access. It does not provide a separate publish transport. A backend that publishes or receives uses useceleris-client, just as any other application does, but it signs its own credentials through credential_provider.
Applications that you ship to users fetch credentials from an authenticated endpoint on your server instead. See Authentication.
2. Serve credentials to your applications
Create one signer from server configuration. The signer is cheap to clone, safe to share between threads, and Debug shows it as redacted:
use useceleris_server::{Signer, SignerOptions};
let signer = Signer::new(SignerOptions {
client_id: std::env::var("CELERIS_CLIENT_ID")?,
signing_secret: std::env::var("CELERIS_SIGNING_SECRET")?,
clock: None,
})?;
The endpoint authenticates the user, decides the claims server-side, and signs fresh credentials for every request. This function does not need a web framework. It returns the HTTP status and the JSON body:
use std::time::Duration;
use useceleris_server::{ChannelScope, Claims, Replay, SegmentClaim, SegmentPermissions, Signer};
/// The user that your authentication found.
pub struct User {
pub id: String,
pub rooms: Vec<String>,
pub moderator: bool,
}
pub fn credential_response(signer: &Signer, user: Option<&User>, channel_reference: &str) -> (u16, String) {
let Some(user) = user else {
return (401, r#"{"error":"unauthenticated"}"#.to_owned());
};
// Authorize the requested channel against what the user can access.
if !user.rooms.iter().any(|room| room == channel_reference) {
return (403, r#"{"error":"forbidden"}"#.to_owned());
}
let claims = Claims {
reference: Some(user.id.clone()), // the identity peers see; no colons
replay: Replay::Lookback(Duration::from_secs(30)),
..Claims::new(
ChannelScope::Restricted(vec![channel_reference.to_owned()]),
SegmentPermissions::Restricted(vec![SegmentClaim {
segment_id: "chat".to_owned(),
read: true,
write: user.moderator,
}]),
)
};
match signer.sign(&claims) {
// Base64 text needs no JSON escapes.
Ok(credentials) => (
200,
format!(
r#"{{"payload":"{}","signature":"{}"}}"#,
credentials.payload, credentials.signature
),
),
Err(_) => (500, r#"{"error":"signing failed"}"#.to_owned()),
}
}
Your web framework finds the user from its session, reads a small request body, and calls the function. The user never comes from the request body. Limit the size of the request body, and set a deadline for the request headers. Never sign permissions that the caller asked for. Never cache or backdate credentials. sign validates the claims. On failure, it returns CelerisError::Configuration and names the claim and the rule that failed.
Scope every credential to what the user needs. Restricted channels and segments are explicit. ChannelScope::All or SegmentPermissions::All { .. } is an opt-in, never a default. Claims has no default, and Claims::new requires the channels and the permissions. Replay and echo default to off.
3. Connect from a backend
use std::error::Error;
use std::time::Duration;
use useceleris_client::{Client, ClientOptions, CredentialReason, read_text, text_payload};
use useceleris_server::{
ChannelScope, Claims, Replay, SegmentClaim, SegmentPermissions, Signer, SignerOptions,
credential_provider,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let signer = Signer::new(SignerOptions {
client_id: std::env::var("CELERIS_CLIENT_ID")?,
signing_secret: std::env::var("CELERIS_SIGNING_SECRET")?,
clock: None,
})?;
let provider = credential_provider(signer, |request| async move {
if request.channel_reference != "demo-room" {
return Err("worker channel is not allowed".into());
}
let mut claims = Claims {
reference: Some("demo-worker".to_owned()),
..Claims::new(
ChannelScope::Restricted(vec!["demo-room".to_owned()]),
SegmentPermissions::Restricted(vec![SegmentClaim {
segment_id: "chat".to_owned(),
read: true,
write: true,
}]),
)
};
if let CredentialReason::Reconnect { replay_lookback, .. } = request.reason {
claims.replay = Replay::Lookback(replay_lookback.min(Duration::from_secs(30)));
}
Ok(claims)
});
let client = Client::new(ClientOptions::new(provider))?;
let channel = client.channel("demo-room")?;
let chat = channel.segment("chat")?;
channel.events().on_error(|error| println!("Error: {error}"));
chat.on_message(|payload, _metadata| println!("Received: {:?}", read_text(payload)));
let _subscription = chat.subscribe()?;
channel.connect().await?;
chat.publish(text_payload("Hello from the backend")).await?;
tokio::signal::ctrl_c().await?; // run until interrupted
channel.close().await;
Ok(())
}
The claims function is the authority. Nothing automatically turns the request into permission. This worker explicitly restricts its channel and segment. It replays only on reconnect, and it caps requested replay at 30 seconds. The provider calls the claims function on every connection attempt, so the function can query a database. When the client drops the provider's future, for example because the channel closed, the provider signs nothing. If the function returns an error or invalid claims, connect fails with the generic CelerisError::Transport. To see the Configuration error that names the claim and the rule, sign the function's result directly with signer.sign.
tokio::signal::ctrl_c needs the signal feature of tokio.
A publish has the same local-acceptance semantics on a server as anywhere else. When publish returns Ok, the SDK handed the bytes to the socket. That result does not confirm delivery.
4. Apply this to your service
Sign from server-owned configuration. For multi-tenant services, authorize each channel. Do not replace the restriction with unrestricted claims. The signer holds no resources and needs no disposal. The client channel owns the socket. Use Reconnection and Recovery to decide how your service reconciles missed or duplicate messages.
Next: Rust server API and Rust client API.