Documentation

Rust Server API

The full reference for useceleris-server covers Signer::new, the claims surface, and the connection to Celeris from a Rust backend.

cargo add useceleris-server

The crate requires Rust 1.88 or newer, and it runs on trusted servers only. The crate name is useceleris_server. This crate holds your signing secret and must never ship in a browser, mobile or desktop application. It depends on useceleris-client for Credentials, CredentialProvider and CelerisError, and it signs with the RustCrypto hmac and sha2 crates. The generated documentation is on docs.rs.

Use your signing secret, never a client secret, and keep it in server-side configuration. Anyone who holds it can impersonate any of your users.

Signer::new()

impl Signer {
    pub fn new(options: SignerOptions) -> Result<Signer, CelerisError>;
    pub fn sign(&self, claims: &Claims) -> Result<Credentials, CelerisError>;
}

pub struct SignerOptions {
    pub client_id: String, // no colon, CR or LF
    pub signing_secret: String,
    pub clock: Option<Arc<dyn Fn() -> SystemTime + Send + Sync>>, // None means SystemTime::now; a test seam
}

sign is synchronous and deterministic for fixed inputs. It validates the claims, stamps the current time and returns Credentials. A Signer is cheap to clone, safe to share between threads, and holds no resources. It keeps the secret only inside its HMAC state. Debug shows SignerOptions, Signer and Credentials as redacted. The crate does not print or log.

use std::time::Duration;

use useceleris_server::{
    ChannelScope, Claims, Replay, SegmentClaim, SegmentPermissions, 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,
})?;

let credentials = signer.sign(&Claims {
    reference: Some("user-8317".to_owned()),
    replay: Replay::Lookback(Duration::from_secs(30)),
    ..Claims::new(
        ChannelScope::Restricted(vec!["room-42".to_owned()]),
        SegmentPermissions::Restricted(vec![SegmentClaim {
            segment_id: "chat".to_owned(),
            read: true,
            write: true,
        }]),
    )
})?;

Return credentials.payload and credentials.signature to the application unchanged, for example as {"payload": ..., "signature": ...}. Both values are opaque: never parse, re-encode or cache them. For the same claims, the signed bytes are equal to the bytes of the JavaScript signer.

The claims surface

pub struct Claims {
    pub channels: ChannelScope,
    pub permissions: SegmentPermissions,
    pub reference: Option<String>,
    pub replay: Replay,
    pub allow_echo: bool,
}

impl Claims {
    pub fn new(channels: ChannelScope, permissions: SegmentPermissions) -> Claims; // no reference, no replay, no echo
}

pub enum ChannelScope {
    All,
    Restricted(Vec<String>),
}

pub enum SegmentPermissions {
    All { read: bool, write: bool },
    Restricted(Vec<SegmentClaim>),
}

pub struct SegmentClaim {
    pub segment_id: String,
    pub read: bool,
    pub write: bool,
}

pub enum Replay {
    None,
    Backlog,
    Lookback(Duration),
}
FieldValuesNotes
channelsChannelScope::All or ChannelScope::Restricted(references)Required. References are 1 to 255 characters of [A-Za-z0-9_-], unique, at least one. None is refused, never read as "all".
permissionsSegmentPermissions::All { read, write } or SegmentPermissions::Restricted(claims)Required. A restricted list can be empty, which grants nothing. Segment ids are unique, non-empty, no CR or LF.
referenceOption<String>Identity label in message metadata and presence. Not empty, and no colon, CR or LF. None lets the server generate one.
replayReplay::None, Replay::Backlog or Replay::Lookback(duration)Claims::new gives Replay::None. A lookback is whole milliseconds, 0 to 4294967295 ms. Lookback(Duration::ZERO) replays nothing older than the join, which is different from None.
allow_echoboolDefaults to false: the publishing connection does not receive its own publishes. Other connections with the same reference do.

Claims has no Default. Claims::new requires the channels and the permissions, and it sets the other fields to their defaults. Change them with struct update syntax, as the example above shows. Unrestricted access is always an explicit opt-in:

let credentials = signer.sign(&Claims::new(
    ChannelScope::All,
    SegmentPermissions::All {
        read: true,
        write: false,
    },
))?;
A token with write: true but read: false can publish and cannot subscribe. The server refuses its subscription with a PermissionDeniedError. On default, such a token receives nothing, with no error. If a client connects but never receives messages, check read first.

credential_provider()

Sometimes a backend is itself a realtime client, for example a worker that publishes events. This function bridges the signer to the client's provider.

pub fn credential_provider<ClaimsFor, Decided>(signer: Signer, claims: ClaimsFor) -> CredentialProvider
where
    ClaimsFor: Fn(CredentialRequest) -> Decided + Send + Sync + 'static,
    Decided: Future<Output = Result<Claims, ProviderError>> + Send + 'static;
ArgumentMeaning
signerThe signer from Signer::new
claimsServer-owned authorization function, called for each connection attempt

The provider calls claims(request) on every attempt, then signs with a fresh timestamp. When the client drops the provider's future, for example because the channel closed, the provider signs nothing. See the client types for CredentialRequest's fields.

use std::time::Duration;

use useceleris_client::{Client, ClientOptions, CredentialReason};
use useceleris_server::{
    ChannelScope, Claims, Replay, SegmentClaim, SegmentPermissions, credential_provider,
};

let provider = credential_provider(signer, |request| async move {
    let mut claims = Claims {
        reference: Some("worker-1".to_owned()),
        ..Claims::new(
            ChannelScope::Restricted(vec![request.channel_reference]),
            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("room-42")?;

channel.connect().await?;

Your claims function runs freshly on every attempt and is the sole authority over scope. The provider copies nothing from the request into the claims automatically. Trusted worker code chooses this example's channel. In an HTTP credential endpoint, authorize the requested channel against the verified user's access before you sign it. The 30-second replay cap is an example policy, not a retention promise.

Invalid claims from the provider reach the client as its generic CelerisError::Transport, which never repeats what went wrong. To check a claims function, sign its result directly with signer.sign, which returns a Configuration error that names the claim and the rule.

A fresh signature does not guarantee a particular credential lifetime, and it does not revoke an existing connection. Keep signed credentials confidential and pass them unchanged.

Errors

Invalid options and claims return CelerisError::Configuration from the client crate. The message names each field that failed and the rule it broke, such as Invalid claims. channels: Must not repeat a channel reference.. The message never repeats your input, secrets or claims.

Returned byWhen
Signer::newclient_id is empty or contains a colon, CR or LF, or signing_secret is empty
Signer::signThe claims are invalid, or clock returned a time outside 1 to 253402300799999 Unix milliseconds

An error returned by your own claims function propagates unchanged from the provider. Through connect it appears as CelerisError::Transport, like any provider failure.

We use Google cookies for analytics and for advertising measurement, only if you allow them. Until you choose, Google sets no cookies. Refer to our Cookie Policy.