mod api;
mod jwks;
mod key;
use std::collections::BTreeMap;
use std::fmt;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::Serialize;
use serde_json::value::RawValue;
pub use api::{ApiClaims, ApiTokenSource, api};
pub use jwks::jwks;
pub use key::Key;
use crate::{FilterNode, SubscribeOptionOverride};
#[derive(Debug, Clone)]
pub struct TokenError(String);
impl TokenError {
pub(crate) fn new(message: impl Into<String>) -> Self {
Self(message.into())
}
}
impl fmt::Display for TokenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for TokenError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Expiry {
At(SystemTime),
Never,
}
impl Expiry {
#[must_use]
pub fn after(d: Duration) -> Self {
SystemTime::now()
.checked_add(d)
.map_or(Self::Never, Self::At)
}
}
pub(crate) fn unix(t: SystemTime) -> Result<i64, TokenError> {
let secs = t
.duration_since(UNIX_EPOCH)
.map_err(|_| TokenError::new("a time before 1970"))?
.as_secs();
i64::try_from(secs).map_err(|_| TokenError::new("a time too far ahead"))
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ConnectionClaims {
pub user: String,
pub expiry: Expiry,
pub connection_expiry: Option<Expiry>,
pub issued_at: Option<SystemTime>,
pub id: String,
pub audience: String,
pub issuer: String,
pub info: Option<Box<RawValue>>,
pub b64info: String,
pub channels: Vec<String>,
pub subs: BTreeMap<String, SubscribeOptions>,
pub meta: Option<Box<RawValue>>,
pub caps: Vec<ChannelsCapability>,
pub labels: BTreeMap<String, String>,
pub profile: String,
}
impl ConnectionClaims {
#[must_use]
pub fn new(user: impl Into<String>, expiry: Expiry) -> Self {
Self {
user: user.into(),
expiry,
connection_expiry: None,
issued_at: None,
id: String::new(),
audience: String::new(),
issuer: String::new(),
info: None,
b64info: String::new(),
channels: Vec::new(),
subs: BTreeMap::new(),
meta: None,
caps: Vec::new(),
labels: BTreeMap::new(),
profile: String::new(),
}
}
#[must_use]
pub fn connection_expiry(mut self, expiry: Expiry) -> Self {
self.connection_expiry = Some(expiry);
self
}
#[must_use]
pub fn issued_at(mut self, t: SystemTime) -> Self {
self.issued_at = Some(t);
self
}
#[must_use]
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = id.into();
self
}
#[must_use]
pub fn audience(mut self, audience: impl Into<String>) -> Self {
self.audience = audience.into();
self
}
#[must_use]
pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
self.issuer = issuer.into();
self
}
#[must_use]
pub fn info(mut self, info: Box<RawValue>) -> Self {
self.info = Some(info);
self
}
#[must_use]
pub fn b64info(mut self, b64info: impl Into<String>) -> Self {
self.b64info = b64info.into();
self
}
#[must_use]
pub fn channels(mut self, channels: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.channels = channels.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn subs(
mut self,
subs: impl IntoIterator<Item = (impl Into<String>, SubscribeOptions)>,
) -> Self {
self.subs = subs.into_iter().map(|(k, v)| (k.into(), v)).collect();
self
}
#[must_use]
pub fn meta(mut self, meta: Box<RawValue>) -> Self {
self.meta = Some(meta);
self
}
#[must_use]
pub fn caps(mut self, caps: impl IntoIterator<Item = ChannelsCapability>) -> Self {
self.caps = caps.into_iter().collect();
self
}
#[must_use]
pub fn labels(
mut self,
labels: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Self {
self.labels = labels
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
self
}
#[must_use]
pub fn profile(mut self, profile: impl Into<String>) -> Self {
self.profile = profile.into();
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
#[non_exhaustive]
pub struct SubscribeOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub info: Option<Box<RawValue>>,
#[serde(skip_serializing_if = "String::is_empty")]
pub b64info: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Box<RawValue>>,
#[serde(skip_serializing_if = "String::is_empty")]
pub b64data: String,
#[serde(rename = "override", skip_serializing_if = "Option::is_none")]
pub r#override: Option<SubscribeOptionOverride>,
#[serde(skip_serializing_if = "Option::is_none")]
pub server_tags_filter: Option<FilterNode>,
}
impl SubscribeOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn info(mut self, info: Box<RawValue>) -> Self {
self.info = Some(info);
self
}
#[must_use]
pub fn data(mut self, data: Box<RawValue>) -> Self {
self.data = Some(data);
self
}
#[must_use]
pub fn r#override(mut self, o: SubscribeOptionOverride) -> Self {
self.r#override = Some(o);
self
}
#[must_use]
pub fn server_tags_filter(mut self, filter: FilterNode) -> Self {
self.server_tags_filter = Some(filter);
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
#[non_exhaustive]
pub struct ChannelsCapability {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub channels: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub allow: Vec<String>,
#[serde(rename = "match", skip_serializing_if = "String::is_empty")]
pub r#match: String,
}
impl ChannelsCapability {
#[must_use]
pub fn new(
channels: impl IntoIterator<Item = impl Into<String>>,
allow: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
Self {
channels: channels.into_iter().map(Into::into).collect(),
allow: allow.into_iter().map(Into::into).collect(),
r#match: String::new(),
}
}
#[must_use]
pub fn r#match(mut self, m: impl Into<String>) -> Self {
self.r#match = m.into();
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SubscriptionClaims {
pub user: String,
pub channel: String,
pub expiry: Expiry,
pub subscription_expiry: Option<Expiry>,
pub issued_at: Option<SystemTime>,
pub id: String,
pub audience: String,
pub issuer: String,
pub info: Option<Box<RawValue>>,
pub b64info: String,
pub data: Option<Box<RawValue>>,
pub b64data: String,
pub r#override: Option<SubscribeOptionOverride>,
pub allow: Vec<String>,
pub server_tags_filter: Option<FilterNode>,
}
impl SubscriptionClaims {
#[must_use]
pub fn new(user: impl Into<String>, channel: impl Into<String>, expiry: Expiry) -> Self {
Self {
user: user.into(),
channel: channel.into(),
expiry,
subscription_expiry: None,
issued_at: None,
id: String::new(),
audience: String::new(),
issuer: String::new(),
info: None,
b64info: String::new(),
data: None,
b64data: String::new(),
r#override: None,
allow: Vec::new(),
server_tags_filter: None,
}
}
#[must_use]
pub fn subscription_expiry(mut self, expiry: Expiry) -> Self {
self.subscription_expiry = Some(expiry);
self
}
#[must_use]
pub fn issued_at(mut self, t: SystemTime) -> Self {
self.issued_at = Some(t);
self
}
#[must_use]
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = id.into();
self
}
#[must_use]
pub fn audience(mut self, audience: impl Into<String>) -> Self {
self.audience = audience.into();
self
}
#[must_use]
pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
self.issuer = issuer.into();
self
}
#[must_use]
pub fn info(mut self, info: Box<RawValue>) -> Self {
self.info = Some(info);
self
}
#[must_use]
pub fn data(mut self, data: Box<RawValue>) -> Self {
self.data = Some(data);
self
}
#[must_use]
pub fn r#override(mut self, o: SubscribeOptionOverride) -> Self {
self.r#override = Some(o);
self
}
#[must_use]
pub fn allow(mut self, allow: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.allow = allow.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn server_tags_filter(mut self, filter: FilterNode) -> Self {
self.server_tags_filter = Some(filter);
self
}
}
#[derive(Serialize)]
struct Registered<'a> {
sub: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
exp: Option<i64>,
iat: i64,
#[serde(skip_serializing_if = "empty_str")]
jti: &'a str,
#[serde(skip_serializing_if = "empty_str")]
aud: &'a str,
#[serde(skip_serializing_if = "empty_str")]
iss: &'a str,
}
impl<'a> Registered<'a> {
fn new(
sub: &'a str,
expiry: Expiry,
issued_at: Option<SystemTime>,
jti: &'a str,
aud: &'a str,
iss: &'a str,
) -> Result<Self, TokenError> {
Ok(Self {
sub,
exp: match expiry {
Expiry::At(t) => Some(unix(t)?),
Expiry::Never => None,
},
iat: unix(issued_at.unwrap_or_else(SystemTime::now))?,
jti,
aud,
iss,
})
}
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn empty_str(s: &&str) -> bool {
s.is_empty()
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn empty_slice<T>(s: &&[T]) -> bool {
s.is_empty()
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn empty_map<K, V>(m: &&BTreeMap<K, V>) -> bool {
m.is_empty()
}
fn expire_at(e: Option<Expiry>) -> Result<Option<i64>, TokenError> {
Ok(match e {
None => None,
Some(Expiry::Never) => Some(0),
Some(Expiry::At(t)) => Some(unix(t)?),
})
}
#[derive(Serialize)]
struct ConnectionWire<'a> {
#[serde(flatten)]
registered: Registered<'a>,
#[serde(skip_serializing_if = "Option::is_none")]
expire_at: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
info: Option<&'a RawValue>,
#[serde(skip_serializing_if = "empty_str")]
b64info: &'a str,
#[serde(skip_serializing_if = "empty_slice")]
channels: &'a [String],
#[serde(skip_serializing_if = "empty_map")]
subs: &'a BTreeMap<String, SubscribeOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
meta: Option<&'a RawValue>,
#[serde(skip_serializing_if = "empty_slice")]
caps: &'a [ChannelsCapability],
#[serde(skip_serializing_if = "empty_map")]
labels: &'a BTreeMap<String, String>,
#[serde(skip_serializing_if = "empty_str")]
profile: &'a str,
}
#[derive(Serialize)]
struct SubscriptionWire<'a> {
#[serde(flatten)]
registered: Registered<'a>,
channel: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
expire_at: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
info: Option<&'a RawValue>,
#[serde(skip_serializing_if = "empty_str")]
b64info: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
data: Option<&'a RawValue>,
#[serde(skip_serializing_if = "empty_str")]
b64data: &'a str,
#[serde(rename = "override", skip_serializing_if = "Option::is_none")]
r#override: Option<&'a SubscribeOptionOverride>,
#[serde(skip_serializing_if = "empty_slice")]
allow: &'a [String],
#[serde(skip_serializing_if = "Option::is_none")]
server_tags_filter: Option<&'a FilterNode>,
}
pub fn connection(key: &Key, c: &ConnectionClaims) -> Result<String, TokenError> {
if !c.channels.is_empty() && !c.subs.is_empty() {
return Err(TokenError::new(
"set channels or subs, not both: Centrifugo ignores channels when subs is set",
));
}
sign(
key,
&ConnectionWire {
registered: Registered::new(
&c.user,
c.expiry,
c.issued_at,
&c.id,
&c.audience,
&c.issuer,
)?,
expire_at: expire_at(c.connection_expiry)?,
info: c.info.as_deref(),
b64info: &c.b64info,
channels: &c.channels,
subs: &c.subs,
meta: c.meta.as_deref(),
caps: &c.caps,
labels: &c.labels,
profile: &c.profile,
},
)
}
pub fn subscription(key: &Key, c: &SubscriptionClaims) -> Result<String, TokenError> {
if c.channel.is_empty() {
return Err(TokenError::new("a subscription token without a channel"));
}
sign(
key,
&SubscriptionWire {
registered: Registered::new(
&c.user,
c.expiry,
c.issued_at,
&c.id,
&c.audience,
&c.issuer,
)?,
channel: &c.channel,
expire_at: expire_at(c.subscription_expiry)?,
info: c.info.as_deref(),
b64info: &c.b64info,
data: c.data.as_deref(),
b64data: &c.b64data,
r#override: c.r#override.as_ref(),
allow: &c.allow,
server_tags_filter: c.server_tags_filter.as_ref(),
},
)
}
fn sign(key: &Key, claims: &impl Serialize) -> Result<String, TokenError> {
#[derive(Serialize)]
struct Header<'a> {
alg: &'a str,
typ: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
kid: Option<&'a str>,
}
let header = serde_json::to_vec(&Header {
alg: key.algorithm(),
typ: "JWT",
kid: key.key_id(),
})
.map_err(|e| TokenError::new(e.to_string()))?;
let claims = serde_json::to_vec(claims).map_err(|e| TokenError::new(e.to_string()))?;
let mut signed = URL_SAFE_NO_PAD.encode(header);
signed.push('.');
signed.push_str(&URL_SAFE_NO_PAD.encode(claims));
let signature = key.sign(signed.as_bytes())?;
signed.push('.');
signed.push_str(&URL_SAFE_NO_PAD.encode(signature));
Ok(signed)
}
#[cfg(test)]
mod tests;