repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/appservice.rs | crates/core/src/appservice.rs | //! (De)serializable types for the [Matrix Application Service
//! API][appservice-api]. These types can be shared by application service and
//! server code.
//!
//! [appservice-api]: https://spec.matrix.org/latest/application-service-api/
use serde::{Deserialize, Serialize};
use url::Url;
pub mod event;
pub mod ping;
pub mod query;
pub mod third_party;
/// A namespace defined by an application service.
///
/// Used for [appservice registration](https://spec.matrix.org/latest/application-service-api/#registration).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Namespace {
/// Whether this application service has exclusive access to events within
/// this namespace.
pub exclusive: bool,
/// A regular expression defining which values this namespace includes.
pub regex: String,
}
impl Namespace {
/// Creates a new `Namespace` with the given exclusivity and regex pattern.
pub fn new(exclusive: bool, regex: String) -> Self {
Namespace { exclusive, regex }
}
}
/// Namespaces defined by an application service.
///
/// Used for [appservice registration](https://spec.matrix.org/latest/application-service-api/#registration).
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Namespaces {
/// Events which are sent from certain users.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub users: Vec<Namespace>,
/// Events which are sent in rooms with certain room aliases.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub aliases: Vec<Namespace>,
/// Events which are sent in rooms with certain room IDs.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rooms: Vec<Namespace>,
}
impl Namespaces {
/// Creates a new `Namespaces` instance with empty namespaces for `users`,
/// `aliases` and `rooms` (none of them are explicitly required)
pub fn new() -> Self {
Self::default()
}
}
/// Information required in the registration yaml file that a homeserver needs.
///
/// To create an instance of this type.
///
/// Used for [appservice registration](https://spec.matrix.org/latest/application-service-api/#registration).
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Registration {
/// A unique, user - defined ID of the application service which will never change.
pub id: String,
/// The URL for the application service.
///
/// Optionally set to `null` if no traffic is required.
pub url: Option<String>,
/// A unique token for application services to use to authenticate requests
/// to HomeServers.
pub as_token: String,
/// A unique token for HomeServers to use to authenticate requests to
/// application services.
pub hs_token: String,
/// The localpart of the user associated with the application service.
pub sender_localpart: String,
/// A list of users, aliases and rooms namespaces that the application
/// service controls.
pub namespaces: Namespaces,
/// Whether requests from masqueraded users are rate-limited.
///
/// The sender is excluded.
#[serde(skip_serializing_if = "Option::is_none")]
pub rate_limited: Option<bool>,
/// The external protocols which the application service provides (e.g.
/// IRC).
#[serde(skip_serializing_if = "Option::is_none")]
pub protocols: Option<Vec<String>>,
/// Whether the application service wants to receive ephemeral data.
///
/// Defaults to `false`.
#[serde(default)]
pub receive_ephemeral: bool,
/// Whether the application service wants to do device management, as part of MSC4190.
///
/// Defaults to `false`
#[serde(default, rename = "io.element.msc4190")]
pub device_management: bool,
}
impl Registration {
pub fn build_url(&self, path: &str) -> Result<Url, url::ParseError> {
let Some(url) = &self.url else {
return Err(url::ParseError::RelativeUrlWithoutBase);
};
let url = if path.starts_with('/') {
format!("{url}/_matrix{path}")
} else {
format!("{url}/_matrix/{path}")
};
Url::parse(&url)
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state.rs | crates/core/src/state.rs | use std::{
borrow::Borrow,
cmp::{Ordering, Reverse},
collections::{BinaryHeap, HashMap, HashSet},
hash::Hash,
sync::OnceLock,
};
use futures_util::{StreamExt, stream};
use tracing::{debug, info, instrument, trace, warn};
mod error;
pub use error::{StateError, StateResult};
pub mod event_auth;
pub mod events;
pub mod room_version;
// #[cfg(test)]
// mod tests;
pub use event_auth::{auth_check, auth_types_for_event, check_state_dependent_auth_rules};
pub use events::Event;
use crate::events::room::member::MembershipState;
use crate::events::room::power_levels::UserPowerLevel;
use crate::events::{StateEventType, TimelineEventType};
use crate::state::events::{
RoomCreateEvent, RoomMemberEvent, RoomPowerLevelsEvent, RoomPowerLevelsIntField,
power_levels::RoomPowerLevelsEventOptionExt,
};
use crate::{
EventId, OwnedEventId, OwnedUserId, UnixMillis,
room_version_rules::{AuthorizationRules, StateResolutionV2Rules},
utils::RoomIdExt,
};
/// A mapping of event type and state_key to some value `T`, usually an `EventId`.
///
/// This is the representation of what the Matrix specification calls a "room state" or a "state
/// map" during [state resolution].
///
/// [state resolution]: https://spec.matrix.org/latest/rooms/v2/#state-resolution
pub type StateMap<T> = HashMap<(StateEventType, String), T>;
pub type StateMapItem<T> = (TypeStateKey, T);
pub type TypeStateKey = (StateEventType, String);
/// Apply the [state resolution] algorithm introduced in room version 2 to resolve the state of a
/// room.
///
/// ## Arguments
///
/// * `auth_rules` - The authorization rules to apply for the version of the current room.
///
/// * `state_res_rules` - The state resolution rules to apply for the version of the current room.
///
/// * `state_maps` - The incoming states to resolve. Each `StateMap` represents a possible fork in
/// the state of a room.
///
/// * `auth_chains` - The list of full recursive sets of `auth_events` for each event in the
/// `state_maps`.
///
/// * `fetch_event` - Function to fetch an event in the room given its event ID.
///
/// * `fetch_conflicted_state_subgraph` - Function to fetch the conflicted state subgraph for the
/// given conflicted state set, for state resolution rules that use it. If it is called and
/// returns `None`, this function will return an error.
///
/// ## Invariants
///
/// The caller of `resolve` must ensure that all the events are from the same room.
///
/// ## Returns
///
/// The resolved room state.
///
/// [state resolution]: https://spec.matrix.org/latest/rooms/v2/#state-resolution
#[instrument(skip_all)]
pub async fn resolve<'a, MapsIter, Pdu, Fetch, Fut>(
auth_rules: &AuthorizationRules,
state_res_rules: StateResolutionV2Rules,
state_maps: impl IntoIterator<IntoIter = MapsIter>,
auth_chains: Vec<HashSet<OwnedEventId>>,
fetch_event: &Fetch,
fetch_conflicted_state_subgraph: impl Fn(
&StateMap<Vec<OwnedEventId>>,
) -> Option<HashSet<OwnedEventId>>,
) -> Result<StateMap<OwnedEventId>, StateError>
where
Fetch: Fn(OwnedEventId) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
Pdu::Id: Clone,
MapsIter: Iterator<Item = &'a StateMap<OwnedEventId>> + Clone,
{
info!("state resolution starting");
// Split the unconflicted state map and the conflicted state set.
let (unconflicted_state_map, conflicted_state_set) =
split_conflicted_state_set(state_maps.into_iter());
info!(count = unconflicted_state_map.len(), "unconflicted events");
trace!(map = ?unconflicted_state_map, "unconflicted events");
if conflicted_state_set.is_empty() {
info!("no conflicted state found");
return Ok(unconflicted_state_map);
}
info!(count = conflicted_state_set.len(), "conflicted events");
trace!(map = ?conflicted_state_set, "conflicted events");
// Since v12, fetch the conflicted state subgraph.
let conflicted_state_subgraph = if state_res_rules.consider_conflicted_state_subgraph {
let conflicted_state_subgraph = fetch_conflicted_state_subgraph(&conflicted_state_set)
.ok_or(StateError::FetchConflictedStateSubgraphFailed)?;
info!(
count = conflicted_state_subgraph.len(),
"events in conflicted state subgraph"
);
trace!(set = ?conflicted_state_subgraph, "conflicted state subgraph");
conflicted_state_subgraph
} else {
HashSet::new()
};
// The full conflicted set is the union of the conflicted state set and the auth difference,
// and since v12, the conflicted state subgraph.
let full_conflicted_set: HashSet<OwnedEventId> = stream::iter(
auth_difference(auth_chains)
.chain(conflicted_state_set.into_values().flatten())
.chain(conflicted_state_subgraph),
)
// Don't honor events we cannot "verify"
.filter_map(|id| async move {
if fetch_event(id.clone()).await.is_ok() {
Some(id)
} else {
None
}
})
.collect()
.await;
info!(count = full_conflicted_set.len(), "full conflicted set");
trace!(set = ?full_conflicted_set, "full conflicted set");
// 1. Select the set X of all power events that appear in the full conflicted set. For each such
// power event P, enlarge X by adding the events in the auth chain of P which also belong to
// the full conflicted set. Sort X into a list using the reverse topological power ordering.
let conflicted_power_events = stream::iter(&full_conflicted_set)
.filter(|&id| async move { is_power_event_id(id.borrow(), fetch_event).await })
.map(|id| id.to_owned())
.collect::<Vec<OwnedEventId>>()
.await;
let sorted_power_events = sort_power_events(
conflicted_power_events,
&full_conflicted_set,
auth_rules,
fetch_event,
)
.await?;
debug!(count = sorted_power_events.len(), "power events");
trace!(list = ?sorted_power_events, "sorted power events");
// 2. Apply the iterative auth checks algorithm, starting from the unconflicted state map, to
// the list of events from the previous step to get a partially resolved state.
// Since v12, begin the first phase of iterative auth checks with an empty state map.
let initial_state_map = if state_res_rules.begin_iterative_auth_check_with_empty_state_map {
HashMap::new()
} else {
unconflicted_state_map.clone()
};
let partially_resolved_state = iterative_auth_check(
auth_rules,
&sorted_power_events,
initial_state_map,
fetch_event,
)
.await?;
debug!(
count = partially_resolved_state.len(),
"resolved power events"
);
trace!(map = ?partially_resolved_state, "resolved power events");
// 3. Take all remaining events that weren’t picked in step 1 and order them by the mainline
// ordering based on the power level in the partially resolved state obtained in step 2.
let sorted_power_events_set = sorted_power_events.into_iter().collect::<HashSet<_>>();
let remaining_events = full_conflicted_set
.iter()
.filter(|id| !sorted_power_events_set.contains(*id))
.cloned()
.collect::<Vec<_>>();
debug!(count = remaining_events.len(), "events left to resolve");
trace!(list = ?remaining_events, "events left to resolve");
// This "epochs" power level event
let power_event = partially_resolved_state.get(&(StateEventType::RoomPowerLevels, "".into()));
debug!(event_id = ?power_event, "power event");
let sorted_remaining_events: Vec<_> =
mainline_sort(&remaining_events, power_event.cloned(), fetch_event).await?;
trace!(list = ?sorted_remaining_events, "events left, sorted");
// 4. Apply the iterative auth checks algorithm on the partial resolved state and the list of
// events from the previous step.
let mut resolved_state = iterative_auth_check(
auth_rules,
&sorted_remaining_events,
partially_resolved_state,
&fetch_event,
)
.await?;
// 5. Update the result by replacing any event with the event with the same key from the
// unconflicted state map, if such an event exists, to get the final resolved state.
resolved_state.extend(unconflicted_state_map);
info!("state resolution finished");
Ok(resolved_state)
}
/// Split the unconflicted state map and the conflicted state set.
///
/// Definition in the specification:
///
/// > If a given key _K_ is present in every _Si_ with the same value _V_ in each state map, then
/// > the pair (_K_, _V_) belongs to the unconflicted state map. Otherwise, _V_ belongs to the
/// > conflicted state set.
///
/// It means that, for a given (event type, state key) tuple, if all state maps have the same event
/// ID, it lands in the unconflicted state map, otherwise the event IDs land in the conflicted state
/// set.
///
/// ## Arguments
///
/// * `state_maps` - The incoming states to resolve. Each `StateMap` represents a possible fork in
/// the state of a room.
///
/// ## Returns
///
/// Returns an `(unconflicted_state_map, conflicted_state_set)` tuple.
fn split_conflicted_state_set<'a, Id>(
state_maps: impl Iterator<Item = &'a StateMap<Id>>,
) -> (StateMap<Id>, StateMap<Vec<Id>>)
where
Id: Clone + Eq + Hash + 'a,
{
let mut state_set_count = 0_usize;
let mut occurrences = HashMap::<_, HashMap<_, _>>::new();
let state_maps = state_maps.inspect(|_| state_set_count += 1);
for (k, v) in state_maps.flatten() {
occurrences
.entry(k)
.or_default()
.entry(v)
.and_modify(|x| *x += 1)
.or_insert(1);
}
let mut unconflicted_state_map = StateMap::new();
let mut conflicted_state_set = StateMap::new();
for (k, v) in occurrences {
for (id, occurrence_count) in v {
if occurrence_count == state_set_count {
unconflicted_state_map.insert((k.0.clone(), k.1.clone()), id.clone());
} else {
conflicted_state_set
.entry((k.0.clone(), k.1.clone()))
.and_modify(|x: &mut Vec<_>| x.push(id.clone()))
.or_insert(vec![id.clone()]);
}
}
}
(unconflicted_state_map, conflicted_state_set)
}
/// Get the auth difference for the given auth chains.
///
/// Definition in the specification:
///
/// > The auth difference is calculated by first calculating the full auth chain for each state
/// > _Si_, that is the union of the auth chains for each event in _Si_, and then taking every event
/// > that doesn’t appear in every auth chain. If _Ci_ is the full auth chain of _Si_, then the auth
/// > difference is ∪_Ci_ − ∩_Ci_.
///
/// ## Arguments
///
/// * `auth_chains` - The list of full recursive sets of `auth_events`.
///
/// ## Returns
///
/// Returns an iterator over all the event IDs that are not present in all the auth chains.
fn auth_difference<Id>(auth_chains: Vec<HashSet<Id>>) -> impl Iterator<Item = Id>
where
Id: Eq + Hash + Borrow<EventId>,
{
let num_sets = auth_chains.len();
let mut id_counts: HashMap<Id, usize> = HashMap::new();
for id in auth_chains.into_iter().flatten() {
*id_counts.entry(id).or_default() += 1;
}
id_counts
.into_iter()
.filter_map(move |(id, count)| (count < num_sets).then_some(id))
}
/// Enlarge the given list of conflicted power events by adding the events in their auth chain that
/// are in the full conflicted set, and sort it using reverse topological power ordering.
///
/// ## Arguments
///
/// * `conflicted_power_events` - The list of power events in the full conflicted set.
///
/// * `full_conflicted_set` - The full conflicted set.
///
/// * `rules` - The authorization rules for the current room version.
///
/// * `fetch_event` - Function to fetch an event in the room given its event ID.
///
/// ## Returns
///
/// Returns the ordered list of event IDs from earliest to latest.
#[instrument(skip_all)]
async fn sort_power_events<Pdu, Fetch, Fut>(
conflicted_power_events: Vec<OwnedEventId>,
full_conflicted_set: &HashSet<OwnedEventId>,
rules: &AuthorizationRules,
fetch_event: &Fetch,
) -> Result<Vec<OwnedEventId>, StateError>
where
Fetch: Fn(OwnedEventId) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
debug!("reverse topological sort of power events");
// A representation of the DAG, a map of event ID to its list of auth events that are in the
// full conflicted set.
let mut graph = HashMap::new();
// Fill the graph.
for event_id in conflicted_power_events {
add_event_and_auth_chain_to_graph(&mut graph, event_id, full_conflicted_set, fetch_event)
.await;
// TODO: if these functions are ever made async here
// is a good place to yield every once in a while so other
// tasks can make progress
}
// The map of event ID to the power level of the sender of the event.
let mut event_to_power_level = HashMap::new();
// We need to know the creator in case of missing power levels. Given that it's the same for all
// the events in the room, we will just load it for the first event and reuse it.
let creators_lock = OnceLock::new();
// Get the power level of the sender of each event in the graph.
for event_id in graph.keys() {
let sender_power_level =
power_level_for_sender(event_id.borrow(), rules, &creators_lock, fetch_event).await?;
debug!(
event_id = event_id.as_str(),
power_level = ?sender_power_level,
"found the power level of an event's sender",
);
event_to_power_level.insert(event_id.clone(), sender_power_level);
// TODO: if these functions are ever made async here
// is a good place to yield every once in a while so other
// tasks can make progress
}
reverse_topological_power_sort(&graph, |event_id| {
let event_id = event_id.to_owned();
let power_level = event_to_power_level.get(&event_id).cloned();
async move {
let power_level =
power_level.ok_or_else(|| StateError::NotFound(event_id.to_owned()))?;
let event = fetch_event(event_id).await?;
Ok((power_level, event.origin_server_ts()))
}
})
.await
}
/// Sorts the given event graph using reverse topological power ordering.
///
/// Definition in the specification:
///
/// > The reverse topological power ordering of a set of events is the lexicographically smallest
/// > topological ordering based on the DAG formed by auth events. The reverse topological power
/// > ordering is ordered from earliest event to latest. For comparing two topological orderings to
/// > determine which is the lexicographically smallest, the following comparison relation on events
/// > is used: for events x and y, x < y if
/// >
/// > 1. x’s sender has greater power level than y’s sender, when looking at their respective
/// > auth_events; or
/// > 2. the senders have the same power level, but x’s origin_server_ts is less than y’s
/// > origin_server_ts; or
/// > 3. the senders have the same power level and the events have the same origin_server_ts, but
/// > x’s event_id is less than y’s event_id.
/// >
/// > The reverse topological power ordering can be found by sorting the events using Kahn’s
/// > algorithm for topological sorting, and at each step selecting, among all the candidate
/// > vertices, the smallest vertex using the above comparison relation.
///
/// ## Arguments
///
/// * `graph` - The graph to sort. A map of event ID to its auth events that are in the full
/// conflicted set.
///
/// * `event_details_fn` - Function to obtain a (power level, origin_server_ts) of an event for
/// breaking ties.
///
/// ## Returns
///
/// Returns the ordered list of event IDs from earliest to latest.
#[instrument(skip_all)]
pub async fn reverse_topological_power_sort<F, Fut>(
graph: &HashMap<OwnedEventId, HashSet<OwnedEventId>>,
event_details_fn: F,
) -> StateResult<Vec<OwnedEventId>>
where
F: Fn(OwnedEventId) -> Fut,
Fut: Future<Output = StateResult<(UserPowerLevel, UnixMillis)>>,
{
#[derive(PartialEq, Eq)]
struct TieBreaker<'a, Id> {
power_level: UserPowerLevel,
origin_server_ts: UnixMillis,
event_id: &'a Id,
}
impl<Id> Ord for TieBreaker<'_, Id>
where
Id: Ord,
{
fn cmp(&self, other: &Self) -> Ordering {
// NOTE: the power level comparison is "backwards" intentionally.
other
.power_level
.cmp(&self.power_level)
.then(self.origin_server_ts.cmp(&other.origin_server_ts))
.then(self.event_id.cmp(other.event_id))
}
}
impl<Id> PartialOrd for TieBreaker<'_, Id>
where
Id: Ord,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
// We consider that the DAG is directed from most recent events to oldest events, so an event is
// an incoming edge to its auth events.
// Map of event to the list of events in its auth events.
let mut outgoing_edges_map = graph.clone();
// Map of event to the list of events that reference it in its auth events.
let mut incoming_edges_map: HashMap<_, HashSet<_>> = HashMap::new();
// Vec of events that have an outdegree of zero (no outgoing edges), i.e. the oldest events.
let mut zero_outdegrees = Vec::new();
// Populate the list of events with an outdegree of zero, and the map of incoming edges.
for (event_id, outgoing_edges) in graph {
if outgoing_edges.is_empty() {
let (power_level, origin_server_ts) = event_details_fn(event_id.to_owned()).await?;
// `Reverse` because `BinaryHeap` sorts largest -> smallest and we need
// smallest -> largest.
zero_outdegrees.push(Reverse(TieBreaker {
power_level,
origin_server_ts,
event_id,
}));
}
incoming_edges_map.entry(event_id.to_owned()).or_default();
for auth_event_id in outgoing_edges {
incoming_edges_map
.entry(auth_event_id.to_owned())
.or_default()
.insert(event_id);
}
}
// Use a BinaryHeap to keep the events with an outdegree of zero sorted.
let mut heap = BinaryHeap::from(zero_outdegrees);
let mut sorted = vec![];
// Apply Kahn's algorithm.
// https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
while let Some(Reverse(item)) = heap.pop() {
let event_id: &EventId = item.event_id.borrow();
for &parent_id in incoming_edges_map
.get(event_id)
.expect("event ID in heap should also be in incoming edges map")
{
let outgoing_edges = outgoing_edges_map
.get_mut(parent_id)
.expect("outgoing edges map should have a key for all event IDs");
outgoing_edges.remove(event_id);
// Push on the heap once all the outgoing edges have been removed.
if outgoing_edges.is_empty() {
let (power_level, origin_server_ts) =
event_details_fn(parent_id.to_owned()).await?;
heap.push(Reverse(TieBreaker {
power_level,
origin_server_ts,
event_id: parent_id,
}));
}
}
sorted.push(event_id.to_owned());
}
Ok(sorted)
}
/// Find the power level for the sender of the event of the given event ID or return a default value
/// of zero.
///
/// We find the most recent `m.room.power_levels` by walking backwards in the auth chain of the
/// event.
///
/// Do NOT use this anywhere but topological sort.
///
/// ## Arguments
///
/// * `event_id` - The event ID of the event to get the power level of the sender of.
///
/// * `rules` - The authorization rules for the current room version.
///
/// * `creator_lock` - A lock used to cache the user ID of the creator of the room. If it is empty
/// the creator will be fetched in the auth chain and used to populate the lock.
///
/// * `fetch_event` - Function to fetch an event in the room given its event ID.
///
/// ## Returns
///
/// Returns the power level of the sender of the event or an `Err(_)` if one of the auth events if
/// malformed.
async fn power_level_for_sender<Pdu, Fetch, Fut>(
event_id: &EventId,
rules: &AuthorizationRules,
creators_lock: &OnceLock<HashSet<OwnedUserId>>,
fetch_event: &Fetch,
) -> StateResult<UserPowerLevel>
where
Fetch: Fn(OwnedEventId) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
let event = fetch_event(event_id.to_owned()).await.ok();
let mut room_create_event = None;
let mut room_power_levels_event = None;
if let Some(event) = &event
&& rules.room_create_event_id_as_room_id
&& creators_lock.get().is_none()
{
// The m.room.create event is not in the auth events, we can get its ID via the room ID.
// room_create_event = event
// .room_id()
// .and_then(|room_id| room_id.room_create_event_id().ok())
// .and_then(|room_create_event_id| fetch_event(&room_create_event_id));
if let Ok(room_create_event_id) = event.room_id().room_create_event_id() {
room_create_event = fetch_event(room_create_event_id.to_owned()).await.ok();
}
}
for auth_event_id in event
.as_ref()
.map(|pdu| pdu.auth_events())
.into_iter()
.flatten()
{
let auth_event_id = auth_event_id.borrow();
if let Ok(auth_event) = fetch_event(auth_event_id.to_owned()).await {
if is_type_and_key(&auth_event, &TimelineEventType::RoomPowerLevels, "") {
room_power_levels_event = Some(RoomPowerLevelsEvent::new(auth_event));
} else if !rules.room_create_event_id_as_room_id
&& creators_lock.get().is_none()
&& is_type_and_key(&auth_event, &TimelineEventType::RoomCreate, "")
{
room_create_event = Some(auth_event);
}
if room_power_levels_event.is_some()
&& (rules.room_create_event_id_as_room_id
|| creators_lock.get().is_some()
|| room_create_event.is_some())
{
break;
}
}
}
// TODO: Use OnceLock::try_or_get_init when it is stabilized.
let creators = if let Some(creators) = creators_lock.get() {
Some(creators)
} else if let Some(room_create_event) = room_create_event {
let room_create_event = RoomCreateEvent::new(room_create_event);
let creators = room_create_event.creators()?;
Some(creators_lock.get_or_init(|| creators))
} else {
None
};
if let Some((event, creators)) = event.zip(creators) {
room_power_levels_event.user_power_level(event.sender(), creators, rules)
} else {
room_power_levels_event
.get_as_int_or_default(RoomPowerLevelsIntField::UsersDefault, rules)
.map(Into::into)
}
}
/// Perform the iterative auth checks to the given list of events.
///
/// Definition in the specification:
///
/// > The iterative auth checks algorithm takes as input an initial room state and a sorted list of
/// > state events, and constructs a new room state by iterating through the event list and applying
/// > the state event to the room state if the state event is allowed by the authorization rules. If
/// > the state event is not allowed by the authorization rules, then the event is ignored. If a
/// > (event_type, state_key) key that is required for checking the authorization rules is not
/// > present in the state, then the appropriate state event from the event’s auth_events is used if
/// > the auth event is not rejected.
///
/// ## Arguments
///
/// * `rules` - The authorization rules for the current room version.
///
/// * `events` - The sorted state events to apply to the `partial_state`.
///
/// * `state` - The current state that was partially resolved for the room.
///
/// * `fetch_event` - Function to fetch an event in the room given its event ID.
///
/// ## Returns
///
/// Returns the partially resolved state, or an `Err(_)` if one of the state events in the room has
/// an unexpected format.
async fn iterative_auth_check<Pdu, Fetch, Fut>(
rules: &AuthorizationRules,
events: &[OwnedEventId],
mut state: StateMap<OwnedEventId>,
fetch_event: &Fetch,
) -> StateResult<StateMap<OwnedEventId>>
where
Fetch: Fn(OwnedEventId) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
debug!("starting iterative auth checks");
trace!(list = ?events, "events to check");
for event_id in events {
let event_id: &EventId = event_id.borrow();
let event = fetch_event(event_id.to_owned()).await?;
let state_key = event.state_key().ok_or(StateError::MissingStateKey)?;
let mut auth_events = StateMap::new();
for auth_event_id in event.auth_events() {
let auth_event_id: &EventId = auth_event_id.borrow();
if let Ok(auth_event) = fetch_event(auth_event_id.to_owned()).await {
if !auth_event.rejected() {
auth_events.insert(
auth_event.event_type().with_state_key(
auth_event.state_key().ok_or(StateError::MissingStateKey)?,
),
auth_event,
);
}
} else {
warn!(event_id = %auth_event_id, "missing auth event");
}
}
// If the `m.room.create` event is not in the auth events, we need to add it, because it's
// always part of the state and required in the auth rules.
if rules.room_create_event_id_as_room_id
&& *event.event_type() != TimelineEventType::RoomCreate
{
// if let Some(room_create_event_id) = event
// .room_id()
// .and_then(|room_id| room_id.room_create_event_id().ok())
// {
// let room_create_event = fetch_event(&room_create_event_id).await?;
// auth_events.insert(
// (StateEventType::RoomCreate, String::new()),
// room_create_event,
// );
// } else {
// warn!("missing m.room.create event");
// }
if let Ok(room_create_event_id) = event.room_id().room_create_event_id() {
let room_create_event = fetch_event(room_create_event_id).await?;
auth_events.insert(
(StateEventType::RoomCreate, String::new()),
room_create_event,
);
} else {
warn!("missing m.room.create event");
}
}
let auth_types = match auth_types_for_event(
event.event_type(),
event.sender(),
Some(state_key),
event.content(),
rules,
) {
Ok(auth_types) => auth_types,
Err(error) => {
warn!("failed to get list of required auth events for malformed event: {error}");
continue;
}
};
for key in auth_types {
if let Some(auth_event_id) = state.get(&key) {
let auth_event_id: &EventId = auth_event_id.borrow();
if let Ok(auth_event) = fetch_event(auth_event_id.to_owned()).await {
if !auth_event.rejected() {
auth_events.insert(key.to_owned(), auth_event);
}
} else {
warn!(event_id = %auth_event_id, "missing auth event");
}
}
}
match check_state_dependent_auth_rules(rules, &event, &|ty, key| {
let pdu = auth_events
.get(&ty.with_state_key(&*key))
.map(|pdu| pdu.to_owned())
.ok_or_else(|| StateError::other("not found"));
async move { pdu }
})
.await
{
Ok(()) => {
// Add event to the partially resolved state.
state.insert(
event.event_type().with_state_key(state_key),
event_id.to_owned(),
);
}
Err(error) => {
// Don't add this event to the state.
warn!("event failed the authentication check: {error}");
}
}
// TODO: if these functions are ever made async here
// is a good place to yield every once in a while so other
// tasks can make progress
}
Ok(state)
}
/// Perform mainline ordering of the given events.
///
/// Definition in the spec:
///
/// > Given mainline positions calculated from P, the mainline ordering based on P of a set of
/// > events is the ordering, from smallest to largest, using the following comparison relation on
/// > events: for events x and y, x < y if
/// >
/// > 1. the mainline position of x is greater than the mainline position of y (i.e. the auth chain
/// > of x is based on an earlier event in the mainline than y); or
/// > 2. the mainline positions of the events are the same, but x’s origin_server_ts is less than
/// > y’s origin_server_ts; or
/// > 3. the mainline positions of the events are the same and the events have the same
/// > origin_server_ts, but x’s event_id is less than y’s event_id.
///
/// ## Arguments
///
/// * `events` - The list of event IDs to sort.
///
/// * `power_level` - The power level event in the current state.
///
/// * `fetch_event` - Function to fetch an event in the room given its event ID.
///
/// ## Returns
///
/// Returns the sorted list of event IDs, or an `Err(_)` if one the event in the room has an
/// unexpected format.
async fn mainline_sort<Pdu, Fetch, Fut>(
events: &[OwnedEventId],
mut power_level: Option<OwnedEventId>,
fetch_event: &Fetch,
) -> StateResult<Vec<OwnedEventId>>
where
Fetch: Fn(OwnedEventId) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
debug!("mainline sort of events");
// There are no events to sort, bail.
if events.is_empty() {
return Ok(vec![]);
}
// Populate the mainline of the power level.
let mut mainline = vec![];
while let Some(power_level_event_id) = power_level {
mainline.push(power_level_event_id.to_owned());
let power_level_event = fetch_event(power_level_event_id.to_owned()).await?;
power_level = None;
for auth_event_id in power_level_event.auth_events() {
let auth_event_id: &EventId = auth_event_id.borrow();
let auth_event = fetch_event(auth_event_id.to_owned()).await?;
if is_type_and_key(&auth_event, &TimelineEventType::RoomPowerLevels, "") {
power_level = Some(auth_event_id.to_owned());
break;
}
}
// TODO: if these functions are ever made async here
// is a good place to yield every once in a while so other
// tasks can make progress
}
let mainline_map = mainline
.iter()
.rev()
.enumerate()
.map(|(idx, event_id)| ((*event_id).clone(), idx))
.collect::<HashMap<_, _>>();
let mut order_map = HashMap::new();
for event_id in events.iter() {
if let Ok(event) = fetch_event(event_id.to_owned()).await
&& let Ok(position) = mainline_position(&event, &mainline_map, &fetch_event).await
{
order_map.insert(
event_id.to_owned(),
(
position,
fetch_event(event_id.to_owned()).await.map(|event| event.origin_server_ts()).ok(),
event_id.to_owned(),
),
);
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | true |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/media.rs | crates/core/src/media.rs | /// Endpoints for the media repository.
mod content;
use std::time::Duration;
pub use content::*;
use reqwest::Url;
use salvo::oapi::{ToParameters, ToSchema};
use serde::{Deserialize, Serialize};
use crate::{
OwnedMxcUri, OwnedServerName, PrivOwnedStr, ServerName, UnixMillis,
sending::{SendRequest, SendResult},
serde::StringEnum,
};
/// The desired resizing method.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Default, StringEnum, Clone)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResizeMethod {
/// Crop the original to produce the requested image dimensions.
Crop,
#[default]
/// Maintain the original aspect ratio of the source image.
Scale,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
/// The default duration that the client should be willing to wait to start
/// receiving data.
pub(crate) fn default_download_timeout() -> Duration {
Duration::from_secs(20)
}
/// Whether the given duration is the default duration that the client should be
/// willing to wait to start receiving data.
pub(crate) fn is_default_download_timeout(timeout: &Duration) -> bool {
timeout.as_secs() == 20
}
// /// `POST /_matrix/media/*/create`
// ///
// /// Create an MXC URI without content.
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixmediav1create
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/media/unstable/fi.mau.msc2246/create",
// 1.7 => "/_matrix/media/v1/create",
// }
// };
/// Response type for the `create_mxc_uri` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct CreateMxcUriResBody {
/// The MXC URI for the about to be uploaded content.
pub content_uri: OwnedMxcUri,
/// The time at which the URI will expire if an upload has not been started.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unused_expires_at: Option<UnixMillis>,
}
// impl CreateMxcUriResBody {
// /// Creates a new `Response` with the given MXC URI.
// pub fn new(content_uri: OwnedMxcUri) -> Self {
// Self {
// content_uri,
// unused_expires_at: None,
// }
// }
// }
// /// `GET /_matrix/media/*/config`
// ///
// /// Gets the config for the media repository.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3config
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/media/r0/config",
// 1.1 => "/_matrix/media/v3/config",
// }
// };
/// Response type for the `get_media_config` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct ConfigResBody {
/// Maximum size of upload in bytes.
#[serde(rename = "m.upload.size")]
pub upload_size: u64,
}
impl ConfigResBody {
/// Creates a new `Response` with the given maximum upload size.
pub fn new(upload_size: u64) -> Self {
Self { upload_size }
}
}
// /// `GET /_matrix/media/*/preview_url`
// ///
// /// Get a preview for a URL.
// /// `/v3/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3preview_url
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: true,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/media/r0/preview_url",
// 1.1 => "/_matrix/media/v3/preview_url",
// }
// };
// /// Request type for the `get_media_preview` endpoint.
// pub struct MediaPreviewReqBody {
// /// URL to get a preview of.
// #[salvo(parameter(parameter_in = Query))]
// pub url: String,
// /// Preferred point in time (in milliseconds) to return a preview for.
// #[salvo(parameter(parameter_in = Query))]
// pub ts: UnixMillis,
// }
// /// Response type for the `get_media_preview` endpoint.
// #[derive(ToSchema,Serialize, Debug)]
// pub struct MediaPreviewResBody {
// /// OpenGraph-like data for the URL.
// ///
// /// Differences from OpenGraph: the image size in bytes is added to the
// `matrix:image:size` /// field, and `og:image` returns the MXC URI to the
// image, if any. #[salvo(schema(value_type = Object, additional_properties
// = true))] pub data: Option<Box<RawJsonValue>>,
// }
// impl MediaPreviewResBody {
// /// Creates an empty `Response`.
// pub fn new() -> Self {
// Self { data: None }
// }
// /// Creates a new `Response` with the given OpenGraph data (in a
// /// `serde_json::value::RawValue`).
// pub fn from_raw_value(data: Box<RawJsonValue>) -> Self {
// Self { data: Some(data) }
// }
// /// Creates a new `Response` with the given OpenGraph data (in any kind
// of serializable /// object).
// pub fn from_serialize<T: Serialize>(data: &T) -> serde_json::Result<Self>
// { Ok(Self {
// data: Some(to_raw_json_value(data)?),
// })
// }
// }
pub fn thumbnail_request(
origin: &str,
server: &ServerName,
args: ThumbnailReqArgs,
) -> SendResult<SendRequest> {
let mut url = Url::parse(&format!(
"{origin}/_matrix/media/v3/thumbnail/{server}/{}",
args.media_id
))?;
{
let mut query = url.query_pairs_mut();
query.append_pair("width", &args.width.to_string());
query.append_pair("height", &args.height.to_string());
query.append_pair("allow_remote", &args.allow_remote.to_string());
query.append_pair("timeout_ms", &args.timeout_ms.as_millis().to_string());
query.append_pair("allow_redirect", &args.allow_redirect.to_string());
}
Ok(crate::sending::get(url))
}
/// Request type for the `get_content_thumbnail` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct ThumbnailReqArgs {
/// The server name from the mxc:// URI (the authoritory component).
#[salvo(parameter(parameter_in = Path))]
pub server_name: OwnedServerName,
/// The media ID from the mxc:// URI (the path component).
#[salvo(parameter(parameter_in = Path))]
pub media_id: String,
/// The desired resizing method.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub method: Option<ResizeMethod>,
/// The *desired* width of the thumbnail.
///
/// The actual thumbnail may not match the size specified.
#[salvo(parameter(parameter_in = Query))]
pub width: u32,
/// The *desired* height of the thumbnail.
///
/// The actual thumbnail may not match the size specified.
#[salvo(parameter(parameter_in = Query))]
pub height: u32,
/// Whether to fetch media deemed remote.
///
/// Used to prevent routing loops. Defaults to `true`.
#[salvo(parameter(parameter_in = Query))]
#[serde(
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
pub allow_remote: bool,
/// The maximum duration that the client is willing to wait to start
/// receiving data, in the case that the content has not yet been
/// uploaded.
///
/// The default value is 20 seconds.
#[salvo(parameter(parameter_in = Query))]
#[serde(
with = "crate::serde::duration::ms",
default = "crate::client::media::default_download_timeout",
skip_serializing_if = "crate::media::is_default_download_timeout"
)]
pub timeout_ms: Duration,
/// Whether the server may return a 307 or 308 redirect response that points
/// at the relevant media content.
///
/// Unless explicitly set to `true`, the server must return the media
/// content itself.
#[salvo(parameter(parameter_in = Query))]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub allow_redirect: bool,
}
// /// Response type for the `get_content_thumbnail` endpoint.
// #[derive(ToSchema, Serialize, Debug)]
// pub struct ThumbnailResBody {
// /// A thumbnail of the requested content.
// #[palpo_api(raw_body)]
// pub file: Vec<u8>,
// /// The content type of the thumbnail.
// #[palpo_api(header = CONTENT_TYPE)]
// pub content_type: Option<String>,
// /// The value of the `Cross-Origin-Resource-Policy` HTTP header.
// ///
// /// See [MDN] for the syntax.
// ///
// /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy#syntax
// #[palpo_api(header = CROSS_ORIGIN_RESOURCE_POLICY)]
// pub cross_origin_resource_policy: Option<String>,
// }
// impl ThumbnailResBody {
// /// Creates a new `Response` with the given thumbnail.
// ///
// /// The Cross-Origin Resource Policy defaults to `cross-origin`.
// pub fn new(file: Vec<u8>) -> Self {
// file,
// content_type: None,
// cross_origin_resource_policy: Some("cross-origin".to_owned()),
// }
// Self {
// }
// }
// #[cfg(test)]
// mod tests {
// use crate::RawJsonValue;
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, value::to_raw_value
// as to_raw_json_value};
// // Since BTreeMap<String, Box<RawJsonValue>> deserialization doesn't seem
// to // work, test that Option<RawJsonValue> works
// #[test]
// fn raw_json_deserialize() {
// type OptRawJson = Option<Box<RawJsonValue>>;
// assert_matches!(from_json_value::<OptRawJson>(json!(null)).unwrap(),
// None); from_json_value::<OptRawJson>(json!("test")).unwrap().
// unwrap(); from_json_value::<OptRawJson>(json!({ "a": "b"
// })).unwrap().unwrap(); }
// // For completeness sake, make sure serialization works too
// #[test]
// fn raw_json_serialize() {
// to_raw_json_value(&json!(null)).unwrap();
// to_raw_json_value(&json!("string")).unwrap();
// to_raw_json_value(&json!({})).unwrap();
// to_raw_json_value(&json!({ "a": "b" })).unwrap();
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/test_utils.rs | crates/core/src/test_utils.rs | use std::{
borrow::Borrow,
collections::{BTreeMap, HashMap, HashSet},
sync::{
Arc,
atomic::{AtomicU64, Ordering::SeqCst},
},
};
use serde_json::{json, value::to_raw_value as to_raw_json_value};
pub(crate) use self::event::PduEvent;
use crate::serde::RawJsonValue;
use crate::{
EventId, MatrixError, OwnedEventId, RoomId, RoomVersionId, UnixMillis, UserId, event_id,
events::{
TimelineEventType,
pdu::{EventHash, Pdu, RoomV3Pdu},
room::{
join_rule::{JoinRule, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent},
},
},
room_id,
state::{Event, EventTypeExt, StateMap, auth_types_for_event},
user_id,
};
static SERVER_TIMESTAMP: AtomicU64 = AtomicU64::new(0);
pub(crate) fn do_check(events: &[Arc<PduEvent>], edges: Vec<Vec<OwnedEventId>>, expected_state_ids: Vec<OwnedEventId>) {
// To activate logging use `RUST_LOG=debug cargo t`
let init_events = INITIAL_EVENTS();
let mut store = TestStore(
init_events
.values()
.chain(events)
.map(|ev| (ev.event_id().to_owned(), ev.clone()))
.collect(),
);
// This will be lexi_topo_sorted for resolution
let mut graph = HashMap::new();
// This is the same as in `resolve` event_id -> OriginalStateEvent
let mut fake_event_map = HashMap::new();
// Create the DB of events that led up to this point
// TODO maybe clean up some of these clones it is just tests but...
for ev in init_events.values().chain(events) {
graph.insert(ev.event_id().to_owned(), HashSet::new());
fake_event_map.insert(ev.event_id().to_owned(), ev.clone());
}
for pair in INITIAL_EDGES().windows(2) {
if let [a, b] = &pair {
graph.entry(a.to_owned()).or_insert_with(HashSet::new).insert(b.clone());
}
}
for edge_list in edges {
for pair in edge_list.windows(2) {
if let [a, b] = &pair {
graph.entry(a.to_owned()).or_insert_with(HashSet::new).insert(b.clone());
}
}
}
// event_id -> PduEvent
let mut event_map: HashMap<OwnedEventId, Arc<PduEvent>> = HashMap::new();
// event_id -> StateMap<OwnedEventId>
let mut state_at_event: HashMap<OwnedEventId, StateMap<OwnedEventId>> = HashMap::new();
// Resolve the current state and add it to the state_at_event map then continue
// on in "time"
for node in crate::state::lexicographical_topological_sort(&graph, |_id| Ok((0, UnixMillis(0)))).unwrap() {
let fake_event = fake_event_map.get(&node).unwrap();
let event_id = fake_event.event_id().to_owned();
let prev_events = graph.get(&node).unwrap();
let state_before: StateMap<OwnedEventId> = if prev_events.is_empty() {
HashMap::new()
} else if prev_events.len() == 1 {
state_at_event.get(prev_events.iter().next().unwrap()).unwrap().clone()
} else {
let state_sets = prev_events
.iter()
.filter_map(|k| state_at_event.get(k))
.collect::<Vec<_>>();
info!(
"{:#?}",
state_sets
.iter()
.map(|map| map
.iter()
.map(|((ty, key), id)| format!("(({ty}{key:?}), {id})"))
.collect::<Vec<_>>())
.collect::<Vec<_>>()
);
let auth_chain_sets = state_sets
.iter()
.map(|map| {
store
.auth_event_ids(room_id(), map.values().cloned().collect())
.unwrap()
})
.collect();
let resolved = crate::state::resolve(&RoomVersionId::V6, state_sets, auth_chain_sets, |id| {
event_map.get(id).map(Arc::clone)
});
match resolved {
Ok(state) => state,
Err(e) => panic!("resolution for {node} failed: {e}"),
}
};
let mut state_after = state_before.clone();
let ty = fake_event.event_type();
let key = fake_event.state_key().unwrap();
state_after.insert(ty.with_state_key(key), event_id.to_owned());
let auth_types = auth_types_for_event(
fake_event.event_type(),
fake_event.sender(),
fake_event.state_key(),
fake_event.content(),
)
.unwrap();
let mut auth_events = vec![];
for key in auth_types {
if state_before.contains_key(&key) {
auth_events.push(state_before[&key].clone());
}
}
// TODO The event is just remade, adding the auth_events and prev_events here
// the `to_pdu_event` was split into `init` and the fn below, could be better
let e = fake_event;
let ev_id = e.event_id();
let event = to_pdu_event(
e.event_id().as_str(),
e.sender(),
e.event_type().clone(),
e.state_key(),
e.content().to_owned(),
&auth_events,
&prev_events.iter().cloned().collect::<Vec<_>>(),
);
// We have to update our store, an actual user of this lib would
// be giving us state from a DB.
store.0.insert(ev_id.to_owned(), event.clone());
state_at_event.insert(node, state_after);
event_map.insert(event_id.to_owned(), Arc::clone(store.0.get(ev_id).unwrap()));
}
let mut expected_state = StateMap::new();
for node in expected_state_ids {
let ev = event_map.get(&node).unwrap_or_else(|| {
panic!(
"{node} not found in {:?}",
event_map.keys().map(ToString::to_string).collect::<Vec<_>>()
)
});
let key = ev.event_type().with_state_key(ev.state_key().unwrap());
expected_state.insert(key, node);
}
let start_state = state_at_event.get(event_id!("$START:foo")).unwrap();
let end_state = state_at_event
.get(event_id!("$END:foo"))
.unwrap()
.iter()
.filter(|(k, v)| {
expected_state.contains_key(k)
|| start_state.get(k) != Some(*v)
// Filter out the dummy messages events.
// These act as points in time where there should be a known state to
// test against.
&& **k != ("m.room.message".into(), "dummy".to_owned())
})
.map(|(k, v)| (k.clone(), v.clone()))
.collect::<StateMap<OwnedEventId>>();
assert_eq!(expected_state, end_state);
}
#[allow(clippy::exhaustive_structs)]
pub(crate) struct TestStore<E: Event>(pub(crate) HashMap<OwnedEventId, Arc<E>>);
impl<E: Event> TestStore<E> {
pub(crate) fn get_event(&self, _: &RoomId, event_id: &EventId) -> Result<Arc<E>, MatrixError> {
self.0
.get(event_id)
.map(Arc::clone)
.ok_or_else(|| MatrixError::not_found(format!("{event_id} not found")))
}
/// Returns a Vec of the related auth events to the given `event`.
pub(crate) fn auth_event_ids(
&self,
room_id: &RoomId,
event_ids: Vec<E::Id>,
) -> Result<HashSet<E::Id>, MatrixError> {
let mut result = HashSet::new();
let mut stack = event_ids;
// DFS for auth event chain
while let Some(ev_id) = stack.pop() {
if result.contains(&ev_id) {
continue;
}
result.insert(ev_id.clone());
let event = self.get_event(room_id, ev_id.borrow())?;
stack.extend(event.auth_events().map(ToOwned::to_owned));
}
Ok(result)
}
}
// A StateStore implementation for testing
#[allow(clippy::type_complexity)]
impl TestStore<PduEvent> {
pub(crate) fn set_up(&mut self) -> (StateMap<OwnedEventId>, StateMap<OwnedEventId>, StateMap<OwnedEventId>) {
let create_event = to_pdu_event::<&EventId>(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&json!({ "creator": alice() })).unwrap(),
&[],
&[],
);
let cre = create_event.event_id().to_owned();
self.0.insert(cre.clone(), Arc::clone(&create_event));
let alice_mem = to_pdu_event(
"IMA",
alice(),
TimelineEventType::RoomMember,
Some(alice().as_str()),
member_content_join(),
&[cre.clone()],
&[cre.clone()],
);
self.0.insert(alice_mem.event_id().to_owned(), Arc::clone(&alice_mem));
let join_rules = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Public)).unwrap(),
&[cre.clone(), alice_mem.event_id().to_owned()],
&[alice_mem.event_id().to_owned()],
);
self.0.insert(join_rules.event_id().to_owned(), join_rules.clone());
// Bob and Charlie join at the same time, so there is a fork
// this will be represented in the state_sets when we resolve
let bob_mem = to_pdu_event(
"IMB",
bob(),
TimelineEventType::RoomMember,
Some(bob().as_str()),
member_content_join(),
&[cre.clone(), join_rules.event_id().to_owned()],
&[join_rules.event_id().to_owned()],
);
self.0.insert(bob_mem.event_id().to_owned(), bob_mem.clone());
let charlie_mem = to_pdu_event(
"IMC",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&[cre, join_rules.event_id().to_owned()],
&[join_rules.event_id().to_owned()],
);
self.0.insert(charlie_mem.event_id().to_owned(), charlie_mem.clone());
let state_at_bob = [&create_event, &alice_mem, &join_rules, &bob_mem]
.iter()
.map(|e| {
(
e.event_type().with_state_key(e.state_key().unwrap()),
e.event_id().to_owned(),
)
})
.collect::<StateMap<_>>();
let state_at_charlie = [&create_event, &alice_mem, &join_rules, &charlie_mem]
.iter()
.map(|e| {
(
e.event_type().with_state_key(e.state_key().unwrap()),
e.event_id().to_owned(),
)
})
.collect::<StateMap<_>>();
let expected = [&create_event, &alice_mem, &join_rules, &bob_mem, &charlie_mem]
.iter()
.map(|e| {
(
e.event_type().with_state_key(e.state_key().unwrap()),
e.event_id().to_owned(),
)
})
.collect::<StateMap<_>>();
(state_at_bob, state_at_charlie, expected)
}
}
pub(crate) fn event_id(id: &str) -> OwnedEventId {
if id.contains('$') {
return id.try_into().unwrap();
}
format!("${id}:foo").try_into().unwrap()
}
pub(crate) fn alice() -> &'static UserId {
user_id!("@alice:foo")
}
pub(crate) fn bob() -> &'static UserId {
user_id!("@bob:foo")
}
pub(crate) fn charlie() -> &'static UserId {
user_id!("@charlie:foo")
}
pub(crate) fn ella() -> &'static UserId {
user_id!("@ella:foo")
}
pub(crate) fn zara() -> &'static UserId {
user_id!("@zara:foo")
}
pub(crate) fn room_id() -> &'static RoomId {
room_id!("!test:foo")
}
pub(crate) fn member_content_ban() -> Box<RawJsonValue> {
to_raw_json_value(&RoomMemberEventContent::new(MembershipState::Ban)).unwrap()
}
pub(crate) fn member_content_join() -> Box<RawJsonValue> {
to_raw_json_value(&RoomMemberEventContent::new(MembershipState::Join)).unwrap()
}
pub(crate) fn to_init_pdu_event(
id: &str,
sender: &UserId,
ev_type: TimelineEventType,
state_key: Option<&str>,
content: Box<RawJsonValue>,
) -> Arc<PduEvent> {
let ts = SERVER_TIMESTAMP.fetch_add(1, SeqCst);
let id = if id.contains('$') {
id.to_owned()
} else {
format!("${id}:foo")
};
let state_key = state_key.map(ToOwned::to_owned);
Arc::new(PduEvent {
event_id: id.try_into().unwrap(),
rest: Pdu::RoomV3Pdu(RoomV3Pdu {
room_id: room_id().to_owned(),
sender: sender.to_owned(),
origin_server_ts: UnixMillis(ts.try_into().unwrap()),
state_key,
kind: ev_type,
content,
redacts: None,
unsigned: BTreeMap::new(),
auth_events: vec![],
prev_events: vec![],
depth: 0,
hashes: EventHash::new("".to_owned()),
signatures: BTreeMap::new(),
}),
})
}
pub(crate) fn to_pdu_event<S>(
id: &str,
sender: &UserId,
ev_type: TimelineEventType,
state_key: Option<&str>,
content: Box<RawJsonValue>,
auth_events: &[S],
prev_events: &[S],
) -> Arc<PduEvent>
where
S: AsRef<str>,
{
let ts = SERVER_TIMESTAMP.fetch_add(1, SeqCst);
let id = if id.contains('$') {
id.to_owned()
} else {
format!("${id}:foo")
};
let auth_events = auth_events.iter().map(AsRef::as_ref).map(event_id).collect::<Vec<_>>();
let prev_events = prev_events.iter().map(AsRef::as_ref).map(event_id).collect::<Vec<_>>();
let state_key = state_key.map(ToOwned::to_owned);
Arc::new(PduEvent {
event_id: id.try_into().unwrap(),
rest: Pdu::RoomV3Pdu(RoomV3Pdu {
room_id: room_id().to_owned(),
sender: sender.to_owned(),
origin_server_ts: UnixMillis(ts.try_into().unwrap()),
state_key,
kind: ev_type,
content,
redacts: None,
unsigned: BTreeMap::new(),
auth_events,
prev_events,
depth: 0,
hashes: EventHash::new("".to_owned()),
signatures: BTreeMap::new(),
}),
})
}
// all graphs start with these input events
#[allow(non_snake_case)]
pub(crate) fn INITIAL_EVENTS() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![
to_pdu_event::<&EventId>(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&json!({ "creator": alice() })).unwrap(),
&[],
&[],
),
to_pdu_event(
"IMA",
alice(),
TimelineEventType::RoomMember,
Some(alice().as_str()),
member_content_join(),
&["CREATE"],
&["CREATE"],
),
to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100 } })).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
),
to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Public)).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
),
to_pdu_event(
"IMB",
bob(),
TimelineEventType::RoomMember,
Some(bob().as_str()),
member_content_join(),
&["CREATE", "IJR", "IPOWER"],
&["IJR"],
),
to_pdu_event(
"IMC",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
),
to_pdu_event::<&EventId>(
"START",
charlie(),
TimelineEventType::RoomMessage,
Some("dummy"),
to_raw_json_value(&json!({})).unwrap(),
&[],
&[],
),
to_pdu_event::<&EventId>(
"END",
charlie(),
TimelineEventType::RoomMessage,
Some("dummy"),
to_raw_json_value(&json!({})).unwrap(),
&[],
&[],
),
]
.into_iter()
.map(|ev| (ev.event_id().to_owned(), ev))
.collect()
}
// all graphs start with these input events
#[allow(non_snake_case)]
pub(crate) fn INITIAL_EVENTS_CREATE_ROOM() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![to_pdu_event::<&EventId>(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&json!({ "creator": alice() })).unwrap(),
&[],
&[],
)]
.into_iter()
.map(|ev| (ev.event_id().to_owned(), ev))
.collect()
}
#[allow(non_snake_case)]
pub(crate) fn INITIAL_EDGES() -> Vec<OwnedEventId> {
vec!["START", "IMC", "IMB", "IJR", "IPOWER", "IMA", "CREATE"]
.into_iter()
.map(event_id)
.collect::<Vec<_>>()
}
// pub(crate) mod event {
// use serde::{Deserialize, Serialize};
// use crate::serde::RawJsonValue;
// use crate::{
// OwnedEventId, RoomId, UnixMillis, UserId,
// events::{TimelineEventType, pdu::Pdu},
// state::Event,
// };
// impl Event for PduEvent {
// type Id = OwnedEventId;
// fn event_id(&self) -> &Self::Id {
// &self.event_id
// }
// fn room_id(&self) -> &RoomId {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => &ev.room_id,
// Pdu::RoomV3Pdu(ev) => &ev.room_id,
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// fn sender(&self) -> &UserId {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => &ev.sender,
// Pdu::RoomV3Pdu(ev) => &ev.sender,
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// fn event_type(&self) -> &TimelineEventType {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => &ev.kind,
// Pdu::RoomV3Pdu(ev) => &ev.kind,
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// fn content(&self) -> &RawJsonValue {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => &ev.content,
// Pdu::RoomV3Pdu(ev) => &ev.content,
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// fn origin_server_ts(&self) -> UnixMillis {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => ev.origin_server_ts,
// Pdu::RoomV3Pdu(ev) => ev.origin_server_ts,
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// fn state_key(&self) -> Option<&str> {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => ev.state_key.as_deref(),
// Pdu::RoomV3Pdu(ev) => ev.state_key.as_deref(),
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// fn prev_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => Box::new(ev.prev_events.iter().map(|(id, _)| id)),
// Pdu::RoomV3Pdu(ev) => Box::new(ev.prev_events.iter()),
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// fn auth_events(&self) -> Box<dyn DoubleEndedIterator<Item = &Self::Id> + '_> {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => Box::new(ev.auth_events.iter().map(|(id, _)| id)),
// Pdu::RoomV3Pdu(ev) => Box::new(ev.auth_events.iter()),
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// fn redacts(&self) -> Option<&Self::Id> {
// match &self.rest {
// Pdu::RoomV1Pdu(ev) => ev.redacts.as_ref(),
// Pdu::RoomV3Pdu(ev) => ev.redacts.as_ref(),
// #[allow(unreachable_patterns)]
// _ => unreachable!("new PDU version"),
// }
// }
// }
// #[derive(Clone, Debug, Deserialize, Serialize)]
// #[allow(clippy::exhaustive_structs)]
// pub(crate) struct PduEvent {
// pub(crate) event_id: OwnedEventId,
// #[serde(flatten)]
// pub(crate) rest: Pdu,
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/room_version_rules.rs | crates/core/src/room_version_rules.rs | //! Types for the rules applied to the different [room versions].
//!
//! [room versions]: https://spec.matrix.org/latest/rooms/
#[allow(clippy::disallowed_types)]
use std::collections::HashSet;
use as_variant::as_variant;
use crate::OwnedUserId;
/// The rules applied to a [room version].
///
/// This type can be constructed from one of its constants (like [`RoomVersionRules::V1`]), or from
/// [`RoomVersionId::rules()`].
///
/// [room version]: https://spec.matrix.org/latest/rooms/
/// [`RoomVersionId::rules()`]: crate::RoomVersionId::rules
#[derive(Debug, Clone)]
pub struct RoomVersionRules {
/// The stability of the room version.
pub disposition: RoomVersionDisposition,
/// The format of event IDs.
pub event_id_format: EventIdFormatVersion,
/// The format of room IDs.
pub room_id_format: RoomIdFormatVersion,
/// The state resolution algorithm used.
pub state_resolution: StateResolutionVersion,
/// Whether to enforce the key validity period when verifying signatures ([spec]), introduced
/// in room version 5.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v5/#signing-key-validity-period
pub enforce_key_validity: bool,
/// The tweaks in the authorization rules.
pub authorization: AuthorizationRules,
/// The tweaks in the redaction algorithm.
pub redaction: RedactionRules,
/// The tweaks for verifying signatures.
pub signatures: SignaturesRules,
/// The tweaks for verifying the event format.
pub event_format: EventFormatRules,
}
impl RoomVersionRules {
/// Rules for [room version 1].
///
/// [room version 1]: https://spec.matrix.org/latest/rooms/v1/
pub const V1: Self = Self {
disposition: RoomVersionDisposition::Stable,
event_id_format: EventIdFormatVersion::V1,
room_id_format: RoomIdFormatVersion::V1,
state_resolution: StateResolutionVersion::V1,
enforce_key_validity: false,
authorization: AuthorizationRules::V1,
redaction: RedactionRules::V1,
signatures: SignaturesRules::V1,
event_format: EventFormatRules::V1,
};
/// Rules for [room version 2].
///
/// [room version 2]: https://spec.matrix.org/latest/rooms/v2/
pub const V2: Self = Self {
state_resolution: StateResolutionVersion::V2(StateResolutionV2Rules::V2_0),
..Self::V1
};
/// Rules for [room version 3].
///
/// [room version 3]: https://spec.matrix.org/latest/rooms/v3/
pub const V3: Self = Self {
event_id_format: EventIdFormatVersion::V2,
authorization: AuthorizationRules::V3,
signatures: SignaturesRules::V3,
event_format: EventFormatRules::V3,
..Self::V2
};
/// Rules for [room version 4].
///
/// [room version 4]: https://spec.matrix.org/latest/rooms/v4/
pub const V4: Self = Self {
event_id_format: EventIdFormatVersion::V3,
..Self::V3
};
/// Rules for [room version 5].
///
/// [room version 5]: https://spec.matrix.org/latest/rooms/v5/
pub const V5: Self = Self {
enforce_key_validity: true,
..Self::V4
};
/// Rules for [room version 6].
///
/// [room version 6]: https://spec.matrix.org/latest/rooms/v6/
pub const V6: Self = Self {
authorization: AuthorizationRules::V6,
redaction: RedactionRules::V6,
..Self::V5
};
/// Rules for [room version 7].
///
/// [room version 7]: https://spec.matrix.org/latest/rooms/v7/
pub const V7: Self = Self {
authorization: AuthorizationRules::V7,
..Self::V6
};
/// Rules for [room version 8].
///
/// [room version 8]: https://spec.matrix.org/latest/rooms/v8/
pub const V8: Self = Self {
authorization: AuthorizationRules::V8,
redaction: RedactionRules::V8,
signatures: SignaturesRules::V8,
..Self::V7
};
/// Rules for [room version 9].
///
/// [room version 9]: https://spec.matrix.org/latest/rooms/v9/
pub const V9: Self = Self {
redaction: RedactionRules::V9,
..Self::V8
};
/// Rules for [room version 10].
///
/// [room version 10]: https://spec.matrix.org/latest/rooms/v10/
pub const V10: Self = Self {
authorization: AuthorizationRules::V10,
..Self::V9
};
/// Rules for [room version 11].
///
/// [room version 11]: https://spec.matrix.org/latest/rooms/v11/
pub const V11: Self = Self {
authorization: AuthorizationRules::V11,
redaction: RedactionRules::V11,
..Self::V10
};
/// Rules for room version 12.
pub const V12: Self = Self {
room_id_format: RoomIdFormatVersion::V2,
authorization: AuthorizationRules::V12,
event_format: EventFormatRules::V12,
state_resolution: StateResolutionVersion::V2(StateResolutionV2Rules::V2_1),
..Self::V11
};
/// Rules for room version `org.matrix.msc2870` ([MSC2870]).
///
/// [MSC2870]: https://github.com/matrix-org/matrix-spec-proposals/pull/2870
#[cfg(feature = "unstable-msc2870")]
pub const MSC2870: Self = Self {
disposition: RoomVersionDisposition::Unstable,
redaction: RedactionRules::MSC2870,
..Self::V11
};
}
/// The stability of a room version.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(clippy::exhaustive_enums)]
pub enum RoomVersionDisposition {
/// A room version that has a stable specification.
Stable,
/// A room version that is not yet fully specified.
Unstable,
}
/// The format of [event IDs] for a room version.
///
/// [event IDs]: https://spec.matrix.org/latest/appendices/#event-ids
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventIdFormatVersion {
/// `$id:server` format ([spec]), introduced in room version 1.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v1/#event-ids
V1,
/// `$hash` format using standard unpadded base64 ([spec]), introduced in room version 3.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v3/#event-ids
V2,
/// `$hash` format using URL-safe unpadded base64 ([spec]), introduced in room version 4.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v4/#event-ids
V3,
}
/// The format of [room IDs] for a room version.
///
/// [room IDs]: https://spec.matrix.org/latest/appendices/#room-ids
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RoomIdFormatVersion {
/// `!id:server` format, introduced in room version 1.
V1,
/// `!hash` format using the reference hash of the `m.room.create` event of the room,
/// introduced in room version 12.
V2,
}
/// The version of [state resolution] for a room version.
///
/// [state resolution]: https://spec.matrix.org/latest/server-server-api/#room-state-resolution
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateResolutionVersion {
/// First version of the state resolution algorithm ([spec]), introduced in room version 1.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v1/#state-resolution
V1,
/// Second version of the state resolution algorithm ([spec]), introduced in room version 2.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v2/#state-resolution
V2(StateResolutionV2Rules),
}
impl StateResolutionVersion {
/// Gets the `StateResolutionV2Rules` for the room version, if it uses the second version of
/// the state resolution algorithm.
pub fn v2_rules(&self) -> Option<StateResolutionV2Rules> {
as_variant!(self, StateResolutionVersion::V2(rules) => *rules)
}
}
/// The tweaks in the [state resolution v2 algorithm] for a room version.
///
/// This type can be constructed from one of its constants (like [`StateResolutionV2Rules::V2_0`]),
/// or by constructing a [`RoomVersionRules`] first and using the `state_resolution` field (if the room
/// version uses version 2 of the state resolution algorithm).
///
/// [state resolution v2 algorithm]: https://spec.matrix.org/latest/rooms/v2/#state-resolution
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StateResolutionV2Rules {
/// Whether to begin the first phase of iterative auth checks with an empty state map, as
/// opposed to one containing the unconflicted state, enabled since room version 12.
pub begin_iterative_auth_check_with_empty_state_map: bool,
/// Whether to include the conflicted state subgraph in the full conflicted state, enabled
/// since room version 12.
pub consider_conflicted_state_subgraph: bool,
}
impl StateResolutionV2Rules {
/// The first version of the second iteration of the state resolution algorithm, introduced in
/// room version 2.
pub const V2_0: Self = Self {
begin_iterative_auth_check_with_empty_state_map: false,
consider_conflicted_state_subgraph: false,
};
/// The second version of the second iteration of the state resolution algorithm, introduced in
/// room version 12.
pub const V2_1: Self = Self {
begin_iterative_auth_check_with_empty_state_map: true,
consider_conflicted_state_subgraph: true,
};
}
/// The tweaks in the [authorization rules] for a room version.
///
/// This type can be constructed from one of its constants (like [`AuthorizationRules::V1`]), or by
/// constructing a [`RoomVersionRules`] first and using the `authorization` field.
///
/// [authorization rules]: https://spec.matrix.org/latest/server-server-api/#authorization-rules
#[derive(Debug, Clone)]
pub struct AuthorizationRules {
/// Whether to apply special authorization rules for `m.room.redaction` events ([spec]),
/// disabled since room version 3.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v3/#handling-redactions
pub special_case_room_redaction: bool,
/// Whether to apply special authorization rules for `m.room.aliases` events ([spec]), disabled
/// since room version 6.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v6/#authorization-rules
pub special_case_room_aliases: bool,
/// Whether to strictly enforce [canonical JSON] ([spec]), introduced in room version 6.
///
/// Numbers in Canonical JSON must be integers in the range [-2<sup>53</sup> + 1,
/// 2<sup>53</sup> - 1], represented without exponents or decimal places, and negative zero
/// (`-0`) MUST NOT appear.
///
/// [canonical JSON]: https://spec.matrix.org/latest/appendices/#canonical-json
/// [spec]: https://spec.matrix.org/latest/rooms/v6/#canonical-json
pub strict_canonical_json: bool,
/// Whether to check the `notifications` field when checking `m.room.power_levels` events
/// ([spec]), introduced in room version 6.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v6/#authorization-rules
pub limit_notifications_power_levels: bool,
/// Whether to allow the `knock` membership for `m.room.member` events and the `knock` join
/// rule for `m.room.join_rules` events ([spec]), introduced in room version 7.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v7/#authorization-rules
pub knocking: bool,
/// Whether to allow the `restricted` join rule for `m.room.join_rules` events ([spec]),
/// introduced in room version 8.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v8/#authorization-rules
pub restricted_join_rule: bool,
/// Whether to allow the `knock_restricted` join rule for `m.room.join_rules` events ([spec]),
/// introduced in room version 10.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v10/#authorization-rules
pub knock_restricted_join_rule: bool,
/// Whether to enforce that power levels values in `m.room.power_levels` events be integers
/// ([spec]), introduced in room version 10.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v10/#values-in-mroompower_levels-events-must-be-integers
pub integer_power_levels: bool,
/// Whether the room creator should be determined using the `m.room.create` event's `sender`,
/// instead of the event content's `creator` field ([spec]), introduced in room version 11.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v11/#event-format
pub use_room_create_sender: bool,
/// Whether room creators should always be considered to have "infinite" power level,
/// introduced in room version 12.
pub explicitly_privilege_room_creators: bool,
/// Whether additional room creators can be set with the `content.additional_creators` field of
/// an `m.room.create` event, introduced in room version 12.
pub additional_room_creators: bool,
/// Whether to use the event ID of the `m.room.create` event of the room as the room ID,
/// introduced in room version 12.
pub room_create_event_id_as_room_id: bool,
}
impl AuthorizationRules {
/// Authorization rules as introduced in room version 1 ([spec]).
///
/// [spec]: https://spec.matrix.org/latest/rooms/v1/#authorization-rules
pub const V1: Self = Self {
special_case_room_redaction: true,
special_case_room_aliases: true,
strict_canonical_json: false,
limit_notifications_power_levels: false,
knocking: false,
restricted_join_rule: false,
knock_restricted_join_rule: false,
integer_power_levels: false,
use_room_create_sender: false,
explicitly_privilege_room_creators: false,
additional_room_creators: false,
room_create_event_id_as_room_id: false,
};
/// Authorization rules with tweaks introduced in room version 3 ([spec]).
///
/// [spec]: https://spec.matrix.org/latest/rooms/v3/#authorization-rules
pub const V3: Self = Self {
special_case_room_redaction: false,
..Self::V1
};
/// Authorization rules with tweaks introduced in room version 6 ([spec]).
///
/// [spec]: https://spec.matrix.org/latest/rooms/v6/#authorization-rules
pub const V6: Self = Self {
special_case_room_aliases: false,
strict_canonical_json: true,
limit_notifications_power_levels: true,
..Self::V3
};
/// Authorization rules with tweaks introduced in room version 7 ([spec]).
///
/// [spec]: https://spec.matrix.org/latest/rooms/v7/#authorization-rules
pub const V7: Self = Self {
knocking: true,
..Self::V6
};
/// Authorization rules with tweaks introduced in room version 8 ([spec]).
///
/// [spec]: https://spec.matrix.org/latest/rooms/v8/#authorization-rules
pub const V8: Self = Self {
restricted_join_rule: true,
..Self::V7
};
/// Authorization rules with tweaks introduced in room version 10 ([spec]).
///
/// [spec]: https://spec.matrix.org/latest/rooms/v10/#authorization-rules
pub const V10: Self = Self {
knock_restricted_join_rule: true,
integer_power_levels: true,
..Self::V8
};
/// Authorization rules with tweaks introduced in room version 11 ([spec]).
///
/// [spec]: https://spec.matrix.org/latest/rooms/v11/#authorization-rules
pub const V11: Self = Self {
use_room_create_sender: true,
..Self::V10
};
/// Authorization rules with tweaks introduced in room version 12.
pub const V12: Self = Self {
explicitly_privilege_room_creators: true,
additional_room_creators: true,
room_create_event_id_as_room_id: true,
..Self::V11
};
}
/// The tweaks in the [redaction] algorithm for a room version.
///
/// This type can be constructed from one of its constants (like [`RedactionRules::V1`]), or by
/// constructing a [`RoomVersionRules`] first and using the `redaction` field.
///
/// [redaction]: https://spec.matrix.org/latest/client-server-api/#redactions
#[derive(Debug, Clone)]
pub struct RedactionRules {
/// Whether to keep the `aliases` field in the `content` of `m.room.aliases` events ([spec]),
/// disabled since room version 6.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v6/#redactions
pub keep_room_aliases_aliases: bool,
/// Whether to keep the `allow` field in the `content` of `m.room.join_rules` events ([spec]),
/// introduced in room version 8.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v8/#redactions
pub keep_room_join_rules_allow: bool,
/// Whether to keep the `join_authorised_via_users_server` field in the `content` of
/// `m.room.member` events ([spec]), introduced in room version 9.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v9/#redactions
pub keep_room_member_join_authorised_via_users_server: bool,
/// Whether to keep the `origin`, `membership` and `prev_state` fields a the top-level of all
/// events ([spec]), disabled since room version 11.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v11/#redactions
pub keep_origin_membership_prev_state: bool,
/// Whether to keep the entire `content` of `m.room.create` events ([spec]), introduced in room
/// version 11.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v11/#redactions
pub keep_room_create_content: bool,
/// Whether to keep the `redacts` field in the `content` of `m.room.redaction` events ([spec]),
/// introduced in room version 11.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v11/#redactions
pub keep_room_redaction_redacts: bool,
/// Whether to keep the `invite` field in the `content` of `m.room.power_levels` events
/// ([spec]), introduced in room version 11.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v11/#redactions
pub keep_room_power_levels_invite: bool,
/// Whether to keep the `signed` field in `third_party_invite` of the `content` of
/// `m.room.member` events ([spec]), introduced in room version 11.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v11/#redactions
pub keep_room_member_third_party_invite_signed: bool,
/// Whether the `content.redacts` field should be used to determine the event an event
/// redacts, as opposed to the top-level `redacts` field ([spec]), introduced in room version
/// 11.
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v11/#redactions
pub content_field_redacts: bool,
/// Whether to keep the `allow`, `deny` and `allow_ip_literals` in the `content` of
/// `m.room.server_acl` events ([MSC2870]).
///
/// [MSC2870]: https://github.com/matrix-org/matrix-spec-proposals/pull/2870
#[cfg(feature = "unstable-msc2870")]
pub keep_room_server_acl_allow_deny_allow_ip_literals: bool,
}
impl RedactionRules {
/// Redaction rules as introduced in room version 1 ([spec]).
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v1/#redactions
pub const V1: Self = Self {
keep_room_aliases_aliases: true,
keep_room_join_rules_allow: false,
keep_room_member_join_authorised_via_users_server: false,
keep_origin_membership_prev_state: true,
keep_room_create_content: false,
keep_room_redaction_redacts: false,
keep_room_power_levels_invite: false,
keep_room_member_third_party_invite_signed: false,
content_field_redacts: false,
#[cfg(feature = "unstable-msc2870")]
keep_room_server_acl_allow_deny_allow_ip_literals: false,
};
/// Redaction rules with tweaks introduced in room version 6 ([spec]).
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v6/#redactions
pub const V6: Self = Self {
keep_room_aliases_aliases: false,
..Self::V1
};
/// Redaction rules with tweaks introduced in room version 8 ([spec]).
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v8/#redactions
pub const V8: Self = Self {
keep_room_join_rules_allow: true,
..Self::V6
};
/// Redaction rules with tweaks introduced in room version 9 ([spec]).
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v9/#redactions
pub const V9: Self = Self {
keep_room_member_join_authorised_via_users_server: true,
..Self::V8
};
/// Redaction rules with tweaks introduced in room version 11 ([spec]).
///
/// [spec]: https://spec.matrix.org/v1.17/rooms/v11/#redactions
pub const V11: Self = Self {
keep_origin_membership_prev_state: false,
keep_room_create_content: true,
keep_room_redaction_redacts: true,
keep_room_power_levels_invite: true,
keep_room_member_third_party_invite_signed: true,
content_field_redacts: true,
..Self::V9
};
/// Redaction rules with tweaks introduced in [MSC2870].
///
/// [MSC2870]: https://github.com/matrix-org/matrix-spec-proposals/pull/2870
#[cfg(feature = "unstable-msc2870")]
pub const MSC2870: Self = Self {
keep_room_server_acl_allow_deny_allow_ip_literals: true,
..Self::V11
};
}
/// The tweaks for [verifying the signatures] for a room version.
///
/// This type can be constructed from one of its constants (like [`SignaturesRules::V1`]), or by
/// constructing a [`RoomVersionRules`] first and using the `signatures` field.
///
/// [verifying the signatures]: https://spec.matrix.org/latest/server-server-api/#validating-hashes-and-signatures-on-received-events
#[derive(Debug, Clone)]
pub struct SignaturesRules {
/// Whether to check the server of the event ID, disabled since room version 3.
pub check_event_id_server: bool,
/// Whether to check the server of the `join_authorised_via_users_server` field in the
/// `content` of `m.room.member` events ([spec]), introduced in room version 8.
///
/// [spec]: https://spec.matrix.org/latest/rooms/v8/#authorization-rules
pub check_join_authorised_via_users_server: bool,
}
impl SignaturesRules {
/// Signatures verification rules as introduced in room version 1.
pub const V1: Self = Self {
check_event_id_server: true,
check_join_authorised_via_users_server: false,
};
/// Signatures verification rules with tweaks introduced in room version 3.
pub const V3: Self = Self {
check_event_id_server: false,
..Self::V1
};
/// Signatures verification rules with tweaks introduced in room version 8.
pub const V8: Self = Self {
check_join_authorised_via_users_server: true,
..Self::V3
};
}
/// The tweaks for verifying the event format for a room version.
///
/// This type can be constructed from one of its constants (like [`EventFormatRules::V1`]), or by
/// constructing a [`RoomVersionRules`] first and using the `event_format` field.
#[derive(Debug, Clone)]
pub struct EventFormatRules {
/// Whether the `event_id` field is required, disabled since room version 3.
pub require_event_id: bool,
/// Whether the `room_id` field is required on the `m.room.create` event, disabled since room
/// version 12.
pub require_room_create_room_id: bool,
/// Whether the `m.room.create` event is allowed to be in the `auth_events`, disabled since
/// room version 12.
pub allow_room_create_in_auth_events: bool,
}
impl EventFormatRules {
/// Event format rules as introduced in room version 1.
pub const V1: Self = Self {
require_event_id: true,
require_room_create_room_id: true,
allow_room_create_in_auth_events: true,
};
/// Event format rules with tweaks introduced in room version 3.
pub const V3: Self = Self {
require_event_id: false,
..Self::V1
};
/// Event format rules with tweaks introduced in room version 12.
pub const V12: Self = Self {
require_room_create_room_id: false,
allow_room_create_in_auth_events: false,
..Self::V3
};
}
/// The tweaks for determining the power level of a user.
#[derive(Clone, Debug)]
pub struct RoomPowerLevelsRules {
/// The creator(s) of the room which are considered to have "infinite" power level, introduced
/// in room version 12.
#[allow(clippy::disallowed_types)]
pub privileged_creators: Option<HashSet<OwnedUserId>>,
}
impl RoomPowerLevelsRules {
/// Creates a new `RoomPowerLevelsRules` from the given parameters, using the `creators` if
/// the rule `explicitly_privilege_room_creators` is `true`.
pub fn new(
rules: &AuthorizationRules,
creators: impl IntoIterator<Item = OwnedUserId>,
) -> Self {
Self {
privileged_creators: rules
.explicitly_privilege_room_creators
.then(|| creators.into_iter().collect()),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client.rs | crates/core/src/client.rs | pub mod account;
pub mod appservice;
pub mod backup;
pub mod dehydrated_device;
pub mod device;
pub mod directory;
pub mod discovery;
pub mod event;
pub mod filter;
pub mod http_header;
pub mod key;
pub mod media;
pub mod membership;
pub mod message;
pub mod presence;
pub mod profile;
pub mod push;
pub mod redact;
pub mod register;
pub mod relation;
pub mod room;
#[cfg(feature = "unstable-msc4143")]
pub mod rtc;
pub mod search;
pub mod server;
pub mod session;
pub mod space;
pub mod state;
pub mod sync_events;
pub mod tag;
pub mod typing;
pub mod uiaa;
pub mod user;
pub mod user_directory;
pub mod voip;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation.rs | crates/core/src/federation.rs | //! (De)serializable types for the [Matrix Server-Server API][federation-api].
//! These types are used by server code.
//!
//! [federation-api]: https://spec.matrix.org/latest/server-server-api/
#![cfg_attr(docsrs, feature(doc_cfg))]
mod serde;
pub mod authenticated_media;
pub mod authentication;
pub mod authorization;
pub mod backfill;
pub mod device;
pub mod directory;
pub mod discovery;
pub mod event;
pub mod key;
pub mod knock;
pub mod media;
pub mod membership;
pub mod openid;
pub mod query;
pub mod room;
pub mod space;
pub mod third_party;
pub mod transaction;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/error.rs | crates/core/src/error.rs | //! Errors that can be sent from the homeserver.
use std::{error::Error as StdError, fmt, iter::FromIterator, num::ParseIntError};
use salvo::{
http::{Response, StatusCode, header},
writing::Scribe,
};
use serde::{Deserialize, Serialize};
use serde_json::{Map as JsonMap, Value as JsonValue, json};
mod auth;
pub use auth::*;
mod kind;
/// Deserialize and Serialize implementations for ErrorKind.
/// Separate module because it's a lot of code.
mod kind_serde;
pub use kind::*;
use kind_serde::{ErrorCode, RetryAfter};
use crate::{MatrixVersion, RoomVersionId};
macro_rules! simple_kind_fns {
($($fname:ident, $kind:ident;)+) => {
$(
/// Create a new `MatrixError`.
pub fn $fname(body: impl Into<ErrorBody>) -> Self {
Self::new(ErrorKind::$kind, body)
}
)+
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ErrorBody(JsonMap<String, JsonValue>);
impl From<String> for ErrorBody {
fn from(message: String) -> Self {
Self(JsonMap::from_iter(vec![(
"error".to_owned(),
json!(message),
)]))
}
}
impl From<&str> for ErrorBody {
fn from(message: &str) -> Self {
Self(JsonMap::from_iter(vec![(
"error".to_owned(),
json!(message),
)]))
}
}
impl From<JsonMap<String, JsonValue>> for ErrorBody {
fn from(inner: JsonMap<String, JsonValue>) -> Self {
Self(inner)
}
}
/// A Matrix Error
#[derive(Debug, Clone)]
#[allow(clippy::exhaustive_structs)]
pub struct MatrixError {
/// The http status code.
pub status_code: Option<http::StatusCode>,
/// The `WWW-Authenticate` header error message.
pub authenticate: Option<AuthenticateError>,
pub kind: ErrorKind,
/// The http response's body.
pub body: ErrorBody,
}
impl MatrixError {
pub fn new(kind: ErrorKind, body: impl Into<ErrorBody>) -> Self {
Self {
status_code: None,
authenticate: None,
kind,
body: body.into(),
}
}
simple_kind_fns! {
bad_alias, BadAlias;
bad_json, BadJson;
bad_state, BadState;
cannot_leave_server_notice_room, CannotLeaveServerNoticeRoom;
cannot_overwrite_media, CannotOverwriteMedia;
captcha_invalid, CaptchaInvalid;
captcha_needed, CaptchaNeeded;
connection_failed, ConnectionFailed;
connection_timeout, ConnectionTimeout;
duplicate_annotation, DuplicateAnnotation;
exclusive, Exclusive;
guest_access_forbidden, GuestAccessForbidden;
invalid_param, InvalidParam;
invalid_room_state, InvalidRoomState;
invalid_username, InvalidUsername;
missing_param, MissingParam;
missing_token, MissingToken;
not_found, NotFound;
not_json, NotJson;
not_yet_uploaded, NotYetUploaded;
room_in_use, RoomInUse;
server_not_trusted, ServerNotTrusted;
threepid_auth_failed, ThreepidAuthFailed;
threepid_denied, ThreepidDenied;
threepid_in_use, ThreepidInUse;
threepid_medium_not_supported, ThreepidMediumNotSupported;
threepid_not_found, ThreepidNotFound;
too_large, TooLarge;
unable_to_authorize_join, UnableToAuthorizeJoin;
unable_to_grant_join, UnableToGrantJoin;
unauthorized, Unauthorized;
unknown, Unknown;
unrecognized, Unrecognized;
unsupported_room_version, UnsupportedRoomVersion;
url_not_set, UrlNotSet;
user_deactivated, UserDeactivated;
user_in_use, UserInUse;
user_locked, UserLocked;
user_suspended, UserSuspended;
weak_password, WeakPassword;
}
pub fn bad_status(status: Option<http::StatusCode>, body: impl Into<ErrorBody>) -> Self {
Self::new(ErrorKind::BadStatus { status, body: None }, body)
}
pub fn forbidden(body: impl Into<ErrorBody>, authenticate: Option<AuthenticateError>) -> Self {
Self::new(ErrorKind::Forbidden { authenticate }, body)
}
#[cfg(feature = "unstable-msc4186")]
pub fn unknown_pos(body: impl Into<ErrorBody>) -> Self {
Self::new(ErrorKind::UnknownPos, body)
}
#[cfg(feature = "unstable-msc3843")]
pub fn unactionable(body: impl Into<ErrorBody>) -> Self {
Self::new(ErrorKind::Unactionable, body)
}
pub fn unknown_token(body: impl Into<ErrorBody>, soft_logout: bool) -> Self {
Self::new(ErrorKind::UnknownToken { soft_logout }, body)
}
pub fn limit_exceeded(body: impl Into<ErrorBody>, retry_after: Option<RetryAfter>) -> Self {
Self::new(ErrorKind::LimitExceeded { retry_after }, body)
}
pub fn incompatible_room_version(
body: impl Into<ErrorBody>,
room_version: RoomVersionId,
) -> Self {
Self::new(ErrorKind::IncompatibleRoomVersion { room_version }, body)
}
pub fn resource_limit_exceeded(body: impl Into<ErrorBody>, admin_contact: String) -> Self {
Self::new(ErrorKind::ResourceLimitExceeded { admin_contact }, body)
}
pub fn wrong_room_keys_version(
body: impl Into<ErrorBody>,
current_version: Option<String>,
) -> Self {
Self::new(ErrorKind::WrongRoomKeysVersion { current_version }, body)
}
pub fn is_not_found(&self) -> bool {
matches!(self.kind, ErrorKind::NotFound)
}
}
impl Serialize for MatrixError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.body.serialize(serializer)
}
}
impl fmt::Display for MatrixError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let code = self.status_code.unwrap_or(StatusCode::BAD_REQUEST).as_u16();
write!(f, "[{code} / {}]: {:?}", self.kind.code(), self.body)
}
}
impl StdError for MatrixError {}
impl From<serde_json::error::Error> for MatrixError {
fn from(e: serde_json::error::Error) -> Self {
Self::bad_json(e.to_string())
}
}
impl Scribe for MatrixError {
fn render(self, res: &mut Response) {
res.add_header(header::CONTENT_TYPE, "application/json", true)
.ok();
if res.status_code.map(|c| c.is_success()).unwrap_or(true) {
let code = self.status_code.unwrap_or_else(|| {
use ErrorKind::*;
match self.kind.clone() {
Forbidden { .. }
| GuestAccessForbidden
| ThreepidAuthFailed
| ThreepidDenied => StatusCode::FORBIDDEN,
Unauthorized | UnknownToken { .. } | MissingToken => StatusCode::UNAUTHORIZED,
NotFound | Unrecognized => StatusCode::NOT_FOUND,
LimitExceeded { .. } => StatusCode::TOO_MANY_REQUESTS,
UserDeactivated => StatusCode::FORBIDDEN,
TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
CannotOverwriteMedia => StatusCode::CONFLICT,
NotYetUploaded => StatusCode::GATEWAY_TIMEOUT,
_ => StatusCode::BAD_REQUEST,
}
});
res.status_code(code);
}
if let Some(auth_error) = &self.authenticate {
res.add_header(header::WWW_AUTHENTICATE, auth_error, true)
.ok();
};
let Self { kind, mut body, .. } = self;
body.0
.insert("errcode".to_owned(), kind.code().to_string().into());
let bytes: Vec<u8> = crate::serde::json_to_buf(&body.0).unwrap();
res.write_body(bytes).ok();
}
}
/// An error that happens when Palpo cannot understand a Matrix version.
#[derive(Debug)]
pub struct UnknownVersionError;
impl fmt::Display for UnknownVersionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "version string was unknown")
}
}
impl StdError for UnknownVersionError {}
/// An error that happens when an incorrect amount of arguments have been passed to [`PathBuilder`]
/// parts formatting.
///
/// [`PathBuilder`]: super::path_builder::PathBuilder
#[derive(Debug)]
pub struct IncorrectArgumentCount {
/// The expected amount of arguments.
pub expected: usize,
/// The amount of arguments received.
pub got: usize,
}
impl fmt::Display for IncorrectArgumentCount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"incorrect path argument count, expected {}, got {}",
self.expected, self.got
)
}
}
impl StdError for IncorrectArgumentCount {}
/// An error when serializing the HTTP headers.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum HeaderSerializationError {
/// Failed to convert a header value to `http::header::HeaderValue`.
#[error(transparent)]
ToHeaderValue(#[from] http::header::InvalidHeaderValue),
/// The `SystemTime` could not be converted to a HTTP date.
///
/// This only happens if the `SystemTime` provided is too far in the past
/// (before the Unix epoch) or the future (after the year 9999).
#[error("invalid HTTP date")]
InvalidHttpDate,
}
/// An error when converting one of ruma's endpoint-specific request or response
/// types to the corresponding http type.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum IntoHttpError {
/// Failed to add the authentication scheme to the request.
#[error("failed to add authentication scheme: {0}")]
Authentication(Box<dyn std::error::Error + Send + Sync + 'static>),
/// Tried to create a request with an old enough version, for which no unstable endpoint
/// exists.
///
/// This is also a fallback error for if the version is too new for this endpoint.
#[error(
"endpoint was not supported by server-reported versions, \
but no unstable path to fall back to was defined"
)]
NoUnstablePath,
/// Tried to create a request with [`MatrixVersion`]s for all of which this endpoint was
/// removed.
#[error(
"could not create any path variant for endpoint, as it was removed in version {}",
.0.as_str().expect("no endpoint was removed in Matrix 1.0")
)]
EndpointRemoved(MatrixVersion),
/// JSON serialization failed.
#[error("JSON serialization failed: {0}")]
Json(#[from] serde_json::Error),
/// Query parameter serialization failed.
#[error("query parameter serialization failed: {0}")]
Query(#[from] serde_html_form::ser::Error),
/// Header serialization failed.
#[error("header serialization failed: {0}")]
Header(#[from] HeaderSerializationError),
/// HTTP request construction failed.
#[error("HTTP request construction failed: {0}")]
Http(#[from] http::Error),
}
impl From<http::header::InvalidHeaderValue> for IntoHttpError {
fn from(value: http::header::InvalidHeaderValue) -> Self {
Self::Header(value.into())
}
}
/// An error when deserializing the HTTP headers.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum HeaderDeserializationError {
/// Failed to convert `http::header::HeaderValue` to `str`.
#[error("{0}")]
ToStrError(#[from] http::header::ToStrError),
/// Failed to convert `http::header::HeaderValue` to an integer.
#[error("{0}")]
ParseIntError(#[from] ParseIntError),
/// Failed to parse a HTTP date from a `http::header::Value`.
#[error("failed to parse HTTP date")]
InvalidHttpDate,
/// The given required header is missing.
#[error("missing header `{0}`")]
MissingHeader(String),
/// The given header failed to parse.
#[error("invalid header: {0}")]
InvalidHeader(Box<dyn std::error::Error + Send + Sync + 'static>),
/// A header was received with a unexpected value.
#[error(
"The {header} header was received with an unexpected value, \
expected {expected}, received {unexpected}"
)]
InvalidHeaderValue {
/// The name of the header containing the invalid value.
header: String,
/// The value the header should have been set to.
expected: String,
/// The value we instead received and rejected.
unexpected: String,
},
/// The `Content-Type` header for a `multipart/mixed` response is missing
/// the `boundary` attribute.
#[error(
"The `Content-Type` header for a `multipart/mixed` response is missing the `boundary` attribute"
)]
MissingMultipartBoundary,
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json};
// use super::{ErrorKind, StandardErrorBody};
// #[test]
// fn deserialize_forbidden() {
// let deserialized: StandardErrorBody = from_json_value(json!({
// "errcode": "M_FORBIDDEN",
// "error": "You are not authorized to ban users in this room.",
// }))
// .unwrap();
// assert_eq!(deserialized.kind, ErrorKind::Forbidden);
// assert_eq!(
// deserialized.message,
// "You are not authorized to ban users in this room."
// );
// }
// #[test]
// fn deserialize_wrong_room_key_version() {
// let deserialized: StandardErrorBody = from_json_value(json!({
// "current_version": "42",
// "errcode": "M_WRONG_ROOM_KEYS_VERSION",
// "error": "Wrong backup version."
// }))
// .expect("We should be able to deserialize a wrong room keys version
// error");
// assert_matches!(deserialized.kind, ErrorKind::WrongRoomKeysVersion {
// current_version }); assert_eq!(current_version.as_deref(),
// Some("42")); assert_eq!(deserialized.message, "Wrong backup
// version."); }
// #[test]
// fn custom_authenticate_error_sanity() {
// use super::AuthenticateError;
// let s = "Bearer error=\"custom_error\", misc=\"some content\"";
// let error = AuthenticateError::from_str(s).unwrap();
// let error_header = http::HeaderValue::try_from(&error).unwrap();
// assert_eq!(error_header.to_str().unwrap(), s);
// }
// #[test]
// fn serialize_insufficient_scope() {
// use super::AuthenticateError;
// let error = AuthenticateError::InsufficientScope {
// scope: "something_privileged".to_owned(),
// };
// let error_header = http::HeaderValue::try_from(&error).unwrap();
// assert_eq!(
// error_header.to_str().unwrap(),
// "Bearer error=\"insufficient_scope\",
// scope=\"something_privileged\"" );
// }
// #[test]
// fn deserialize_insufficient_scope() {
// use super::{AuthenticateError, Error, ErrorBody};
// use crate::api::EndpointError;
// let response = http::Response::builder()
// .header(
// http::header::WWW_AUTHENTICATE,
// "Bearer error=\"insufficient_scope\",
// scope=\"something_privileged\"", )
// .status(http::StatusCode::UNAUTHORIZED)
// .body(
// serde_json::to_string(&json!({
// "errcode": "M_FORBIDDEN",
// "error": "Insufficient privilege",
// }))
// .unwrap(),
// )
// .unwrap();
// let error = Error::from_http_response(response);
// assert_eq!(error.status_code, http::StatusCode::UNAUTHORIZED);
// assert_matches!(error.body, ErrorBody::Standard { kind, message });
// assert_eq!(kind, ErrorKind::Forbidden);
// assert_eq!(message, "Insufficient privilege");
// assert_matches!(error.authenticate,
// Some(AuthenticateError::InsufficientScope { scope })); assert_eq!
// (scope, "something_privileged"); }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/utils.rs | crates/core/src/utils.rs | use crate::{EventId, IdParseError, OwnedEventId, RoomId};
/// Convenience extension trait for [`RoomId`].
pub(crate) trait RoomIdExt {
/// Get the event ID of the `m.room.create` event of the room from a PDU, for room versions
/// using it as the room ID.
fn room_create_event_id(&self) -> Result<OwnedEventId, IdParseError>;
}
impl<T> RoomIdExt for T
where
T: AsRef<RoomId>,
{
fn room_create_event_id(&self) -> Result<OwnedEventId, IdParseError> {
EventId::parse(format!("${}", self.as_ref().strip_sigil()))
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/invite_permission_config.rs | crates/core/src/invite_permission_config.rs | //! Types for the [`m.invite_permission_config`] account data event.
//!
//! [`m.invite_permission_config`]: https://github.com/matrix-org/matrix-spec-proposals/pull/4380
use palpo_core_macros::EventContent;
use serde::{Deserialize, Serialize};
/// The content of an `m.invite_permission_config` event.
///
/// A single property: `block_all`.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[palpo_event(
kind = GlobalAccountData,
type = "org.matrix.msc4380.invite_permission_config",
alias = "m.invite_permission_config",
)]
pub struct InvitePermissionConfigEventContent {
/// When set to true, indicates that the user does not wish to receive *any* room invites, and
/// they should be blocked.
#[serde(default)]
#[serde(deserialize_with = "crate::serde::default_on_error")]
pub block_all: bool,
}
impl InvitePermissionConfigEventContent {
/// Creates a new `InvitePermissionConfigEventContent` from the desired boolean state.
pub fn new(block_all: bool) -> Self {
Self { block_all }
}
}
#[cfg(test)]
mod tests {
use assert_matches2::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::InvitePermissionConfigEventContent;
use crate::AnyGlobalAccountDataEvent;
#[test]
fn serialization() {
let invite_permission_config = InvitePermissionConfigEventContent::new(true);
let json = json!({
"block_all": true
});
assert_eq!(to_json_value(invite_permission_config).unwrap(), json);
}
#[test]
fn deserialization() {
let json = json!({
"content": {
"block_all": true
},
"type": "m.invite_permission_config"
});
assert_matches!(
from_json_value::<AnyGlobalAccountDataEvent>(json),
Ok(AnyGlobalAccountDataEvent::InvitePermissionConfig(ev))
);
assert!(ev.content.block_all);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/http_headers.rs | crates/core/src/http_headers.rs | //! Helpers for HTTP headers.
use std::borrow::Cow;
mod content_disposition;
mod rfc8187;
pub use self::content_disposition::{
ContentDisposition, ContentDispositionParseError, ContentDispositionType, TokenString,
TokenStringParseError,
};
/// Whether the given byte is a [`token` char].
///
/// [`token` char]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.2
pub const fn is_tchar(b: u8) -> bool {
b.is_ascii_alphanumeric()
|| matches!(
b,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'.'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~'
)
}
/// Whether the given bytes slice is a [`token`].
///
/// [`token`]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.2
pub fn is_token(bytes: &[u8]) -> bool {
bytes.iter().all(|b| is_tchar(*b))
}
/// Whether the given string is a [`token`].
///
/// [`token`]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.2
pub fn is_token_string(s: &str) -> bool {
is_token(s.as_bytes())
}
/// Whether the given char is a [visible US-ASCII char].
///
/// [visible US-ASCII char]: https://datatracker.ietf.org/doc/html/rfc5234#appendix-B.1
pub const fn is_vchar(c: char) -> bool {
matches!(c, '\x21'..='\x7E')
}
/// Whether the given char is in the US-ASCII character set and allowed inside a
/// [quoted string].
///
/// Contrary to the definition of quoted strings, this doesn't allow `obs-text`
/// characters, i.e. non-US-ASCII characters, as we usually deal with UTF-8
/// strings rather than ISO-8859-1 strings.
///
/// [quoted string]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.4
pub const fn is_ascii_string_quotable(c: char) -> bool {
is_vchar(c) || matches!(c, '\x09' | '\x20')
}
/// Remove characters that do not pass [`is_ascii_string_quotable()`] from the
/// given string.
///
/// [quoted string]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.4
pub fn sanitize_for_ascii_quoted_string(value: &str) -> Cow<'_, str> {
if value.chars().all(is_ascii_string_quotable) {
return Cow::Borrowed(value);
}
Cow::Owned(
value
.chars()
.filter(|c| is_ascii_string_quotable(*c))
.collect(),
)
}
/// If the US-ASCII field value does not contain only token chars, convert it to
/// a [quoted string].
///
/// The string should be sanitized with [`sanitize_for_ascii_quoted_string()`]
/// or should only contain characters that pass [`is_ascii_string_quotable()`].
///
/// [quoted string]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.4
pub fn quote_ascii_string_if_required(value: &str) -> Cow<'_, str> {
if !value.is_empty() && is_token_string(value) {
return Cow::Borrowed(value);
}
let value = value.replace('\\', r#"\\"#).replace('"', r#"\""#);
Cow::Owned(format!("\"{value}\""))
}
/// Removes the escape backslashes in the given string.
pub fn unescape_string(s: &str) -> String {
let mut is_escaped = false;
s.chars()
.filter(|c| {
is_escaped = *c == '\\' && !is_escaped;
!is_escaped
})
.collect()
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/authentication.rs | crates/core/src/authentication.rs | //! Common types for authentication.
use salvo::prelude::*;
use crate::{PrivOwnedStr, serde::StringEnum};
/// Access token types.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum TokenType {
/// Bearer token type
Bearer,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/to_device.rs | crates/core/src/to_device.rs | use std::collections::BTreeMap;
/// Common types for the Send-To-Device Messaging
///
/// [send-to-device]: https://spec.matrix.org/latest/client-server-api/#send-to-device-messaging
use std::fmt::{Display, Formatter, Result as FmtResult};
use salvo::prelude::*;
use serde::{
Deserialize, Deserializer, Serialize, Serializer,
de::{self, Unexpected},
};
use crate::{
OwnedDeviceId, OwnedTransactionId, OwnedUserId,
events::{AnyToDeviceEventContent, ToDeviceEventType},
serde::RawJson,
};
/// Represents one or all of a user's devices.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[allow(clippy::exhaustive_enums)]
pub enum DeviceIdOrAllDevices {
/// Represents a device Id for one of a user's devices.
DeviceId(OwnedDeviceId),
/// Represents all devices for a user.
AllDevices,
}
impl Display for DeviceIdOrAllDevices {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
DeviceIdOrAllDevices::DeviceId(device_id) => write!(f, "{device_id}"),
DeviceIdOrAllDevices::AllDevices => write!(f, "*"),
}
}
}
impl From<OwnedDeviceId> for DeviceIdOrAllDevices {
fn from(d: OwnedDeviceId) -> Self {
DeviceIdOrAllDevices::DeviceId(d)
}
}
impl TryFrom<&str> for DeviceIdOrAllDevices {
type Error = &'static str;
fn try_from(device_id_or_all_devices: &str) -> Result<Self, Self::Error> {
if device_id_or_all_devices.is_empty() {
Err("Device identifier cannot be empty")
} else if "*" == device_id_or_all_devices {
Ok(DeviceIdOrAllDevices::AllDevices)
} else {
Ok(DeviceIdOrAllDevices::DeviceId(
device_id_or_all_devices.into(),
))
}
}
}
impl Serialize for DeviceIdOrAllDevices {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::DeviceId(device_id) => device_id.serialize(serializer),
Self::AllDevices => serializer.serialize_str("*"),
}
}
}
impl<'de> Deserialize<'de> for DeviceIdOrAllDevices {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = crate::serde::deserialize_cow_str(deserializer)?;
DeviceIdOrAllDevices::try_from(s.as_ref()).map_err(|_| {
de::Error::invalid_value(Unexpected::Str(&s), &"a valid device identifier or '*'")
})
}
}
/// `PUT /_matrix/client/*/sendToDevice/{eventType}/{txn_id}`
///
/// Send an event to a device or devices.
/// `/v3/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/client/r0/sendToDevice/:event_type/:txn_id",
// 1.1 => "/_matrix/client/v3/sendToDevice/:event_type/:txn_id",
// }
// };
#[derive(ToParameters, Deserialize, Debug)]
pub struct SendEventToDeviceReqArgs {
/// Type of event being sent to each device.
#[salvo(parameter(parameter_in = Path))]
pub event_type: ToDeviceEventType,
/// The transaction ID for this event.
///
/// Clients should generate a unique ID across requests within the
/// same session. A session is identified by an access token, and
/// persists when the [access token is refreshed].
///
/// It will be used by the server to ensure idempotency of requests.
///
/// [access token is refreshed]: https://spec.matrix.org/latest/client-server-api/#refreshing-access-tokens
#[salvo(parameter(parameter_in = Path))]
pub txn_id: OwnedTransactionId,
}
/// Request type for the `send_event_to_device` endpoint.
#[derive(ToSchema, Deserialize, Debug)]
pub struct SendEventToDeviceReqBody {
/// Messages to send.
///
/// Different message events can be sent to different devices in the same
/// request, but all events within one request must be of the same type.
#[salvo(schema(value_type = Object))]
pub messages: Messages,
}
/// Messages to send in a send-to-device request.
///
/// Represented as a map of `{ user-ids => { device-ids => message-content } }`.
pub type Messages =
BTreeMap<OwnedUserId, BTreeMap<DeviceIdOrAllDevices, RawJson<AnyToDeviceEventContent>>>;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/auth_scheme.rs | crates/core/src/auth_scheme.rs | //! The `AuthScheme` trait used to specify the authentication scheme used by endpoints and the types
//! that implement it.
#![allow(clippy::exhaustive_structs)]
use as_variant::as_variant;
use http::HeaderMap;
use http::header::{self, InvalidHeaderValue};
use serde::Deserialize;
/// Trait implemented by types representing an authentication scheme used by an endpoint.
pub trait AuthScheme: Sized {
/// The input necessary to generate the authentication.
type Input<'a>;
/// The error type returned from [`add_authentication()`](Self::add_authentication).
type AddAuthenticationError: Into<Box<dyn std::error::Error + Send + Sync + 'static>>;
/// The authentication data that can be extracted from a request.
type Output;
/// The error type returned from [`extract_authentication()`](Self::extract_authentication).
type ExtractAuthenticationError: Into<Box<dyn std::error::Error + Send + Sync + 'static>>;
/// Add this authentication scheme to the given outgoing request, if necessary.
///
/// Returns an error if the endpoint requires authentication but the input doesn't provide it,
/// or if the input fails to serialize to the proper format.
fn add_authentication<T: AsRef<[u8]>>(
request: &mut http::Request<T>,
input: Self::Input<'_>,
) -> Result<(), Self::AddAuthenticationError>;
/// Extract the data of this authentication scheme from the given incoming request.
///
/// Returns an error if the endpoint requires authentication but the request doesn't provide it,
/// or if the output fails to deserialize to the proper format.
fn extract_authentication<T: AsRef<[u8]>>(
request: &http::Request<T>,
) -> Result<Self::Output, Self::ExtractAuthenticationError>;
}
/// No authentication is performed.
///
/// This type accepts a [`SendAccessToken`] as input to be able to send it regardless of whether it
/// is required.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoAuthentication;
impl AuthScheme for NoAuthentication {
type Input<'a> = SendAccessToken<'a>;
type AddAuthenticationError = header::InvalidHeaderValue;
type Output = ();
type ExtractAuthenticationError = std::convert::Infallible;
fn add_authentication<T: AsRef<[u8]>>(
request: &mut http::Request<T>,
access_token: SendAccessToken<'_>,
) -> Result<(), Self::AddAuthenticationError> {
if let Some(access_token) = access_token.get_not_required_for_endpoint() {
add_access_token_as_authorization_header(request.headers_mut(), access_token)?;
}
Ok(())
}
/// Since this endpoint doesn't expect any authentication, this is a noop.
fn extract_authentication<T: AsRef<[u8]>>(
_request: &http::Request<T>,
) -> Result<(), Self::ExtractAuthenticationError> {
Ok(())
}
}
/// Authentication is performed by including an access token in the `Authentication` http
/// header, or an `access_token` query parameter.
///
/// Using the query parameter is deprecated since Matrix 1.11.
#[derive(Debug, Clone, Copy, Default)]
pub struct AccessToken;
impl AuthScheme for AccessToken {
type Input<'a> = SendAccessToken<'a>;
type AddAuthenticationError = AddRequiredTokenError;
/// The access token.
type Output = String;
type ExtractAuthenticationError = ExtractTokenError;
fn add_authentication<T: AsRef<[u8]>>(
request: &mut http::Request<T>,
access_token: SendAccessToken<'_>,
) -> Result<(), Self::AddAuthenticationError> {
let token = access_token
.get_required_for_endpoint()
.ok_or(AddRequiredTokenError::MissingAccessToken)?;
Ok(add_access_token_as_authorization_header(
request.headers_mut(),
token,
)?)
}
fn extract_authentication<T: AsRef<[u8]>>(
request: &http::Request<T>,
) -> Result<String, Self::ExtractAuthenticationError> {
extract_bearer_or_query_token(request)?.ok_or(ExtractTokenError::MissingAccessToken)
}
}
/// Authentication is optional, and it is performed by including an access token in the
/// `Authentication` http header, or an `access_token` query parameter.
///
/// Using the query parameter is deprecated since Matrix 1.11.
#[derive(Debug, Clone, Copy, Default)]
pub struct AccessTokenOptional;
impl AuthScheme for AccessTokenOptional {
type Input<'a> = SendAccessToken<'a>;
type AddAuthenticationError = header::InvalidHeaderValue;
/// The access token, if any.
type Output = Option<String>;
type ExtractAuthenticationError = ExtractTokenError;
fn add_authentication<T: AsRef<[u8]>>(
request: &mut http::Request<T>,
access_token: SendAccessToken<'_>,
) -> Result<(), Self::AddAuthenticationError> {
if let Some(access_token) = access_token.get_required_for_endpoint() {
add_access_token_as_authorization_header(request.headers_mut(), access_token)?;
}
Ok(())
}
fn extract_authentication<T: AsRef<[u8]>>(
request: &http::Request<T>,
) -> Result<Option<String>, Self::ExtractAuthenticationError> {
extract_bearer_or_query_token(request)
}
}
/// Authentication is required, and can only be performed for appservices, by including an
/// appservice access token in the `Authentication` http header, or `access_token` query
/// parameter.
///
/// Using the query parameter is deprecated since Matrix 1.11.
#[derive(Debug, Clone, Copy, Default)]
pub struct AppserviceToken;
impl AuthScheme for AppserviceToken {
type Input<'a> = SendAccessToken<'a>;
type AddAuthenticationError = AddRequiredTokenError;
/// The appservice token.
type Output = String;
type ExtractAuthenticationError = ExtractTokenError;
fn add_authentication<T: AsRef<[u8]>>(
request: &mut http::Request<T>,
access_token: SendAccessToken<'_>,
) -> Result<(), Self::AddAuthenticationError> {
let token = access_token
.get_required_for_appservice()
.ok_or(AddRequiredTokenError::MissingAccessToken)?;
Ok(add_access_token_as_authorization_header(
request.headers_mut(),
token,
)?)
}
fn extract_authentication<T: AsRef<[u8]>>(
request: &http::Request<T>,
) -> Result<String, Self::ExtractAuthenticationError> {
extract_bearer_or_query_token(request)?.ok_or(ExtractTokenError::MissingAccessToken)
}
}
/// No authentication is performed for clients, but it can be performed for appservices, by
/// including an appservice access token in the `Authentication` http header, or an
/// `access_token` query parameter.
///
/// Using the query parameter is deprecated since Matrix 1.11.
#[derive(Debug, Clone, Copy, Default)]
pub struct AppserviceTokenOptional;
impl AuthScheme for AppserviceTokenOptional {
type Input<'a> = SendAccessToken<'a>;
type AddAuthenticationError = header::InvalidHeaderValue;
/// The appservice token, if any.
type Output = Option<String>;
type ExtractAuthenticationError = ExtractTokenError;
fn add_authentication<T: AsRef<[u8]>>(
request: &mut http::Request<T>,
access_token: SendAccessToken<'_>,
) -> Result<(), Self::AddAuthenticationError> {
if let Some(access_token) = access_token.get_required_for_appservice() {
add_access_token_as_authorization_header(request.headers_mut(), access_token)?;
}
Ok(())
}
fn extract_authentication<T: AsRef<[u8]>>(
request: &http::Request<T>,
) -> Result<Option<String>, Self::ExtractAuthenticationError> {
extract_bearer_or_query_token(request)
}
}
/// Add the given access token as an `Authorization` HTTP header to the given map.
fn add_access_token_as_authorization_header(
headers: &mut HeaderMap,
token: &str,
) -> Result<(), InvalidHeaderValue> {
headers.insert(header::AUTHORIZATION, format!("Bearer {token}").try_into()?);
Ok(())
}
/// Extract the access token from the `Authorization` HTTP header or the query string of the given
/// request.
fn extract_bearer_or_query_token<T>(
request: &http::Request<T>,
) -> Result<Option<String>, ExtractTokenError> {
if let Some(token) = extract_bearer_token_from_authorization_header(request.headers())? {
return Ok(Some(token));
}
if let Some(query) = request.uri().query() {
Ok(extract_access_token_from_query(query)?)
} else {
Ok(None)
}
}
/// Extract the value of the `Authorization` HTTP header with a `Bearer` scheme.
fn extract_bearer_token_from_authorization_header(
headers: &HeaderMap,
) -> Result<Option<String>, ExtractTokenError> {
const EXPECTED_START: &str = "bearer ";
let Some(value) = headers.get(header::AUTHORIZATION) else {
return Ok(None);
};
let value = value.to_str()?;
if value.len() < EXPECTED_START.len()
|| !value[..EXPECTED_START.len()].eq_ignore_ascii_case(EXPECTED_START)
{
return Err(ExtractTokenError::InvalidAuthorizationScheme);
}
Ok(Some(value[EXPECTED_START.len()..].to_owned()))
}
/// Extract the `access_token` from the given query string.
fn extract_access_token_from_query(
query: &str,
) -> Result<Option<String>, serde_html_form::de::Error> {
#[derive(Deserialize)]
struct AccessTokenDeHelper {
access_token: Option<String>,
}
serde_html_form::from_str::<AccessTokenDeHelper>(query).map(|helper| helper.access_token)
}
/// An enum to control whether an access token should be added to outgoing requests
#[derive(Clone, Copy, Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum SendAccessToken<'a> {
/// Add the given access token to the request only if the `METADATA` on the request requires
/// it.
IfRequired(&'a str),
/// Always add the access token.
Always(&'a str),
/// Add the given appservice token to the request only if the `METADATA` on the request
/// requires it.
Appservice(&'a str),
/// Don't add an access token.
///
/// This will lead to an error if the request endpoint requires authentication
None,
}
impl<'a> SendAccessToken<'a> {
/// Get the access token for an endpoint that requires one.
///
/// Returns `Some(_)` if `self` contains an access token.
pub fn get_required_for_endpoint(self) -> Option<&'a str> {
as_variant!(self, Self::IfRequired | Self::Appservice | Self::Always)
}
/// Get the access token for an endpoint that should not require one.
///
/// Returns `Some(_)` only if `self` is `SendAccessToken::Always(_)`.
pub fn get_not_required_for_endpoint(self) -> Option<&'a str> {
as_variant!(self, Self::Always)
}
/// Gets the access token for an endpoint that requires one for appservices.
///
/// Returns `Some(_)` if `self` is either `SendAccessToken::Appservice(_)`
/// or `SendAccessToken::Always(_)`
pub fn get_required_for_appservice(self) -> Option<&'a str> {
as_variant!(self, Self::Appservice | Self::Always)
}
}
/// An error that can occur when adding an [`AuthScheme`] that requires an access token.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AddRequiredTokenError {
/// No access token was provided, but the endpoint requires one.
#[error("no access token provided, but this endpoint requires one")]
MissingAccessToken,
/// Failed to convert the authentication to a header value.
#[error(transparent)]
IntoHeader(#[from] header::InvalidHeaderValue),
}
/// An error that can occur when extracting an [`AuthScheme`] that expects an access token.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ExtractTokenError {
/// No access token was found, but the endpoint requires one.
#[error("no access token found, but this endpoint requires one")]
MissingAccessToken,
/// Failed to convert the header value to a UTF-8 string.
#[error(transparent)]
FromHeader(#[from] header::ToStrError),
/// The scheme of the Authorization HTTP header is invalid.
#[error("invalid authorization header scheme")]
InvalidAuthorizationScheme,
/// Failed to deserialize the query string.
#[error("failed to deserialize query string: {0}")]
FromQuery(#[from] serde_html_form::de::Error),
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/events.rs | crates/core/src/events.rs | //! (De)serializable types for the events in the [Matrix](https://matrix.org) specification.
//! These types are used by other Palpo use crate::s.
//!
//! All data exchanged over Matrix is expressed as an event.
//! Different event types represent different actions, such as joining a room or
//! sending a message. Events are stored and transmitted as simple JSON
//! structures. While anyone can create a new event type for their own purposes,
//! the Matrix specification defines a number of event types which are
//! considered core to the protocol. This module contains Rust types for all of
//! the event types defined by the specification and facilities for extending
//! the event system for custom event types.
//!
//! # Core event types
//!
//! This module includes Rust types for all event types in the Matrix
//! specification. To better organize the crate, these types live in separate
//! modules with a hierarchy that matches the reverse domain name notation of
//! the event type. For example, the `m.room.message` event
//! lives at `palpo::events::room::message::RoomMessageEvent`. Each type's
//! module also contains a Rust type for that event type's `content` field, and
//! any other supporting types required by the event's other fields.
//!
//! # Extending Palpo with custom events
//!
//! For our examples we will start with a simple custom state event.
//! `palpo_event` specifies the state event's `type` and its `kind`.
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//!
//! use palpo_core::macros::EventContent;
//! use palpo_core::RoomVersionId;
//!
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[palpo_event(type = "org.example.event", kind = State, state_key_type = String)]
//! pub struct ExampleContent {
//! field: String,
//! }
//! ```
//!
//! This can be used with events structs, such as passing it into
//! `palpo::api::client::state::send_state_event`'s `Request`.
//!
//! As a more advanced example we create a reaction message event. For this
//! event we will use a [`OriginalSyncMessageLikeEvent`] struct but any
//! [`OriginalMessageLikeEvent`] struct would work.
//!
//! ```rust
//! use palpo_core::{RoomVersionId, OwnedEventId};
//! use palpo_core::events::OriginalSyncMessageLikeEvent;
//! use palpo_core::macros::EventContent;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize)]
//! #[serde(tag = "rel_type")]
//! pub enum RelatesTo {
//! #[serde(rename = "m.annotation")]
//! Annotation {
//! /// The event this reaction relates to.
//! event_id: OwnedEventId,
//! /// The displayable content of the reaction.
//! key: String,
//! },
//!
//! /// Since this event is not fully specified in the Matrix spec
//! /// it may change or types may be added, we are ready!
//! #[serde(rename = "m.whatever")]
//! Whatever,
//! }
//!
//! /// The payload for our reaction event.
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[palpo_event(type = "m.reaction", kind = MessageLike)]
//! pub struct ReactionEventContent {
//! #[serde(rename = "m.relates_to")]
//! pub relates_to: RelatesTo,
//! }
//!
//! let json = serde_json::json!({
//! "content": {
//! "m.relates_to": {
//! "event_id": "$xxxx-xxxx",
//! "key": "👍",
//! "rel_type": "m.annotation"
//! }
//! },
//! "event_id": "$xxxx-xxxx",
//! "origin_server_ts": 1,
//! "sender": "@someone:example.org",
//! "type": "m.reaction",
//! "unsigned": {
//! "age": 85
//! }
//! });
//!
//! // The downside of this event is we cannot use it with event enums,
//! // but could be deserialized from a `RawJson<_>` that has failed to deserialize.
//! assert!(matches!(
//! serde_json::from_value::<OriginalSyncMessageLikeEvent<ReactionEventContent>>(json),
//! Ok(OriginalSyncMessageLikeEvent {
//! content: ReactionEventContent {
//! relates_to: RelatesTo::Annotation { key, .. },
//! },
//! ..
//! }) if key == "👍"
//! ));
//! ```
// Needs to be public for trybuild tests
#[doc(hidden)]
pub mod _custom;
mod content;
mod enums;
mod kinds;
mod state_key;
mod unsigned;
#[cfg(feature = "unstable-msc3927")]
pub mod audio;
#[cfg(feature = "unstable-msc3489")]
pub mod beacon;
#[cfg(feature = "unstable-msc3489")]
pub mod beacon_info;
pub mod call;
pub mod direct;
#[cfg(feature = "unstable-msc4359")]
pub mod do_not_disturb;
pub mod dummy;
#[cfg(feature = "unstable-msc3954")]
pub mod emote;
#[cfg(feature = "unstable-msc3956")]
pub mod encrypted;
#[cfg(feature = "unstable-msc3551")]
pub mod file;
pub mod forwarded_room_key;
pub mod fully_read;
pub mod identity_server;
pub mod ignored_user_list;
#[cfg(feature = "unstable-msc3552")]
pub mod image;
#[cfg(feature = "unstable-msc2545")]
pub mod image_pack;
#[cfg(feature = "unstable-msc4380")]
pub mod invite_permission_config;
pub mod key;
#[cfg(feature = "unstable-msc3488")]
pub mod location;
pub mod marked_unread;
#[cfg(feature = "unstable-msc4278")]
pub mod media_preview_config;
#[cfg(feature = "unstable-msc4171")]
pub mod member_hints;
pub mod message;
// pub mod pdu;
pub mod policy;
#[cfg(feature = "unstable-msc3381")]
pub mod poll;
pub mod presence;
pub mod push_rules;
pub mod reaction;
pub mod receipt;
pub mod relation;
pub mod room;
pub mod room_key;
#[cfg(feature = "unstable-msc4268")]
pub mod room_key_bundle;
pub mod room_key_request;
#[cfg(any(feature = "unstable-msc4310", feature = "unstable-msc4075"))]
pub mod rtc;
pub mod secret;
pub mod secret_storage;
pub mod space;
#[cfg(feature = "unstable-msc3230")]
pub mod space_order;
pub mod sticker;
pub mod tag;
pub mod typing;
#[cfg(feature = "unstable-msc3553")]
pub mod video;
#[cfg(feature = "unstable-msc3245")]
pub mod voice;
use std::collections::BTreeSet;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize, Serializer, de::IgnoredAny};
pub use self::{
content::*,
enums::*,
kinds::*,
relation::{BundledMessageLikeRelations, BundledStateRelations},
state_key::EmptyStateKey,
unsigned::{MessageLikeUnsigned, RedactedUnsigned, StateUnsigned, UnsignedRoomRedactionEvent},
};
use crate::room_version_rules::RedactionRules;
use crate::{EventEncryptionAlgorithm, OwnedUserId};
const INLINE_SIZE: usize = 48;
/// Trait to define the behavior of redact an event's content object.
pub trait RedactContent {
/// The redacted form of the event's content.
type Redacted;
/// Transform `self` into a redacted form (removing most or all fields) according to the spec.
///
/// A small number of events have room-version specific redaction behavior, so a
/// [`RedactionRules`] has to be specified.
fn redact(self, rules: &RedactionRules) -> Self::Redacted;
}
/// Helper struct to determine the event kind from a
/// `serde_json::value::RawValue`.
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct EventTypeDeHelper<'a> {
#[serde(borrow, rename = "type")]
pub ev_type: std::borrow::Cow<'a, str>,
}
/// Helper struct to determine if an event has been redacted.
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct RedactionDeHelper {
/// Used to check whether redacted_because exists.
pub unsigned: Option<UnsignedDeHelper>,
}
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct UnsignedDeHelper {
/// This is the field that signals an event has been redacted.
pub redacted_because: Option<IgnoredAny>,
}
/// Helper function for erroring when trying to serialize an event enum _Custom
/// variant that can only be created by deserializing from an unknown event
/// type.
#[doc(hidden)]
#[allow(clippy::ptr_arg)]
pub fn serialize_custom_event_error<T, S: Serializer>(_: &T, _: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom(
"Failed to serialize event [content] enum: Unknown event type.\n\
To send custom events, turn them into `RawJson<EnumType>` by going through
`serde_json::value::to_raw_value` and `RawJson::from_json`.",
))
}
/// Describes whether the event mentions other users or the room.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Mentions {
/// The list of mentioned users.
///
/// Defaults to an empty `BTreeSet`.
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub user_ids: BTreeSet<OwnedUserId>,
/// Whether the whole room is mentioned.
///
/// Defaults to `false`.
#[serde(default, skip_serializing_if = "palpo_core::serde::is_default")]
pub room: bool,
}
impl Mentions {
/// Create a `Mentions` with the default values.
pub fn new() -> Self {
Self::default()
}
/// Create a `Mentions` for the given user IDs.
pub fn with_user_ids(user_ids: impl IntoIterator<Item = OwnedUserId>) -> Self {
Self {
user_ids: BTreeSet::from_iter(user_ids),
..Default::default()
}
}
/// Create a `Mentions` for a room mention.
pub fn with_room_mention() -> Self {
Self {
room: true,
..Default::default()
}
}
fn add(&mut self, mentions: Self) {
self.user_ids.extend(mentions.user_ids);
self.room |= mentions.room;
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity.rs | crates/core/src/identity.rs | //! (De)serializable types for the [Matrix Identity Service API][identity-api].
//! These types can be shared by client and identity service code.
//!
//! [identity-api]: https://spec.matrix.org/latest/identity-service-api/
use std::fmt;
pub mod association;
pub mod authentication;
pub mod discovery;
pub mod invitation;
pub mod keys;
pub mod lookup;
pub mod tos;
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/space.rs | crates/core/src/space.rs | //! Common types for [spaces].
//!
//! [spaces]: https://spec.matrix.org/latest/client-server-api/#spaces
use salvo::prelude::*;
use crate::macros::StringEnum;
use crate::{PrivOwnedStr, room::JoinRule};
/// The rule used for users wishing to join a room.
///
/// In contrast to the regular `JoinRule` in `palpo_core::events`, this enum
/// does not hold the conditions for joining restricted rooms. Instead, the
/// server is assumed to only return rooms the user is allowed to join in a
/// space hierarchy listing response.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, Default, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
pub enum SpaceRoomJoinRule {
/// A user who wishes to join the room must first receive an invite to the
/// room from someone already inside of the room.
Invite,
/// Users can join the room if they are invited, or they can request an
/// invite to the room.
///
/// They can be allowed (invited) or denied (kicked/banned) access.
Knock,
/// Reserved but not yet implemented by the Matrix specification.
Private,
/// Users can join the room if they are invited, or if they meet any of the
/// conditions described in a set of allow rules.
///
/// These rules are not made available as part of a space hierarchy listing
/// response and can only be seen by users inside the room.
Restricted,
/// Users can join the room if they are invited, or if they meet any of the
/// conditions described in a set of allow rules, or they can request an
/// invite to the room.
KnockRestricted,
/// Anyone can join the room without any prior action.
#[default]
Public,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
impl From<JoinRule> for SpaceRoomJoinRule {
fn from(value: JoinRule) -> Self {
value.as_str().into()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/metadata.rs | crates/core/src/metadata.rs | mod matrix_version;
pub use matrix_version::*;
mod supported_versions;
pub use supported_versions::*;
// #[cfg(test)]
// mod tests;
// /// The complete history of this endpoint as far as Palpo knows, together
// with all variants on /// versions stable and unstable.
// ///
// /// The amount and positioning of path variables are the same over all path
// variants. #[derive(Clone, Debug)]
// #[allow(clippy::exhaustive_structs)]
// pub struct VersionHistory {
// /// A list of unstable paths over this endpoint's history.
// ///
// /// For endpoint querying purposes, the last item will be used.
// unstable_paths: &'static [&'static str],
// /// A list of path versions, mapped to Matrix versions.
// ///
// /// Sorted (ascending) by Matrix version, will not mix major versions.
// stable_paths: &'static [(MatrixVersion, &'static str)],
// /// The Matrix version that deprecated this endpoint.
// ///
// /// Deprecation often precedes one Matrix version before removal.
// ///
// /// This will make
// [`try_into_http_request`](super::OutgoingRequest::try_into_http_request)
// /// emit a warning, see the corresponding documentation for more
// information. deprecated: Option<MatrixVersion>,
// /// The Matrix version that removed this endpoint.
// ///
// /// This will make
// [`try_into_http_request`](super::OutgoingRequest::try_into_http_request)
// /// emit an error, see the corresponding documentation for more
// information. removed: Option<MatrixVersion>,
// }
// impl VersionHistory {
// /// Constructs an instance of [`VersionHistory`], erroring on compilation
// if it does not pass /// invariants.
// ///
// /// Specifically, this checks the following invariants:
// /// - Path Arguments are equal (in order, amount, and argument name) in
// all path strings /// - In stable_paths:
// /// - matrix versions are in ascending order
// /// - no matrix version is referenced twice
// /// - deprecated's version comes after the latest version mentioned in
// stable_paths, except for /// version 1.0, and only if any stable path
// is defined /// - removed comes after deprecated, or after the latest
// referenced stable_paths, like /// deprecated
// pub const fn new(
// unstable_paths: &'static [&'static str],
// stable_paths: &'static [(MatrixVersion, &'static str)],
// deprecated: Option<MatrixVersion>,
// removed: Option<MatrixVersion>,
// ) -> Self {
// use konst::{iter, slice, string};
// const fn check_path_is_valid(path: &'static str) {
// iter::for_each!(path_b in slice::iter(path.as_bytes()) => {
// match *path_b {
// 0x21..=0x7E => {},
// _ => panic!("path contains invalid (non-ascii or
// whitespace) characters") }
// });
// }
// const fn check_path_args_equal(first: &'static str, second: &'static
// str) { let mut second_iter = string::split(second, "/").next();
// iter::for_each!(first_s in string::split(first, "/") => {
// if let Some(first_arg) = string::strip_prefix(first_s, ":") {
// let second_next_arg: Option<&'static str> = loop {
// let (second_s, second_n_iter) = match second_iter {
// Some(tuple) => tuple,
// None => break None,
// };
// let maybe_second_arg = string::strip_prefix(second_s,
// ":");
// second_iter = second_n_iter.next();
// if let Some(second_arg) = maybe_second_arg {
// break Some(second_arg);
// }
// };
// if let Some(second_next_arg) = second_next_arg {
// if !string::eq_str(second_next_arg, first_arg) {
// panic!("Path Arguments do not match");
// }
// } else {
// panic!("Amount of Path Arguments do not match");
// }
// }
// });
// // If second iterator still has some values, empty first.
// while let Some((second_s, second_n_iter)) = second_iter {
// if string::starts_with(second_s, ":") {
// panic!("Amount of Path Arguments do not match");
// }
// second_iter = second_n_iter.next();
// }
// }
// // The path we're going to use to compare all other paths with
// let ref_path: &str = if let Some(s) = unstable_paths.first() {
// s
// } else if let Some((_, s)) = stable_paths.first() {
// s
// } else {
// panic!("No paths supplied")
// };
// iter::for_each!(unstable_path in slice::iter(unstable_paths) => {
// check_path_is_valid(unstable_path);
// check_path_args_equal(ref_path, unstable_path);
// });
// let mut prev_seen_version: Option<MatrixVersion> = None;
// iter::for_each!(stable_path in slice::iter(stable_paths) => {
// check_path_is_valid(stable_path.1);
// check_path_args_equal(ref_path, stable_path.1);
// let current_version = stable_path.0;
// if let Some(prev_seen_version) = prev_seen_version {
// let cmp_result =
// current_version.const_ord(&prev_seen_version);
// if cmp_result.is_eq() {
// // Found a duplicate, current == previous
// panic!("Duplicate matrix version in stable_paths")
// } else if cmp_result.is_lt() {
// // Found an older version, current < previous
// panic!("No ascending order in stable_paths")
// }
// }
// prev_seen_version = Some(current_version);
// });
// if let Some(deprecated) = deprecated {
// if let Some(prev_seen_version) = prev_seen_version {
// let ord_result = prev_seen_version.const_ord(&deprecated);
// if !deprecated.is_legacy() && ord_result.is_eq() {
// // prev_seen_version == deprecated, except for 1.0.
// // It is possible that an endpoint was both made stable
// and deprecated in the // legacy versions.
// panic!("deprecated version is equal to latest stable path
// version") } else if ord_result.is_gt() {
// // prev_seen_version > deprecated
// panic!("deprecated version is older than latest stable
// path version") }
// } else {
// panic!("Defined deprecated version while no stable path
// exists") }
// }
// if let Some(removed) = removed {
// if let Some(deprecated) = deprecated {
// let ord_result = deprecated.const_ord(&removed);
// if ord_result.is_eq() {
// // deprecated == removed
// panic!("removed version is equal to deprecated version")
// } else if ord_result.is_gt() {
// // deprecated > removed
// panic!("removed version is older than deprecated
// version") }
// } else {
// panic!("Defined removed version while no deprecated version
// exists") }
// }
// VersionHistory {
// unstable_paths,
// stable_paths,
// deprecated,
// removed,
// }
// }
// // This function helps picks the right path (or an error) from a set of
// Matrix versions. fn select_path(&self, versions: &[MatrixVersion]) ->
// Result<&'static str, IntoHttpError> { match
// self.versioning_decision_for(versions) {
// VersioningDecision::Removed => Err(IntoHttpError::EndpointRemoved(
// self.removed.expect("VersioningDecision::Removed implies
// metadata.removed"), )),
// VersioningDecision::Stable {
// any_deprecated,
// all_deprecated,
// any_removed,
// } => {
// if any_removed {
// if all_deprecated {
// warn!(
// "endpoint is removed in some (and deprecated in
// ALL) \ of the following versions: {versions:?}",
// );
// } else if any_deprecated {
// warn!(
// "endpoint is removed (and deprecated) in some of
// the \ following versions: {versions:?}",
// );
// } else {
// unreachable!("any_removed implies *_deprecated");
// }
// } else if all_deprecated {
// warn!(
// "endpoint is deprecated in ALL of the following
// versions: \ {versions:?}",
// );
// } else if any_deprecated {
// warn!(
// "endpoint is deprecated in some of the following
// versions: \ {versions:?}",
// );
// }
// Ok(self
// .stable_endpoint_for(versions)
// .expect("VersioningDecision::Stable implies that a stable
// path exists")) }
// VersioningDecision::Unstable =>
// self.unstable().ok_or(IntoHttpError::NoUnstablePath), }
// }
// /// Will decide how a particular set of Matrix versions sees an endpoint.
// ///
// /// It will only return `Deprecated` or `Removed` if all versions denote
// it. ///
// /// In other words, if in any version it tells it supports the endpoint
// in a stable fashion, /// this will return `Stable`, even if some versions
// in this set will denote deprecation or /// removal.
// ///
// /// If resulting [`VersioningDecision`] is `Stable`, it will also detail
// if any version denoted /// deprecation or removal.
// pub fn versioning_decision_for(&self, versions: &[MatrixVersion]) ->
// VersioningDecision { let greater_or_equal_any = |version:
// MatrixVersion| versions.iter().any(|v| v.is_superset_of(version));
// let greater_or_equal_all = |version: MatrixVersion|
// versions.iter().all(|v| v.is_superset_of(version));
// // Check if all versions removed this endpoint.
// if self.removed.is_some_and(greater_or_equal_all) {
// return VersioningDecision::Removed;
// }
// // Check if *any* version marks this endpoint as stable.
// if self.added_in().is_some_and(greater_or_equal_any) {
// let all_deprecated =
// self.deprecated.is_some_and(greater_or_equal_all);
// return VersioningDecision::Stable {
// any_deprecated: all_deprecated ||
// self.deprecated.is_some_and(greater_or_equal_any),
// all_deprecated, any_removed:
// self.removed.is_some_and(greater_or_equal_any), };
// }
// VersioningDecision::Unstable
// }
// /// Returns the *first* version this endpoint was added in.
// ///
// /// Is `None` when this endpoint is unstable/unreleased.
// pub fn added_in(&self) -> Option<MatrixVersion> {
// self.stable_paths.first().map(|(v, _)| *v)
// }
// /// Returns the Matrix version that deprecated this endpoint, if any.
// pub fn deprecated_in(&self) -> Option<MatrixVersion> {
// self.deprecated
// }
// /// Returns the Matrix version that removed this endpoint, if any.
// pub fn removed_in(&self) -> Option<MatrixVersion> {
// self.removed
// }
// /// Picks the last unstable path, if it exists.
// pub fn unstable(&self) -> Option<&'static str> {
// self.unstable_paths.last().copied()
// }
// /// Returns all path variants in canon form, for use in server routers.
// pub fn all_paths(&self) -> impl Iterator<Item = &'static str> {
// self.unstable_paths().chain(self.stable_paths().map(|(_, path)|
// path)) }
// /// Returns all unstable path variants in canon form.
// pub fn unstable_paths(&self) -> impl Iterator<Item = &'static str> {
// self.unstable_paths.iter().copied()
// }
// /// Returns all stable path variants in canon form, with corresponding
// Matrix version. pub fn stable_paths(&self) -> impl Iterator<Item =
// (MatrixVersion, &'static str)> { self.stable_paths.iter().
// map(|(version, data)| (*version, *data)) }
// /// The path that should be used to query the endpoint, given a series of
// versions. ///
// /// This will pick the latest path that the version accepts.
// ///
// /// This will return an endpoint in the following format;
// ///
// /// Note: This will not keep in mind endpoint removals, check with
// /// [`versioning_decision_for`](VersionHistory::versioning_decision_for)
// to see if this endpoint /// is still available.
// pub fn stable_endpoint_for(&self, versions: &[MatrixVersion]) ->
// Option<&'static str> { // Go reverse, to check the "latest" version
// first. for (ver, path) in self.stable_paths.iter().rev() {
// // Check if any of the versions are equal or greater than the
// version the path needs. if versions.iter().any(|v|
// v.is_superset_of(*ver)) { return Some(path);
// }
// }
// None
// }
// }
// /// A versioning "decision" derived from a set of Matrix versions.
// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
// #[allow(clippy::exhaustive_enums)]
// pub enum VersioningDecision {
// /// The unstable endpoint should be used.
// Unstable,
// /// The stable endpoint should be used.
// Stable {
// /// If any version denoted deprecation.
// any_deprecated: bool,
// /// If *all* versions denoted deprecation.
// all_deprecated: bool,
// /// If any version denoted removal.
// any_removed: bool,
// },
// /// This endpoint was removed in all versions, it should not be used.
// Removed,
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/room.rs | crates/core/src/room.rs | //! Common types for rooms.
use std::{
borrow::{Borrow, Cow},
collections::BTreeMap,
};
use as_variant::as_variant;
use salvo::prelude::*;
use serde::de::Error as _;
use serde::{Deserialize, Serialize, de};
use serde_json::{Value as JsonValue, value::RawValue as RawJsonValue};
use crate::{
Direction, EventEncryptionAlgorithm, OwnedEventId, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId,
OwnedUserId, PrivOwnedStr, RoomId, RoomVersionId, UnixMillis,
events::StateEventType,
serde::{StringEnum, JsonObject, from_raw_json_value},
};
/// An enum of possible room types.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum RoomType {
/// Defines the room as a space.
#[palpo_enum(rename = "m.space")]
Space,
/// Defines the room as a custom type.
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, Default, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Visibility {
/// Indicates that the room will be shown in the published room list.
Public,
/// Indicates that the room will not be shown in the published room list.
#[default]
Private,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct RoomEventReqArgs {
/// Room in which the event to be reported is located.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// Event to report.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct RoomTypingReqArgs {
/// Room in which the event to be reported is located.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// Event to report.
#[salvo(parameter(parameter_in = Path))]
pub user_id: OwnedUserId,
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct RoomUserReqArgs {
/// Room in which the event to be reported is located.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// Event to report.
#[salvo(parameter(parameter_in = Path))]
pub event_id: OwnedEventId,
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct RoomEventTypeReqArgs {
/// The ID of the room the event is in.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The ID of the event.
#[salvo(parameter(parameter_in = Path))]
pub event_type: StateEventType,
}
/// The rule used for users wishing to join this room.
///
/// This type can hold an arbitrary join rule. To check for values that are not available as a
/// documented variant here, get its kind with [`.kind()`](Self::kind) or its string representation
/// with [`.as_str()`](Self::as_str), and its associated data with [`.data()`](Self::data).
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "join_rule", rename_all = "snake_case")]
pub enum JoinRule {
/// A user who wishes to join the room must first receive an invite to the
/// room from someone already inside of the room.
Invite,
/// Users can join the room if they are invited, or they can request an
/// invite to the room.
///
/// They can be allowed (invited) or denied (kicked/banned) access.
Knock,
/// Reserved but not yet implemented by the Matrix specification.
Private,
/// Users can join the room if they are invited, or if they meet any of the
/// conditions described in a set of [`AllowRule`]s.
Restricted(Restricted),
/// Users can join the room if they are invited, or if they meet any of the
/// conditions described in a set of [`AllowRule`]s, or they can request
/// an invite to the room.
KnockRestricted(Restricted),
/// Anyone can join the room without any prior action.
Public,
#[doc(hidden)]
#[salvo(schema(value_type = Object))]
_Custom(CustomJoinRule),
}
impl JoinRule {
/// Returns the kind of this `JoinRule`.
pub fn kind(&self) -> JoinRuleKind {
match self {
Self::Invite => JoinRuleKind::Invite,
Self::Knock => JoinRuleKind::Knock,
Self::Private => JoinRuleKind::Private,
Self::Restricted(_) => JoinRuleKind::Restricted,
Self::KnockRestricted(_) => JoinRuleKind::KnockRestricted,
Self::Public => JoinRuleKind::Public,
Self::_Custom(CustomJoinRule { join_rule, .. }) => {
JoinRuleKind::_Custom(PrivOwnedStr(join_rule.as_str().into()))
}
}
}
pub fn is_restricted(&self) -> bool {
matches!(self, JoinRule::Restricted(_) | JoinRule::KnockRestricted(_))
}
pub fn restriction_rooms(&self) -> Vec<OwnedRoomId> {
match self {
JoinRule::Restricted(restricted) | JoinRule::KnockRestricted(restricted) => restricted
.allow
.iter()
.filter_map(|a| match a {
AllowRule::RoomMembership(r) => Some(r.room_id.clone()),
_ => None,
})
.collect(),
_ => Vec::new(),
}
}
/// Returns allowed room_id's for restricted rooms; empty for other variants
pub fn allowed_rooms(&self) -> impl Iterator<Item = &RoomId> + Send {
let rules = match self {
JoinRule::Restricted(rules) | JoinRule::KnockRestricted(rules) => Some(rules),
_ => None,
};
rules
.into_iter()
.flat_map(|rules| rules.allow.iter())
.filter_map(|rule| {
if let AllowRule::RoomMembership(RoomMembership {
room_id: membership,
}) = rule
{
Some(membership.borrow())
} else {
None
}
})
}
/// Returns the string name of this `JoinRule`
pub fn as_str(&self) -> &str {
match self {
JoinRule::Invite => "invite",
JoinRule::Knock => "knock",
JoinRule::Private => "private",
JoinRule::Restricted(_) => "restricted",
JoinRule::KnockRestricted(_) => "knock_restricted",
JoinRule::Public => "public",
JoinRule::_Custom(CustomJoinRule { join_rule, .. }) => join_rule,
}
}
/// Returns the associated data of this `JoinRule`.
///
/// The returned JSON object won't contain the `join_rule` field, use
/// [`.kind()`](Self::kind) or [`.as_str()`](Self::as_str) to access those.
///
/// Prefer to use the public variants of `JoinRule` where possible; this method is meant to
/// be used for custom join rules only.
pub fn data(&self) -> Cow<'_, JsonObject> {
fn serialize<T: Serialize>(obj: &T) -> JsonObject {
match serde_json::to_value(obj).expect("join rule serialization should succeed") {
JsonValue::Object(mut obj) => {
obj.remove("body");
obj
}
_ => panic!("all message types should serialize to objects"),
}
}
match self {
JoinRule::Invite | JoinRule::Knock | JoinRule::Private | JoinRule::Public => {
Cow::Owned(JsonObject::new())
}
JoinRule::Restricted(restricted) | JoinRule::KnockRestricted(restricted) => {
Cow::Owned(serialize(restricted))
}
Self::_Custom(c) => Cow::Borrowed(&c.data),
}
}
}
impl<'de> Deserialize<'de> for JoinRule {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json: Box<RawJsonValue> = Box::deserialize(deserializer)?;
#[derive(Deserialize)]
struct ExtractType<'a> {
#[serde(borrow)]
join_rule: Option<Cow<'a, str>>,
}
let join_rule = serde_json::from_str::<ExtractType<'_>>(json.get())
.map_err(serde::de::Error::custom)?
.join_rule
.ok_or_else(|| D::Error::missing_field("join_rule"))?;
match join_rule.as_ref() {
"invite" => Ok(Self::Invite),
"knock" => Ok(Self::Knock),
"private" => Ok(Self::Private),
"restricted" => from_raw_json_value(&json).map(Self::Restricted),
"knock_restricted" => from_raw_json_value(&json).map(Self::KnockRestricted),
"public" => Ok(Self::Public),
_ => from_raw_json_value(&json).map(Self::_Custom),
}
}
}
/// The payload for an unsupported join rule.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct CustomJoinRule {
/// The kind of join rule.
join_rule: String,
/// The remaining data.
#[serde(flatten)]
data: JsonObject,
}
/// Configuration of the `Restricted` join rule.
#[derive(ToSchema, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Restricted {
/// Allow rules which describe conditions that allow joining a room.
#[serde(default, deserialize_with = "crate::serde::ignore_invalid_vec_items")]
pub allow: Vec<AllowRule>,
}
impl Restricted {
/// Constructs a new rule set for restricted rooms with the given rules.
pub fn new(allow: Vec<AllowRule>) -> Self {
Self { allow }
}
}
/// An allow rule which defines a condition that allows joining a room.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum AllowRule {
/// Joining is allowed if a user is already a member of the room with the id
/// `room_id`.
RoomMembership(RoomMembership),
#[doc(hidden)]
_Custom(Box<CustomAllowRule>),
}
impl AllowRule {
/// Constructs an `AllowRule` with membership of the room with the given id
/// as its predicate.
pub fn room_membership(room_id: OwnedRoomId) -> Self {
Self::RoomMembership(RoomMembership::new(room_id))
}
}
/// Allow rule which grants permission to join based on the membership of
/// another room.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename = "m.room_membership")]
pub struct RoomMembership {
/// The id of the room which being a member of grants permission to join
/// another room.
pub room_id: OwnedRoomId,
}
impl RoomMembership {
/// Constructs a new room membership rule for the given room id.
pub fn new(room_id: OwnedRoomId) -> Self {
Self { room_id }
}
}
#[doc(hidden)]
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CustomAllowRule {
#[serde(rename = "type")]
rule_type: String,
#[serde(flatten)]
#[salvo(schema(value_type = Object, additional_properties = true))]
extra: BTreeMap<String, JsonValue>,
}
impl<'de> Deserialize<'de> for AllowRule {
fn deserialize<D>(deserializer: D) -> Result<AllowRule, D::Error>
where
D: de::Deserializer<'de>,
{
let json: Box<RawJsonValue> = Box::deserialize(deserializer)?;
// Extracts the `type` value.
#[derive(Deserialize)]
struct ExtractType<'a> {
#[serde(borrow, rename = "type")]
rule_type: Option<Cow<'a, str>>,
}
// Get the value of `type` if present.
let rule_type = serde_json::from_str::<ExtractType<'_>>(json.get())
.map_err(serde::de::Error::custom)?
.rule_type;
match rule_type.as_deref() {
Some("m.room_membership") => from_raw_json_value(&json).map(Self::RoomMembership),
Some(_) => from_raw_json_value(&json).map(Self::_Custom),
None => Err(D::Error::missing_field("type")),
}
}
}
/// The kind of rule used for users wishing to join this room.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, Default, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
pub enum JoinRuleKind {
/// A user who wishes to join the room must first receive an invite to the room from someone
/// already inside of the room.
Invite,
/// Users can join the room if they are invited, or they can request an invite to the room.
///
/// They can be allowed (invited) or denied (kicked/banned) access.
Knock,
/// Reserved but not yet implemented by the Matrix specification.
Private,
/// Users can join the room if they are invited, or if they meet any of the conditions
/// described in a set of rules.
Restricted,
/// Users can join the room if they are invited, or if they meet any of the conditions
/// described in a set of rules, or they can request an invite to the room.
KnockRestricted,
/// Anyone can join the room without any prior action.
#[default]
Public,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl From<JoinRuleKind> for JoinRuleSummary {
fn from(value: JoinRuleKind) -> Self {
match value {
JoinRuleKind::Invite => Self::Invite,
JoinRuleKind::Knock => Self::Knock,
JoinRuleKind::Private => Self::Private,
JoinRuleKind::Restricted => Self::Restricted(Default::default()),
JoinRuleKind::KnockRestricted => Self::KnockRestricted(Default::default()),
JoinRuleKind::Public => Self::Public,
JoinRuleKind::_Custom(s) => Self::_Custom(s),
}
}
}
/// The summary of a room's state.
#[derive(Debug, Clone, Serialize)]
pub struct RoomSummary {
/// The ID of the room.
pub room_id: OwnedRoomId,
/// The canonical alias of the room, if any.
///
/// If the `compat-empty-string-null` cargo feature is enabled, this field being an empty
/// string in JSON will result in `None` here during deserialization.
#[serde(skip_serializing_if = "Option::is_none")]
pub canonical_alias: Option<OwnedRoomAliasId>,
/// The name of the room, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The topic of the room, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub topic: Option<String>,
/// The URL for the room's avatar, if one is set.
///
/// If you activate the `compat-empty-string-null` feature, this field being an empty string in
/// JSON will result in `None` here during deserialization.
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<OwnedMxcUri>,
/// The type of room from `m.room.create`, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub room_type: Option<RoomType>,
/// The number of members joined to the room.
pub num_joined_members: u64,
/// The join rule of the room.
#[serde(flatten, skip_serializing_if = "crate::serde::is_default")]
pub join_rule: JoinRuleSummary,
/// Whether the room may be viewed by users without joining.
pub world_readable: bool,
/// Whether guest users may join the room and participate in it.
///
/// If they can, they will be subject to ordinary power level rules like any other user.
pub guest_can_join: bool,
/// If the room is encrypted, the algorithm used for this room.
#[serde(skip_serializing_if = "Option::is_none")]
pub encryption: Option<EventEncryptionAlgorithm>,
/// The version of the room.
#[serde(skip_serializing_if = "Option::is_none")]
pub room_version: Option<RoomVersionId>,
}
impl RoomSummary {
/// Construct a new `RoomSummary` with the given required fields.
pub fn new(
room_id: OwnedRoomId,
join_rule: JoinRuleSummary,
guest_can_join: bool,
num_joined_members: u64,
world_readable: bool,
) -> Self {
Self {
room_id,
canonical_alias: None,
name: None,
topic: None,
avatar_url: None,
room_type: None,
num_joined_members,
join_rule,
world_readable,
guest_can_join,
encryption: None,
room_version: None,
}
}
}
impl<'de> Deserialize<'de> for RoomSummary {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
/// Helper type to deserialize [`RoomSummary`] because using `flatten` on `join_rule`
/// returns an error.
#[derive(Deserialize)]
struct RoomSummaryDeHelper {
room_id: OwnedRoomId,
#[cfg_attr(
feature = "compat-empty-string-null",
serde(default, deserialize_with = "crate::serde::empty_string_as_none")
)]
canonical_alias: Option<OwnedRoomAliasId>,
name: Option<String>,
topic: Option<String>,
#[cfg_attr(
feature = "compat-empty-string-null",
serde(default, deserialize_with = "crate::serde::empty_string_as_none")
)]
avatar_url: Option<OwnedMxcUri>,
room_type: Option<RoomType>,
num_joined_members: u64,
world_readable: bool,
guest_can_join: bool,
encryption: Option<EventEncryptionAlgorithm>,
room_version: Option<RoomVersionId>,
}
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let RoomSummaryDeHelper {
room_id,
canonical_alias,
name,
topic,
avatar_url,
room_type,
num_joined_members,
world_readable,
guest_can_join,
encryption,
room_version,
} = from_raw_json_value(&json)?;
let join_rule: JoinRuleSummary = from_raw_json_value(&json)?;
Ok(Self {
room_id,
canonical_alias,
name,
topic,
avatar_url,
room_type,
num_joined_members,
join_rule,
world_readable,
guest_can_join,
encryption,
room_version,
})
}
}
/// The rule used for users wishing to join a room.
///
/// In contrast to the regular [`JoinRule`], this enum holds only simplified conditions for joining
/// restricted rooms.
///
/// This type can hold an arbitrary join rule. To check for values that are not available as a
/// documented variant here, get its kind with `.kind()` or use its string representation, obtained
/// through `.as_str()`.
///
/// Because this type contains a few neighbouring fields instead of a whole object, and it is not
/// possible to know which fields to parse for unknown variants, this type will fail to serialize if
/// it doesn't match one of the documented variants. It is only possible to construct an
/// undocumented variant by deserializing it, so do not re-serialize this type.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(tag = "join_rule", rename_all = "snake_case")]
pub enum JoinRuleSummary {
/// A user who wishes to join the room must first receive an invite to the room from someone
/// already inside of the room.
Invite,
/// Users can join the room if they are invited, or they can request an invite to the room.
///
/// They can be allowed (invited) or denied (kicked/banned) access.
Knock,
/// Reserved but not yet implemented by the Matrix specification.
Private,
/// Users can join the room if they are invited, or if they meet one of the conditions
/// described in the [`RestrictedSummary`].
Restricted(RestrictedSummary),
/// Users can join the room if they are invited, or if they meet one of the conditions
/// described in the [`RestrictedSummary`], or they can request an invite to the room.
KnockRestricted(RestrictedSummary),
/// Anyone can join the room without any prior action.
#[default]
Public,
#[doc(hidden)]
#[serde(skip_serializing)]
_Custom(PrivOwnedStr),
}
impl JoinRuleSummary {
/// Returns the kind of this `JoinRuleSummary`.
pub fn kind(&self) -> JoinRuleKind {
match self {
Self::Invite => JoinRuleKind::Invite,
Self::Knock => JoinRuleKind::Knock,
Self::Private => JoinRuleKind::Private,
Self::Restricted(_) => JoinRuleKind::Restricted,
Self::KnockRestricted(_) => JoinRuleKind::KnockRestricted,
Self::Public => JoinRuleKind::Public,
Self::_Custom(rule) => JoinRuleKind::_Custom(rule.clone()),
}
}
/// Returns the string name of this `JoinRuleSummary`.
pub fn as_str(&self) -> &str {
match self {
Self::Invite => "invite",
Self::Knock => "knock",
Self::Private => "private",
Self::Restricted(_) => "restricted",
Self::KnockRestricted(_) => "knock_restricted",
Self::Public => "public",
Self::_Custom(rule) => &rule.0,
}
}
}
impl From<JoinRule> for JoinRuleSummary {
fn from(value: JoinRule) -> Self {
match value {
JoinRule::Invite => Self::Invite,
JoinRule::Knock => Self::Knock,
JoinRule::Private => Self::Private,
JoinRule::Restricted(restricted) => Self::Restricted(restricted.into()),
JoinRule::KnockRestricted(restricted) => Self::KnockRestricted(restricted.into()),
JoinRule::Public => Self::Public,
JoinRule::_Custom(CustomJoinRule { join_rule, .. }) => {
Self::_Custom(PrivOwnedStr(join_rule.into()))
}
}
}
}
impl<'de> Deserialize<'de> for JoinRuleSummary {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json: Box<RawJsonValue> = Box::deserialize(deserializer)?;
#[derive(Deserialize)]
struct ExtractType<'a> {
#[serde(borrow)]
join_rule: Option<Cow<'a, str>>,
}
let Some(join_rule) = serde_json::from_str::<ExtractType<'_>>(json.get())
.map_err(de::Error::custom)?
.join_rule
else {
return Ok(Self::default());
};
match join_rule.as_ref() {
"invite" => Ok(Self::Invite),
"knock" => Ok(Self::Knock),
"private" => Ok(Self::Private),
"restricted" => from_raw_json_value(&json).map(Self::Restricted),
"knock_restricted" => from_raw_json_value(&json).map(Self::KnockRestricted),
"public" => Ok(Self::Public),
_ => Ok(Self::_Custom(PrivOwnedStr(join_rule.into()))),
}
}
}
/// A summary of the conditions for joining a restricted room.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RestrictedSummary {
/// The room IDs which are specified by the join rules.
#[serde(default)]
pub allowed_room_ids: Vec<OwnedRoomId>,
}
impl RestrictedSummary {
/// Constructs a new `RestrictedSummary` with the given room IDs.
pub fn new(allowed_room_ids: Vec<OwnedRoomId>) -> Self {
Self { allowed_room_ids }
}
}
impl From<Restricted> for RestrictedSummary {
fn from(value: Restricted) -> Self {
let allowed_room_ids = value
.allow
.into_iter()
.filter_map(|allow_rule| {
let membership = as_variant!(allow_rule, AllowRule::RoomMembership)?;
Some(membership.room_id)
})
.collect();
Self::new(allowed_room_ids)
}
}
/// Request type for the `get_event_by_timestamp` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct TimestampToEventReqArgs {
/// The ID of the room the event is in.
#[salvo(parameter(parameter_in = Path))]
pub room_id: OwnedRoomId,
/// The timestamp to search from, inclusively.
#[salvo(parameter(parameter_in = Query))]
pub ts: UnixMillis,
/// The direction in which to search.
#[salvo(parameter(parameter_in = Query))]
pub dir: Direction,
}
/// Response type for the `get_event_by_timestamp` endpoint.
#[derive(ToSchema, Deserialize, Serialize, Debug)]
pub struct TimestampToEventResBody {
/// The ID of the event found.
pub event_id: OwnedEventId,
/// The event's timestamp.
pub origin_server_ts: UnixMillis,
}
impl TimestampToEventResBody {
/// Creates a new `Response` with the given event ID and timestamp.
pub fn new(event_id: OwnedEventId, origin_server_ts: UnixMillis) -> Self {
Self {
event_id,
origin_server_ts,
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crate::{OwnedRoomId, owned_room_id};
use assert_matches2::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{
AllowRule, CustomAllowRule, JoinRule, JoinRuleSummary, Restricted, RestrictedSummary,
RoomMembership, RoomSummary,
};
#[test]
fn deserialize_summary_no_join_rule() {
let json = json!({
"room_id": "!room:localhost",
"num_joined_members": 5,
"world_readable": false,
"guest_can_join": false,
});
let summary: RoomSummary = from_json_value(json).unwrap();
assert_eq!(summary.room_id, "!room:localhost");
assert_eq!(summary.num_joined_members, 5);
assert!(!summary.world_readable);
assert!(!summary.guest_can_join);
assert_matches!(summary.join_rule, JoinRuleSummary::Public);
}
#[test]
fn deserialize_summary_private_join_rule() {
let json = json!({
"room_id": "!room:localhost",
"num_joined_members": 5,
"world_readable": false,
"guest_can_join": false,
"join_rule": "private",
});
let summary: RoomSummary = from_json_value(json).unwrap();
assert_eq!(summary.room_id, "!room:localhost");
assert_eq!(summary.num_joined_members, 5);
assert!(!summary.world_readable);
assert!(!summary.guest_can_join);
assert_matches!(summary.join_rule, JoinRuleSummary::Private);
}
#[test]
fn deserialize_summary_restricted_join_rule() {
let json = json!({
"room_id": "!room:localhost",
"num_joined_members": 5,
"world_readable": false,
"guest_can_join": false,
"join_rule": "restricted",
"allowed_room_ids": ["!otherroom:localhost"],
});
let summary: RoomSummary = from_json_value(json).unwrap();
assert_eq!(summary.room_id, "!room:localhost");
assert_eq!(summary.num_joined_members, 5);
assert!(!summary.world_readable);
assert!(!summary.guest_can_join);
assert_matches!(summary.join_rule, JoinRuleSummary::Restricted(restricted));
assert_eq!(restricted.allowed_room_ids.len(), 1);
}
#[test]
fn deserialize_summary_restricted_join_rule_no_allowed_room_ids() {
let json = json!({
"room_id": "!room:localhost",
"num_joined_members": 5,
"world_readable": false,
"guest_can_join": false,
"join_rule": "restricted",
});
let summary: RoomSummary = from_json_value(json).unwrap();
assert_eq!(summary.room_id, "!room:localhost");
assert_eq!(summary.num_joined_members, 5);
assert!(!summary.world_readable);
assert!(!summary.guest_can_join);
assert_matches!(summary.join_rule, JoinRuleSummary::Restricted(restricted));
assert_eq!(restricted.allowed_room_ids.len(), 0);
}
#[test]
fn serialize_summary_knock_join_rule() {
let summary = RoomSummary::new(
owned_room_id!("!room:localhost"),
JoinRuleSummary::Knock,
false,
5,
false,
);
assert_eq!(
to_json_value(&summary).unwrap(),
json!({
"room_id": "!room:localhost",
"num_joined_members": 5,
"world_readable": false,
"guest_can_join": false,
"join_rule": "knock",
})
);
}
#[test]
fn serialize_summary_restricted_join_rule() {
let summary = RoomSummary::new(
owned_room_id!("!room:localhost"),
JoinRuleSummary::Restricted(RestrictedSummary::new(vec![owned_room_id!(
"!otherroom:localhost"
)])),
false,
5,
false,
);
assert_eq!(
to_json_value(&summary).unwrap(),
json!({
"room_id": "!room:localhost",
"num_joined_members": 5,
"world_readable": false,
"guest_can_join": false,
"join_rule": "restricted",
"allowed_room_ids": ["!otherroom:localhost"],
})
);
}
#[test]
fn join_rule_to_join_rule_summary() {
assert_eq!(JoinRuleSummary::Invite, JoinRule::Invite.into());
assert_eq!(JoinRuleSummary::Knock, JoinRule::Knock.into());
assert_eq!(JoinRuleSummary::Public, JoinRule::Public.into());
assert_eq!(JoinRuleSummary::Private, JoinRule::Private.into());
assert_matches!(
JoinRule::KnockRestricted(Restricted::default()).into(),
JoinRuleSummary::KnockRestricted(restricted)
);
assert_eq!(restricted.allowed_room_ids, &[] as &[OwnedRoomId]);
let room_id = owned_room_id!("!room:localhost");
assert_matches!(
JoinRule::Restricted(Restricted::new(vec![AllowRule::RoomMembership(
RoomMembership::new(room_id.clone())
)]))
.into(),
JoinRuleSummary::Restricted(restricted)
);
assert_eq!(restricted.allowed_room_ids, [room_id]);
}
#[test]
fn roundtrip_custom_allow_rule() {
let json = r#"{"type":"org.msc9000.something","foo":"bar"}"#;
let allow_rule: AllowRule = serde_json::from_str(json).unwrap();
assert_matches!(&allow_rule, AllowRule::_Custom(_));
assert_eq!(serde_json::to_string(&allow_rule).unwrap(), json);
}
#[test]
fn invalid_allow_items() {
let json = r#"{
"join_rule": "restricted",
"allow": [
{
"type": "m.room_membership",
"room_id": "!mods:example.org"
},
{
"type": "m.room_membership",
"room_id": ""
},
{
"type": "m.room_membership",
"room_id": "not a room id"
},
{
"type": "org.example.custom",
"org.example.minimum_role": "developer"
},
{
"not even close": "to being correct",
"any object": "passes this test",
"only non-objects in this array": "cause deserialization to fail"
}
]
}"#;
let join_rule: JoinRule = serde_json::from_str(json).unwrap();
assert_matches!(join_rule, JoinRule::Restricted(restricted));
assert_eq!(
restricted.allow,
&[
AllowRule::room_membership(owned_room_id!("!mods:example.org")),
AllowRule::_Custom(Box::new(CustomAllowRule {
rule_type: "org.example.custom".into(),
extra: BTreeMap::from([(
"org.example.minimum_role".into(),
"developer".into()
)])
}))
]
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/directory.rs | crates/core/src/directory.rs | /// Common types for room directory endpoints.
use serde::{Deserialize, Serialize};
mod filter_room_type_serde;
mod room_network_serde;
use salvo::prelude::*;
use crate::{
OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, PrivOwnedStr, UnixMillis, room::RoomType,
serde::StringEnum,
};
/// A chunk of a room list response, describing one room.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PublicRoomsChunk {
/// The canonical alias of the room, if any.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub canonical_alias: Option<OwnedRoomAliasId>,
/// The name of the room, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// The number of members joined to the room.
pub num_joined_members: u64,
/// The ID of the room.
pub room_id: OwnedRoomId,
/// The topic of the room, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub topic: Option<String>,
/// Whether the room may be viewed by guest users without joining.
pub world_readable: bool,
/// Whether guest users may join the room and participate in it.
///
/// If they can, they will be subject to ordinary power level rules like any
/// other user.
pub guest_can_join: bool,
/// The URL for the room's avatar, if one is set.
#[serde(
skip_serializing_if = "Option::is_none",
default,
deserialize_with = "crate::serde::empty_string_as_none"
)]
pub avatar_url: Option<OwnedMxcUri>,
/// The join rule of the room.
#[serde(default)]
pub join_rule: PublicRoomJoinRule,
/// The type of room from `m.room.create`, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub room_type: Option<RoomType>,
}
/// A filter for public rooms lists.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct PublicRoomFilter {
/// A string to search for in the room e.g. name, topic, canonical alias
/// etc.
#[serde(skip_serializing_if = "Option::is_none")]
pub generic_search_term: Option<String>,
/// The room types to include in the results.
///
/// Includes all room types if it is empty.
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "crate::serde::none_as_default"
)]
pub room_types: Vec<RoomTypeFilter>,
}
impl PublicRoomFilter {
/// Creates an empty `Filter`.
pub fn new() -> Self {
Default::default()
}
/// Returns `true` if the filter is empty.
pub fn is_empty(&self) -> bool {
self.generic_search_term.is_none()
}
}
/// Information about which networks/protocols from application services on the
/// homeserver from which to request rooms.
#[derive(ToSchema, Clone, Debug, Default, PartialEq, Eq)]
pub enum RoomNetwork {
/// Return rooms from the Matrix network.
#[default]
Matrix,
/// Return rooms from all the networks/protocols the homeserver knows about.
All,
/// Return rooms from a specific third party network/protocol.
ThirdParty(String),
}
/// The rule used for users wishing to join a public room.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, Default, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
pub enum PublicRoomJoinRule {
/// Users can request an invite to the room.
Knock,
KnockRestricted,
/// Anyone can join the room without any prior action.
#[default]
Public,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
/// An enum of possible room types to filter.
///
/// This type can hold an arbitrary string. To build this with a custom value,
/// convert it from an `Option<string>` with `::from()` / `.into()`.
/// [`RoomTypeFilter::Default`] can be constructed from `None`.
///
/// To check for values that are not available as a documented variant here, use
/// its string representation, obtained through [`.as_str()`](Self::as_str()).
#[derive(ToSchema, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RoomTypeFilter {
/// The default room type, defined without a `room_type`.
Default,
/// A space.
Space,
/// A custom room type.
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
impl RoomTypeFilter {
/// Get the string representation of this `RoomTypeFilter`.
///
/// [`RoomTypeFilter::Default`] returns `None`.
pub fn as_str(&self) -> Option<&str> {
match self {
RoomTypeFilter::Default => None,
RoomTypeFilter::Space => Some("m.space"),
RoomTypeFilter::_Custom(s) => Some(&s.0),
}
}
}
impl<T> From<Option<T>> for RoomTypeFilter
where
T: AsRef<str> + Into<Box<str>>,
{
fn from(s: Option<T>) -> Self {
match s {
None => Self::Default,
Some(s) => match s.as_ref() {
"m.space" => Self::Space,
_ => Self::_Custom(PrivOwnedStr(s.into())),
},
}
}
}
impl From<Option<RoomType>> for RoomTypeFilter {
fn from(t: Option<RoomType>) -> Self {
match t {
None => Self::Default,
Some(s) => match s {
RoomType::Space => Self::Space,
_ => Self::from(Some(s.as_str())),
},
}
}
}
/// The query criteria.
#[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)]
pub struct QueryCriteria {
/// A millisecond POSIX timestamp in milliseconds indicating when the
/// returned certificates will need to be valid until to be useful to the
/// requesting server.
///
/// If not supplied, the current time as determined by the notary server is
/// used.
// This doesn't use `serde(default)` because the default would then be
// determined by the client rather than the server (and it would take more
// bandwidth because `skip_serializing_if` couldn't be used).
#[serde(skip_serializing_if = "Option::is_none")]
pub minimum_valid_until_ts: Option<UnixMillis>,
}
impl QueryCriteria {
/// Creates empty `QueryCriteria`.
pub fn new() -> Self {
Default::default()
}
}
/// Arbitrary values that identify this implementation.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct Server {
/// Arbitrary name that identifies this implementation.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Version of this implementation.
///
/// The version format depends on the implementation.
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
impl Server {
/// Creates an empty `Server`.
pub fn new() -> Self {
Default::default()
}
}
// /// Request type for the `get_public_rooms` endpoint.
/// Response type for the `get_public_rooms` endpoint.
#[derive(ToSchema, Serialize, Deserialize, Default, Debug)]
pub struct PublicRoomsResBody {
/// A paginated chunk of public rooms.
pub chunk: Vec<PublicRoomsChunk>,
/// A pagination token for the response.
#[serde(skip_serializing_if = "Option::is_none")]
pub next_batch: Option<String>,
/// A pagination token that allows fetching previous results.
#[serde(skip_serializing_if = "Option::is_none")]
pub prev_batch: Option<String>,
/// An estimate on the total number of public rooms, if the server has an
/// estimate.
pub total_room_count_estimate: Option<u64>,
}
impl PublicRoomsResBody {
/// Creates an empty `Response`.
pub fn new() -> Self {
Default::default()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/conditional_push_rule.rs | crates/core/src/push/conditional_push_rule.rs | //! Common types for the [push notifications module][push].
//!
//! [push]: https://spec.matrix.org/latest/client-server-api/#push-notifications
//!
//! ## Understanding the types of this module
//!
//! Push rules are grouped in `RuleSet`s, and are grouped in five kinds (for
//! more details about the different kind of rules, see the `Ruleset`
//! documentation, or the specification). These five kinds are, by order of
//! priority:
//!
//! - override rules
//! - content rules
//! - room rules
//! - sender rules
//! - underride rules
use std::hash::{Hash, Hasher};
use indexmap::Equivalent;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
#[cfg(feature = "unstable-msc3932")]
use crate::push::RoomVersionFeature;
use crate::push::{
Action, FlattenedJson, PredefinedOverrideRuleId, PushCondition, PushConditionRoomCtx, PushRule,
};
/// Like `SimplePushRule`, but with an additional `conditions` field.
///
/// Only applicable to underride and override rules.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct ConditionalPushRule {
/// Actions to determine if and how a notification is delivered for events
/// matching this rule.
pub actions: Vec<Action>,
/// Whether this is a default rule, or has been set explicitly.
pub default: bool,
/// Whether the push rule is enabled or not.
pub enabled: bool,
/// The ID of this rule.
pub rule_id: String,
/// The conditions that must hold true for an event in order for a rule to
/// be applied to an event.
///
/// A rule with no conditions always matches.
#[serde(default)]
pub conditions: Vec<PushCondition>,
}
impl ConditionalPushRule {
/// Check if the push rule applies to the event.
///
/// # Arguments
///
/// * `event` - The flattened JSON representation of a room message event.
/// * `context` - The context of the room at the time of the event.
pub async fn applies(&self, event: &FlattenedJson, context: &PushConditionRoomCtx) -> bool {
if !self.enabled {
return false;
}
// These 3 rules always apply.
#[cfg(feature = "unstable-msc3932")]
{
if self.rule_id != PredefinedOverrideRuleId::Master.as_ref()
&& self.rule_id != PredefinedOverrideRuleId::RoomNotif.as_ref()
&& self.rule_id != PredefinedOverrideRuleId::ContainsDisplayName.as_ref()
{
// Push rules which don't specify a `room_version_supports` condition are
// assumed to not support extensible events and are therefore
// expected to be treated as disabled when a room version does
// support extensible events.
let room_supports_ext_ev = context
.supported_features
.contains(&RoomVersionFeature::ExtensibleEvents);
let rule_has_room_version_supports = self.conditions.iter().any(|condition| {
matches!(condition, PushCondition::RoomVersionSupports { .. })
});
if room_supports_ext_ev && !rule_has_room_version_supports {
return false;
}
}
}
// The old mention rules are disabled when an m.mentions field is present.
#[allow(deprecated)]
if (self.rule_id == PredefinedOverrideRuleId::RoomNotif.as_ref()
|| self.rule_id == PredefinedOverrideRuleId::ContainsDisplayName.as_ref())
&& event.contains_mentions()
{
return false;
}
for cond in &self.conditions {
if !cond.applies(event, context).await {
return false;
}
}
true
}
}
// The following trait are needed to be able to make
// an IndexSet of the type
impl Hash for ConditionalPushRule {
fn hash<H: Hasher>(&self, state: &mut H) {
self.rule_id.hash(state);
}
}
impl PartialEq for ConditionalPushRule {
fn eq(&self, other: &Self) -> bool {
self.rule_id == other.rule_id
}
}
impl Eq for ConditionalPushRule {}
impl Equivalent<ConditionalPushRule> for str {
fn equivalent(&self, key: &ConditionalPushRule) -> bool {
self == key.rule_id
}
}
/// A conditional push rule to update or create.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct NewConditionalPushRule {
/// The ID of this rule.
pub rule_id: String,
/// The conditions that must hold true for an event in order for a rule to
/// be applied to an event.
///
/// A rule with no conditions always matches.
#[serde(default)]
pub conditions: Vec<PushCondition>,
/// Actions to determine if and how a notification is delivered for events
/// matching this rule.
pub actions: Vec<Action>,
}
impl NewConditionalPushRule {
/// Creates a `NewConditionalPushRule` with the given ID, conditions and
/// actions.
pub fn new(rule_id: String, conditions: Vec<PushCondition>, actions: Vec<Action>) -> Self {
Self {
rule_id,
conditions,
actions,
}
}
}
impl From<ConditionalPushRule> for PushRule {
fn from(push_rule: ConditionalPushRule) -> Self {
let ConditionalPushRule {
actions,
default,
enabled,
rule_id,
conditions,
..
} = push_rule;
Self {
actions,
default,
enabled,
rule_id,
conditions: Some(conditions),
pattern: None,
}
}
}
impl From<NewConditionalPushRule> for ConditionalPushRule {
fn from(new_rule: NewConditionalPushRule) -> Self {
let NewConditionalPushRule {
rule_id,
conditions,
actions,
} = new_rule;
Self {
actions,
default: false,
enabled: true,
rule_id,
conditions,
}
}
}
impl From<PushRule> for ConditionalPushRule {
fn from(push_rule: PushRule) -> Self {
let PushRule {
actions,
default,
enabled,
rule_id,
conditions,
..
} = push_rule;
ConditionalPushRule {
actions,
default,
enabled,
rule_id,
conditions: conditions.unwrap_or_default(),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/simple_push_rule.rs | crates/core/src/push/simple_push_rule.rs | //! Common types for the [push notifications module][push].
//!
//! [push]: https://spec.matrix.org/latest/client-server-api/#push-notifications
//!
//! ## Understanding the types of this module
//!
//! Push rules are grouped in `RuleSet`s, and are grouped in five kinds (for
//! more details about the different kind of rules, see the `Ruleset`
//! documentation, or the specification). These five kinds are, by order of
//! priority:
//!
//! - override rules
//! - content rules
//! - room rules
//! - sender rules
//! - underride rules
use std::hash::{Hash, Hasher};
use indexmap::Equivalent;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::push::{Action, push_rule::PushRule};
/// A push rule is a single rule that states under what conditions an event
/// should be passed onto a push gateway and how the notification should be
/// presented.
///
/// These rules are stored on the user's homeserver. They are manually
/// configured by the user, who can create and view them via the Client/Server
/// API.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct SimplePushRule<T>
where
T: 'static,
{
/// Actions to determine if and how a notification is delivered for events
/// matching this rule.
pub actions: Vec<Action>,
/// Whether this is a default rule, or has been set explicitly.
pub default: bool,
/// Whether the push rule is enabled or not.
pub enabled: bool,
/// The ID of this rule.
///
/// This is generally the Matrix ID of the entity that it applies to.
pub rule_id: T,
}
// The following trait are needed to be able to make
// an IndexSet of the type
impl<T> Hash for SimplePushRule<T>
where
T: Hash,
{
fn hash<H: Hasher>(&self, state: &mut H) {
self.rule_id.hash(state);
}
}
impl<T> PartialEq for SimplePushRule<T>
where
T: PartialEq<T>,
{
fn eq(&self, other: &Self) -> bool {
self.rule_id == other.rule_id
}
}
impl<T> Eq for SimplePushRule<T> where T: Eq {}
impl<T> Equivalent<SimplePushRule<T>> for str
where
T: AsRef<str>,
{
fn equivalent(&self, key: &SimplePushRule<T>) -> bool {
self == key.rule_id.as_ref()
}
}
/// A simple push rule to update or create.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct NewSimplePushRule<T>
where
T: ToSchema + 'static,
{
/// The ID of this rule.
///
/// This is generally the Matrix ID of the entity that it applies to.
pub rule_id: T,
/// Actions to determine if and how a notification is delivered for events
/// matching this rule.
pub actions: Vec<Action>,
}
impl<T> NewSimplePushRule<T>
where
T: ToSchema,
{
/// Creates a `NewSimplePushRule` with the given ID and actions.
pub fn new(rule_id: T, actions: Vec<Action>) -> Self {
Self { rule_id, actions }
}
}
impl<T> From<SimplePushRule<T>> for PushRule
where
T: Into<String>,
{
fn from(push_rule: SimplePushRule<T>) -> Self {
let SimplePushRule {
actions,
default,
enabled,
rule_id,
..
} = push_rule;
let rule_id = rule_id.into();
Self {
actions,
default,
enabled,
rule_id,
conditions: None,
pattern: None,
}
}
}
impl<T> From<NewSimplePushRule<T>> for SimplePushRule<T>
where
T: ToSchema,
{
fn from(new_rule: NewSimplePushRule<T>) -> Self {
let NewSimplePushRule { rule_id, actions } = new_rule;
Self {
actions,
default: false,
enabled: true,
rule_id,
}
}
}
impl<T> TryFrom<PushRule> for SimplePushRule<T>
where
T: TryFrom<String>,
{
type Error = <T as TryFrom<String>>::Error;
fn try_from(push_rule: PushRule) -> Result<Self, Self::Error> {
let PushRule {
actions,
default,
enabled,
rule_id,
..
} = push_rule;
let rule_id = T::try_from(rule_id)?;
Ok(SimplePushRule {
actions,
default,
enabled,
rule_id,
})
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/push_gateway.rs | crates/core/src/push/push_gateway.rs | //! `GET /_matrix/client/*/notifications`
//!
//! Paginate through the list of events that the user has been, or would have
//! been notified about. `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3notifications
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
PrivOwnedStr, UnixSeconds,
events::TimelineEventType,
identifiers::*,
push::{PusherData, Tweak},
serde::{RawJsonValue, StringEnum},
};
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: None,
// history: {
// 1.0 => "/_matrix/push/v1/notify",
// }
// };
#[derive(ToSchema, Serialize, Debug)]
pub struct SendEventNotificationReqBody {
/// Information about the push notification
pub notification: Notification,
}
crate::json_body_modifier!(SendEventNotificationReqBody);
impl SendEventNotificationReqBody {
pub fn new(notification: Notification) -> Self {
Self { notification }
}
}
/// Response type for the `send_event_notification` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct SendEventNotificationResBody {
/// A list of all pushkeys given in the notification request that are not
/// valid.
///
/// These could have been rejected by an upstream gateway because they have
/// expired or have never been valid. Homeservers must cease sending
/// notification requests for these pushkeys and remove the associated
/// pushers. It may not necessarily be the notification in the request
/// that failed: it could be that a previous notification to the same
/// pushkey failed. May be empty.
pub rejected: Vec<String>,
}
impl SendEventNotificationResBody {
/// Creates a new `Response` with the given list of rejected pushkeys.
pub fn new(rejected: Vec<String>) -> Self {
Self { rejected }
}
}
/// Represents a notification.
#[derive(ToSchema, Default, Deserialize, Serialize, Clone, Debug)]
pub struct Notification {
/// The Matrix event ID of the event being notified about.
///
/// Required if the notification is about a particular Matrix event. May be
/// omitted for notifications that only contain updated badge counts.
/// This ID can and should be used to detect duplicate notification
/// requests.
#[serde(skip_serializing_if = "Option::is_none")]
pub event_id: Option<OwnedEventId>,
/// The ID of the room in which this event occurred.
///
/// Required if the notification relates to a specific Matrix event.
#[serde(skip_serializing_if = "Option::is_none")]
pub room_id: Option<OwnedRoomId>,
/// The type of the event as in the event's `type` field.
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub event_type: Option<TimelineEventType>,
/// The sender of the event as in the corresponding event field.
#[serde(skip_serializing_if = "Option::is_none")]
pub sender: Option<OwnedUserId>,
/// The current display name of the sender in the room in which the event
/// occurred.
#[serde(skip_serializing_if = "Option::is_none")]
pub sender_display_name: Option<String>,
/// The name of the room in which the event occurred.
#[serde(skip_serializing_if = "Option::is_none")]
pub room_name: Option<String>,
/// An alias to display for the room in which the event occurred.
#[serde(skip_serializing_if = "Option::is_none")]
pub room_alias: Option<OwnedRoomAliasId>,
/// Whether the user receiving the notification is the subject of a member
/// event (i.e. the `state_key` of the member event is equal to the
/// user's Matrix ID).
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub user_is_target: bool,
/// The priority of the notification.
///
/// If omitted, `high` is assumed. This may be used by push gateways to
/// deliver less time-sensitive notifications in a way that will
/// preserve battery power on mobile devices.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub prio: NotificationPriority,
/// The `content` field from the event, if present.
///
/// The pusher may omit this if the event had no content or for any other
/// reason.
#[serde(skip_serializing_if = "Option::is_none")]
#[salvo(schema(value_type = Object))]
pub content: Option<Box<RawJsonValue>>,
/// Current number of unacknowledged communications for the recipient user.
///
/// Counts whose value is zero should be omitted.
#[serde(default, skip_serializing_if = "NotificationCounts::is_default")]
pub counts: NotificationCounts,
/// An array of devices that the notification should be sent to.
pub devices: Vec<Device>,
}
impl Notification {
/// Create a new notification for the given devices.
pub fn new(devices: Vec<Device>) -> Self {
Notification {
devices,
..Default::default()
}
}
}
/// Type for passing information about notification priority.
///
/// This may be used by push gateways to deliver less time-sensitive
/// notifications in a way that will preserve battery power on mobile devices.
///
/// This type can hold an arbitrary string. To build this with a custom value,
/// convert it from a string with `::from()` / `.into()`. To check for values
/// that are not available as a documented variant here, use its string
/// representation, obtained through `.as_str()`.
#[derive(ToSchema, Clone, Default, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum NotificationPriority {
/// A high priority notification
#[default]
High,
/// A low priority notification
Low,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// Type for passing information about notification counts.
#[derive(ToSchema, Deserialize, Serialize, Default, Clone, Debug)]
pub struct NotificationCounts {
/// The number of unread messages a user has across all of the rooms they
/// are a member of.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub unread: u64,
/// The number of unacknowledged missed calls a user has across all rooms of
/// which they are a member.
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub missed_calls: u64,
}
impl NotificationCounts {
/// Create new notification counts from the given unread and missed call
/// counts.
pub fn new(unread: u64, missed_calls: u64) -> Self {
NotificationCounts {
unread,
missed_calls,
}
}
fn is_default(&self) -> bool {
self.unread == 0 && self.missed_calls == 0
}
}
/// Type for passing information about devices.
#[derive(ToSchema, Clone, Debug, Deserialize, Serialize)]
pub struct Device {
/// The `app_id` given when the pusher was created.
///
/// Max length: 64 chars.
pub app_id: String,
/// The `pushkey` given when the pusher was created.
///
/// Max length: 512 bytes.
pub pushkey: String,
/// The unix timestamp (in seconds) when the pushkey was last updated.
#[serde(skip_serializing_if = "Option::is_none")]
pub pushkey_ts: Option<UnixSeconds>,
/// A dictionary of additional pusher-specific data.
#[serde(default, skip_serializing_if = "PusherData::is_empty")]
pub data: PusherData,
/// A dictionary of customisations made to the way this notification is to
/// be presented.
///
/// These are added by push rules.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tweaks: Vec<Tweak>,
}
impl Device {
/// Create a new device with the given app id and pushkey
pub fn new(app_id: String, pushkey: String) -> Self {
Device {
app_id,
pushkey,
pushkey_ts: None,
data: PusherData::new(),
tweaks: Vec::new(),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/error.rs | crates/core/src/push/error.rs | use std::{error::Error as StdError, fmt};
use thiserror::Error;
/// The error type returned when trying to insert a user-defined push rule into
/// a `Ruleset`.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum InsertPushRuleError {
/// The rule ID starts with a dot (`.`), which is reserved for
/// server-default rules.
#[error("rule IDs starting with a dot are reserved for server-default rules")]
ServerDefaultRuleId,
/// The rule ID contains an invalid character.
#[error("invalid rule ID")]
InvalidRuleId,
/// The rule is being placed relative to a server-default rule, which is
/// forbidden.
#[error("can't place rule relative to server-default rule")]
RelativeToServerDefaultRule,
/// The `before` or `after` rule could not be found.
#[error("The before or after rule could not be found")]
UnknownRuleId,
/// `before` has a higher priority than `after`.
#[error("before has a higher priority than after")]
BeforeHigherThanAfter,
}
/// The error type returned when trying modify a push rule that could not be
/// found in a `Ruleset`.
#[derive(Debug, Error)]
#[non_exhaustive]
#[error("The rule could not be found")]
pub struct RuleNotFoundError;
/// The error type returned when trying to remove a user-defined push rule from
/// a `Ruleset`.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum RemovePushRuleError {
/// The rule is a server-default rules and they can't be removed.
#[error("server-default rules cannot be removed")]
ServerDefault,
/// The rule was not found.
#[error("rule not found")]
NotFound,
}
/// An error that happens when `PushRule` cannot
/// be converted into `PatternedPushRule`
#[derive(Debug)]
pub struct MissingPatternError;
impl fmt::Display for MissingPatternError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Push rule does not have a pattern.")
}
}
impl StdError for MissingPatternError {}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/push_rule.rs | crates/core/src/push/push_rule.rs | //! Common types for the [push notifications module][push].
//!
//! [push]: https://spec.matrix.org/latest/client-server-api/#push-notifications
//!
//! ## Understanding the types of this module
//!
//! Push rules are grouped in `RuleSet`s, and are grouped in five kinds (for
//! more details about the different kind of rules, see the `Ruleset`
//! documentation, or the specification). These five kinds are, by order of
//! priority:
//!
//! - override rules
//! - content rules
//! - room rules
//! - sender rules
//! - underride rules
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
OwnedRoomId, OwnedUserId, PrivOwnedStr,
push::{
Action, NewConditionalPushRule, NewPatternedPushRule, NewSimplePushRule, PushCondition,
},
serde::StringEnum,
};
/// The kinds of push rules that are available.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RuleKind {
/// User-configured rules that override all other kinds.
Override,
/// Lowest priority user-defined rules.
Underride,
/// Sender-specific rules.
Sender,
/// Room-specific rules.
Room,
/// Content-specific rules.
Content,
/// Post-content specific rules.
#[cfg(feature = "unstable-msc4306")]
#[palpo_enum(rename = "io.element.msc4306.postcontent")]
PostContent,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
/// A push rule to update or create.
#[derive(ToSchema, Deserialize, Clone, Debug)]
pub enum NewPushRule {
/// Rules that override all other kinds.
Override(NewConditionalPushRule),
/// Content-specific rules.
Content(NewPatternedPushRule),
/// Post-content specific rules.
#[cfg(feature = "unstable-msc4306")]
PostContent(NewConditionalPushRule),
/// Room-specific rules.
Room(NewSimplePushRule<OwnedRoomId>),
/// Sender-specific rules.
Sender(NewSimplePushRule<OwnedUserId>),
/// Lowest priority rules.
Underride(NewConditionalPushRule),
}
impl NewPushRule {
/// The kind of this `NewPushRule`.
pub fn kind(&self) -> RuleKind {
match self {
NewPushRule::Override(_) => RuleKind::Override,
NewPushRule::Content(_) => RuleKind::Content,
#[cfg(feature = "unstable-msc4306")]
NewPushRule::PostContent(_) => RuleKind::PostContent,
NewPushRule::Room(_) => RuleKind::Room,
NewPushRule::Sender(_) => RuleKind::Sender,
NewPushRule::Underride(_) => RuleKind::Underride,
}
}
/// The ID of this `NewPushRule`.
pub fn rule_id(&self) -> &str {
match self {
NewPushRule::Override(r) => &r.rule_id,
NewPushRule::Content(r) => &r.rule_id,
#[cfg(feature = "unstable-msc4306")]
NewPushRule::PostContent(r) => &r.rule_id,
NewPushRule::Room(r) => r.rule_id.as_ref(),
NewPushRule::Sender(r) => r.rule_id.as_ref(),
NewPushRule::Underride(r) => &r.rule_id,
}
}
}
/// The scope of a push rule.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
#[palpo_enum(rename_all = "lowercase")]
#[non_exhaustive]
pub enum RuleScope {
/// The global rules.
Global,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// Like `SimplePushRule`, but may represent any kind of push rule thanks to
/// `pattern` and `conditions` being optional.
///
/// To create an instance of this type, use one of its `From` implementations.
#[derive(ToSchema, Clone, Debug, Serialize, Deserialize)]
pub struct PushRule {
/// The actions to perform when this rule is matched.
pub actions: Vec<Action>,
/// Whether this is a default rule, or has been set explicitly.
pub default: bool,
/// Whether the push rule is enabled or not.
pub enabled: bool,
/// The ID of this rule.
pub rule_id: String,
/// The conditions that must hold true for an event in order for a rule to
/// be applied to an event.
///
/// A rule with no conditions always matches. Only applicable to underride
/// and override rules.
#[serde(skip_serializing_if = "Option::is_none")]
pub conditions: Option<Vec<PushCondition>>,
/// The glob-style pattern to match against.
///
/// Only applicable to content rules.
#[serde(skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,
}
#[derive(ToParameters, Deserialize, Debug)]
pub struct ScopeKindRuleReqArgs {
/// The scope to fetch rules from.
#[salvo(parameter(parameter_in = Path))]
pub scope: RuleScope,
/// The kind of rule.
#[salvo(parameter(parameter_in = Path))]
pub kind: RuleKind,
/// The identifier for the rule.
#[salvo(parameter(parameter_in = Path))]
pub rule_id: String,
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/condition.rs | crates/core/src/push/condition.rs | #[cfg(feature = "unstable-msc4306")]
use std::panic::RefUnwindSafe;
use std::{collections::BTreeMap, ops::RangeBounds, str::FromStr};
#[cfg(feature = "unstable-msc4306")]
use std::{future::Future, pin::Pin, sync::Arc};
use regex::bytes::Regex;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use serde_json::value::Value as JsonValue;
use wildmatch::WildMatch;
#[cfg(feature = "unstable-msc4306")]
use crate::EventId;
use crate::macros::StringEnum;
use crate::{
OwnedRoomId, OwnedUserId, PrivOwnedStr, RoomVersionId, UserId,
power_levels::NotificationPowerLevels, room_version_rules::RoomPowerLevelsRules,
};
mod flattened_json;
mod push_condition_serde;
mod room_member_count_is;
pub use self::{
flattened_json::{FlattenedJson, FlattenedJsonValue, ScalarJsonValue},
room_member_count_is::{ComparisonOperator, RoomMemberCountIs},
};
/// Features supported by room versions.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(ToSchema, Clone, StringEnum)]
pub enum RoomVersionFeature {
/// m.extensible_events
///
/// The room supports [extensible events].
///
/// [extensible events]: https://github.com/matrix-org/matrix-spec-proposals/pull/1767
#[palpo_enum(rename = "org.matrix.msc3932.extensible_events")]
ExtensibleEvents,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
impl RoomVersionFeature {
/// Get the default features for the given room version.
pub fn list_for_room_version(version: &RoomVersionId) -> Vec<Self> {
match version {
RoomVersionId::V1
| RoomVersionId::V2
| RoomVersionId::V3
| RoomVersionId::V4
| RoomVersionId::V5
| RoomVersionId::V6
| RoomVersionId::V7
| RoomVersionId::V8
| RoomVersionId::V9
| RoomVersionId::V10
| RoomVersionId::V11
| RoomVersionId::V12
| RoomVersionId::_Custom(_) => vec![],
#[cfg(feature = "unstable-msc2870")]
RoomVersionId::MSC2870 => vec![],
}
}
}
/// A condition that must apply for an associated push rule's action to be taken.
#[derive(ToSchema, Clone, Debug)]
pub enum PushCondition {
/// A glob pattern match on a field of the event.
EventMatch {
/// The [dot-separated path] of the property of the event to match.
///
/// [dot-separated path]: https://spec.matrix.org/latest/appendices/#dot-separated-property-paths
key: String,
/// The glob-style pattern to match against.
///
/// Patterns with no special glob characters should be treated as having
/// asterisks prepended and appended when testing the condition.
pattern: String,
},
/// Matches unencrypted messages where `content.body` contains the owner's
/// display name in that room.
#[deprecated]
ContainsDisplayName,
/// Matches the current number of members in the room.
RoomMemberCount {
/// The condition on the current number of members in the room.
is: RoomMemberCountIs,
},
/// Takes into account the current power levels in the room, ensuring the
/// sender of the event has high enough power to trigger the
/// notification.
SenderNotificationPermission {
/// The field in the power level event the user needs a minimum power
/// level for.
///
/// Fields must be specified under the `notifications` property in the
/// power level event's `content`.
key: String,
},
/// Apply the rule only to rooms that support a given feature.
#[cfg(feature = "unstable-msc3931")]
RoomVersionSupports {
/// The feature the room must support for the push rule to apply.
feature: RoomVersionFeature,
},
/// Exact value match on a property of the event.
EventPropertyIs {
/// The [dot-separated path] of the property of the event to match.
///
/// [dot-separated path]: https://spec.matrix.org/latest/appendices/#dot-separated-property-paths
key: String,
/// The value to match against.
#[salvo(schema(value_type = Object, additional_properties = true))]
value: ScalarJsonValue,
},
/// Exact value match on a value in an array property of the event.
EventPropertyContains {
/// The [dot-separated path] of the property of the event to match.
///
/// [dot-separated path]: https://spec.matrix.org/latest/appendices/#dot-separated-property-paths
key: String,
/// The value to match against.
#[salvo(schema(value_type = Object, additional_properties = true))]
value: ScalarJsonValue,
},
/// Matches a thread event based on the user's thread subscription status, as defined by
/// [MSC4306].
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
ThreadSubscription {
/// Whether the user must be subscribed (`true`) or unsubscribed (`false`) to the thread
/// for the condition to match.
subscribed: bool,
},
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(_CustomPushCondition),
}
pub(super) fn check_event_match(
event: &FlattenedJson,
key: &str,
pattern: &str,
context: &PushConditionRoomCtx,
) -> bool {
let value = match key {
"room_id" => context.room_id.as_str(),
_ => match event.get_str(key) {
Some(v) => v,
None => return false,
},
};
value.matches_pattern(pattern, key == "content.body")
}
impl PushCondition {
/// Check if this condition applies to the event.
///
/// # Arguments
///
/// * `event` - The flattened JSON representation of a room message event.
/// * `context` - The context of the room at the time of the event. If the
/// power levels context is missing from it, conditions that depend on it
/// will never apply.
pub async fn applies(&self, event: &FlattenedJson, context: &PushConditionRoomCtx) -> bool {
if event
.get_str("sender")
.is_some_and(|sender| sender == context.user_id)
{
return false;
}
match self {
Self::EventMatch { key, pattern } => check_event_match(event, key, pattern, context),
#[allow(deprecated)]
Self::ContainsDisplayName => {
let value = match event.get_str("content.body") {
Some(v) => v,
None => return false,
};
value.matches_pattern(&context.user_display_name, true)
}
Self::RoomMemberCount { is } => is.contains(&context.member_count),
Self::SenderNotificationPermission { key } => {
let Some(power_levels) = &context.power_levels else {
return false;
};
let sender_id = match event.get_str("sender") {
Some(v) => match <&UserId>::try_from(v) {
Ok(u) => u,
Err(_) => return false,
},
None => return false,
};
let sender_level = power_levels
.users
.get(sender_id)
.unwrap_or(&power_levels.users_default);
match power_levels.notifications.get(key) {
Some(l) => sender_level >= l,
None => false,
}
}
#[cfg(feature = "unstable-msc3931")]
Self::RoomVersionSupports { feature } => match feature {
RoomVersionFeature::ExtensibleEvents => context
.supported_features
.contains(&RoomVersionFeature::ExtensibleEvents),
RoomVersionFeature::_Custom(_) => false,
},
Self::EventPropertyIs { key, value } => event.get(key).is_some_and(|v| v == value),
Self::EventPropertyContains { key, value } => event
.get(key)
.and_then(FlattenedJsonValue::as_array)
.is_some_and(|a| a.contains(value)),
#[cfg(feature = "unstable-msc4306")]
Self::ThreadSubscription {
subscribed: must_be_subscribed,
} => {
let Some(has_thread_subscription_fn) = &context.has_thread_subscription_fn else {
// If we don't have a function to check thread subscriptions, we can't
// determine if the condition applies.
return false;
};
// The event must have a relation of type `m.thread`.
if event.get_str("content.m\\.relates_to.rel_type") != Some("m.thread") {
return false;
}
// Retrieve the thread root event ID.
let Some(Ok(thread_root)) = event
.get_str("content.m\\.relates_to.event_id")
.map(<&EventId>::try_from)
else {
return false;
};
let is_subscribed = has_thread_subscription_fn(thread_root).await;
*must_be_subscribed == is_subscribed
}
Self::_Custom(_) => false,
}
}
}
/// An unknown push condition.
#[doc(hidden)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::exhaustive_structs)]
pub struct _CustomPushCondition {
/// The kind of the condition.
kind: String,
/// The additional fields that the condition contains.
#[serde(flatten)]
data: BTreeMap<String, JsonValue>,
}
/// The context of the room associated to an event to be able to test all push
/// conditions.
#[derive(Clone)]
#[allow(clippy::exhaustive_structs)]
pub struct PushConditionRoomCtx {
/// The ID of the room.
pub room_id: OwnedRoomId,
/// The number of members in the room.
pub member_count: u64,
/// The user's matrix ID.
pub user_id: OwnedUserId,
/// The display name of the current user in the room.
pub user_display_name: String,
/// The room power levels context for the room.
///
/// If this is missing, push rules that require this will never match.
pub power_levels: Option<PushConditionPowerLevelsCtx>,
/// The list of features this room's version or the room itself supports.
#[cfg(feature = "unstable-msc3931")]
pub supported_features: Vec<RoomVersionFeature>,
/// A closure that returns a future indicating if the given thread (represented by its thread
/// root event id) is subscribed to by the current user, where subscriptions are defined as per
/// [MSC4306].
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
pub has_thread_subscription_fn: Option<Arc<HasThreadSubscriptionFn>>,
/// When the `unstable-msc4306` feature is enabled with the field above, it changes the auto
/// trait implementations of the struct to `!RefUnwindSafe` and `!UnwindSafe`. So we use
/// `PhantomData` to keep the same bounds on the field when the feature is disabled, to always
/// have the same auto trait implementations.
#[cfg(not(feature = "unstable-msc4306"))]
has_thread_subscription_fn: std::marker::PhantomData<Arc<HasThreadSubscriptionFn>>,
}
impl PushConditionRoomCtx {
/// Create a new `PushConditionRoomCtx`.
pub fn new(
room_id: OwnedRoomId,
member_count: u64,
user_id: OwnedUserId,
user_display_name: String,
) -> Self {
Self {
room_id,
member_count,
user_id,
user_display_name,
power_levels: None,
#[cfg(feature = "unstable-msc3931")]
supported_features: Vec::new(),
has_thread_subscription_fn: Default::default(),
}
}
/// Set a function to check if the user is subscribed to a thread, so as to define the push
/// rules defined in [MSC4306].
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
pub fn with_has_thread_subscription_fn(
self,
#[cfg(not(target_family = "wasm"))]
has_thread_subscription_fn: impl for<'a> Fn(
&'a EventId,
) -> HasThreadSubscriptionFuture<'a>
+ Send
+ Sync
+ 'static,
#[cfg(target_family = "wasm")]
has_thread_subscription_fn: impl for<'a> Fn(
&'a EventId,
) -> HasThreadSubscriptionFuture<'a>
+ 'static,
) -> Self {
Self {
has_thread_subscription_fn: Some(Arc::new(has_thread_subscription_fn)),
..self
}
}
/// Add the given power levels context to this `PushConditionRoomCtx`.
pub fn with_power_levels(self, power_levels: PushConditionPowerLevelsCtx) -> Self {
Self {
power_levels: Some(power_levels),
..self
}
}
}
/// The room power levels context to be able to test the corresponding push
/// conditions.
#[derive(Clone, Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct PushConditionPowerLevelsCtx {
/// The power levels of the users of the room.
pub users: BTreeMap<OwnedUserId, i64>,
/// The default power level of the users of the room.
pub users_default: i64,
/// The notification power levels of the room.
pub notifications: NotificationPowerLevels,
/// The tweaks for determining the power level of a user.
pub rules: RoomPowerLevelsRules,
}
impl PushConditionPowerLevelsCtx {
/// Create a new `PushConditionPowerLevelsCtx`.
pub fn new(
users: BTreeMap<OwnedUserId, i64>,
users_default: i64,
notifications: NotificationPowerLevels,
rules: RoomPowerLevelsRules,
) -> Self {
Self {
users,
users_default,
notifications,
rules,
}
}
}
/// Additional functions for character matching.
trait CharExt {
/// Whether or not this char can be part of a word.
fn is_word_char(&self) -> bool;
}
impl CharExt for char {
fn is_word_char(&self) -> bool {
self.is_ascii_alphanumeric() || *self == '_'
}
}
/// Additional functions for string matching.
trait StrExt {
/// Get the length of the char at `index`. The byte index must correspond to
/// the start of a char boundary.
fn char_len(&self, index: usize) -> usize;
/// Get the char at `index`. The byte index must correspond to the start of
/// a char boundary.
fn char_at(&self, index: usize) -> char;
/// Get the index of the char that is before the char at `index`. The byte
/// index must correspond to a char boundary.
///
/// Returns `None` if there's no previous char. Otherwise, returns the char.
fn find_prev_char(&self, index: usize) -> Option<char>;
/// Matches this string against `pattern`.
///
/// The pattern can be a glob with wildcards `*` and `?`.
///
/// The match is case insensitive.
///
/// If `match_words` is `true`, checks that the pattern is separated from
/// other words.
fn matches_pattern(&self, pattern: &str, match_words: bool) -> bool;
/// Matches this string against `pattern`, with word boundaries.
///
/// The pattern can be a glob with wildcards `*` and `?`.
///
/// A word boundary is defined as the start or end of the value, or any
/// character not in the sets `[A-Z]`, `[a-z]`, `[0-9]` or `_`.
///
/// The match is case sensitive.
fn matches_word(&self, pattern: &str) -> bool;
/// Translate the wildcards in `self` to a regex syntax.
///
/// `self` must only contain wildcards.
fn wildcards_to_regex(&self) -> String;
}
impl StrExt for str {
fn char_len(&self, index: usize) -> usize {
let mut len = 1;
while !self.is_char_boundary(index + len) {
len += 1;
}
len
}
fn char_at(&self, index: usize) -> char {
let end = index + self.char_len(index);
let char_str = &self[index..end];
char::from_str(char_str)
.unwrap_or_else(|_| panic!("Could not convert str '{char_str}' to char"))
}
fn find_prev_char(&self, index: usize) -> Option<char> {
if index == 0 {
return None;
}
let mut pos = index - 1;
while !self.is_char_boundary(pos) {
pos -= 1;
}
Some(self.char_at(pos))
}
fn matches_pattern(&self, pattern: &str, match_words: bool) -> bool {
let value = &self.to_lowercase();
let pattern = &pattern.to_lowercase();
if match_words {
value.matches_word(pattern)
} else {
WildMatch::new(pattern).matches(value)
}
}
fn matches_word(&self, pattern: &str) -> bool {
if self == pattern {
return true;
}
if pattern.is_empty() {
return false;
}
let has_wildcards = pattern.contains(['?', '*']);
if has_wildcards {
let mut chunks: Vec<String> = vec![];
let mut prev_wildcard = false;
let mut chunk_start = 0;
for (i, c) in pattern.char_indices() {
if matches!(c, '?' | '*') && !prev_wildcard {
if i != 0 {
chunks.push(regex::escape(&pattern[chunk_start..i]));
chunk_start = i;
}
prev_wildcard = true;
} else if prev_wildcard {
let chunk = &pattern[chunk_start..i];
chunks.push(chunk.wildcards_to_regex());
chunk_start = i;
prev_wildcard = false;
}
}
let len = pattern.len();
if !prev_wildcard {
chunks.push(regex::escape(&pattern[chunk_start..len]));
} else if prev_wildcard {
let chunk = &pattern[chunk_start..len];
chunks.push(chunk.wildcards_to_regex());
}
// The word characters in ASCII compatible mode (with the `-u` flag) match the
// definition in the spec: any character not in the set `[A-Za-z0-9_]`.
let regex = format!(r"(?-u:^|\W|\b){}(?-u:\b|\W|$)", chunks.concat());
let re = Regex::new(®ex).expect("regex construction should succeed");
re.is_match(self.as_bytes())
} else {
match self.find(pattern) {
Some(start) => {
let end = start + pattern.len();
// Look if the match has word boundaries.
let word_boundary_start = !self.char_at(start).is_word_char()
|| !self.find_prev_char(start).is_some_and(|c| c.is_word_char());
if word_boundary_start {
let word_boundary_end = end == self.len()
|| !self.find_prev_char(end).unwrap().is_word_char()
|| !self.char_at(end).is_word_char();
if word_boundary_end {
return true;
}
}
// Find next word.
let non_word_str = &self[start..];
let non_word = match non_word_str.find(|c: char| !c.is_word_char()) {
Some(pos) => pos,
None => return false,
};
let word_str = &non_word_str[non_word..];
let word = match word_str.find(|c: char| c.is_word_char()) {
Some(pos) => pos,
None => return false,
};
word_str[word..].matches_word(pattern)
}
None => false,
}
}
}
fn wildcards_to_regex(&self) -> String {
// Simplify pattern to avoid performance issues:
// - The glob `?**?**?` is equivalent to the glob `???*`
// - The glob `???*` is equivalent to the regex `.{3,}`
let question_marks = self.matches('?').count();
if self.contains('*') {
format!(".{{{question_marks},}}")
} else {
format!(".{{{question_marks}}}")
}
}
}
#[cfg(not(target_family = "wasm"))]
type HasThreadSubscriptionFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
#[cfg(target_family = "wasm")]
type HasThreadSubscriptionFuture<'a> = Pin<Box<dyn Future<Output = bool> + 'a>>;
#[cfg(not(target_family = "wasm"))]
type HasThreadSubscriptionFn =
dyn for<'a> Fn(&'a EventId) -> HasThreadSubscriptionFuture<'a> + Send + Sync;
#[cfg(target_family = "wasm")]
type HasThreadSubscriptionFn = dyn for<'a> Fn(&'a EventId) -> HasThreadSubscriptionFuture<'a>;
// #[cfg(test)]
// mod tests {
// use std::collections::BTreeMap;
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value, Value as JsonValue};
// use super::{
// FlattenedJson, PushCondition, PushConditionPowerLevelsCtx,
// PushConditionRoomCtx, RoomMemberCountIs, StrExt, };
// use crate::{owned_room_id, owned_user_id,
// power_levels::NotificationPowerLevels, serde::RawJson, OwnedUserId};
// #[test]
// fn serialize_event_match_condition() {
// let json_data = json!({
// "key": "content.msgtype",
// "kind": "event_match",
// "pattern": "m.notice"
// });
// assert_eq!(
// to_json_value(PushCondition::EventMatch {
// key: "content.msgtype".into(),
// pattern: "m.notice".into(),
// })
// .unwrap(),
// json_data
// );
// }
// #[test]
// #[allow(deprecated)]
// fn serialize_contains_display_name_condition() {
// assert_eq!(
// to_json_value(PushCondition::ContainsDisplayName).unwrap(),
// json!({ "kind": "contains_display_name" })
// );
// }
// #[test]
// fn serialize_room_member_count_condition() {
// let json_data = json!({
// "is": "2",
// "kind": "room_member_count"
// });
// assert_eq!(
// to_json_value(PushCondition::RoomMemberCount {
// is: RoomMemberCountIs::from(2)
// })
// .unwrap(),
// json_data
// );
// }
// #[test]
// fn serialize_sender_notification_permission_condition() {
// let json_data = json!({
// "key": "room",
// "kind": "sender_notification_permission"
// });
// assert_eq!(
// json_data,
// to_json_value(PushCondition::SenderNotificationPermission { key:
// "room".into() }).unwrap() );
// }
// #[test]
// fn deserialize_event_match_condition() {
// let json_data = json!({
// "key": "content.msgtype",
// "kind": "event_match",
// "pattern": "m.notice"
// });
// assert_matches!(
// from_json_value::<PushCondition>(json_data).unwrap(),
// PushCondition::EventMatch { key, pattern }
// );
// assert_eq!(key, "content.msgtype");
// assert_eq!(pattern, "m.notice");
// }
// #[test]
// fn deserialize_contains_display_name_condition() {
// assert_matches!(
// from_json_value::<PushCondition>(json!({ "kind":
// "contains_display_name" })).unwrap(),
// PushCondition::ContainsDisplayName );
// }
// #[test]
// fn deserialize_room_member_count_condition() {
// let json_data = json!({
// "is": "2",
// "kind": "room_member_count"
// });
// assert_matches!(
// from_json_value::<PushCondition>(json_data).unwrap(),
// PushCondition::RoomMemberCount { is }
// );
// assert_eq!(is, RoomMemberCountIs::from(2));
// }
// #[test]
// fn deserialize_sender_notification_permission_condition() {
// let json_data = json!({
// "key": "room",
// "kind": "sender_notification_permission"
// });
// assert_matches!(
// from_json_value::<PushCondition>(json_data).unwrap(),
// PushCondition::SenderNotificationPermission { key }
// );
// assert_eq!(key, "room");
// }
// #[test]
// fn words_match() {
// assert!("foo bar".matches_word("foo"));
// assert!(!"Foo bar".matches_word("foo"));
// assert!(!"foobar".matches_word("foo"));
// assert!("foobar foo".matches_word("foo"));
// assert!(!"foobar foobar".matches_word("foo"));
// assert!(!"foobar bar".matches_word("bar bar"));
// assert!("foobar bar bar".matches_word("bar bar"));
// assert!(!"foobar bar barfoo".matches_word("bar bar"));
// assert!("palpo ⚡️".matches_word("palpo ⚡️"));
// assert!("palpo ⚡️".matches_word("palpo"));
// assert!("palpo ⚡️".matches_word("⚡️"));
// assert!("palpo⚡️".matches_word("palpo"));
// assert!("palpo⚡️".matches_word("⚡️"));
// assert!("⚡️palpo".matches_word("palpo"));
// assert!("⚡️palpo".matches_word("⚡️"));
// assert!("Palpo Dev👩💻".matches_word("Dev"));
// assert!("Palpo Dev👩💻".matches_word("👩💻"));
// assert!("Palpo Dev👩💻".matches_word("Dev👩💻"));
// // Regex syntax is escaped
// assert!(!"matrix".matches_word(r"\w*"));
// assert!(r"\w".matches_word(r"\w*"));
// assert!(!"matrix".matches_word("[a-z]*"));
// assert!("[a-z] and [0-9]".matches_word("[a-z]*"));
// assert!(!"m".matches_word("[[:alpha:]]?"));
// assert!("[[:alpha:]]!".matches_word("[[:alpha:]]?"));
// From the spec: <https://spec.matrix.org/v1.17/client-server-api/#conditions-1>
// assert!("An example event.".matches_word("ex*ple"));
// assert!("exple".matches_word("ex*ple"));
// assert!("An exciting triple-whammy".matches_word("ex*ple"));
// }
// #[test]
// fn patterns_match() {
// // Word matching without glob
// assert!("foo bar".matches_pattern("foo", true));
// assert!("Foo bar".matches_pattern("foo", true));
// assert!(!"foobar".matches_pattern("foo", true));
// assert!("".matches_pattern("", true));
// assert!(!"foo".matches_pattern("", true));
// assert!("foo bar".matches_pattern("foo bar", true));
// assert!(" foo bar ".matches_pattern("foo bar", true));
// assert!("baz foo bar baz".matches_pattern("foo bar", true));
// assert!("foo baré".matches_pattern("foo bar", true));
// assert!(!"bar foo".matches_pattern("foo bar", true));
// assert!("foo bar".matches_pattern("foo ", true));
// assert!("foo ".matches_pattern("foo ", true));
// assert!("foo ".matches_pattern("foo ", true));
// assert!(" foo ".matches_pattern("foo ", true));
// // Word matching with glob
// assert!("foo bar".matches_pattern("foo*", true));
// assert!("foo bar".matches_pattern("foo b?r", true));
// assert!(" foo bar ".matches_pattern("foo b?r", true));
// assert!("baz foo bar baz".matches_pattern("foo b?r", true));
// assert!("foo baré".matches_pattern("foo b?r", true));
// assert!(!"bar foo".matches_pattern("foo b?r", true));
// assert!("foo bar".matches_pattern("f*o ", true));
// assert!("foo ".matches_pattern("f*o ", true));
// assert!("foo ".matches_pattern("f*o ", true));
// assert!(" foo ".matches_pattern("f*o ", true));
// // Glob matching
// assert!(!"foo bar".matches_pattern("foo", false));
// assert!("foo".matches_pattern("foo", false));
// assert!("foo".matches_pattern("foo*", false));
// assert!("foobar".matches_pattern("foo*", false));
// assert!("foo bar".matches_pattern("foo*", false));
// assert!(!"foo".matches_pattern("foo?", false));
// assert!("fooo".matches_pattern("foo?", false));
// assert!("FOO".matches_pattern("foo", false));
// assert!("".matches_pattern("", false));
// assert!("".matches_pattern("*", false));
// assert!(!"foo".matches_pattern("", false));
// // From the spec: <https://spec.matrix.org/v1.17/client-server-api/#conditions-1>
// assert!("Lunch plans".matches_pattern("lunc?*", false));
// assert!("LUNCH".matches_pattern("lunc?*", false));
// assert!(!" lunch".matches_pattern("lunc?*", false));
// assert!(!"lunc".matches_pattern("lunc?*", false));
// }
// fn sender() -> OwnedUserId {
// owned_user_id!("@worthy_whale:server.name")
// }
// fn push_context() -> PushConditionRoomCtx {
// let mut users = BTreeMap::new();
// users.insert(sender(), 25);
// let power_levels = PushConditionPowerLevelsCtx {
// users,
// users_default: 50,
// notifications: NotificationPowerLevels { room: 50 },
// };
// PushConditionRoomCtx {
// room_id: owned_room_id!("!room:server.name"),
// member_count: u3,
// user_id: owned_user_id!("@gorilla:server.name"),
// user_display_name: "Groovy Gorilla".into(),
// power_levels: Some(power_levels),
// supported_features: Default::default(),
// }
// }
// fn first_flattened_event() -> FlattenedJson {
// let raw = serde_json::from_str::<RawJson<JsonValue>>(
// r#"{
// "sender": "@worthy_whale:server.name",
// "content": {
// "msgtype": "m.text",
// "body": "@room Give a warm welcome to Groovy Gorilla"
// }
// }"#,
// )
// .unwrap();
// FlattenedJson::from_raw(&raw)
// }
// fn second_flattened_event() -> FlattenedJson {
// let raw = serde_json::from_str::<RawJson<JsonValue>>(
// r#"{
// "sender": "@party_bot:server.name",
// "content": {
// "msgtype": "m.notice",
// "body": "Everybody come to party!"
// }
// }"#,
// )
// .unwrap();
// FlattenedJson::from_raw(&raw)
// }
// #[test]
// fn event_match_applies() {
// let context = push_context();
// let first_event = first_flattened_event();
// let second_event = second_flattened_event();
// let correct_room = PushCondition::EventMatch {
// key: "room_id".into(),
// pattern: "!room:server.name".into(),
// };
// let incorrect_room = PushCondition::EventMatch {
// key: "room_id".into(),
// pattern: "!incorrect:server.name".into(),
// };
// assert!(correct_room.applies(&first_event, &context));
// assert!(!incorrect_room.applies(&first_event, &context));
// let keyword = PushCondition::EventMatch {
// key: "content.body".into(),
// pattern: "come".into(),
// };
// assert!(!keyword.applies(&first_event, &context));
// assert!(keyword.applies(&second_event, &context));
// let msgtype = PushCondition::EventMatch {
// key: "content.msgtype".into(),
// pattern: "m.notice".into(),
// };
// assert!(!msgtype.applies(&first_event, &context));
// assert!(msgtype.applies(&second_event, &context));
// }
// #[test]
// fn room_member_count_is_applies() {
// let context = push_context();
// let event = first_flattened_event();
// let member_count_eq = PushCondition::RoomMemberCount {
// is: RoomMemberCountIs::from(u3),
// };
// let member_count_gt = PushCondition::RoomMemberCount {
// is: RoomMemberCountIs::from(u2..),
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | true |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/predefined.rs | crates/core/src/push/predefined.rs | //! Constructors for [predefined push rules].
//!
//! [predefined push rules]: https://spec.matrix.org/latest/client-server-api/#predefined-rules
use crate::macros::StringEnum;
use super::{
Action, ConditionalPushRule, PushCondition::*, RoomMemberCountIs, RuleKind, Ruleset, Tweak,
};
use crate::{PrivOwnedStr, UserId};
impl Ruleset {
/// The list of all [predefined push rules].
///
/// # Parameters
///
/// - `user_id`: the user for which to generate the default rules. Some
/// rules depend on the user's ID (for instance those to send
/// notifications when they are mentioned).
///
/// [predefined push rules]: https://spec.matrix.org/latest/client-server-api/#predefined-rules
pub fn server_default(user_id: &UserId) -> Self {
Self {
content: Default::default(),
override_: [
ConditionalPushRule::master(),
ConditionalPushRule::suppress_notices(),
ConditionalPushRule::invite_for_me(user_id),
ConditionalPushRule::member_event(),
ConditionalPushRule::is_user_mention(user_id),
// deprecated, but added for complement test `TestThreadedReceipts`.
ConditionalPushRule::contains_display_name(),
ConditionalPushRule::is_room_mention(),
ConditionalPushRule::tombstone(),
ConditionalPushRule::reaction(),
ConditionalPushRule::server_acl(),
ConditionalPushRule::suppress_edits(),
#[cfg(feature = "unstable-msc3930")]
ConditionalPushRule::poll_response(),
]
.into(),
#[cfg(feature = "unstable-msc4306")]
postcontent: [
ConditionalPushRule::unsubscribed_thread(),
ConditionalPushRule::subscribed_thread(),
]
.into(),
underride: [
ConditionalPushRule::call(),
ConditionalPushRule::encrypted_room_one_to_one(),
ConditionalPushRule::room_one_to_one(),
ConditionalPushRule::message(),
ConditionalPushRule::encrypted(),
#[cfg(feature = "unstable-msc3930")]
ConditionalPushRule::poll_start_one_to_one(),
#[cfg(feature = "unstable-msc3930")]
ConditionalPushRule::poll_start(),
#[cfg(feature = "unstable-msc3930")]
ConditionalPushRule::poll_end_one_to_one(),
#[cfg(feature = "unstable-msc3930")]
ConditionalPushRule::poll_end(),
]
.into(),
..Default::default()
}
}
/// Update this ruleset with the given server-default push rules.
///
/// This will replace the server-default rules in this ruleset (with
/// `default` set to `true`) with the given ones while keeping the
/// `enabled` and `actions` fields in the same state.
///
/// The default rules in this ruleset that are not in the new server-default
/// rules are removed.
///
/// # Parameters
///
/// - `server_default`: the new server-default push rules. This ruleset must
/// not contain non-default rules.
pub fn update_with_server_default(&mut self, mut new_server_default: Ruleset) {
// Copy the default rules states from the old rules to the new rules and remove
// the server-default rules from the old rules.
macro_rules! copy_rules_state {
($new_ruleset:ident, $old_ruleset:ident, @fields $($field_name:ident),+) => {
$(
$new_ruleset.$field_name = $new_ruleset
.$field_name
.into_iter()
.map(|mut new_rule| {
if let Some(old_rule) =
$old_ruleset.$field_name.swap_take(new_rule.rule_id.as_str())
{
new_rule.enabled = old_rule.enabled;
new_rule.actions = old_rule.actions;
}
new_rule
})
.collect();
)+
};
}
copy_rules_state!(new_server_default, self, @fields override_, content, room, sender, underride);
// Remove the remaining server-default rules from the old rules.
macro_rules! remove_remaining_default_rules {
($ruleset:ident, @fields $($field_name:ident),+) => {
$(
$ruleset.$field_name.retain(|rule| !rule.default);
)+
};
}
remove_remaining_default_rules!(self, @fields override_, content, room, sender, underride);
// `.m.rule.master` comes before all other push rules, while the other
// server-default push rules come after.
if let Some(master_rule) = new_server_default
.override_
.shift_take(PredefinedOverrideRuleId::Master.as_str())
{
let (pos, _) = self.override_.insert_full(master_rule);
self.override_.move_index(pos, 0);
}
// Merge the new server-default rules into the old rules.
macro_rules! merge_rules {
($old_ruleset:ident, $new_ruleset:ident, @fields $($field_name:ident),+) => {
$(
$old_ruleset.$field_name.extend($new_ruleset.$field_name);
)+
};
}
merge_rules!(self, new_server_default, @fields override_, content, room, sender, underride);
}
}
/// Default override push rules
impl ConditionalPushRule {
/// Matches all events, this can be enabled to turn off all push
/// notifications other than those generated by override rules set by
/// the user.
pub fn master() -> Self {
Self {
actions: vec![],
default: true,
enabled: false,
rule_id: PredefinedOverrideRuleId::Master.to_string(),
conditions: vec![],
}
}
/// Matches messages with a `msgtype` of `notice`.
pub fn suppress_notices() -> Self {
Self {
actions: vec![],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::SuppressNotices.to_string(),
conditions: vec![EventMatch {
key: "content.msgtype".into(),
pattern: "m.notice".into(),
}],
}
}
/// Matches any invites to a new room for this user.
pub fn invite_for_me(user_id: &UserId) -> Self {
Self {
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("default".into())),
Action::SetTweak(Tweak::Highlight(false)),
],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::InviteForMe.to_string(),
conditions: vec![
EventMatch {
key: "type".into(),
pattern: "m.room.member".into(),
},
EventMatch {
key: "content.membership".into(),
pattern: "invite".into(),
},
EventMatch {
key: "state_key".into(),
pattern: user_id.to_string(),
},
],
}
}
/// Matches any `m.room.member_event`.
pub fn member_event() -> Self {
Self {
actions: vec![],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::MemberEvent.to_string(),
conditions: vec![EventMatch {
key: "type".into(),
pattern: "m.room.member".into(),
}],
}
}
/// Matches any message which contains the user’s Matrix ID in the list of
/// `user_ids` under the `m.mentions` property.
pub fn is_user_mention(user_id: &UserId) -> Self {
Self {
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("default".to_owned())),
Action::SetTweak(Tweak::Highlight(true)),
],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::IsUserMention.to_string(),
conditions: vec![EventPropertyContains {
key: r"content.m\.mentions.user_ids".to_owned(),
value: user_id.as_str().into(),
}],
}
}
// do not remove for complement test `TestThreadedReceipts`.
/// Matches any message whose content is unencrypted and contains the user's current display
/// name in the room in which it was sent.
///
/// Since Matrix 1.7, this rule only matches if the event's content does not contain an
/// `m.mentions` property.
#[deprecated = "Since Matrix 1.7. Use the m.mentions property with ConditionalPushRule::is_user_mention() instead."]
pub fn contains_display_name() -> Self {
#[allow(deprecated)]
Self {
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("default".into())),
Action::SetTweak(Tweak::Highlight(true)),
],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::ContainsDisplayName.to_string(),
conditions: vec![ContainsDisplayName],
}
}
/// Matches any state event whose type is `m.room.tombstone`. This
/// is intended to notify users of a room when it is upgraded,
/// similar to what an `@room` notification would accomplish.
pub fn tombstone() -> Self {
Self {
actions: vec![Action::Notify, Action::SetTweak(Tweak::Highlight(true))],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::Tombstone.to_string(),
conditions: vec![
EventMatch {
key: "type".into(),
pattern: "m.room.tombstone".into(),
},
EventMatch {
key: "state_key".into(),
pattern: "".into(),
},
],
}
}
/// Matches any message from a sender with the proper power level with the
/// `room` property of the `m.mentions` property set to `true`.
pub fn is_room_mention() -> Self {
Self {
actions: vec![Action::Notify, Action::SetTweak(Tweak::Highlight(true))],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::IsRoomMention.to_string(),
conditions: vec![
EventPropertyIs {
key: r"content.m\.mentions.room".to_owned(),
value: true.into(),
},
SenderNotificationPermission {
key: "room".to_owned(),
},
],
}
}
/// Matches [reactions] to a message.
///
/// [reactions]: https://spec.matrix.org/latest/client-server-api/#event-annotations-and-reactions
pub fn reaction() -> Self {
Self {
actions: vec![],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::Reaction.to_string(),
conditions: vec![EventMatch {
key: "type".into(),
pattern: "m.reaction".into(),
}],
}
}
/// Matches [room server ACLs].
///
/// [room server ACLs]: https://spec.matrix.org/latest/client-server-api/#server-access-control-lists-acls-for-rooms
pub fn server_acl() -> Self {
Self {
actions: vec![],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::RoomServerAcl.to_string(),
conditions: vec![
EventMatch {
key: "type".into(),
pattern: "m.room.server_acl".into(),
},
EventMatch {
key: "state_key".into(),
pattern: "".into(),
},
],
}
}
/// Matches [event replacements].
///
/// [event replacements]: https://spec.matrix.org/latest/client-server-api/#event-replacements
pub fn suppress_edits() -> Self {
Self {
actions: vec![],
default: true,
enabled: true,
rule_id: PredefinedOverrideRuleId::SuppressEdits.to_string(),
conditions: vec![EventPropertyIs {
key: r"content.m\.relates_to.rel_type".to_owned(),
value: "m.replace".into(),
}],
}
}
/// Matches a poll response event sent in any room.
///
/// This rule uses the unstable prefixes defined in [MSC3381] and [MSC3930].
///
/// [MSC3381]: https://github.com/matrix-org/matrix-spec-proposals/pull/3381
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
pub fn poll_response() -> Self {
Self {
rule_id: PredefinedOverrideRuleId::PollResponse.to_string(),
default: true,
enabled: true,
// conditions: vec![EventPropertyIs {
// key: "type".to_owned(),
// value: "org.matrix.msc3381.poll.response".into(),
// }],
// complement test use event match
conditions: vec![EventMatch {
key: "type".to_owned(),
pattern: "org.matrix.msc3381.poll.response".into(),
}],
actions: vec![],
}
}
}
/// Default underrides push rules
impl ConditionalPushRule {
/// Matches any incoming VOIP call.
pub fn call() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::Call.to_string(),
default: true,
enabled: true,
conditions: vec![EventMatch {
key: "type".into(),
pattern: "m.call.invite".into(),
}],
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("ring".into())),
Action::SetTweak(Tweak::Highlight(false)),
],
}
}
/// Matches any encrypted event sent in a room with exactly two members.
///
/// Unlike other push rules, this rule cannot be matched against the content
/// of the event by nature of it being encrypted. This causes the rule
/// to be an "all or nothing" match where it either matches all events
/// that are encrypted (in 1:1 rooms) or none.
pub fn encrypted_room_one_to_one() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::EncryptedRoomOneToOne.to_string(),
default: true,
enabled: true,
conditions: vec![
RoomMemberCount {
is: RoomMemberCountIs::from(2),
},
EventMatch {
key: "type".into(),
pattern: "m.room.encrypted".into(),
},
],
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("default".into())),
Action::SetTweak(Tweak::Highlight(false)),
],
}
}
/// Matches any message sent in a room with exactly two members.
pub fn room_one_to_one() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::RoomOneToOne.to_string(),
default: true,
enabled: true,
conditions: vec![
RoomMemberCount {
is: RoomMemberCountIs::from(2),
},
EventMatch {
key: "type".into(),
pattern: "m.room.message".into(),
},
],
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("default".into())),
Action::SetTweak(Tweak::Highlight(false)),
],
}
}
/// Matches all chat messages.
pub fn message() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::Message.to_string(),
default: true,
enabled: true,
conditions: vec![EventMatch {
key: "type".into(),
pattern: "m.room.message".into(),
}],
actions: vec![Action::Notify, Action::SetTweak(Tweak::Highlight(false))],
}
}
/// Matches all encrypted events.
///
/// Unlike other push rules, this rule cannot be matched against the content
/// of the event by nature of it being encrypted. This causes the rule
/// to be an "all or nothing" match where it either matches all events
/// that are encrypted (in group rooms) or none.
pub fn encrypted() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::Encrypted.to_string(),
default: true,
enabled: true,
conditions: vec![EventMatch {
key: "type".into(),
pattern: "m.room.encrypted".into(),
}],
actions: vec![Action::Notify, Action::SetTweak(Tweak::Highlight(false))],
}
}
/// Matches a poll start event sent in a room with exactly two members.
///
/// This rule uses the unstable prefixes defined in [MSC3381] and [MSC3930].
///
/// [MSC3381]: https://github.com/matrix-org/matrix-spec-proposals/pull/3381
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
pub fn poll_start_one_to_one() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::PollStartOneToOne.to_string(),
default: true,
enabled: true,
conditions: vec![
RoomMemberCount {
is: RoomMemberCountIs::from(2),
},
// complement test use event match
// EventPropertyIs {
// key: "type".to_owned(),
// value: "org.matrix.msc3381.poll.start".into(),
// },
EventMatch {
key: "type".into(),
pattern: "org.matrix.msc3381.poll.start".into(),
},
],
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("default".into())),
],
}
}
/// Matches a poll start event sent in any room.
///
/// This rule uses the unstable prefixes defined in [MSC3381] and [MSC3930].
///
/// [MSC3381]: https://github.com/matrix-org/matrix-spec-proposals/pull/3381
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
pub fn poll_start() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::PollStart.to_string(),
default: true,
enabled: true,
// conditions: vec![EventPropertyIs {
// key: "type".to_owned(),
// value: "org.matrix.msc3381.poll.start".into(),
// }],
// complement test use event match
conditions: vec![EventMatch {
key: "type".to_owned(),
pattern: "org.matrix.msc3381.poll.start".into(),
}],
actions: vec![Action::Notify],
}
}
/// Matches a poll end event sent in a room with exactly two members.
///
/// This rule uses the unstable prefixes defined in [MSC3381] and [MSC3930].
///
/// [MSC3381]: https://github.com/matrix-org/matrix-spec-proposals/pull/3381
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
pub fn poll_end_one_to_one() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::PollEndOneToOne.to_string(),
default: true,
enabled: true,
conditions: vec![
RoomMemberCount {
is: RoomMemberCountIs::from(2),
},
// complement test use event match
// EventPropertyIs {
// key: "type".to_owned(),
// value: "org.matrix.msc3381.poll.end".into(),
// },
EventMatch {
key: "type".to_owned(),
pattern: "org.matrix.msc3381.poll.end".into(),
},
],
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("default".into())),
],
}
}
/// Matches a poll end event sent in any room.
///
/// This rule uses the unstable prefixes defined in [MSC3381] and [MSC3930].
///
/// [MSC3381]: https://github.com/matrix-org/matrix-spec-proposals/pull/3381
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
pub fn poll_end() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::PollEnd.to_string(),
default: true,
enabled: true,
// conditions: vec![EventPropertyIs {
// key: "type".to_owned(),
// value: "org.matrix.msc3381.poll.end".into(),
// }],
// complement test use event match
conditions: vec![EventMatch {
key: "type".to_owned(),
pattern: "org.matrix.msc3381.poll.end".into(),
}],
actions: vec![Action::Notify],
}
}
/// Matches an event that's part of a thread, that is *not* subscribed to, by the current user.
///
/// Thread subscriptions are defined in [MSC4306].
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
pub fn unsubscribed_thread() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::UnsubscribedThread.to_string(),
default: true,
enabled: true,
conditions: vec![ThreadSubscription { subscribed: false }],
actions: vec![],
}
}
/// Matches an event that's part of a thread, that *is* subscribed to, by the current user.
///
/// Thread subscriptions are defined in [MSC4306].
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
pub fn subscribed_thread() -> Self {
Self {
rule_id: PredefinedUnderrideRuleId::SubscribedThread.to_string(),
default: true,
enabled: true,
conditions: vec![ThreadSubscription { subscribed: true }],
actions: vec![
Action::Notify,
Action::SetTweak(Tweak::Sound("default".into())),
],
}
}
}
/// The rule IDs of the predefined server push rules.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum PredefinedRuleId {
/// User-configured rules that override all other kinds.
Override(PredefinedOverrideRuleId),
/// Lowest priority user-defined rules.
Underride(PredefinedUnderrideRuleId),
/// Content-specific rules.
Content(PredefinedContentRuleId),
}
impl PredefinedRuleId {
/// Creates a string slice from this `PredefinedRuleId`.
pub fn as_str(&self) -> &str {
match self {
Self::Override(id) => id.as_str(),
Self::Underride(id) => id.as_str(),
Self::Content(id) => id.as_str(),
}
}
/// Get the kind of this `PredefinedRuleId`.
pub fn kind(&self) -> RuleKind {
match self {
Self::Override(id) => id.kind(),
Self::Underride(id) => id.kind(),
Self::Content(id) => id.kind(),
}
}
}
impl AsRef<str> for PredefinedRuleId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// The rule IDs of the predefined override server push rules.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = ".m.rule.", rule = "snake_case"))]
#[non_exhaustive]
pub enum PredefinedOverrideRuleId {
/// `.m.rule.master`
Master,
/// `.m.rule.suppress_notices`
SuppressNotices,
/// `.m.rule.invite_for_me`
InviteForMe,
/// `.m.rule.member_event`
MemberEvent,
/// `.m.rule.is_user_mention`
IsUserMention,
/// `.m.rule.contains_display_name`
#[deprecated = "Since Matrix 1.7. Use the m.mentions property with PredefinedOverrideRuleId::IsUserMention instead."]
ContainsDisplayName,
/// `.m.rule.is_room_mention`
IsRoomMention,
/// `.m.rule.roomnotif`
#[palpo_enum(rename = ".m.rule.roomnotif")]
#[deprecated = "Since Matrix 1.7. Use the m.mentions property with PredefinedOverrideRuleId::IsRoomMention instead."]
RoomNotif,
/// `.m.rule.tombstone`
Tombstone,
/// `.m.rule.reaction`
Reaction,
/// `.m.rule.room.server_acl`
#[palpo_enum(rename = ".m.rule.room.server_acl")]
RoomServerAcl,
/// `.m.rule.suppress_edits`
SuppressEdits,
/// `.m.rule.poll_response`
///
/// This uses the unstable prefix defined in [MSC3930].
///
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
#[palpo_enum(rename = ".org.matrix.msc3930.rule.poll_response")]
PollResponse,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl PredefinedOverrideRuleId {
/// Get the kind of this `PredefinedOverrideRuleId`.
pub fn kind(&self) -> RuleKind {
RuleKind::Override
}
}
/// The rule IDs of the predefined underride server push rules.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = ".m.rule.", rule = "snake_case"))]
#[non_exhaustive]
pub enum PredefinedUnderrideRuleId {
/// `.m.rule.call`
Call,
/// `.m.rule.encrypted_room_one_to_one`
EncryptedRoomOneToOne,
/// `.m.rule.room_one_to_one`
RoomOneToOne,
/// `.m.rule.message`
Message,
/// `.m.rule.encrypted`
Encrypted,
/// `.m.rule.poll_start_one_to_one`
///
/// This uses the unstable prefix defined in [MSC3930].
///
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
#[palpo_enum(rename = ".org.matrix.msc3930.rule.poll_start_one_to_one")]
PollStartOneToOne,
/// `.m.rule.poll_start`
///
/// This uses the unstable prefix defined in [MSC3930].
///
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
#[palpo_enum(rename = ".org.matrix.msc3930.rule.poll_start")]
PollStart,
/// `.m.rule.poll_end_one_to_one`
///
/// This uses the unstable prefix defined in [MSC3930].
///
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
#[palpo_enum(rename = ".org.matrix.msc3930.rule.poll_end_one_to_one")]
PollEndOneToOne,
/// `.m.rule.poll_end`
///
/// This uses the unstable prefix defined in [MSC3930].
///
/// [MSC3930]: https://github.com/matrix-org/matrix-spec-proposals/pull/3930
#[cfg(feature = "unstable-msc3930")]
#[palpo_enum(rename = ".org.matrix.msc3930.rule.poll_end")]
PollEnd,
/// `.m.rule.unsubscribed_thread`
///
/// This uses the unstable prefix defined in [MSC4306].
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
#[palpo_enum(rename = ".io.element.msc4306.rule.unsubscribed_thread")]
UnsubscribedThread,
/// `.m.rule.subscribed_thread`
///
/// This uses the unstable prefix defined in [MSC4306].
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
#[palpo_enum(rename = ".io.element.msc4306.rule.subscribed_thread")]
SubscribedThread,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl PredefinedUnderrideRuleId {
/// Get the kind of this `PredefinedUnderrideRuleId`.
pub fn kind(&self) -> RuleKind {
RuleKind::Underride
}
}
/// The rule IDs of the predefined content server push rules.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[palpo_enum(rename_all(prefix = ".m.rule.", rule = "snake_case"))]
#[non_exhaustive]
pub enum PredefinedContentRuleId {
/// `.m.rule.contains_user_name`
#[deprecated = "Since Matrix 1.7. Use the m.mentions property with PredefinedOverrideRuleId::IsUserMention instead."]
ContainsUserName,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl PredefinedContentRuleId {
/// Get the kind of this `PredefinedContentRuleId`.
pub fn kind(&self) -> RuleKind {
RuleKind::Content
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use assign::assign;
// use super::PredefinedOverrideRuleId;
// use crate::{
// push::{Action, ConditionalPushRule, ConditionalPushRuleInit,
// Ruleset}, user_id,
// };
// #[test]
// fn update_with_server_default() {
// let user_rule_id = "user_always_true";
// let default_rule_id = ".default_always_true";
// let override_ = [
// // Default `.m.rule.master` push rule with non-default state.
// assign!(ConditionalPushRule::master(), { enabled: true, actions:
// vec![Action::Notify]}), // User-defined push rule.
// ConditionalPushRuleInit {
// actions: vec![],
// default: false,
// enabled: false,
// rule_id: user_rule_id.to_owned(),
// conditions: vec![],
// }
// .into(),
// // Old server-default push rule.
// ConditionalPushRuleInit {
// actions: vec![],
// default: true,
// enabled: true,
// rule_id: default_rule_id.to_owned(),
// conditions: vec![],
// }
// .into(),
// ]
// .into_iter()
// .collect();
// let mut ruleset = Ruleset {
// override_,
// ..Default::default()
// };
// let new_server_default =
// Ruleset::server_default(user_id!("@user:localhost"));
// ruleset.update_with_server_default(new_server_default);
// // Master rule is in first position.
// let master_rule = &ruleset.override_[0];
// assert_eq!(master_rule.rule_id,
// PredefinedOverrideRuleId::Master.as_str());
// // `enabled` and `actions` have been copied from the old rules.
// assert!(master_rule.enabled);
// assert_eq!(master_rule.actions.len(), 1);
// assert_matches!(&master_rule.actions[0], Action::Notify);
// // Non-server-default rule is still present and hasn't changed.
// let user_rule = ruleset.override_.get(user_rule_id).unwrap();
// assert!(!user_rule.enabled);
// assert_eq!(user_rule.actions.len(), 0);
// // Old server-default rule is gone.
// assert_matches!(ruleset.override_.get(default_rule_id), None);
// // New server-default rule is present and hasn't changed.
// let member_event_rule = ruleset
// .override_
// .get(PredefinedOverrideRuleId::MemberEvent.as_str())
// .unwrap();
// assert!(member_event_rule.enabled);
// assert_eq!(member_event_rule.actions.len(), 0);
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/ruleset.rs | crates/core/src/push/ruleset.rs | //! Constructors for [predefined push rules].
//!
//! [predefined push rules]: https://spec.matrix.org/latest/client-server-api/#predefined-rules
use indexmap::IndexSet;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use tracing::instrument;
use super::{
Action, AnyPushRuleRef, ConditionalPushRule, FlattenedJson, InsertPushRuleError, NewPushRule,
PatternedPushRule, PushConditionRoomCtx, RuleKind, RuleNotFoundError, RulesetIter,
SimplePushRule, insert_and_move_rule,
};
use crate::{OwnedRoomId, OwnedUserId, push::RemovePushRuleError, serde::RawJson};
/// A push ruleset scopes a set of rules according to some criteria.
///
/// For example, some rules may only be applied for messages from a particular
/// sender, a particular room, or by default. The push ruleset contains the
/// entire set of scopes and rules.
#[derive(ToSchema, Deserialize, Serialize, Default, Clone, Debug)]
pub struct Ruleset {
/// These rules configure behavior for (unencrypted) messages that match
/// certain patterns.
#[serde(default, skip_serializing_if = "IndexSet::is_empty")]
#[salvo(schema(value_type = HashSet<PatternedPushRule>))]
pub content: IndexSet<PatternedPushRule>,
/// These rules are identical to override rules, but have a lower priority than `room` and
/// `sender` rules.
#[cfg(feature = "unstable-msc4306")]
#[serde(default, skip_serializing_if = "IndexSet::is_empty")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub postcontent: IndexSet<ConditionalPushRule>,
/// These user-configured rules are given the highest priority.
///
/// This field is named `override_` instead of `override` because the latter
/// is a reserved keyword in Rust.
#[serde(
rename = "override",
default,
skip_serializing_if = "IndexSet::is_empty"
)]
#[salvo(schema(value_type = HashSet<ConditionalPushRule>))]
pub override_: IndexSet<ConditionalPushRule>,
/// These rules change the behavior of all messages for a given room.
#[serde(default, skip_serializing_if = "IndexSet::is_empty")]
#[salvo(schema(value_type = HashSet<SimplePushRule<OwnedRoomId>>))]
pub room: IndexSet<SimplePushRule<OwnedRoomId>>,
/// These rules configure notification behavior for messages from a specific
/// Matrix user ID.
#[serde(default, skip_serializing_if = "IndexSet::is_empty")]
#[salvo(schema(value_type = HashSet<SimplePushRule<OwnedUserId>>))]
pub sender: IndexSet<SimplePushRule<OwnedUserId>>,
/// These rules are identical to override rules, but have a lower priority
/// than `content`, `room` and `sender` rules.
#[serde(default, skip_serializing_if = "IndexSet::is_empty")]
#[salvo(schema(value_type = HashSet<ConditionalPushRule>))]
pub underride: IndexSet<ConditionalPushRule>,
}
impl Ruleset {
/// Creates an empty `Ruleset`.
pub fn new() -> Self {
Default::default()
}
/// Creates a borrowing iterator over all push rules in this `Ruleset`.
///
/// For an owning iterator, use `.into_iter()`.
pub fn iter(&self) -> RulesetIter<'_> {
self.into_iter()
}
/// Inserts a user-defined rule in the rule set.
///
/// If a rule with the same kind and `rule_id` exists, it will be replaced.
///
/// If `after` or `before` is set, the rule will be moved relative to the
/// rule with the given ID. If both are set, the rule will become the
/// next-most important rule with respect to `before`. If neither are
/// set, and the rule is newly inserted, it will become the rule with
/// the highest priority of its kind.
///
/// Returns an error if the parameters are invalid.
pub fn insert(
&mut self,
rule: NewPushRule,
after: Option<&str>,
before: Option<&str>,
) -> Result<(), InsertPushRuleError> {
let rule_id = rule.rule_id();
if rule_id.starts_with('.') {
return Err(InsertPushRuleError::ServerDefaultRuleId);
}
if rule_id.contains('/') {
return Err(InsertPushRuleError::InvalidRuleId);
}
if rule_id.contains('\\') {
return Err(InsertPushRuleError::InvalidRuleId);
}
if after.is_some_and(|s| s.starts_with('.')) {
return Err(InsertPushRuleError::RelativeToServerDefaultRule);
}
if before.is_some_and(|s| s.starts_with('.')) {
return Err(InsertPushRuleError::RelativeToServerDefaultRule);
}
match rule {
NewPushRule::Override(r) => {
let mut rule = ConditionalPushRule::from(r);
if let Some(prev_rule) = self.override_.get(rule.rule_id.as_str()) {
rule.enabled = prev_rule.enabled;
}
// `m.rule.master` should always be the rule with the highest priority, so we
// insert this one at most at the second place.
let default_position = 1;
insert_and_move_rule(&mut self.override_, rule, default_position, after, before)
}
#[cfg(feature = "unstable-msc4306")]
NewPushRule::PostContent(r) => {
let mut rule = ConditionalPushRule::from(r);
if let Some(prev_rule) = self.postcontent.get(rule.rule_id.as_str()) {
rule.enabled = prev_rule.enabled;
}
insert_and_move_rule(&mut self.postcontent, rule, 0, after, before)
}
NewPushRule::Underride(r) => {
let mut rule = ConditionalPushRule::from(r);
if let Some(prev_rule) = self.underride.get(rule.rule_id.as_str()) {
rule.enabled = prev_rule.enabled;
}
insert_and_move_rule(&mut self.underride, rule, 0, after, before)
}
NewPushRule::Content(r) => {
let mut rule = PatternedPushRule::from(r);
if let Some(prev_rule) = self.content.get(rule.rule_id.as_str()) {
rule.enabled = prev_rule.enabled;
}
insert_and_move_rule(&mut self.content, rule, 0, after, before)
}
NewPushRule::Room(r) => {
let mut rule = SimplePushRule::from(r);
if let Some(prev_rule) = self.room.get(rule.rule_id.as_str()) {
rule.enabled = prev_rule.enabled;
}
insert_and_move_rule(&mut self.room, rule, 0, after, before)
}
NewPushRule::Sender(r) => {
let mut rule = SimplePushRule::from(r);
if let Some(prev_rule) = self.sender.get(rule.rule_id.as_str()) {
rule.enabled = prev_rule.enabled;
}
insert_and_move_rule(&mut self.sender, rule, 0, after, before)
}
}
}
/// Get the rule from the given kind and with the given `rule_id` in the
/// rule set.
pub fn get(&self, kind: RuleKind, rule_id: impl AsRef<str>) -> Option<AnyPushRuleRef<'_>> {
let rule_id = rule_id.as_ref();
match kind {
RuleKind::Override => self.override_.get(rule_id).map(AnyPushRuleRef::Override),
RuleKind::Underride => self.underride.get(rule_id).map(AnyPushRuleRef::Underride),
RuleKind::Sender => self.sender.get(rule_id).map(AnyPushRuleRef::Sender),
RuleKind::Room => self.room.get(rule_id).map(AnyPushRuleRef::Room),
RuleKind::Content => self.content.get(rule_id).map(AnyPushRuleRef::Content),
#[cfg(feature = "unstable-msc4306")]
RuleKind::PostContent => self
.postcontent
.get(rule_id)
.map(AnyPushRuleRef::PostContent),
RuleKind::_Custom(_) => None,
}
}
/// Set whether the rule from the given kind and with the given `rule_id` in
/// the rule set is enabled.
///
/// Returns an error if the rule can't be found.
pub fn set_enabled(
&mut self,
kind: RuleKind,
rule_id: impl AsRef<str>,
enabled: bool,
) -> Result<(), RuleNotFoundError> {
let rule_id = rule_id.as_ref();
match kind {
RuleKind::Override => {
let mut rule = self
.override_
.get(rule_id)
.ok_or(RuleNotFoundError)?
.clone();
rule.enabled = enabled;
self.override_.replace(rule);
}
RuleKind::Underride => {
let mut rule = self
.underride
.get(rule_id)
.ok_or(RuleNotFoundError)?
.clone();
rule.enabled = enabled;
self.underride.replace(rule);
}
RuleKind::Sender => {
let mut rule = self.sender.get(rule_id).ok_or(RuleNotFoundError)?.clone();
rule.enabled = enabled;
self.sender.replace(rule);
}
RuleKind::Room => {
let mut rule = self.room.get(rule_id).ok_or(RuleNotFoundError)?.clone();
rule.enabled = enabled;
self.room.replace(rule);
}
RuleKind::Content => {
let mut rule = self.content.get(rule_id).ok_or(RuleNotFoundError)?.clone();
rule.enabled = enabled;
self.content.replace(rule);
}
#[cfg(feature = "unstable-msc4306")]
RuleKind::PostContent => {
let mut rule = self
.postcontent
.get(rule_id)
.ok_or(RuleNotFoundError)?
.clone();
rule.enabled = enabled;
self.postcontent.replace(rule);
}
RuleKind::_Custom(_) => return Err(RuleNotFoundError),
}
Ok(())
}
/// Set the actions of the rule from the given kind and with the given
/// `rule_id` in the rule set.
///
/// Returns an error if the rule can't be found.
pub fn set_actions(
&mut self,
kind: RuleKind,
rule_id: impl AsRef<str>,
actions: Vec<Action>,
) -> Result<(), RuleNotFoundError> {
let rule_id = rule_id.as_ref();
match kind {
RuleKind::Override => {
let mut rule = self
.override_
.get(rule_id)
.ok_or(RuleNotFoundError)?
.clone();
rule.actions = actions;
self.override_.replace(rule);
}
RuleKind::Underride => {
let mut rule = self
.underride
.get(rule_id)
.ok_or(RuleNotFoundError)?
.clone();
rule.actions = actions;
self.underride.replace(rule);
}
RuleKind::Sender => {
let mut rule = self.sender.get(rule_id).ok_or(RuleNotFoundError)?.clone();
rule.actions = actions;
self.sender.replace(rule);
}
RuleKind::Room => {
let mut rule = self.room.get(rule_id).ok_or(RuleNotFoundError)?.clone();
rule.actions = actions;
self.room.replace(rule);
}
RuleKind::Content => {
let mut rule = self.content.get(rule_id).ok_or(RuleNotFoundError)?.clone();
rule.actions = actions;
self.content.replace(rule);
}
#[cfg(feature = "unstable-msc4306")]
RuleKind::PostContent => {
let mut rule = self
.postcontent
.get(rule_id)
.ok_or(RuleNotFoundError)?
.clone();
rule.actions = actions;
self.postcontent.replace(rule);
}
RuleKind::_Custom(_) => return Err(RuleNotFoundError),
}
Ok(())
}
/// Get the first push rule that applies to this event, if any.
///
/// # Arguments
///
/// * `event` - The raw JSON of a room message event.
/// * `context` - The context of the message and room at the time of the
/// event.
#[instrument(skip_all, fields(context.room_id = %context.room_id))]
pub async fn get_match<T>(
&self,
event: &RawJson<T>,
context: &PushConditionRoomCtx,
) -> Option<AnyPushRuleRef<'_>> {
let event = FlattenedJson::from_raw(event);
if event
.get_str("sender")
.is_some_and(|sender| sender == context.user_id)
{
// no need to look at the rules if the event was by the user themselves
return None;
}
for rule in self {
if rule.applies(&event, context).await {
return Some(rule);
}
}
None
}
/// Get the push actions that apply to this event.
///
/// Returns an empty slice if no push rule applies.
///
/// # Arguments
///
/// * `event` - The raw JSON of a room message event.
/// * `context` - The context of the message and room at the time of the
/// event.
#[instrument(skip_all, fields(context.room_id = %context.room_id))]
pub async fn get_actions<T>(
&self,
event: &RawJson<T>,
context: &PushConditionRoomCtx,
) -> &[Action] {
self.get_match(event, context)
.await
.map(|rule| rule.actions())
.unwrap_or(&[])
}
/// Removes a user-defined rule in the rule set.
///
/// Returns an error if the parameters are invalid.
pub fn remove(
&mut self,
kind: RuleKind,
rule_id: impl AsRef<str>,
) -> Result<(), RemovePushRuleError> {
let rule_id = rule_id.as_ref();
if let Some(rule) = self.get(kind.clone(), rule_id) {
if rule.is_server_default() {
return Err(RemovePushRuleError::ServerDefault);
}
} else {
return Err(RemovePushRuleError::NotFound);
}
match kind {
RuleKind::Override => {
self.override_.shift_remove(rule_id);
}
RuleKind::Underride => {
self.underride.shift_remove(rule_id);
}
RuleKind::Sender => {
self.sender.shift_remove(rule_id);
}
RuleKind::Room => {
self.room.shift_remove(rule_id);
}
RuleKind::Content => {
self.content.shift_remove(rule_id);
}
#[cfg(feature = "unstable-msc4306")]
RuleKind::PostContent => {
self.postcontent.shift_remove(rule_id);
}
// This has been handled in the `self.get` call earlier.
RuleKind::_Custom(_) => unreachable!(),
}
Ok(())
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use assign::assign;
// use super::PredefinedOverrideRuleId;
// use crate::{
// push::{Action, ConditionalPushRule, ConditionalPushRuleInit,
// Ruleset}, user_id,
// };
// #[test]
// fn update_with_server_default() {
// let user_rule_id = "user_always_true";
// let default_rule_id = ".default_always_true";
// let override_ = [
// // Default `.m.rule.master` push rule with non-default state.
// assign!(ConditionalPushRule::master(), { enabled: true, actions:
// vec![Action::Notify]}), // User-defined push rule.
// ConditionalPushRuleInit {
// actions: vec![],
// default: false,
// enabled: false,
// rule_id: user_rule_id.to_owned(),
// conditions: vec![],
// }
// .into(),
// // Old server-default push rule.
// ConditionalPushRuleInit {
// actions: vec![],
// default: true,
// enabled: true,
// rule_id: default_rule_id.to_owned(),
// conditions: vec![],
// }
// .into(),
// ]
// .into_iter()
// .collect();
// let mut ruleset = Ruleset {
// override_,
// ..Default::default()
// };
// let new_server_default =
// Ruleset::server_default(user_id!("@user:localhost"));
// ruleset.update_with_server_default(new_server_default);
// // Master rule is in first position.
// let master_rule = &ruleset.override_[0];
// assert_eq!(master_rule.rule_id,
// PredefinedOverrideRuleId::Master.as_str());
// // `enabled` and `actions` have been copied from the old rules.
// assert!(master_rule.enabled);
// assert_eq!(master_rule.actions.len(), 1);
// assert_matches!(&master_rule.actions[0], Action::Notify);
// // Non-server-default rule is still present and hasn't changed.
// let user_rule = ruleset.override_.get(user_rule_id).unwrap();
// assert!(!user_rule.enabled);
// assert_eq!(user_rule.actions.len(), 0);
// // Old server-default rule is gone.
// assert_matches!(ruleset.override_.get(default_rule_id), None);
// // New server-default rule is present and hasn't changed.
// let member_event_rule = ruleset
// .override_
// .get(PredefinedOverrideRuleId::MemberEvent.as_str())
// .unwrap();
// assert!(member_event_rule.enabled);
// assert_eq!(member_event_rule.actions.len(), 0);
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/patterned_push_rule.rs | crates/core/src/push/patterned_push_rule.rs | //! Common types for the [push notifications module][push].
//!
//! [push]: https://spec.matrix.org/latest/client-server-api/#push-notifications
//!
//! ## Understanding the types of this module
//!
//! Push rules are grouped in `RuleSet`s, and are grouped in five kinds (for
//! more details about the different kind of rules, see the `Ruleset`
//! documentation, or the specification). These five kinds are, by order of
//! priority:
//!
//! - override rules
//! - content rules
//! - room rules
//! - sender rules
//! - underride rules
use std::hash::{Hash, Hasher};
use indexmap::Equivalent;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::push::{
Action, FlattenedJson, MissingPatternError, PredefinedContentRuleId, PushConditionRoomCtx,
PushRule, condition,
};
/// Like `SimplePushRule`, but with an additional `pattern` field.
///
/// Only applicable to content rules.
///
/// To create an instance of this type.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct PatternedPushRule {
/// Actions to determine if and how a notification is delivered for events
/// matching this rule.
pub actions: Vec<Action>,
/// Whether this is a default rule, or has been set explicitly.
pub default: bool,
/// Whether the push rule is enabled or not.
pub enabled: bool,
/// The ID of this rule.
pub rule_id: String,
/// The glob-style pattern to match against.
pub pattern: String,
}
impl PatternedPushRule {
/// Check if the push rule applies to the event.
///
/// # Arguments
///
/// * `event` - The flattened JSON representation of a room message event.
/// * `context` - The context of the room at the time of the event.
pub fn applies_to(
&self,
key: &str,
event: &FlattenedJson,
context: &PushConditionRoomCtx,
) -> bool {
// The old mention rules are disabled when an m.mentions field is present.
#[allow(deprecated)]
if self.rule_id == PredefinedContentRuleId::ContainsUserName.as_ref()
&& event.contains_mentions()
{
return false;
}
if event
.get_str("sender")
.is_some_and(|sender| sender == context.user_id)
{
return false;
}
self.enabled && condition::check_event_match(event, key, &self.pattern, context)
}
}
// The following trait are needed to be able to make
// an IndexSet of the type
impl Hash for PatternedPushRule {
fn hash<H: Hasher>(&self, state: &mut H) {
self.rule_id.hash(state);
}
}
impl PartialEq for PatternedPushRule {
fn eq(&self, other: &Self) -> bool {
self.rule_id == other.rule_id
}
}
impl Eq for PatternedPushRule {}
impl Equivalent<PatternedPushRule> for str {
fn equivalent(&self, key: &PatternedPushRule) -> bool {
self == key.rule_id
}
}
/// A patterned push rule to update or create.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
pub struct NewPatternedPushRule {
/// The ID of this rule.
pub rule_id: String,
/// The glob-style pattern to match against.
pub pattern: String,
/// Actions to determine if and how a notification is delivered for events
/// matching this rule.
pub actions: Vec<Action>,
}
impl NewPatternedPushRule {
/// Creates a `NewPatternedPushRule` with the given ID, pattern and actions.
pub fn new(rule_id: String, pattern: String, actions: Vec<Action>) -> Self {
Self {
rule_id,
pattern,
actions,
}
}
}
impl From<NewPatternedPushRule> for PatternedPushRule {
fn from(new_rule: NewPatternedPushRule) -> Self {
let NewPatternedPushRule {
rule_id,
pattern,
actions,
} = new_rule;
Self {
actions,
default: false,
enabled: true,
rule_id,
pattern,
}
}
}
impl From<PatternedPushRule> for PushRule {
fn from(push_rule: PatternedPushRule) -> Self {
let PatternedPushRule {
actions,
default,
enabled,
rule_id,
pattern,
..
} = push_rule;
Self {
actions,
default,
enabled,
rule_id,
conditions: None,
pattern: Some(pattern),
}
}
}
impl TryFrom<PushRule> for PatternedPushRule {
type Error = MissingPatternError;
fn try_from(push_rule: PushRule) -> Result<Self, Self::Error> {
if let PushRule {
actions,
default,
enabled,
rule_id,
pattern: Some(pattern),
..
} = push_rule
{
Ok(PatternedPushRule {
actions,
default,
enabled,
rule_id,
pattern,
})
} else {
Err(MissingPatternError)
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/action.rs | crates/core/src/push/action.rs | use std::collections::BTreeMap;
use as_variant::as_variant;
use salvo::prelude::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::serde::{JsonValue, RawJsonValue, from_raw_json_value};
/// This represents the different actions that should be taken when a rule is
/// matched, and controls how notifications are delivered to the client.
///
/// See [the spec](https://spec.matrix.org/latest/client-server-api/#actions) for details.
#[derive(ToSchema, Clone, Debug)]
pub enum Action {
/// Causes matching events to generate a notification.
Notify,
/// Sets an entry in the 'tweaks' dictionary sent to the push gateway.
SetTweak(Tweak),
/// An unknown action.
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(CustomAction),
}
impl Action {
/// Whether this action is an `Action::SetTweak(Tweak::Highlight(true))`.
pub fn is_highlight(&self) -> bool {
matches!(self, Action::SetTweak(Tweak::Highlight(true)))
}
/// Whether this action should trigger a notification.
pub fn should_notify(&self) -> bool {
matches!(self, Action::Notify)
}
/// The sound that should be played with this action, if any.
pub fn sound(&self) -> Option<&str> {
as_variant!(self, Action::SetTweak(Tweak::Sound(sound)) => sound)
}
}
/// The `set_tweak` action.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug)]
#[serde(from = "tweak_serde::Tweak", into = "tweak_serde::Tweak")]
pub enum Tweak {
/// A string representing the sound to be played when this notification
/// arrives.
///
/// A value of "default" means to play a default sound. A device may choose
/// to alert the user by some other means if appropriate, eg. vibration.
Sound(String),
/// A boolean representing whether or not this message should be highlighted
/// in the UI.
///
/// This will normally take the form of presenting the message in a
/// different color and/or style. The UI might also be adjusted to draw
/// particular attention to the room in which the event occurred. If a
/// `highlight` tweak is given with no value, its value is defined to be
/// `true`. If no highlight tweak is given at all then the value of
/// `highlight` is defined to be `false`.
Highlight(#[serde(default = "crate::serde::default_true")] bool),
/// A custom tweak
Custom {
/// The name of the custom tweak (`set_tweak` field)
name: String,
/// The value of the custom tweak
#[salvo(schema(value_type = Object, additional_properties = true))]
value: Box<RawJsonValue>,
},
}
impl<'de> Deserialize<'de> for Action {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let custom: CustomAction = from_raw_json_value(&json)?;
match &custom {
CustomAction::String(s) => match s.as_str() {
"notify" => Ok(Action::Notify),
_ => Ok(Action::_Custom(custom)),
},
CustomAction::Object(o) => {
if o.get("set_tweak").is_some() {
Ok(Action::SetTweak(from_raw_json_value(&json)?))
} else {
Ok(Action::_Custom(custom))
}
}
}
}
}
impl Serialize for Action {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Action::Notify => serializer.serialize_unit_variant("Action", 0, "notify"),
Action::SetTweak(kind) => kind.serialize(serializer),
Action::_Custom(custom) => custom.serialize(serializer),
}
}
}
/// An unknown action.
#[doc(hidden)]
#[allow(unknown_lints, unnameable_types)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CustomAction {
/// A string.
String(String),
/// An object.
Object(BTreeMap<String, JsonValue>),
}
mod tweak_serde {
use serde::{Deserialize, Serialize};
use crate::serde::RawJsonValue;
/// Values for the `set_tweak` action.
#[derive(Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub(crate) enum Tweak {
Sound(SoundTweak),
Highlight(HighlightTweak),
Custom {
#[serde(rename = "set_tweak")]
name: String,
value: Box<RawJsonValue>,
},
}
#[derive(Clone, PartialEq, Deserialize, Serialize)]
#[serde(tag = "set_tweak", rename = "sound")]
pub(crate) struct SoundTweak {
value: String,
}
#[derive(Clone, PartialEq, Deserialize, Serialize)]
#[serde(tag = "set_tweak", rename = "highlight")]
pub(crate) struct HighlightTweak {
#[serde(
default = "crate::serde::default_true",
skip_serializing_if = "crate::serde::is_true"
)]
value: bool,
}
impl From<super::Tweak> for Tweak {
fn from(tweak: super::Tweak) -> Self {
use super::Tweak::*;
match tweak {
Sound(value) => Self::Sound(SoundTweak { value }),
Highlight(value) => Self::Highlight(HighlightTweak { value }),
Custom { name, value } => Self::Custom { name, value },
}
}
}
impl From<Tweak> for super::Tweak {
fn from(tweak: Tweak) -> Self {
use Tweak::*;
match tweak {
Sound(SoundTweak { value }) => Self::Sound(value),
Highlight(HighlightTweak { value }) => Self::Highlight(value),
Custom { name, value } => Self::Custom { name, value },
}
}
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::{Action, Tweak};
// #[test]
// fn serialize_string() {
// assert_eq!(to_json_value(&Action::Notify).unwrap(), json!("notify"));
// }
// #[test]
// fn serialize_tweak_sound() {
// assert_eq!(
//
// to_json_value(&Action::SetTweak(Tweak::Sound("default".into()))).unwrap(),
// json!({ "set_tweak": "sound", "value": "default" })
// );
// }
// #[test]
// fn serialize_tweak_highlight() {
// assert_eq!(
//
// to_json_value(&Action::SetTweak(Tweak::Highlight(true))).unwrap(),
// json!({ "set_tweak": "highlight" })
// );
// assert_eq!(
//
// to_json_value(&Action::SetTweak(Tweak::Highlight(false))).unwrap(),
// json!({ "set_tweak": "highlight", "value": false })
// );
// }
// #[test]
// fn deserialize_string() {
// assert_matches!(from_json_value::<Action>(json!("notify")),
// Ok(Action::Notify)); }
// #[test]
// fn deserialize_tweak_sound() {
// let json_data = json!({
// "set_tweak": "sound",
// "value": "default"
// });
// assert_matches!(
// from_json_value::<Action>(json_data),
// Ok(Action::SetTweak(Tweak::Sound(value)))
// );
// assert_eq!(value, "default");
// }
// #[test]
// fn deserialize_tweak_highlight() {
// let json_data = json!({
// "set_tweak": "highlight",
// "value": true
// });
// assert_matches!(
// from_json_value::<Action>(json_data),
// Ok(Action::SetTweak(Tweak::Highlight(true)))
// );
// }
// #[test]
// fn deserialize_tweak_highlight_with_default_value() {
// assert_matches!(
// from_json_value::<Action>(json!({ "set_tweak": "highlight" })),
// Ok(Action::SetTweak(Tweak::Highlight(true)))
// );
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/iter.rs | crates/core/src/push/iter.rs | use indexmap::set::{IntoIter as IndexSetIntoIter, Iter as IndexSetIter};
use super::{
Action, ConditionalPushRule, FlattenedJson, PatternedPushRule, PushConditionRoomCtx, PushRule,
Ruleset, SimplePushRule, condition,
};
use crate::{OwnedRoomId, OwnedUserId};
/// The kinds of push rules that are available.
#[derive(Clone, Debug)]
pub enum AnyPushRule {
/// Rules that override all other kinds.
Override(ConditionalPushRule),
/// Content-specific rules.
Content(PatternedPushRule),
/// Post-content specific rules.
#[cfg(feature = "unstable-msc4306")]
PostContent(ConditionalPushRule),
/// Room-specific rules.
Room(SimplePushRule<OwnedRoomId>),
/// Sender-specific rules.
Sender(SimplePushRule<OwnedUserId>),
/// Lowest priority rules.
Underride(ConditionalPushRule),
}
impl AnyPushRule {
/// Convert `AnyPushRule` to `AnyPushRuleRef`.
pub fn as_ref(&self) -> AnyPushRuleRef<'_> {
match self {
Self::Override(o) => AnyPushRuleRef::Override(o),
Self::Content(c) => AnyPushRuleRef::Content(c),
#[cfg(feature = "unstable-msc4306")]
Self::PostContent(c) => AnyPushRuleRef::PostContent(c),
Self::Room(r) => AnyPushRuleRef::Room(r),
Self::Sender(s) => AnyPushRuleRef::Sender(s),
Self::Underride(u) => AnyPushRuleRef::Underride(u),
}
}
/// Get the `enabled` flag of the push rule.
pub fn enabled(&self) -> bool {
self.as_ref().enabled()
}
/// Get the `actions` of the push rule.
pub fn actions(&self) -> &[Action] {
self.as_ref().actions()
}
/// Whether an event that matches the push rule should be highlighted.
pub fn triggers_highlight(&self) -> bool {
self.as_ref().triggers_highlight()
}
/// Whether an event that matches the push rule should trigger a
/// notification.
pub fn triggers_notification(&self) -> bool {
self.as_ref().triggers_notification()
}
/// The sound that should be played when an event matches the push rule, if
/// any.
pub fn triggers_sound(&self) -> Option<&str> {
self.as_ref().triggers_sound()
}
/// Get the `rule_id` of the push rule.
pub fn rule_id(&self) -> &str {
self.as_ref().rule_id()
}
/// Whether the push rule is a server-default rule.
pub fn is_server_default(&self) -> bool {
self.as_ref().is_server_default()
}
/// Check if the push rule applies to the event.
///
/// # Arguments
///
/// * `event` - The flattened JSON representation of a room message event.
/// * `context` - The context of the room at the time of the event.
pub async fn applies(&self, event: &FlattenedJson, context: &PushConditionRoomCtx) -> bool {
self.as_ref().applies(event, context).await
}
}
impl From<AnyPushRule> for PushRule {
fn from(push_rule: AnyPushRule) -> Self {
#[allow(unreachable_patterns)]
match push_rule {
AnyPushRule::Override(r) => r.into(),
AnyPushRule::Content(r) => r.into(),
AnyPushRule::Room(r) => r.into(),
AnyPushRule::Sender(r) => r.into(),
AnyPushRule::Underride(r) => r.into(),
_ => unreachable!(),
}
}
}
impl<'a> From<AnyPushRuleRef<'a>> for PushRule {
fn from(push_rule: AnyPushRuleRef<'a>) -> Self {
push_rule.to_owned().into()
}
}
/// Iterator type for `Ruleset`
#[derive(Debug)]
pub struct RulesetIntoIter {
content: IndexSetIntoIter<PatternedPushRule>,
#[cfg(feature = "unstable-msc4306")]
postcontent: IndexSetIntoIter<ConditionalPushRule>,
override_: IndexSetIntoIter<ConditionalPushRule>,
room: IndexSetIntoIter<SimplePushRule<OwnedRoomId>>,
sender: IndexSetIntoIter<SimplePushRule<OwnedUserId>>,
underride: IndexSetIntoIter<ConditionalPushRule>,
}
impl Iterator for RulesetIntoIter {
type Item = AnyPushRule;
fn next(&mut self) -> Option<Self::Item> {
let it = self
.override_
.next()
.map(AnyPushRule::Override)
.or_else(|| self.content.next().map(AnyPushRule::Content));
#[cfg(feature = "unstable-msc4306")]
let it = it.or_else(|| self.postcontent.next().map(AnyPushRule::PostContent));
it.or_else(|| self.room.next().map(AnyPushRule::Room))
.or_else(|| self.sender.next().map(AnyPushRule::Sender))
.or_else(|| self.underride.next().map(AnyPushRule::Underride))
}
}
impl IntoIterator for Ruleset {
type Item = AnyPushRule;
type IntoIter = RulesetIntoIter;
fn into_iter(self) -> Self::IntoIter {
RulesetIntoIter {
content: self.content.into_iter(),
#[cfg(feature = "unstable-msc4306")]
postcontent: self.postcontent.into_iter(),
override_: self.override_.into_iter(),
room: self.room.into_iter(),
sender: self.sender.into_iter(),
underride: self.underride.into_iter(),
}
}
}
/// Reference to any kind of push rule.
#[derive(Clone, Copy, Debug)]
pub enum AnyPushRuleRef<'a> {
/// Rules that override all other kinds.
Override(&'a ConditionalPushRule),
/// Content-specific rules.
Content(&'a PatternedPushRule),
/// Post-content specific rules.
#[cfg(feature = "unstable-msc4306")]
PostContent(&'a ConditionalPushRule),
/// Room-specific rules.
Room(&'a SimplePushRule<OwnedRoomId>),
/// Sender-specific rules.
Sender(&'a SimplePushRule<OwnedUserId>),
/// Lowest priority rules.
Underride(&'a ConditionalPushRule),
}
impl<'a> AnyPushRuleRef<'a> {
/// Convert `AnyPushRuleRef` to `AnyPushRule` by cloning the inner value.
pub fn to_owned(self) -> AnyPushRule {
match self {
Self::Override(o) => AnyPushRule::Override(o.clone()),
Self::Content(c) => AnyPushRule::Content(c.clone()),
#[cfg(feature = "unstable-msc4306")]
Self::PostContent(c) => AnyPushRule::PostContent(c.clone()),
Self::Room(r) => AnyPushRule::Room(r.clone()),
Self::Sender(s) => AnyPushRule::Sender(s.clone()),
Self::Underride(u) => AnyPushRule::Underride(u.clone()),
}
}
/// Get the `enabled` flag of the push rule.
pub fn enabled(self) -> bool {
match self {
Self::Override(rule) => rule.enabled,
Self::Underride(rule) => rule.enabled,
Self::Content(rule) => rule.enabled,
#[cfg(feature = "unstable-msc4306")]
Self::PostContent(rule) => rule.enabled,
Self::Room(rule) => rule.enabled,
Self::Sender(rule) => rule.enabled,
}
}
/// Get the `actions` of the push rule.
pub fn actions(self) -> &'a [Action] {
match self {
Self::Override(rule) => &rule.actions,
Self::Underride(rule) => &rule.actions,
Self::Content(rule) => &rule.actions,
#[cfg(feature = "unstable-msc4306")]
Self::PostContent(rule) => &rule.actions,
Self::Room(rule) => &rule.actions,
Self::Sender(rule) => &rule.actions,
}
}
/// Whether an event that matches the push rule should be highlighted.
pub fn triggers_highlight(self) -> bool {
self.actions().iter().any(|a| a.is_highlight())
}
/// Whether an event that matches the push rule should trigger a
/// notification.
pub fn triggers_notification(self) -> bool {
self.actions().iter().any(|a| a.should_notify())
}
/// The sound that should be played when an event matches the push rule, if
/// any.
pub fn triggers_sound(self) -> Option<&'a str> {
self.actions().iter().find_map(|a| a.sound())
}
/// Get the `rule_id` of the push rule.
pub fn rule_id(self) -> &'a str {
match self {
Self::Override(rule) => &rule.rule_id,
Self::Underride(rule) => &rule.rule_id,
Self::Content(rule) => &rule.rule_id,
#[cfg(feature = "unstable-msc4306")]
Self::PostContent(rule) => &rule.rule_id,
Self::Room(rule) => rule.rule_id.as_ref(),
Self::Sender(rule) => rule.rule_id.as_ref(),
}
}
/// Whether the push rule is a server-default rule.
pub fn is_server_default(self) -> bool {
match self {
Self::Override(rule) => rule.default,
Self::Underride(rule) => rule.default,
Self::Content(rule) => rule.default,
#[cfg(feature = "unstable-msc4306")]
Self::PostContent(rule) => rule.default,
Self::Room(rule) => rule.default,
Self::Sender(rule) => rule.default,
}
}
/// Check if the push rule applies to the event.
///
/// # Arguments
///
/// * `event` - The flattened JSON representation of a room message event.
/// * `context` - The context of the room at the time of the event.
pub async fn applies(self, event: &FlattenedJson, context: &PushConditionRoomCtx) -> bool {
if event
.get_str("sender")
.is_some_and(|sender| sender == context.user_id)
{
return false;
}
match self {
Self::Override(rule) => rule.applies(event, context).await,
Self::Underride(rule) => rule.applies(event, context).await,
Self::Content(rule) => rule.applies_to("content.body", event, context),
#[cfg(feature = "unstable-msc4306")]
Self::PostContent(rule) => rule.applies(event, context).await,
Self::Room(rule) => {
rule.enabled
&& condition::check_event_match(
event,
"room_id",
rule.rule_id.as_ref(),
context,
)
}
Self::Sender(rule) => {
rule.enabled
&& condition::check_event_match(event, "sender", rule.rule_id.as_ref(), context)
}
}
}
}
/// Iterator type for `Ruleset`
#[derive(Debug)]
pub struct RulesetIter<'a> {
content: IndexSetIter<'a, PatternedPushRule>,
#[cfg(feature = "unstable-msc4306")]
postcontent: IndexSetIter<'a, ConditionalPushRule>,
override_: IndexSetIter<'a, ConditionalPushRule>,
room: IndexSetIter<'a, SimplePushRule<OwnedRoomId>>,
sender: IndexSetIter<'a, SimplePushRule<OwnedUserId>>,
underride: IndexSetIter<'a, ConditionalPushRule>,
}
impl<'a> Iterator for RulesetIter<'a> {
type Item = AnyPushRuleRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
let it = self
.override_
.next()
.map(AnyPushRuleRef::Override)
.or_else(|| self.content.next().map(AnyPushRuleRef::Content));
#[cfg(feature = "unstable-msc4306")]
let it = it.or_else(|| self.postcontent.next().map(AnyPushRuleRef::PostContent));
it.or_else(|| self.room.next().map(AnyPushRuleRef::Room))
.or_else(|| self.sender.next().map(AnyPushRuleRef::Sender))
.or_else(|| self.underride.next().map(AnyPushRuleRef::Underride))
}
}
impl<'a> IntoIterator for &'a Ruleset {
type Item = AnyPushRuleRef<'a>;
type IntoIter = RulesetIter<'a>;
fn into_iter(self) -> Self::IntoIter {
RulesetIter {
content: self.content.iter(),
#[cfg(feature = "unstable-msc4306")]
postcontent: self.postcontent.iter(),
override_: self.override_.iter(),
room: self.room.iter(),
sender: self.sender.iter(),
underride: self.underride.iter(),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/pusher.rs | crates/core/src/push/pusher.rs | //! Common types for the [push notifications module][push].
//!
//! [push]: https://spec.matrix.org/latest/client-server-api/#push-notifications
//!
//! ## Understanding the types of this module
//!
//! Push rules are grouped in `RuleSet`s, and are grouped in five kinds (for
//! more details about the different kind of rules, see the `Ruleset`
//! documentation, or the specification). These five kinds are, by order of
//! priority:
//!
//! - override rules
//! - content rules
//! - room rules
//! - sender rules
//! - underride rules
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize, de, ser::SerializeStruct};
use serde_json::value::from_value as from_json_value;
use crate::{
push::PushFormat,
serde::{JsonObject, JsonValue, RawJsonValue, from_raw_json_value},
};
/// Information for a pusher using the Push Gateway API.
#[derive(ToSchema, Serialize, Deserialize, Clone, Debug)]
pub struct HttpPusherData {
/// The URL to use to send notifications to.
///
/// Required if the pusher's kind is http.
pub url: String,
/// The format to use when sending notifications to the Push Gateway.
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<PushFormat>,
/// iOS (+ macOS?) specific default payload that will be sent to apple push
/// notification service.
///
/// For more information, see [Sygnal docs][sygnal].
///
/// [sygnal]: https://github.com/matrix-org/sygnal/blob/main/docs/applications.md#ios-applications-beware
// Not specified, issue: https://github.com/matrix-org/matrix-spec/issues/921
#[serde(default, skip_serializing_if = "JsonValue::is_null")]
#[salvo(schema(value_type = Object, additional_properties = true))]
pub default_payload: JsonValue,
}
impl HttpPusherData {
/// Creates a new `HttpPusherData` with the given URL.
pub fn new(url: String) -> Self {
Self {
url,
format: None,
default_payload: JsonValue::default(),
}
}
}
/// Which kind a pusher is, and the information for that kind.
#[derive(ToSchema, Clone, Debug)]
#[non_exhaustive]
pub enum PusherKind {
/// A pusher that sends HTTP pokes.
Http(HttpPusherData),
/// A pusher that emails the user with unread notifications.
Email(EmailPusherData),
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(CustomPusherData),
}
impl PusherKind {
pub fn try_new(kind: &str, data: JsonValue) -> Result<Self, serde_json::Error> {
match kind {
"http" => from_json_value(data).map(Self::Http),
"email" => Ok(Self::Email(EmailPusherData)),
_ => from_json_value(data).map(Self::_Custom),
}
}
pub fn name(&self) -> &str {
match self {
PusherKind::Http(_) => "http",
PusherKind::Email(_) => "email",
PusherKind::_Custom(data) => data.kind.as_str(),
}
}
pub fn json_data(&self) -> Result<JsonValue, serde_json::Error> {
match self {
PusherKind::Http(data) => serde_json::to_value(data),
PusherKind::Email(data) => serde_json::to_value(data),
PusherKind::_Custom(data) => serde_json::to_value(data),
}
}
}
impl Serialize for PusherKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut st = serializer.serialize_struct("PusherAction", 3)?;
match self {
PusherKind::Http(data) => {
st.serialize_field("kind", &"http")?;
st.serialize_field("data", data)?;
}
PusherKind::Email(_) => {
st.serialize_field("kind", &"email")?;
st.serialize_field("data", &JsonObject::new())?;
}
PusherKind::_Custom(custom) => {
st.serialize_field("kind", &custom.kind)?;
st.serialize_field("data", &custom.data)?;
}
}
st.end()
}
}
#[derive(Debug, Deserialize)]
struct PusherKindDeHelper {
kind: String,
data: Box<RawJsonValue>,
}
impl<'de> Deserialize<'de> for PusherKind {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let PusherKindDeHelper { kind, data } = from_raw_json_value(&json)?;
match kind.as_ref() {
"http" => from_raw_json_value(&data).map(Self::Http),
"email" => Ok(Self::Email(EmailPusherData)),
_ => from_raw_json_value(&json).map(Self::_Custom),
}
}
}
/// Defines a pusher.
///
/// To create an instance of this type.
#[derive(ToSchema, Serialize, Clone, Debug)]
pub struct Pusher {
/// Identifiers for this pusher.
#[serde(flatten)]
pub ids: PusherIds,
/// The kind of the pusher and the information for that kind.
#[serde(flatten)]
pub kind: PusherKind,
/// A string that will allow the user to identify what application owns this
/// pusher.
pub app_display_name: String,
/// A string that will allow the user to identify what device owns this
/// pusher.
pub device_display_name: String,
/// The preferred language for receiving notifications (e.g. 'en' or
/// 'en-US')
pub lang: String,
/// Determines which set of device specific rules this pusher executes.
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_tag: Option<String>,
}
#[derive(Debug, Deserialize)]
struct PusherDeHelper {
#[serde(flatten)]
ids: PusherIds,
app_display_name: String,
device_display_name: String,
profile_tag: Option<String>,
lang: String,
}
impl<'de> Deserialize<'de> for Pusher {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let PusherDeHelper {
ids,
app_display_name,
device_display_name,
profile_tag,
lang,
} = from_raw_json_value(&json)?;
let kind = from_raw_json_value(&json)?;
Ok(Self {
ids,
kind,
app_display_name,
device_display_name,
profile_tag,
lang,
})
}
}
/// Strings to uniquely identify a `Pusher`.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
/// A unique identifier for the pusher.
pub struct PusherIds {
///
/// The maximum allowed length is 512 bytes.
pub pushkey: String,
/// A reverse-DNS style identifier for the application.
///
/// The maximum allowed length is 64 bytes.
pub app_id: String,
}
impl PusherIds {
/// Creates a new `PusherIds` with the given pushkey and application ID.
pub fn new(pushkey: String, app_id: String) -> Self {
Self { pushkey, app_id }
}
}
/// Information for an email pusher.
#[derive(ToSchema, Deserialize, Serialize, Clone, Debug, Default)]
pub struct EmailPusherData;
impl EmailPusherData {
/// Creates a new empty `EmailPusherData`.
pub fn new() -> Self {
Default::default()
}
}
#[doc(hidden)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct CustomPusherData {
kind: String,
data: JsonObject,
}
/// Information for the pusher implementation itself.
///
/// This is the data dictionary passed in at pusher creation minus the `url`
/// key.
///
/// It can be constructed from [`crate::push::HttpPusherData`] with `::from()` /
/// `.into()`.
#[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)]
pub struct PusherData {
/// The format to use when sending notifications to the Push Gateway.
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<PushFormat>,
/// iOS (+ macOS?) specific default payload that will be sent to apple push
/// notification service.
///
/// For more information, see [Sygnal docs][sygnal].
///
/// [sygnal]: https://github.com/matrix-org/sygnal/blob/main/docs/applications.md#ios-applications-beware
// Not specified, issue: https://github.com/matrix-org/matrix-spec/issues/921
#[serde(default, skip_serializing_if = "JsonValue::is_null")]
pub default_payload: JsonValue,
}
impl PusherData {
/// Creates an empty `PusherData`.
pub fn new() -> Self {
Default::default()
}
/// Returns `true` if all fields are `None`.
pub fn is_empty(&self) -> bool {
#[cfg(not(feature = "unstable-unspecified"))]
{
self.format.is_none()
}
#[cfg(feature = "unstable-unspecified")]
{
self.format.is_none() && self.default_payload.is_null()
}
}
}
impl From<crate::push::HttpPusherData> for PusherData {
fn from(data: crate::push::HttpPusherData) -> Self {
let crate::push::HttpPusherData {
format,
default_payload,
..
} = data;
Self {
format,
default_payload,
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/condition/push_condition_serde.rs | crates/core/src/push/condition/push_condition_serde.rs | use serde::{Deserialize, Serialize, Serializer, de};
use super::{PushCondition, RoomMemberCountIs, RoomVersionFeature, ScalarJsonValue};
use crate::serde::{RawJsonValue, from_raw_json_value};
impl Serialize for PushCondition {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
PushCondition::_Custom(custom) => custom.serialize(serializer),
_ => PushConditionSerDeHelper::from(self.clone()).serialize(serializer),
}
}
}
impl<'de> Deserialize<'de> for PushCondition {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let ExtractKind { kind } = from_raw_json_value(&json)?;
match kind.as_ref() {
"event_match"
| "contains_display_name"
| "room_member_count"
| "sender_notification_permission"
| "event_property_is"
| "event_property_contains" => {
let helper: PushConditionSerDeHelper = from_raw_json_value(&json)?;
Ok(helper.into())
}
"org.matrix.msc3931.room_version_supports" => {
let helper: PushConditionSerDeHelper = from_raw_json_value(&json)?;
Ok(helper.into())
}
#[cfg(feature = "unstable-msc4306")]
"io.element.msc4306.thread_subscription" => {
let helper: PushConditionSerDeHelper = from_raw_json_value(&json)?;
Ok(helper.into())
}
_ => from_raw_json_value(&json).map(Self::_Custom),
}
}
}
#[derive(Deserialize)]
struct ExtractKind {
kind: String,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum PushConditionSerDeHelper {
/// A glob pattern match on a field of the event.
EventMatch {
/// The dot-separated field of the event to match.
key: String,
/// The glob-style pattern to match against.
///
/// Patterns with no special glob characters should be treated as having
/// asterisks prepended and appended when testing the condition.
pattern: String,
},
/// Matches unencrypted messages where `content.body` contains the owner's
/// display name in that room.
ContainsDisplayName,
/// Matches the current number of members in the room.
RoomMemberCount {
/// The condition on the current number of members in the room.
is: RoomMemberCountIs,
},
/// Takes into account the current power levels in the room, ensuring the
/// sender of the event has high enough power to trigger the
/// notification.
SenderNotificationPermission {
/// The field in the power level event the user needs a minimum power
/// level for.
///
/// Fields must be specified under the `notifications` property in the
/// power level event's `content`.
key: String,
},
/// Apply the rule only to rooms that support a given feature.
#[cfg(feature = "unstable-msc3931")]
#[serde(rename = "org.matrix.msc3931.room_version_supports")]
RoomVersionSupports {
/// The feature the room must support for the push rule to apply.
feature: RoomVersionFeature,
},
EventPropertyIs {
key: String,
value: ScalarJsonValue,
},
EventPropertyContains {
key: String,
value: ScalarJsonValue,
},
/// Matches a thread event based on the user's thread subscription status, as defined by
/// [MSC4306].
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
#[serde(rename = "io.element.msc4306.thread_subscription")]
ThreadSubscription {
/// Whether the user must be subscribed to the thread for the condition to match.
subscribed: bool,
},
}
impl From<PushConditionSerDeHelper> for PushCondition {
fn from(value: PushConditionSerDeHelper) -> Self {
match value {
PushConditionSerDeHelper::EventMatch { key, pattern } => {
Self::EventMatch { key, pattern }
}
#[allow(deprecated)]
PushConditionSerDeHelper::ContainsDisplayName => Self::ContainsDisplayName,
PushConditionSerDeHelper::RoomMemberCount { is } => Self::RoomMemberCount { is },
PushConditionSerDeHelper::SenderNotificationPermission { key } => {
Self::SenderNotificationPermission { key }
}
#[cfg(feature = "unstable-msc3931")]
PushConditionSerDeHelper::RoomVersionSupports { feature } => {
Self::RoomVersionSupports { feature }
}
PushConditionSerDeHelper::EventPropertyIs { key, value } => {
Self::EventPropertyIs { key, value }
}
PushConditionSerDeHelper::EventPropertyContains { key, value } => {
Self::EventPropertyContains { key, value }
}
#[cfg(feature = "unstable-msc4306")]
PushConditionSerDeHelper::ThreadSubscription { subscribed } => {
Self::ThreadSubscription { subscribed }
}
}
}
}
impl From<PushCondition> for PushConditionSerDeHelper {
fn from(value: PushCondition) -> Self {
match value {
PushCondition::EventMatch { key, pattern } => Self::EventMatch { key, pattern },
#[allow(deprecated)]
PushCondition::ContainsDisplayName => Self::ContainsDisplayName,
PushCondition::RoomMemberCount { is } => Self::RoomMemberCount { is },
PushCondition::SenderNotificationPermission { key } => {
Self::SenderNotificationPermission { key }
}
#[cfg(feature = "unstable-msc3931")]
PushCondition::RoomVersionSupports { feature } => Self::RoomVersionSupports { feature },
PushCondition::EventPropertyIs { key, value } => Self::EventPropertyIs { key, value },
PushCondition::EventPropertyContains { key, value } => {
Self::EventPropertyContains { key, value }
}
#[cfg(feature = "unstable-msc4306")]
PushCondition::ThreadSubscription { subscribed } => {
Self::ThreadSubscription { subscribed }
}
PushCondition::_Custom(_) => unimplemented!(),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/condition/flattened_json.rs | crates/core/src/push/condition/flattened_json.rs | use std::collections::BTreeMap;
use as_variant::as_variant;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{to_value as to_json_value, value::Value as JsonValue};
use thiserror::Error;
use tracing::{instrument, warn};
use crate::serde::RawJson;
/// The flattened representation of a JSON object.
#[derive(Clone, Debug)]
pub struct FlattenedJson {
/// The internal map containing the flattened JSON as a pair path, value.
map: BTreeMap<String, FlattenedJsonValue>,
}
impl FlattenedJson {
/// Create a `FlattenedJson` from `Raw`.
pub fn from_raw<T>(raw: &RawJson<T>) -> Self {
let mut s = Self {
map: BTreeMap::new(),
};
s.flatten_value(to_json_value(raw).unwrap(), "".into());
s
}
/// Flatten and insert the `value` at `path`.
#[instrument(skip(self, value))]
fn flatten_value(&mut self, value: JsonValue, path: String) {
match value {
JsonValue::Object(fields) => {
if fields.is_empty() {
if self
.map
.insert(path.clone(), FlattenedJsonValue::EmptyObject)
.is_some()
{
warn!("duplicate path in flattened json: {path}");
}
} else {
for (key, value) in fields {
let key = escape_key(&key);
let path = if path.is_empty() {
key
} else {
format!("{path}.{key}")
};
self.flatten_value(value, path);
}
}
}
value => {
if let Some(v) = FlattenedJsonValue::from_json_value(value)
&& self.map.insert(path.clone(), v).is_some()
{
warn!("duplicate path in flattened json: {path}");
}
}
}
}
/// Get the value associated with the given `path`.
pub fn get(&self, path: &str) -> Option<&FlattenedJsonValue> {
self.map.get(path)
}
/// Get the value associated with the given `path`, if it is a string.
pub fn get_str(&self, path: &str) -> Option<&str> {
self.map.get(path).and_then(|v| v.as_str())
}
/// Whether this flattened JSON contains an `m.mentions` property under the
/// `content` property.
pub fn contains_mentions(&self) -> bool {
self.map
.keys()
.any(|s| s == r"content.m\.mentions" || s.starts_with(r"content.m\.mentions."))
}
}
/// Escape a key for path matching.
///
/// This escapes the dots (`.`) and backslashes (`\`) in the key with a
/// backslash.
fn escape_key(key: &str) -> String {
key.replace('\\', r"\\").replace('.', r"\.")
}
/// The set of possible errors when converting to a JSON subset.
#[derive(Debug, Error)]
#[allow(clippy::exhaustive_enums)]
enum IntoJsonSubsetError {
/// The numeric value failed conversion to int.
#[error("number found is not a valid `int`")]
IntConvert,
/// The JSON type is not accepted in this subset.
#[error("JSON type is not accepted in this subset")]
NotInSubset,
}
/// Scalar (non-compound) JSON values.
#[derive(Debug, Clone, Default, Eq, PartialEq)]
#[allow(clippy::exhaustive_enums)]
pub enum ScalarJsonValue {
/// Represents a `null` value.
#[default]
Null,
/// Represents a boolean.
Bool(bool),
/// Represents an integer.
Integer(i64),
/// Represents a string.
String(String),
}
impl ScalarJsonValue {
fn try_from_json_value(val: JsonValue) -> Result<Self, IntoJsonSubsetError> {
Ok(match val {
JsonValue::Bool(b) => Self::Bool(b),
JsonValue::Number(num) => {
Self::Integer(num.as_i64().ok_or(IntoJsonSubsetError::IntConvert)?)
}
JsonValue::String(string) => Self::String(string),
JsonValue::Null => Self::Null,
_ => Err(IntoJsonSubsetError::NotInSubset)?,
})
}
/// If the `ScalarJsonValue` is a `Bool`, return the inner value.
pub fn as_bool(&self) -> Option<bool> {
as_variant!(self, Self::Bool).copied()
}
/// If the `ScalarJsonValue` is an `Integer`, return the inner value.
pub fn as_integer(&self) -> Option<i64> {
as_variant!(self, Self::Integer).copied()
}
/// If the `ScalarJsonValue` is a `String`, return a reference to the inner
/// value.
pub fn as_str(&self) -> Option<&str> {
as_variant!(self, Self::String)
}
}
impl Serialize for ScalarJsonValue {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Null => serializer.serialize_unit(),
Self::Bool(b) => serializer.serialize_bool(*b),
Self::Integer(n) => n.serialize(serializer),
Self::String(s) => serializer.serialize_str(s),
}
}
}
impl<'de> Deserialize<'de> for ScalarJsonValue {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let val = JsonValue::deserialize(deserializer)?;
ScalarJsonValue::try_from_json_value(val).map_err(serde::de::Error::custom)
}
}
impl From<bool> for ScalarJsonValue {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<i64> for ScalarJsonValue {
fn from(value: i64) -> Self {
Self::Integer(value)
}
}
impl From<String> for ScalarJsonValue {
fn from(value: String) -> Self {
Self::String(value)
}
}
impl From<&str> for ScalarJsonValue {
fn from(value: &str) -> Self {
value.to_owned().into()
}
}
impl PartialEq<FlattenedJsonValue> for ScalarJsonValue {
fn eq(&self, other: &FlattenedJsonValue) -> bool {
match self {
Self::Null => *other == FlattenedJsonValue::Null,
Self::Bool(b) => other.as_bool() == Some(*b),
Self::Integer(i) => other.as_integer() == Some(*i),
Self::String(s) => other.as_str() == Some(s),
}
}
}
/// Possible JSON values after an object is flattened.
#[derive(Debug, Clone, Default, Eq, PartialEq)]
#[allow(clippy::exhaustive_enums)]
pub enum FlattenedJsonValue {
/// Represents a `null` value.
#[default]
Null,
/// Represents a boolean.
Bool(bool),
/// Represents an integer.
Integer(i64),
/// Represents a string.
String(String),
/// Represents an array.
Array(Vec<ScalarJsonValue>),
/// Represents an empty object.
EmptyObject,
}
impl FlattenedJsonValue {
fn from_json_value(val: JsonValue) -> Option<Self> {
Some(match val {
JsonValue::Bool(b) => Self::Bool(b),
JsonValue::Number(num) => Self::Integer(num.as_i64()?),
JsonValue::String(string) => Self::String(string),
JsonValue::Null => Self::Null,
JsonValue::Array(vec) => Self::Array(
// Drop values we don't need instead of throwing an error.
vec.into_iter()
.filter_map(|v| ScalarJsonValue::try_from_json_value(v).ok())
.collect::<Vec<_>>(),
),
_ => None?,
})
}
/// If the `FlattenedJsonValue` is a `Bool`, return the inner value.
pub fn as_bool(&self) -> Option<bool> {
as_variant!(self, Self::Bool).copied()
}
/// If the `FlattenedJsonValue` is an `Integer`, return the inner value.
pub fn as_integer(&self) -> Option<i64> {
as_variant!(self, Self::Integer).copied()
}
/// If the `FlattenedJsonValue` is a `String`, return a reference to the
/// inner value.
pub fn as_str(&self) -> Option<&str> {
as_variant!(self, Self::String)
}
/// If the `FlattenedJsonValue` is an `Array`, return a reference to the
/// inner value.
pub fn as_array(&self) -> Option<&[ScalarJsonValue]> {
as_variant!(self, Self::Array)
}
}
impl From<bool> for FlattenedJsonValue {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<i64> for FlattenedJsonValue {
fn from(value: i64) -> Self {
Self::Integer(value)
}
}
impl From<String> for FlattenedJsonValue {
fn from(value: String) -> Self {
Self::String(value)
}
}
impl From<&str> for FlattenedJsonValue {
fn from(value: &str) -> Self {
value.to_owned().into()
}
}
impl From<Vec<ScalarJsonValue>> for FlattenedJsonValue {
fn from(value: Vec<ScalarJsonValue>) -> Self {
Self::Array(value)
}
}
impl PartialEq<ScalarJsonValue> for FlattenedJsonValue {
fn eq(&self, other: &ScalarJsonValue) -> bool {
match self {
Self::Null => *other == ScalarJsonValue::Null,
Self::Bool(b) => other.as_bool() == Some(*b),
Self::Integer(i) => other.as_integer() == Some(*i),
Self::String(s) => other.as_str() == Some(s),
Self::Array(_) | Self::EmptyObject => false,
}
}
}
#[cfg(test)]
mod tests {
use maplit::btreemap;
use serde_json::Value as JsonValue;
use super::{FlattenedJson, FlattenedJsonValue};
use crate::serde::RawJson;
#[test]
fn flattened_json_values() {
let raw = serde_json::from_str::<RawJson<JsonValue>>(
r#"{
"string": "Hello World",
"number": 10,
"array": [1, 2],
"boolean": true,
"null": null,
"empty_object": {}
}"#,
)
.unwrap();
let flattened = FlattenedJson::from_raw(&raw);
assert_eq!(
flattened.map,
btreemap! {
"string".into() => "Hello World".into(),
"number".into() => 10.into(),
"array".into() => vec![1.into(), 2.into()].into(),
"boolean".into() => true.into(),
"null".into() => FlattenedJsonValue::Null,
"empty_object".into() => FlattenedJsonValue::EmptyObject,
}
);
}
#[test]
fn flattened_json_nested() {
let raw = serde_json::from_str::<RawJson<JsonValue>>(
r#"{
"desc": "Level 0",
"desc.bis": "Level 0 bis",
"up": {
"desc": 1,
"desc.bis": null,
"up": {
"desc": ["Level 2a", "Level 2b"],
"desc\\bis": true
}
}
}"#,
)
.unwrap();
let flattened = FlattenedJson::from_raw(&raw);
assert_eq!(
flattened.map,
btreemap! {
"desc".into() => "Level 0".into(),
r"desc\.bis".into() => "Level 0 bis".into(),
"up.desc".into() => 1.into(),
r"up.desc\.bis".into() => FlattenedJsonValue::Null,
"up.up.desc".into() => vec!["Level 2a".into(), "Level 2b".into()].into(),
r"up.up.desc\\bis".into() => true.into(),
},
);
}
#[test]
fn contains_mentions() {
let raw = serde_json::from_str::<RawJson<JsonValue>>(
r#"{
"m.mentions": {},
"content": {
"body": "Text"
}
}"#,
)
.unwrap();
let flattened = FlattenedJson::from_raw(&raw);
assert!(!flattened.contains_mentions());
let raw = serde_json::from_str::<RawJson<JsonValue>>(
r#"{
"content": {
"body": "Text",
"m.mentions": {}
}
}"#,
)
.unwrap();
let flattened = FlattenedJson::from_raw(&raw);
assert!(flattened.contains_mentions());
let raw = serde_json::from_str::<RawJson<JsonValue>>(
r#"{
"content": {
"body": "Text",
"m.mentions": {
"room": true
}
}
}"#,
)
.unwrap();
let flattened = FlattenedJson::from_raw(&raw);
assert!(flattened.contains_mentions());
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/push/condition/room_member_count_is.rs | crates/core/src/push/condition/room_member_count_is.rs | use std::{
fmt,
ops::{Bound, RangeBounds, RangeFrom, RangeTo, RangeToInclusive},
str::FromStr,
};
use salvo::oapi::ToSchema;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// One of `==`, `<`, `>`, `>=` or `<=`.
///
/// Used by `RoomMemberCountIs`. Defaults to `==`.
#[derive(ToSchema, Copy, Clone, Debug, Default, Eq, PartialEq)]
#[allow(clippy::exhaustive_enums)]
pub enum ComparisonOperator {
/// Equals
#[default]
Eq,
/// Less than
Lt,
/// Greater than
Gt,
/// Greater or equal
Ge,
/// Less or equal
Le,
}
/// A decimal integer optionally prefixed by one of `==`, `<`, `>`, `>=` or
/// `<=`.
///
/// A prefix of `<` matches rooms where the member count is strictly less than
/// the given number and so forth. If no prefix is present, this parameter
/// defaults to `==`.
///
/// Can be constructed from a number or a range:
/// ```
/// use palpo_core::push::RoomMemberCountIs;
///
/// // equivalent to `is: "3"` or `is: "==3"`
/// let exact = RoomMemberCountIs::from(3);
///
/// // equivalent to `is: ">=3"`
/// let greater_or_equal = RoomMemberCountIs::from(3..);
///
/// // equivalent to `is: "<3"`
/// let less = RoomMemberCountIs::from(..3);
///
/// // equivalent to `is: "<=3"`
/// let less_or_equal = RoomMemberCountIs::from(..=3);
///
/// // An exclusive range can be constructed with `RoomMemberCountIs::gt`:
/// // (equivalent to `is: ">3"`)
/// let greater = RoomMemberCountIs::gt(3);
/// ```
#[derive(ToSchema, Copy, Clone, Debug, Eq, PartialEq)]
#[allow(clippy::exhaustive_structs)]
pub struct RoomMemberCountIs {
/// One of `==`, `<`, `>`, `>=`, `<=`, or no prefix.
pub prefix: ComparisonOperator,
/// The number of people in the room.
pub count: u64,
}
impl RoomMemberCountIs {
/// Creates an instance of `RoomMemberCount` equivalent to `<X`,
/// where X is the specified member count.
pub fn gt(count: u64) -> Self {
RoomMemberCountIs {
prefix: ComparisonOperator::Gt,
count,
}
}
}
impl From<u64> for RoomMemberCountIs {
fn from(x: u64) -> Self {
RoomMemberCountIs {
prefix: ComparisonOperator::Eq,
count: x,
}
}
}
impl From<RangeFrom<u64>> for RoomMemberCountIs {
fn from(x: RangeFrom<u64>) -> Self {
RoomMemberCountIs {
prefix: ComparisonOperator::Ge,
count: x.start,
}
}
}
impl From<RangeTo<u64>> for RoomMemberCountIs {
fn from(x: RangeTo<u64>) -> Self {
RoomMemberCountIs {
prefix: ComparisonOperator::Lt,
count: x.end,
}
}
}
impl From<RangeToInclusive<u64>> for RoomMemberCountIs {
fn from(x: RangeToInclusive<u64>) -> Self {
RoomMemberCountIs {
prefix: ComparisonOperator::Le,
count: x.end,
}
}
}
impl fmt::Display for RoomMemberCountIs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use ComparisonOperator as Op;
let prefix = match self.prefix {
Op::Eq => "",
Op::Lt => "<",
Op::Gt => ">",
Op::Ge => ">=",
Op::Le => "<=",
};
write!(f, "{prefix}{}", self.count)
}
}
impl Serialize for RoomMemberCountIs {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = self.to_string();
s.serialize(serializer)
}
}
impl FromStr for RoomMemberCountIs {
type Err = std::num::ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use ComparisonOperator as Op;
let (prefix, count_str) = match s {
s if s.starts_with("<=") => (Op::Le, &s[2..]),
s if s.starts_with('<') => (Op::Lt, &s[1..]),
s if s.starts_with(">=") => (Op::Ge, &s[2..]),
s if s.starts_with('>') => (Op::Gt, &s[1..]),
s if s.starts_with("==") => (Op::Eq, &s[2..]),
s => (Op::Eq, s),
};
Ok(RoomMemberCountIs {
prefix,
count: u64::from_str(count_str)?,
})
}
}
impl<'de> Deserialize<'de> for RoomMemberCountIs {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = crate::serde::deserialize_cow_str(deserializer)?;
FromStr::from_str(&s).map_err(serde::de::Error::custom)
}
}
impl RangeBounds<u64> for RoomMemberCountIs {
fn start_bound(&self) -> Bound<&u64> {
use ComparisonOperator as Op;
match self.prefix {
Op::Eq => Bound::Included(&self.count),
Op::Lt | Op::Le => Bound::Unbounded,
Op::Gt => Bound::Excluded(&self.count),
Op::Ge => Bound::Included(&self.count),
}
}
fn end_bound(&self) -> Bound<&u64> {
use ComparisonOperator as Op;
match self.prefix {
Op::Eq => Bound::Included(&self.count),
Op::Gt | Op::Ge => Bound::Unbounded,
Op::Lt => Bound::Excluded(&self.count),
Op::Le => Bound::Included(&self.count),
}
}
}
// #[cfg(test)]
// mod tests {
// use std::ops::RangeBounds;
// use super::RoomMemberCountIs;
// #[test]
// fn eq_range_contains_its_own_count() {
// let count = u2;
// let range = RoomMemberCountIs::from(count);
// assert!(range.contains(&count));
// }
// #[test]
// fn ge_range_contains_large_number() {
// let range = RoomMemberCountIs::from(u2..);
// let large_number = 9001;
// assert!(range.contains(&large_number));
// }
// #[test]
// fn gt_range_does_not_contain_initial_point() {
// let range = RoomMemberCountIs::gt(2);
// let initial_point = u2;
// assert!(!range.contains(&initial_point));
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/event_auth.rs | crates/core/src/state/event_auth.rs | use std::{
borrow::Borrow,
collections::{BTreeMap, BTreeSet, HashSet},
};
use serde_json::value::RawValue as RawJsonValue;
use tracing::{debug, info, instrument};
mod room_member;
// #[cfg(test)]
// mod tests;
use self::room_member::check_room_member;
use crate::{
OwnedEventId, OwnedUserId, UserId,
events::{
StateEventType, TimelineEventType,
room::{member::MembershipState, power_levels::UserPowerLevel},
},
room::JoinRuleKind,
room_version_rules::AuthorizationRules,
state::events::{
RoomCreateEvent, RoomJoinRulesEvent, RoomMemberEvent, RoomPowerLevelsEvent,
RoomThirdPartyInviteEvent,
member::{RoomMemberEventContent, RoomMemberEventOptionExt},
power_levels::{RoomPowerLevelsEventOptionExt, RoomPowerLevelsIntField},
},
state::{Event, StateError, StateResult},
utils::RoomIdExt,
};
/// Get the list of [relevant auth events] required to authorize the event of the given type.
///
/// Returns a list of `(event_type, state_key)` tuples.
///
/// # Errors
///
/// Returns an `Err(_)` if a field could not be deserialized because `content` does not respect the
/// expected format for the `event_type`.
///
/// [relevant auth events]: https://spec.matrix.org/latest/server-server-api/#auth-events-selection
pub fn auth_types_for_event(
event_type: &TimelineEventType,
sender: &UserId,
state_key: Option<&str>,
content: &RawJsonValue,
rules: &AuthorizationRules,
) -> StateResult<Vec<(StateEventType, String)>> {
// The `auth_events` for the `m.room.create` event in a room is empty.
if event_type == &TimelineEventType::RoomCreate {
return Ok(vec![]);
}
// For other events, it should be the following subset of the room state:
//
// - The current `m.room.power_levels` event, if any.
// - The sender’s current `m.room.member` event, if any.
let mut auth_types = vec![
(StateEventType::RoomPowerLevels, "".to_owned()),
(StateEventType::RoomMember, sender.to_string()),
];
// We don't need `m.room.create` event for room version 12?
// v1-v11, the `m.room.create` event.
if !rules.room_create_event_id_as_room_id {
auth_types.push((StateEventType::RoomCreate, "".to_owned()));
}
// If type is `m.room.member`:
if event_type == &TimelineEventType::RoomMember {
// The target’s current `m.room.member` event, if any.
let Some(state_key) = state_key else {
return Err(StateError::other(
"missing `state_key` field for `m.room.member` event",
));
};
let key = (StateEventType::RoomMember, state_key.to_owned());
if !auth_types.contains(&key) {
auth_types.push(key);
}
let content = RoomMemberEventContent::new(content);
let membership = content.membership()?;
// If `membership` is `join`, `invite` or `knock`, the current `m.room.join_rules` event, if
// any.
if matches!(
membership,
MembershipState::Join | MembershipState::Invite | MembershipState::Knock
) {
let key = (StateEventType::RoomJoinRules, "".to_owned());
if !auth_types.contains(&key) {
auth_types.push(key);
}
}
// If `membership` is `invite` and `content` contains a `third_party_invite` property, the
// current `m.room.third_party_invite` event with `state_key` matching
// `content.third_party_invite.signed.token`, if any.
if membership == MembershipState::Invite {
let third_party_invite = content.third_party_invite()?;
if let Some(third_party_invite) = third_party_invite {
let token = third_party_invite.token()?.to_owned();
let key = (StateEventType::RoomThirdPartyInvite, token);
if !auth_types.contains(&key) {
auth_types.push(key);
}
}
}
// If `content.join_authorised_via_users_server` is present, and the room version supports
// restricted rooms, then the `m.room.member` event with `state_key` matching
// `content.join_authorised_via_users_server`.
//
// Note: And the membership is join (https://github.com/matrix-org/matrix-spec/pull/2100)
if membership == MembershipState::Join && rules.restricted_join_rule {
let join_authorised_via_users_server = content.join_authorised_via_users_server()?;
if let Some(user_id) = join_authorised_via_users_server {
let key = (StateEventType::RoomMember, user_id.to_string());
if !auth_types.contains(&key) {
auth_types.push(key);
}
}
}
}
Ok(auth_types)
}
/// Authenticate the incoming `event`.
///
/// The steps of authentication are:
///
/// * check that the event is being authenticated for the correct room
/// * then there are checks for specific event types
///
/// The `fetch_state` closure should gather state from a state snapshot. We need
/// to know if the event passes auth against some state not a recursive
/// collection of auth_events fields.
pub async fn auth_check<FetchEvent, EventFut, FetchState, StateFut, Pdu>(
rules: &AuthorizationRules,
incoming_event: &Pdu,
fetch_event: &FetchEvent,
fetch_state: &FetchState,
) -> StateResult<()>
where
FetchEvent: Fn(OwnedEventId) -> EventFut + Sync,
EventFut: Future<Output = StateResult<Pdu>> + Send,
FetchState: Fn(StateEventType, String) -> StateFut + Sync,
StateFut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
check_state_dependent_auth_rules(rules, incoming_event, fetch_state).await?;
check_state_independent_auth_rules(rules, incoming_event, fetch_event).await
}
/// Check whether the incoming event passes the state-independent [authorization rules] for the
/// given room version rules.
///
/// The state-independent rules are the first few authorization rules that check an incoming
/// `m.room.create` event (which cannot have `auth_events`), and the list of `auth_events` of other
/// events.
///
/// This method only needs to be called once, when the event is received.
///
/// # Errors
///
/// If the check fails, this returns an `Err(_)` with a description of the check that failed.
///
/// [authorization rules]: https://spec.matrix.org/latest/server-server-api/#authorization-rules
#[instrument(skip_all)]
pub async fn check_state_independent_auth_rules<Pdu, Fetch, Fut>(
rules: &AuthorizationRules,
incoming_event: &Pdu,
fetch_event: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(OwnedEventId) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
debug!("starting state-independent auth check");
// Since v1, if type is m.room.create:
if *incoming_event.event_type() == TimelineEventType::RoomCreate {
let room_create_event = RoomCreateEvent::new(incoming_event);
return check_room_create(room_create_event, rules);
}
let expected_auth_types = auth_types_for_event(
incoming_event.event_type(),
incoming_event.sender(),
incoming_event.state_key(),
incoming_event.content(),
rules,
)?
.into_iter()
.map(|(event_type, state_key)| (TimelineEventType::from(event_type), state_key))
.collect::<HashSet<_>>();
// let Some(room_id) = incoming_event.room_id() else {
// return Err(StateError::other("missing `room_id` field for event"));
// };
let room_id = incoming_event.room_id();
let mut seen_auth_types: HashSet<(TimelineEventType, String)> =
HashSet::with_capacity(expected_auth_types.len());
// Since v1, considering auth_events:
for auth_event_id in incoming_event.auth_events() {
let event_id = auth_event_id.borrow();
let Ok(auth_event) = fetch_event(event_id.to_owned()).await else {
return Err(StateError::other(format!(
"failed to find auth event {event_id}"
)));
};
// TODO: Room Version 12
// The auth event must be in the same room as the incoming event.
// if auth_event
// .room_id()
// .is_none_or(|auth_room_id| auth_room_id != room_id)
// {
// return Err(StateError::other(format!(
// "auth event {event_id} not in the same room"
// )));
// }
if auth_event.room_id() != room_id {
tracing::error!(
"auth_event.room_id(): {} != {room_id}",
auth_event.room_id()
);
return Err(StateError::other(format!(
"auth event {event_id} not in the same room"
)));
}
let event_type = auth_event.event_type();
let state_key = auth_event
.state_key()
.ok_or_else(|| format!("auth event {event_id} has no `state_key`"))?;
let key = (event_type.clone(), state_key.to_owned());
// Since v1, if there are duplicate entries for a given type and state_key pair, reject.
if seen_auth_types.contains(&key) {
return Err(StateError::other(format!(
"duplicate auth event {event_id} for ({event_type}, {state_key}) pair"
)));
}
// Since v1, if there are entries whose type and state_key don’t match those specified by
// the auth events selection algorithm described in the server specification, reject.
if !expected_auth_types.contains(&key) {
return Err(StateError::other(format!(
"unexpected auth event {event_id} with ({event_type}, {state_key}) pair"
)));
}
// Since v1, if there are entries which were themselves rejected under the checks performed
// on receipt of a PDU, reject.
if auth_event.rejected() {
return Err(StateError::other(format!("rejected auth event {event_id}")));
}
seen_auth_types.insert(key);
}
// v1-v11, if there is no m.room.create event among the entries, reject.
if !rules.room_create_event_id_as_room_id
&& !seen_auth_types
.iter()
.any(|(event_type, _)| *event_type == TimelineEventType::RoomCreate)
{
return Err(StateError::other(
"no `m.room.create` event in auth events".to_owned(),
));
}
// Since v12, the room_id must be the reference hash of an accepted m.room.create event.
if rules.room_create_event_id_as_room_id {
let room_create_event_id = room_id.room_create_event_id().map_err(|error| {
StateError::other(format!(
"could not construct `m.room.create` event ID from room ID: {error}"
))
})?;
let room_create_event = fetch_event(room_create_event_id.to_owned()).await?;
if room_create_event.rejected() {
return Err(StateError::other(format!(
"rejected `m.room.create` event {room_create_event_id}"
)));
}
}
Ok(())
}
/// Check whether the incoming event passes the state-dependent [authorization rules] for the given
/// room version rules.
///
/// The state-dependent rules are all the remaining rules not checked by
/// [`check_state_independent_auth_rules()`].
///
/// This method should be called several times for an event, to perform the [checks on receipt of a
/// PDU].
///
/// The `fetch_state` closure should gather state from a state snapshot. We need to know if the
/// event passes auth against some state not a recursive collection of auth_events fields.
///
/// This assumes that `palpo_core::signatures::verify_event()` was called previously, as some authorization
/// rules depend on the signatures being valid on the event.
///
/// # Errors
///
/// If the check fails, this returns an `Err(_)` with a description of the check that failed.
///
/// [authorization rules]: https://spec.matrix.org/latest/server-server-api/#authorization-rules
/// [checks on receipt of a PDU]: https://spec.matrix.org/latest/server-server-api/#checks-performed-on-receipt-of-a-pdu
#[instrument(skip_all)]
pub async fn check_state_dependent_auth_rules<Pdu, Fetch, Fut>(
auth_rules: &AuthorizationRules,
incoming_event: &Pdu,
fetch_state: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(StateEventType, String) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
debug!("starting state-dependent auth check");
// There are no state-dependent auth rules for create events.
if *incoming_event.event_type() == TimelineEventType::RoomCreate {
debug!("allowing `m.room.create` event");
return Ok(());
}
let room_create_event = fetch_state.room_create_event().await?;
let room_create_event = RoomCreateEvent::new(&room_create_event);
// Since v1, if the create event content has the field m.federate set to false and the sender
// domain of the event does not match the sender domain of the create event, reject.
let federate = room_create_event.federate()?;
if !federate
&& room_create_event.sender().server_name() != incoming_event.sender().server_name()
{
return Err(StateError::forbidden(
"room is not federated and event's sender domain \
does not match `m.room.create` event's sender domain",
));
}
let sender = incoming_event.sender();
// v1-v5, if type is m.room.aliases:
if auth_rules.special_case_room_aliases
&& *incoming_event.event_type() == TimelineEventType::RoomAliases
{
debug!("starting m.room.aliases check");
// v1-v5, if event has no state_key, reject.
//
// v1-v5, if sender's domain doesn't match state_key, reject.
if incoming_event.state_key() != Some(sender.server_name().as_str()) {
return Err(StateError::forbidden(
"server name of the `state_key` of `m.room.aliases` event \
does not match the server name of the sender",
));
}
// Otherwise, allow.
info!("`m.room.aliases` event was allowed");
return Ok(());
}
// Since v1, if type is m.room.member:
if *incoming_event.event_type() == TimelineEventType::RoomMember {
let room_member_event = RoomMemberEvent::new(incoming_event);
return check_room_member(
room_member_event,
auth_rules,
room_create_event,
fetch_state,
)
.await;
}
// Since v1, if the sender's current membership state is not join, reject.
let sender_membership = fetch_state.user_membership(sender).await?;
if sender_membership != MembershipState::Join {
return Err(StateError::forbidden("sender's membership is not `join`"));
}
let creators = room_create_event.creators()?;
let current_room_power_levels_event = fetch_state.room_power_levels_event().await;
let sender_power_level =
current_room_power_levels_event.user_power_level(sender, &creators, auth_rules)?;
// Since v1, if type is m.room.third_party_invite:
if *incoming_event.event_type() == TimelineEventType::RoomThirdPartyInvite {
// Since v1, allow if and only if sender's current power level is greater than
// or equal to the invite level.
let invite_power_level = current_room_power_levels_event
.get_as_int_or_default(RoomPowerLevelsIntField::Invite, auth_rules)?;
if sender_power_level < invite_power_level {
return Err(StateError::forbidden(
"sender does not have enough power to send invites in this room",
));
}
info!("`m.room.third_party_invite` event was allowed");
return Ok(());
}
// Since v1, if the event type's required power level is greater than the sender's power level,
// reject.
let event_type_power_level = current_room_power_levels_event.event_power_level(
incoming_event.event_type(),
incoming_event.state_key(),
auth_rules,
)?;
if sender_power_level < event_type_power_level {
return Err(StateError::forbidden(format!(
"sender does not have enough power to send event of type `{}`",
incoming_event.event_type()
)));
}
// Since v1, if the event has a state_key that starts with an @ and does not match the sender,
// reject.
if incoming_event
.state_key()
.is_some_and(|k| k.starts_with('@'))
&& incoming_event.state_key() != Some(incoming_event.sender().as_str())
{
return Err(StateError::forbidden(
"sender cannot send event with `state_key` matching another user's ID",
));
}
// If type is m.room.power_levels
if *incoming_event.event_type() == TimelineEventType::RoomPowerLevels {
let room_power_levels_event = RoomPowerLevelsEvent::new(incoming_event);
return check_room_power_levels(
room_power_levels_event,
current_room_power_levels_event,
auth_rules,
sender_power_level,
&creators,
);
}
// v1-v2, if type is m.room.redaction:
if auth_rules.special_case_room_redaction
&& *incoming_event.event_type() == TimelineEventType::RoomRedaction
{
return check_room_redaction(
incoming_event,
current_room_power_levels_event,
auth_rules,
sender_power_level,
);
}
// Otherwise, allow.
info!("allowing event passed all checks");
Ok(())
}
/// Check whether the given event passes the `m.room.create` authorization rules.
fn check_room_create(
room_create_event: RoomCreateEvent<impl Event>,
rules: &AuthorizationRules,
) -> StateResult<()> {
debug!("start `m.room.create` check");
// Since v1, if it has any previous events, reject.
if !room_create_event.prev_events().is_empty() {
return Err(StateError::other(
"`m.room.create` event cannot have previous events",
));
}
if rules.room_create_event_id_as_room_id {
// TODO
// // Since v12, if the create event has a room_id, reject.
// if room_create_event.room_id().is_some() {
// return Err(StateError::other(
// "`m.room.create` event cannot have a `room_id` field",
// ));
// }
} else {
// // v1-v11, if the domain of the room_id does not match the domain of the sender, reject.
// let Some(room_id) = room_create_event.room_id() else {
// return Err(StateError::other(
// "missing `room_id` field in `m.room.create` event",
// ));
// };
let Ok(room_id_server_name) = room_create_event.room_id().server_name() else {
return Err(StateError::other(
"invalid `room_id` field in `m.room.create` event: could not parse server name",
));
};
if room_id_server_name != room_create_event.sender().server_name() {
return Err(StateError::other(
"invalid `room_id` field in `m.room.create` event: server name does not match sender's server name",
));
}
}
// Since v1, if `content.room_version` is present and is not a recognized version, reject.
//
// This check is assumed to be done before calling auth_check because we have an
// AuthorizationRules, which means that we recognized the version.
// v1-v10, if content has no creator field, reject.
if !rules.use_room_create_sender && !room_create_event.has_creator()? {
return Err(StateError::other(
"missing `creator` field in `m.room.create` event",
));
}
// Since v12, if the `additional_creators` field is present and is not an array of strings
// where each string passes the same user ID validation that is applied to the sender, reject.
room_create_event.additional_creators()?;
// Otherwise, allow.
info!("`m.room.create` event was allowed");
Ok(())
}
/// Check whether the given event passes the `m.room.power_levels` authorization rules.
fn check_room_power_levels(
room_power_levels_event: RoomPowerLevelsEvent<impl Event>,
current_room_power_levels_event: Option<RoomPowerLevelsEvent<impl Event>>,
rules: &AuthorizationRules,
sender_power_level: UserPowerLevel,
room_creators: &HashSet<OwnedUserId>,
) -> StateResult<()> {
debug!("starting m.room.power_levels check");
// Since v10, if any of the properties users_default, events_default, state_default, ban,
// redact, kick, or invite in content are present and not an integer, reject.
let new_int_fields = room_power_levels_event.int_fields_map(rules)?;
// Since v10, if either of the properties events or notifications in content are present and not
// a dictionary with values that are integers, reject.
let new_events = room_power_levels_event.events(rules)?;
let new_notifications = room_power_levels_event.notifications(rules)?;
// v1-v9, If the users property in content is not an object with keys that are valid user IDs
// with values that are integers (or a string that is an integer), reject.
// Since v10, if the users property in content is not an object with keys that are valid user
// IDs with values that are integers, reject.
let new_users = room_power_levels_event.users(rules)?;
// Since v12, if the `users` property in `content` contains the `sender` of the `m.room.create`
// event or any of the user IDs in the create event's `content.additional_creators`, reject.
if rules.explicitly_privilege_room_creators
&& new_users.is_some_and(|new_users| {
room_creators
.iter()
.any(|creator| new_users.contains_key(creator))
})
{
return Err(StateError::other(
"creator user IDs are not allowed in the `content.users` field",
));
}
debug!("validation of power event finished");
// Since v1, if there is no previous m.room.power_levels event in the room, allow.
let Some(current_room_power_levels_event) = current_room_power_levels_event else {
info!("initial m.room.power_levels event allowed");
return Ok(());
};
// Since v1, for the properties users_default, events_default, state_default, ban, redact, kick,
// invite check if they were added, changed or removed. For each found alteration:
for field in RoomPowerLevelsIntField::ALL {
let current_power_level = current_room_power_levels_event.get_as_int(*field, rules)?;
let new_power_level = new_int_fields.get(field).copied();
if current_power_level == new_power_level {
continue;
}
// Since v1, if the current value is higher than the sender’s current power level,
// reject.
let current_power_level_too_big =
current_power_level.unwrap_or_else(|| field.default_value()) > sender_power_level;
// Since v1, if the new value is higher than the sender’s current power level, reject.
let new_power_level_too_big =
new_power_level.unwrap_or_else(|| field.default_value()) > sender_power_level;
if current_power_level_too_big || new_power_level_too_big {
return Err(StateError::other(format!(
"sender does not have enough power to change the power level of `{field}`"
)));
}
}
// Since v1, for each entry being added to, or changed in, the events property:
// - Since v1, if the new value is higher than the sender's current power level, reject.
let current_events = current_room_power_levels_event.events(rules)?;
check_power_level_maps(
current_events.as_ref(),
new_events.as_ref(),
&sender_power_level,
|_, current_power_level| {
// Since v1, for each entry being changed in, or removed from, the events property:
// - Since v1, if the current value is higher than the sender's current power level,
// reject.
current_power_level > sender_power_level
},
|ev_type| {
format!(
"sender does not have enough power to change the `{ev_type}` event type power level"
)
},
)?;
// Since v6, for each entry being added to, or changed in, the notifications property:
// - Since v6, if the new value is higher than the sender's current power level, reject.
if rules.limit_notifications_power_levels {
let current_notifications = current_room_power_levels_event.notifications(rules)?;
check_power_level_maps(
current_notifications.as_ref(),
new_notifications.as_ref(),
&sender_power_level,
|_, current_power_level| {
// Since v6, for each entry being changed in, or removed from, the notifications
// property:
// - Since v6, if the current value is higher than the sender's current power level,
// reject.
current_power_level > sender_power_level
},
|key| {
format!(
"sender does not have enough power to change the `{key}` notification power level"
)
},
)?;
}
// Since v1, for each entry being added to, or changed in, the users property:
// - Since v1, if the new value is greater than the sender’s current power level, reject.
let current_users = current_room_power_levels_event.users(rules)?;
check_power_level_maps(
current_users,
new_users,
&sender_power_level,
|user_id, current_power_level| {
// Since v1, for each entry being changed in, or removed from, the users property, other
// than the sender’s own entry:
// - Since v1, if the current value is greater than or equal to the sender’s current
// power level, reject.
user_id != room_power_levels_event.sender() && current_power_level >= sender_power_level
},
|user_id| format!("sender does not have enough power to change `{user_id}`'s power level"),
)?;
// Otherwise, allow.
info!("m.room.power_levels event allowed");
Ok(())
}
/// Check the power levels changes between the current and the new maps.
///
/// # Arguments
///
/// * `current`: the map with the current power levels.
/// * `new`: the map with the new power levels.
/// * `sender_power_level`: the power level of the sender of the new map.
/// * `reject_current_power_level_change_fn`: the function to check if a power level change or
/// removal must be rejected given its current value.
///
/// The arguments to the method are the key of the power level and the current value of the power
/// level. It must return `true` if the change or removal is rejected.
///
/// Note that another check is done after this one to check if the change is allowed given the new
/// value of the power level.
/// * `error_fn`: the function to generate an error when the change for the given key is not
/// allowed.
fn check_power_level_maps<K: Ord>(
current: Option<&BTreeMap<K, i64>>,
new: Option<&BTreeMap<K, i64>>,
sender_power_level: &UserPowerLevel,
reject_current_power_level_change_fn: impl FnOnce(&K, i64) -> bool + Copy,
error_fn: impl FnOnce(&K) -> String,
) -> Result<(), String> {
let keys_to_check = current
.iter()
.flat_map(|m| m.keys())
.chain(new.iter().flat_map(|m| m.keys()))
.collect::<BTreeSet<_>>();
for key in keys_to_check {
let current_power_level = current.as_ref().and_then(|m| m.get(key));
let new_power_level = new.as_ref().and_then(|m| m.get(key));
if current_power_level == new_power_level {
continue;
}
// For each entry being changed in, or removed from, the property.
let current_power_level_change_rejected = current_power_level
.is_some_and(|power_level| reject_current_power_level_change_fn(key, *power_level));
// For each entry being added to, or changed in, the property:
// - If the new value is higher than the sender's current power level, reject.
let new_power_level_too_big = new_power_level.is_some_and(|pl| pl > sender_power_level);
if current_power_level_change_rejected || new_power_level_too_big {
return Err(error_fn(key));
}
}
Ok(())
}
/// Check whether the given event passes the `m.room.redaction` authorization rules.
fn check_room_redaction<Pdu>(
room_redaction_event: &Pdu,
current_room_power_levels_event: Option<RoomPowerLevelsEvent<Pdu>>,
rules: &AuthorizationRules,
sender_level: UserPowerLevel,
) -> StateResult<()>
where
Pdu: Event + Clone + Sync + Send,
{
let redact_level = current_room_power_levels_event
.get_as_int_or_default(RoomPowerLevelsIntField::Redact, rules)?;
// v1-v2, if the sender’s power level is greater than or equal to the redact level, allow.
if sender_level >= redact_level {
info!("`m.room.redaction` event allowed via power levels");
return Ok(());
}
// v1-v2, if the domain of the event_id of the event being redacted is the same as the
// domain of the event_id of the m.room.redaction, allow.
if room_redaction_event.event_id().borrow().server_name()
== room_redaction_event
.redacts()
.as_ref()
.and_then(|&id| id.borrow().server_name())
{
info!("`m.room.redaction` event allowed via room version 1 rules");
return Ok(());
}
// Otherwise, reject.
Err(StateError::other(
"`m.room.redaction` event did not pass any of the allow rules",
))
}
trait FetchStateExt<E: Event> {
fn room_create_event(&self) -> impl Future<Output = StateResult<E>>;
fn user_membership(
&self,
user_id: &UserId,
) -> impl Future<Output = StateResult<MembershipState>>;
fn room_power_levels_event(&self) -> impl Future<Output = Option<RoomPowerLevelsEvent<E>>>;
fn join_rule(&self) -> impl Future<Output = StateResult<JoinRuleKind>>;
fn room_third_party_invite_event(
&self,
token: &str,
) -> impl Future<Output = Option<RoomThirdPartyInviteEvent<E>>>;
}
impl<Pdu, F, Fut> FetchStateExt<Pdu> for F
where
F: Fn(StateEventType, String) -> Fut,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event,
{
async fn room_create_event(&self) -> StateResult<Pdu> {
self(StateEventType::RoomCreate, "".into()).await
}
async fn user_membership(&self, user_id: &UserId) -> StateResult<MembershipState> {
self(StateEventType::RoomMember, user_id.as_str().into())
.await
.map(RoomMemberEvent::new)
.ok()
.membership()
}
async fn room_power_levels_event(&self) -> Option<RoomPowerLevelsEvent<Pdu>> {
self(StateEventType::RoomPowerLevels, "".into())
.await
.ok()
.map(RoomPowerLevelsEvent::new)
}
async fn join_rule(&self) -> StateResult<JoinRuleKind> {
self(StateEventType::RoomJoinRules, "".into())
.await
.map(RoomJoinRulesEvent::new)?
.join_rule()
}
async fn room_third_party_invite_event(
&self,
token: &str,
) -> Option<RoomThirdPartyInviteEvent<Pdu>> {
self(StateEventType::RoomThirdPartyInvite, token.into())
.await
.ok()
.map(RoomThirdPartyInviteEvent::new)
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/tests.rs | crates/core/src/state/tests.rs | use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use maplit::{hashmap, hashset};
use rand::seq::SliceRandom;
use crate::{
room_version_rules::{AuthorizationRules, StateResolutionV2Rules},
UnixMillis, OwnedEventId,
};
use crate::events::{
room::join_rules::{JoinRule, RoomJoinRulesEventContent},
StateEventType, TimelineEventType,
};
use serde_json::{json, value::to_raw_value as to_raw_json_value};
use tracing::debug;
use super::{is_power_event, EventTypeExt, StateMap};
use crate::{
test_utils::{
alice, bob, charlie, do_check, ella, event_id, member_content_ban, member_content_join,
room_id, to_init_pdu_event, to_pdu_event, zara, PduEvent, TestStore, INITIAL_EVENTS,
},
Event,
};
fn test_event_sort() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let events = INITIAL_EVENTS();
let event_map = events
.values()
.map(|ev| (ev.event_type().with_state_key(ev.state_key().unwrap()), ev.clone()))
.collect::<StateMap<_>>();
let auth_chain: HashSet<OwnedEventId> = HashSet::new();
let power_events = event_map
.values()
.filter(|&pdu| is_power_event(&**pdu))
.map(|pdu| pdu.event_id.clone())
.collect::<Vec<_>>();
let sorted_power_events =
super::sort_power_events(power_events, &auth_chain, &AuthorizationRules::V6, |id| {
events.get(id).cloned()
})
.unwrap();
let resolved_power = super::iterative_auth_check(
&AuthorizationRules::V6,
&sorted_power_events,
HashMap::new(), // unconflicted events
|id| events.get(id).cloned(),
)
.expect("iterative auth check failed on resolved events");
// don't remove any events so we know it sorts them all correctly
let mut events_to_sort = events.keys().cloned().collect::<Vec<_>>();
events_to_sort.shuffle(&mut rand::thread_rng());
let power_level =
resolved_power.get(&(StateEventType::RoomPowerLevels, "".to_owned())).cloned();
let sorted_event_ids =
super::mainline_sort(&events_to_sort, power_level, |id| events.get(id).cloned()).unwrap();
assert_eq!(
vec![
"$CREATE:foo",
"$IMA:foo",
"$IPOWER:foo",
"$IJR:foo",
"$IMB:foo",
"$IMC:foo",
"$START:foo",
"$END:foo"
],
sorted_event_ids.iter().map(|id| id.to_string()).collect::<Vec<_>>()
);
}
#[test]
fn test_sort() {
for _ in 0..20 {
// since we shuffle the eventIds before we sort them introducing randomness
// seems like we should test this a few times
test_event_sort();
}
}
#[test]
fn ban_vs_power_level() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let events = &[
to_init_pdu_event(
"PA",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
),
to_init_pdu_event(
"MA",
alice(),
TimelineEventType::RoomMember,
Some(alice().to_string().as_str()),
member_content_join(),
),
to_init_pdu_event(
"MB",
alice(),
TimelineEventType::RoomMember,
Some(bob().to_string().as_str()),
member_content_ban(),
),
to_init_pdu_event(
"PB",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
),
];
let edges = vec![vec!["END", "MB", "MA", "PA", "START"], vec!["END", "PA", "PB"]]
.into_iter()
.map(|list| list.into_iter().map(event_id).collect::<Vec<_>>())
.collect::<Vec<_>>();
let expected_state_ids = vec!["PA", "MA", "MB"].into_iter().map(event_id).collect::<Vec<_>>();
do_check(events, edges, expected_state_ids);
}
#[test]
fn topic_basic() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let events = &[
to_init_pdu_event(
"T1",
alice(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
to_init_pdu_event(
"PA1",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
),
to_init_pdu_event(
"T2",
alice(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
to_init_pdu_event(
"PA2",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 0 } })).unwrap(),
),
to_init_pdu_event(
"PB",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
),
to_init_pdu_event(
"T3",
bob(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
];
let edges =
vec![vec!["END", "PA2", "T2", "PA1", "T1", "START"], vec!["END", "T3", "PB", "PA1"]]
.into_iter()
.map(|list| list.into_iter().map(event_id).collect::<Vec<_>>())
.collect::<Vec<_>>();
let expected_state_ids = vec!["PA2", "T2"].into_iter().map(event_id).collect::<Vec<_>>();
do_check(events, edges, expected_state_ids);
}
#[test]
fn topic_reset() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let events = &[
to_init_pdu_event(
"T1",
alice(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
to_init_pdu_event(
"PA",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
),
to_init_pdu_event(
"T2",
bob(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
to_init_pdu_event(
"MB",
alice(),
TimelineEventType::RoomMember,
Some(bob().to_string().as_str()),
member_content_ban(),
),
];
let edges = vec![vec!["END", "MB", "T2", "PA", "T1", "START"], vec!["END", "T1"]]
.into_iter()
.map(|list| list.into_iter().map(event_id).collect::<Vec<_>>())
.collect::<Vec<_>>();
let expected_state_ids = vec!["T1", "MB", "PA"].into_iter().map(event_id).collect::<Vec<_>>();
do_check(events, edges, expected_state_ids);
}
#[test]
fn join_rule_evasion() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let events = &[
to_init_pdu_event(
"JR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Private)).unwrap(),
),
to_init_pdu_event(
"ME",
ella(),
TimelineEventType::RoomMember,
Some(ella().to_string().as_str()),
member_content_join(),
),
];
let edges = vec![vec!["END", "JR", "START"], vec!["END", "ME", "START"]]
.into_iter()
.map(|list| list.into_iter().map(event_id).collect::<Vec<_>>())
.collect::<Vec<_>>();
let expected_state_ids = vec![event_id("JR")];
do_check(events, edges, expected_state_ids);
}
#[test]
fn offtopic_power_level() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let events = &[
to_init_pdu_event(
"PA",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
),
to_init_pdu_event(
"PB",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50, charlie(): 50 } }))
.unwrap(),
),
to_init_pdu_event(
"PC",
charlie(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50, charlie(): 0 } }))
.unwrap(),
),
];
let edges = vec![vec!["END", "PC", "PB", "PA", "START"], vec!["END", "PA"]]
.into_iter()
.map(|list| list.into_iter().map(event_id).collect::<Vec<_>>())
.collect::<Vec<_>>();
let expected_state_ids = vec!["PC"].into_iter().map(event_id).collect::<Vec<_>>();
do_check(events, edges, expected_state_ids);
}
#[test]
fn topic_setting() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let events = &[
to_init_pdu_event(
"T1",
alice(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
to_init_pdu_event(
"PA1",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
),
to_init_pdu_event(
"T2",
alice(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
to_init_pdu_event(
"PA2",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 0 } })).unwrap(),
),
to_init_pdu_event(
"PB",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
),
to_init_pdu_event(
"T3",
bob(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
to_init_pdu_event(
"MZ1",
zara(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
to_init_pdu_event(
"T4",
alice(),
TimelineEventType::RoomTopic,
Some(""),
to_raw_json_value(&json!({})).unwrap(),
),
];
let edges = vec![
vec!["END", "T4", "MZ1", "PA2", "T2", "PA1", "T1", "START"],
vec!["END", "MZ1", "T3", "PB", "PA1"],
]
.into_iter()
.map(|list| list.into_iter().map(event_id).collect::<Vec<_>>())
.collect::<Vec<_>>();
let expected_state_ids = vec!["T4", "PA2"].into_iter().map(event_id).collect::<Vec<_>>();
do_check(events, edges, expected_state_ids);
}
#[test]
fn test_event_map_none() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let mut store = TestStore::<PduEvent>(hashmap! {});
// build up the DAG
let (state_at_bob, state_at_charlie, expected) = store.set_up();
let ev_map = store.0.clone();
let state_sets = [state_at_bob, state_at_charlie];
let resolved = match crate::resolve(
&AuthorizationRules::V1,
StateResolutionV2Rules::V2_0,
&state_sets,
state_sets
.iter()
.map(|map| store.auth_event_ids(room_id(), map.values().cloned().collect()).unwrap())
.collect(),
|id| ev_map.get(id).cloned(),
|_| unreachable!(),
) {
Ok(state) => state,
Err(e) => panic!("{e}"),
};
assert_eq!(expected, resolved);
}
// #[test]
// fn test_reverse_topological_power_sort() {
// let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
// let graph = hashmap! {
// event_id("l") => hashset![event_id("o")],
// event_id("m") => hashset![event_id("n"), event_id("o")],
// event_id("n") => hashset![event_id("o")],
// event_id("o") => hashset![], // "o" has zero outgoing edges but 4 incoming edges
// event_id("p") => hashset![event_id("o")],
// };
// let res = crate::reverse_topological_power_sort(&graph, |_id| {
// Ok((int!(0).into(), UnixMillis(uint!(0))))
// }).await
// .unwrap();
// assert_eq!(
// vec!["o", "l", "n", "m", "p"],
// res.iter()
// .map(ToString::to_string)
// .map(|s| s.replace('$', "").replace(":foo", ""))
// .collect::<Vec<_>>()
// );
// }
#[test]
fn ban_with_auth_chains() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let ban = BAN_STATE_SET();
let edges = vec![vec!["END", "MB", "PA", "START"], vec!["END", "IME", "MB"]]
.into_iter()
.map(|list| list.into_iter().map(event_id).collect::<Vec<_>>())
.collect::<Vec<_>>();
let expected_state_ids = vec!["PA", "MB"].into_iter().map(event_id).collect::<Vec<_>>();
do_check(&ban.values().cloned().collect::<Vec<_>>(), edges, expected_state_ids);
}
#[test]
fn ban_with_auth_chains2() {
let _ = tracing::subscriber::set_default(tracing_subscriber::fmt().with_test_writer().finish());
let init = INITIAL_EVENTS();
let ban = BAN_STATE_SET();
let mut inner = init.clone();
inner.extend(ban);
let store = TestStore(inner.clone());
let state_set_a = [
inner.get(&event_id("CREATE")).unwrap(),
inner.get(&event_id("IJR")).unwrap(),
inner.get(&event_id("IMA")).unwrap(),
inner.get(&event_id("IMB")).unwrap(),
inner.get(&event_id("IMC")).unwrap(),
inner.get(&event_id("MB")).unwrap(),
inner.get(&event_id("PA")).unwrap(),
]
.iter()
.map(|ev| (ev.event_type().with_state_key(ev.state_key().unwrap()), ev.event_id.clone()))
.collect::<StateMap<_>>();
let state_set_b = [
inner.get(&event_id("CREATE")).unwrap(),
inner.get(&event_id("IJR")).unwrap(),
inner.get(&event_id("IMA")).unwrap(),
inner.get(&event_id("IMB")).unwrap(),
inner.get(&event_id("IMC")).unwrap(),
inner.get(&event_id("IME")).unwrap(),
inner.get(&event_id("PA")).unwrap(),
]
.iter()
.map(|ev| (ev.event_type().with_state_key(ev.state_key().unwrap()), ev.event_id.clone()))
.collect::<StateMap<_>>();
let ev_map = &store.0;
let state_sets = [state_set_a, state_set_b];
let resolved = match crate::resolve(
&AuthorizationRules::V6,
&StateResolutionV2Rules::V2_0,
&state_sets,
state_sets
.iter()
.map(|map| store.auth_event_ids(room_id(), map.values().cloned().collect()).unwrap())
.collect(),
|id| ev_map.get(id).cloned(),
|_| unreachable!(),
) {
Ok(state) => state,
Err(e) => panic!("{e}"),
};
debug!(
resolved = ?resolved
.iter()
.map(|((ty, key), id)| format!("(({ty}{key:?}), {id})"))
.collect::<Vec<_>>(),
"resolved state",
);
let expected =
["$CREATE:foo", "$IJR:foo", "$PA:foo", "$IMA:foo", "$IMB:foo", "$IMC:foo", "$MB:foo"];
for id in expected.iter().map(|i| event_id(i)) {
// make sure our resolved events are equal to the expected list
assert!(resolved.values().any(|eid| eid == &id) || init.contains_key(&id), "{id}");
}
assert_eq!(expected.len(), resolved.len());
}
#[test]
fn join_rule_with_auth_chain() {
let join_rule = JOIN_RULE();
let edges = vec![vec!["END", "JR", "START"], vec!["END", "IMZ", "START"]]
.into_iter()
.map(|list| list.into_iter().map(event_id).collect::<Vec<_>>())
.collect::<Vec<_>>();
let expected_state_ids = vec!["JR"].into_iter().map(event_id).collect::<Vec<_>>();
do_check(&join_rule.values().cloned().collect::<Vec<_>>(), edges, expected_state_ids);
}
#[allow(non_snake_case)]
fn BAN_STATE_SET() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![
to_pdu_event(
"PA",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
&["CREATE", "IMA", "IPOWER"], // auth_events
&["START"], // prev_events
),
to_pdu_event(
"PB",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, bob(): 50 } })).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["END"],
),
to_pdu_event(
"MB",
alice(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
member_content_ban(),
&["CREATE", "IMA", "PB"],
&["PA"],
),
to_pdu_event(
"IME",
ella(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
member_content_join(),
&["CREATE", "IJR", "PA"],
&["MB"],
),
]
.into_iter()
.map(|ev| (ev.event_id.clone(), ev))
.collect()
}
#[allow(non_snake_case)]
fn JOIN_RULE() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![
to_pdu_event(
"JR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&json!({ "join_rule": "invite" })).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["START"],
),
to_pdu_event(
"IMZ",
zara(),
TimelineEventType::RoomPowerLevels,
Some(zara().as_str()),
member_content_join(),
&["CREATE", "JR", "IPOWER"],
&["START"],
),
]
.into_iter()
.map(|ev| (ev.event_id.clone(), ev))
.collect()
}
macro_rules! state_set {
($($kind:expr => $key:expr => $id:expr),* $(,)?) => {{
#[allow(unused_mut)]
let mut x = StateMap::new();
$(
x.insert(($kind, $key.to_owned()), $id);
)*
x
}};
}
#[test]
fn split_conflicted_state_set_conflicted_unique_state_keys() {
let (unconflicted, conflicted) = super::split_conflicted_state_set(
[
state_set![StateEventType::RoomMember => "@a:hs1" => 0],
state_set![StateEventType::RoomMember => "@b:hs1" => 1],
state_set![StateEventType::RoomMember => "@c:hs1" => 2],
]
.iter(),
);
assert_eq!(unconflicted, StateMap::new());
assert_eq!(
conflicted,
state_set![
StateEventType::RoomMember => "@a:hs1" => vec![0],
StateEventType::RoomMember => "@b:hs1" => vec![1],
StateEventType::RoomMember => "@c:hs1" => vec![2],
],
);
}
#[test]
fn split_conflicted_state_set_conflicted_same_state_key() {
let (unconflicted, mut conflicted) = super::split_conflicted_state_set(
[
state_set![StateEventType::RoomMember => "@a:hs1" => 0],
state_set![StateEventType::RoomMember => "@a:hs1" => 1],
state_set![StateEventType::RoomMember => "@a:hs1" => 2],
]
.iter(),
);
// HashMap iteration order is random, so sort this before asserting on it
for v in conflicted.values_mut() {
v.sort_unstable();
}
assert_eq!(unconflicted, StateMap::new());
assert_eq!(
conflicted,
state_set![
StateEventType::RoomMember => "@a:hs1" => vec![0, 1, 2],
],
);
}
#[test]
fn split_conflicted_state_set_unconflicted() {
let (unconflicted, conflicted) = super::split_conflicted_state_set(
[
state_set![StateEventType::RoomMember => "@a:hs1" => 0],
state_set![StateEventType::RoomMember => "@a:hs1" => 0],
state_set![StateEventType::RoomMember => "@a:hs1" => 0],
]
.iter(),
);
assert_eq!(
unconflicted,
state_set![
StateEventType::RoomMember => "@a:hs1" => 0,
],
);
assert_eq!(conflicted, StateMap::new());
}
#[test]
fn split_conflicted_state_set_mixed() {
let (unconflicted, conflicted) = super::split_conflicted_state_set(
[
state_set![StateEventType::RoomMember => "@a:hs1" => 0],
state_set![
StateEventType::RoomMember => "@a:hs1" => 0,
StateEventType::RoomMember => "@b:hs1" => 1,
],
state_set![
StateEventType::RoomMember => "@a:hs1" => 0,
StateEventType::RoomMember => "@c:hs1" => 2,
],
]
.iter(),
);
assert_eq!(
unconflicted,
state_set![
StateEventType::RoomMember => "@a:hs1" => 0,
],
);
assert_eq!(
conflicted,
state_set![
StateEventType::RoomMember => "@b:hs1" => vec![1],
StateEventType::RoomMember => "@c:hs1" => vec![2],
],
);
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/room_version.rs | crates/core/src/state/room_version.rs | #[derive(Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum RoomDisposition {
/// A room version that has a stable specification.
Stable,
/// A room version that is not yet fully specified.
Unstable,
}
#[derive(Debug)]
pub enum EventFormatVersion {
/// $id:server event id format
V1,
/// MSC1659-style $hash event id format: introduced for room v3
V2,
/// MSC1884-style $hash format: introduced for room v4
V3,
}
#[derive(Debug)]
pub enum StateResolutionVersion {
/// State resolution for rooms at version 1.
V1,
/// State resolution for room at version 2 or later.
V2,
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/error.rs | crates/core/src/state/error.rs | use thiserror::Error;
use crate::OwnedEventId;
/// Result type for state resolution.
pub type StateResult<T> = std::result::Result<T, StateError>;
/// Represents the various errors that arise when resolving state.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum StateError {
/// The given event was not found.
#[error("failed to find event {0}")]
NotFound(OwnedEventId),
/// Forbidden.
#[error("forbidden: {0}")]
Forbidden(String),
/// An auth event is invalid.
#[error("invalid auth event: {0}")]
AuthEvent(String),
/// A state event doesn't have a `state_key`.
#[error("state event has no `state_key`")]
MissingStateKey,
/// Provided `fetch_conflicted_state_subgraph` function failed.
#[error("fetch conflicted state subgraph failed")]
FetchConflictedStateSubgraphFailed,
#[error("other state error: {0}")]
Other(String),
}
impl StateError {
pub fn auth_event(error: impl Into<String>) -> Self {
StateError::AuthEvent(error.into())
}
pub fn forbidden(error: impl Into<String>) -> Self {
StateError::Forbidden(error.into())
}
pub fn other(error: impl Into<String>) -> Self {
StateError::Other(error.into())
}
}
impl From<String> for StateError {
fn from(error: String) -> Self {
StateError::Other(error)
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/events.rs | crates/core/src/state/events.rs | //! Helper traits and types to work with events (aka PDUs).
mod create;
mod join_rules;
pub(crate) mod member;
pub(crate) mod power_levels;
mod third_party_invite;
pub use self::{
create::RoomCreateEvent,
join_rules::RoomJoinRulesEvent,
member::RoomMemberEvent,
power_levels::{RoomPowerLevelsEvent, RoomPowerLevelsIntField},
third_party_invite::RoomThirdPartyInviteEvent,
};
use std::{
borrow::Borrow,
fmt::{Debug, Display},
hash::Hash,
sync::Arc,
};
use crate::{EventId, RoomId, UnixMillis, UserId, events::TimelineEventType, serde::RawJsonValue};
/// Abstraction of a PDU so users can have their own PDU types.
pub trait Event: Debug {
type Id: Clone + Debug + Display + Eq + Ord + Hash + Borrow<EventId>;
/// The `EventId` of this event.
fn event_id(&self) -> &Self::Id;
/// The `RoomId` of this event.
fn room_id(&self) -> &RoomId;
/// The `UserId` of this event.
fn sender(&self) -> &UserId;
/// The time of creation on the originating server.
fn origin_server_ts(&self) -> UnixMillis;
/// The event type.
fn event_type(&self) -> &TimelineEventType;
/// The event's content.
fn content(&self) -> &RawJsonValue;
/// The state key for this event.
fn state_key(&self) -> Option<&str>;
/// The events before this event.
// Requires GATs to avoid boxing (and TAIT for making it convenient).
fn prev_events(&self) -> &[Self::Id];
/// All the authenticating events for this event.
// Requires GATs to avoid boxing (and TAIT for making it convenient).
fn auth_events(&self) -> &[Self::Id];
/// If this event is a redaction event this is the event it redacts.
fn redacts(&self) -> Option<&Self::Id>;
/// Whether this event was rejected for not passing the checks on reception of a PDU.
fn rejected(&self) -> bool;
}
impl<T: Event> Event for &T {
type Id = T::Id;
fn event_id(&self) -> &Self::Id {
(*self).event_id()
}
fn room_id(&self) -> &RoomId {
(*self).room_id()
}
fn sender(&self) -> &UserId {
(*self).sender()
}
fn origin_server_ts(&self) -> UnixMillis {
(*self).origin_server_ts()
}
fn event_type(&self) -> &TimelineEventType {
(*self).event_type()
}
fn content(&self) -> &RawJsonValue {
(*self).content()
}
fn state_key(&self) -> Option<&str> {
(*self).state_key()
}
fn prev_events(&self) -> &[Self::Id] {
(*self).prev_events()
}
fn auth_events(&self) -> &[Self::Id] {
(*self).auth_events()
}
fn redacts(&self) -> Option<&Self::Id> {
(*self).redacts()
}
fn rejected(&self) -> bool {
(*self).rejected()
}
}
impl<T: Event> Event for Arc<T> {
type Id = T::Id;
fn event_id(&self) -> &Self::Id {
(**self).event_id()
}
fn room_id(&self) -> &RoomId {
(**self).room_id()
}
fn sender(&self) -> &UserId {
(**self).sender()
}
fn origin_server_ts(&self) -> UnixMillis {
(**self).origin_server_ts()
}
fn event_type(&self) -> &TimelineEventType {
(**self).event_type()
}
fn content(&self) -> &RawJsonValue {
(**self).content()
}
fn state_key(&self) -> Option<&str> {
(**self).state_key()
}
fn prev_events(&self) -> &[Self::Id] {
(**self).prev_events()
}
fn auth_events(&self) -> &[Self::Id] {
(**self).auth_events()
}
fn redacts(&self) -> Option<&Self::Id> {
(**self).redacts()
}
fn rejected(&self) -> bool {
(**self).rejected()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/event_auth/room_member.rs | crates/core/src/state/event_auth/room_member.rs | use std::borrow::Borrow;
use tracing::debug;
// #[cfg(test)]
// mod tests;
use super::FetchStateExt;
use crate::events::{StateEventType, room::member::MembershipState};
use crate::state::{
Event, StateError, StateResult,
events::{
RoomCreateEvent, RoomMemberEvent,
member::ThirdPartyInvite,
power_levels::{RoomPowerLevelsEventOptionExt, RoomPowerLevelsIntField},
},
};
use crate::{
AnyKeyName, SigningKeyId, UserId,
room::JoinRuleKind,
room_version_rules::AuthorizationRules,
serde::{Base64, base64::Standard},
signatures::verify_canonical_json_bytes,
};
/// Check whether the given event passes the `m.room.roomber` authorization rules.
///
/// This assumes that `palpo_core::signatures::verify_event()` was called previously, as some authorization
/// rules depend on the signatures being valid on the event.
pub(super) async fn check_room_member<Pdu, Fetch, Fut>(
room_member_event: RoomMemberEvent<&Pdu>,
auth_rules: &AuthorizationRules,
room_create_event: RoomCreateEvent<&Pdu>,
fetch_state: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(StateEventType, String) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
debug!("starting m.room.member check");
// Since v1, if there is no state_key property, or no membership property in content,
// reject.
let Some(state_key) = room_member_event.state_key() else {
return Err(StateError::forbidden(
"missing `state_key` field in `m.room.member` event",
));
};
let target_user = <&UserId>::try_from(state_key).map_err(|e| {
StateError::forbidden(format!(
"invalid `state_key` field in `m.room.member` event: {e}"
))
})?;
let target_membership = room_member_event.membership()?;
// These checks are done `in palpo_core::signatures::verify_event()`:
//
// Since v8, if content has a join_authorised_via_users_server property:
//
// - Since v8, if the event is not validly signed by the homeserver of the user ID denoted by
// the key, reject.
match target_membership {
// Since v1, if membership is join:
MembershipState::Join => {
check_room_member_join(
room_member_event,
target_user,
auth_rules,
room_create_event,
fetch_state,
)
.await
}
// Since v1, if membership is invite:
MembershipState::Invite => {
check_room_member_invite(
room_member_event,
target_user,
auth_rules,
room_create_event,
fetch_state,
)
.await
}
// Since v1, if membership is leave:
MembershipState::Leave => {
check_room_member_leave(
room_member_event,
target_user,
auth_rules,
room_create_event,
fetch_state,
)
.await
}
// Since v1, if membership is ban:
MembershipState::Ban => {
check_room_member_ban(
room_member_event,
target_user,
auth_rules,
room_create_event,
fetch_state,
)
.await
}
// Since v7, if membership is knock:
MembershipState::Knock if auth_rules.knocking => {
check_room_member_knock(room_member_event, target_user, auth_rules, fetch_state).await
}
// Since v1, otherwise, the membership is unknown. Reject.
_ => Err(StateError::forbidden("unknown membership")),
}
}
/// Check whether the given event passes the `m.room.member` authorization rules with a membership
/// of `join`.
async fn check_room_member_join<Pdu, Fetch, Fut>(
room_member_event: RoomMemberEvent<&Pdu>,
target_user: &UserId,
rules: &AuthorizationRules,
room_create_event: RoomCreateEvent<&Pdu>,
fetch_state: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(StateEventType, String) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
let creator = room_create_event.creator()?;
let creators = room_create_event.creators()?;
let prev_events = room_member_event.prev_events();
let prev_event_is_room_create_event = prev_events
.first()
.is_some_and(|event_id| event_id.borrow() == room_create_event.event_id().borrow());
let prev_event_is_only_room_create_event =
prev_event_is_room_create_event && prev_events.len() == 1;
// v1-v10, if the only previous event is an m.room.create and the state_key is the
// creator, allow.
// Since v11, if the only previous event is an m.room.create and the state_key is the
// sender of the m.room.create, allow.
if prev_event_is_only_room_create_event && *target_user == *creator {
return Ok(());
}
// Since v1, if the sender does not match state_key, reject.
if room_member_event.sender() != target_user {
return Err(StateError::forbidden(
"sender of join event must match target user",
));
}
let current_membership = fetch_state.user_membership(target_user).await?;
// Since v1, if the sender is banned, reject.
if current_membership == MembershipState::Ban {
return Err(StateError::forbidden("banned user cannot join room"));
}
let join_rule = fetch_state.join_rule().await?;
// v1-v6, if the join_rule is invite then allow if membership state is invite or
// join.
// Since v7, if the join_rule is invite or knock then allow if membership state is
// invite or join.
if (join_rule == JoinRuleKind::Invite || rules.knocking && join_rule == JoinRuleKind::Knock)
&& matches!(
current_membership,
MembershipState::Invite | MembershipState::Join
)
{
return Ok(());
}
// v8-v9, if the join_rule is restricted:
// Since v10, if the join_rule is restricted or knock_restricted:
if rules.restricted_join_rule && matches!(join_rule, JoinRuleKind::Restricted)
|| rules.knock_restricted_join_rule && matches!(join_rule, JoinRuleKind::KnockRestricted)
{
// Since v8, if membership state is join or invite, allow.
if matches!(
current_membership,
MembershipState::Join | MembershipState::Invite
) {
return Ok(());
}
// Since v8, if the join_authorised_via_users_server key in content is not a user with
// sufficient permission to invite other users or is not a joined member of the room,
// reject.
//
// Otherwise, allow.
let Some(authorized_via_user) = room_member_event.join_authorised_via_users_server()?
else {
// The field is absent, we cannot authorize.
return Err(StateError::forbidden(
"cannot join restricted room without `join_authorised_via_users_server` field \
if not invited",
));
};
// The member needs to be in the room to have any kind of permission.
let authorized_via_user_membership =
fetch_state.user_membership(&authorized_via_user).await?;
if authorized_via_user_membership != MembershipState::Join {
return Err(StateError::forbidden(
"`join_authorised_via_users_server` is not joined",
));
}
let room_power_levels_event = fetch_state.room_power_levels_event().await;
let authorized_via_user_power_level =
room_power_levels_event.user_power_level(&authorized_via_user, &creators, rules)?;
let invite_power_level = room_power_levels_event
.get_as_int_or_default(RoomPowerLevelsIntField::Invite, rules)?;
return if authorized_via_user_power_level >= invite_power_level {
Ok(())
} else {
Err(StateError::forbidden(
"`join_authorised_via_users_server` does not have enough power",
))
};
}
// Since v1, if the join_rule is public, allow.
// Otherwise, reject.
if join_rule == JoinRuleKind::Public {
Ok(())
} else {
Err(StateError::forbidden(
"cannot join a room that is not `public`",
))
}
}
/// Check whether the given event passes the `m.room.member` authorization rules with a membership
/// of `invite`.
async fn check_room_member_invite<Pdu, Fetch, Fut>(
room_member_event: RoomMemberEvent<&Pdu>,
target_user: &UserId,
rules: &AuthorizationRules,
room_create_event: RoomCreateEvent<&Pdu>,
fetch_state: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(StateEventType, String) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
let third_party_invite = room_member_event.third_party_invite()?;
// Since v1, if content has a third_party_invite property:
if let Some(third_party_invite) = third_party_invite {
return check_third_party_invite(
room_member_event,
&third_party_invite,
target_user,
fetch_state,
)
.await;
}
let sender_membership = fetch_state
.user_membership(room_member_event.sender())
.await?;
// Since v1, if the sender’s current membership state is not join, reject.
if sender_membership != MembershipState::Join {
return Err(StateError::forbidden(
"cannot invite user if sender is not joined",
));
}
let current_target_user_membership = fetch_state.user_membership(target_user).await?;
// Since v1, if target user’s current membership state is join or ban, reject??? complement test looks failed.
// TestRestrictedRoomsRemoteJoinInMSC3787Room/Join_should_succeed_when_invited
if matches!(
current_target_user_membership,
MembershipState::Join | MembershipState::Ban
) {
tracing::warn!(
?current_target_user_membership,
"cannot invite user that is already joined or banned"
);
return Err(StateError::forbidden(
"cannot invite user that is joined or banned",
));
}
let creators = room_create_event.creators()?;
let room_power_levels_event = fetch_state.room_power_levels_event().await;
let sender_power_level =
room_power_levels_event.user_power_level(room_member_event.sender(), &creators, rules)?;
let invite_power_level =
room_power_levels_event.get_as_int_or_default(RoomPowerLevelsIntField::Invite, rules)?;
// Since v1, if the sender’s power level is greater than or equal to the invite
// level, allow.
//
// Otherwise, reject.
if sender_power_level >= invite_power_level {
Ok(())
} else {
Err(StateError::forbidden(
"sender does not have enough power to invite",
))
}
}
/// Check whether the `third_party_invite` from the `m.room.member` event passes the authorization
/// rules.
async fn check_third_party_invite<Pdu, Fetch, Fut>(
room_member_event: RoomMemberEvent<&Pdu>,
third_party_invite: &ThirdPartyInvite,
target_user: &UserId,
fetch_state: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(StateEventType, String) -> Fut + Sync,
Fut: Future<Output = StateResult<Pdu>> + Send,
Pdu: Event + Clone + Sync + Send,
{
let current_target_user_membership = fetch_state.user_membership(target_user).await?;
// Since v1, if target user is banned, reject.
if current_target_user_membership == MembershipState::Ban {
return Err(StateError::other("cannot invite user that is banned"));
}
// Since v1, if content.third_party_invite does not have a signed property, reject.
// Since v1, if signed does not have mxid and token properties, reject.
let third_party_invite_token = third_party_invite.token()?;
let third_party_invite_mxid = third_party_invite.mxid()?;
// Since v1, if mxid does not match state_key, reject.
if target_user != third_party_invite_mxid {
return Err(StateError::other(
"third-party invite mxid does not match target user",
));
}
// Since v1, if there is no m.room.third_party_invite event in the current room state with
// state_key matching token, reject.
let Some(room_third_party_invite_event) = fetch_state
.room_third_party_invite_event(third_party_invite_token)
.await
else {
return Err(StateError::other(
"no `m.room.third_party_invite` in room state matches the token",
));
};
// Since v1, if sender does not match sender of the m.room.third_party_invite, reject.
if room_member_event.sender() != room_third_party_invite_event.sender() {
return Err(StateError::other(
"sender of `m.room.third_party_invite` does not match sender of `m.room.member`",
));
}
let public_keys = room_third_party_invite_event.public_keys()?;
let signatures = third_party_invite.signatures()?;
let signed_canonical_json = third_party_invite.signed_canonical_json()?;
// Since v1, if any signature in signed matches any public key in the m.room.third_party_invite
// event, allow.
for entity_signatures_value in signatures.values() {
let Some(entity_signatures) = entity_signatures_value.as_object() else {
return Err(StateError::other(format!(
"unexpected format of `signatures` field in `third_party_invite.signed` \
of `m.room.member` event: expected a map of string to object, got {entity_signatures_value:?}"
)));
};
// We will ignore any error from now on, we just want to find a signature that can be
// verified from a public key.
for (key_id, signature_value) in entity_signatures {
let Ok(parsed_key_id) = <&SigningKeyId<AnyKeyName>>::try_from(key_id.as_str()) else {
continue;
};
let algorithm = parsed_key_id.algorithm();
let Some(signature_str) = signature_value.as_str() else {
continue;
};
let Ok(signature) = Base64::<Standard>::parse(signature_str) else {
continue;
};
for encoded_public_key in &public_keys {
let Ok(public_key) = encoded_public_key.decode() else {
continue;
};
if verify_canonical_json_bytes(
&algorithm,
&public_key,
signature.as_bytes(),
signed_canonical_json.as_bytes(),
)
.is_ok()
{
return Ok(());
}
}
}
}
// Otherwise, reject.
Err(StateError::other(
"no signature on third-party invite matches a public key \
in `m.room.third_party_invite` event",
))
}
/// Check whether the given event passes the `m.room.member` authorization rules with a membership
/// of `leave`.
async fn check_room_member_leave<Pdu, Fetch, Fut>(
room_member_event: RoomMemberEvent<&Pdu>,
target_user: &UserId,
rules: &AuthorizationRules,
room_create_event: RoomCreateEvent<&Pdu>,
fetch_state: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(StateEventType, String) -> Fut + Sync,
Fut: Future<Output = Result<Pdu, StateError>> + Send,
Pdu: Event + Clone + Sync + Send,
{
let sender_membership = fetch_state
.user_membership(room_member_event.sender())
.await?;
// v1-v6, if the sender matches state_key, allow if and only if that user’s current
// membership state is invite or join.
// Since v7, if the sender matches state_key, allow if and only if that user’s current
// membership state is invite, join, or knock.
if room_member_event.sender() == target_user {
let membership_is_invite_or_join = matches!(
sender_membership,
MembershipState::Join | MembershipState::Invite
);
let membership_is_knock = rules.knocking && sender_membership == MembershipState::Knock;
return if membership_is_invite_or_join || membership_is_knock {
Ok(())
} else {
Err(StateError::forbidden(
"cannot leave if not joined, invited or knocked",
))
};
}
// Since v1, if the sender’s current membership state is not join, reject.
if sender_membership != MembershipState::Join {
return Err(StateError::forbidden("cannot kick if sender is not joined"));
}
let creators = room_create_event.creators()?;
let room_power_levels_event = fetch_state.room_power_levels_event().await;
let current_target_user_membership = fetch_state.user_membership(target_user).await?;
let sender_power_level =
room_power_levels_event.user_power_level(room_member_event.sender(), &creators, rules)?;
let ban_power_level =
room_power_levels_event.get_as_int_or_default(RoomPowerLevelsIntField::Ban, rules)?;
// Since v1, if the target user’s current membership state is ban, and the sender’s
// power level is less than the ban level, reject.
if current_target_user_membership == MembershipState::Ban
&& sender_power_level < ban_power_level
{
return Err(StateError::forbidden(
"sender does not have enough power to unban",
));
}
let kick_power_level =
room_power_levels_event.get_as_int_or_default(RoomPowerLevelsIntField::Kick, rules)?;
let target_user_power_level =
room_power_levels_event.user_power_level(target_user, &creators, rules)?;
// Since v1, if the sender’s power level is greater than or equal to the kick level,
// and the target user’s power level is less than the sender’s power level, allow.
//
// Otherwise, reject.
if sender_power_level >= kick_power_level && target_user_power_level < sender_power_level {
Ok(())
} else {
Err(StateError::forbidden(
"sender does not have enough power to kick target user",
))
}
}
/// Check whether the given event passes the `m.room.member` authorization rules with a membership
/// of `ban`.
async fn check_room_member_ban<Pdu, Fetch, Fut>(
room_member_event: RoomMemberEvent<&Pdu>,
target_user: &UserId,
rules: &AuthorizationRules,
room_create_event: RoomCreateEvent<&Pdu>,
fetch_state: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(StateEventType, String) -> Fut + Sync,
Fut: Future<Output = Result<Pdu, StateError>> + Send,
Pdu: Event + Clone + Sync + Send,
{
let sender_membership = fetch_state
.user_membership(room_member_event.sender())
.await?;
// Since v1, if the sender’s current membership state is not join, reject.
if sender_membership != MembershipState::Join {
return Err(StateError::forbidden("cannot ban if sender is not joined"));
}
let creators = room_create_event.creators()?;
let room_power_levels_event = fetch_state.room_power_levels_event().await;
let sender_power_level =
room_power_levels_event.user_power_level(room_member_event.sender(), &creators, rules)?;
let ban_power_level =
room_power_levels_event.get_as_int_or_default(RoomPowerLevelsIntField::Ban, rules)?;
let target_user_power_level =
room_power_levels_event.user_power_level(target_user, &creators, rules)?;
// If the sender’s power level is greater than or equal to the ban level, and the
// target user’s power level is less than the sender’s power level, allow.
//
// Otherwise, reject.
if sender_power_level >= ban_power_level && target_user_power_level < sender_power_level {
Ok(())
} else {
Err(StateError::forbidden(
"sender does not have enough power to ban target user",
))
}
}
/// Check whether the given event passes the `m.room.member` authorization rules with a membership
/// of `knock`.
async fn check_room_member_knock<Pdu, Fetch, Fut>(
room_member_event: RoomMemberEvent<&Pdu>,
target_user: &UserId,
auth_rules: &AuthorizationRules,
fetch_state: &Fetch,
) -> StateResult<()>
where
Fetch: Fn(StateEventType, String) -> Fut + Sync,
Fut: Future<Output = Result<Pdu, StateError>> + Send,
Pdu: Event + Clone + Sync + Send,
{
let join_rule = fetch_state.join_rule().await?;
// TODO: Not same with ruma for testing?
// v7-v9, if the join_rule is anything other than knock, reject.
// Since v10, if the join_rule is anything other than knock or knock_restricted,
// reject.
if (!auth_rules.knock_restricted_join_rule && join_rule != JoinRuleKind::Knock)
|| (auth_rules.knock_restricted_join_rule
&& !matches!(join_rule, JoinRuleKind::KnockRestricted))
{
return Err(StateError::forbidden(
"join rule is not set to knock or knock_restricted, knocking is not allowed",
));
}
// Since v7, if sender does not match state_key, reject.
if room_member_event.sender() != target_user {
return Err(StateError::forbidden(
"cannot make another user knock, sender does not match target user",
));
}
let sender_membership = fetch_state
.user_membership(room_member_event.sender())
.await?;
// Since v7, if the sender’s current membership is not ban, invite, or join, allow.
// Otherwise, reject.
if !matches!(
sender_membership,
MembershipState::Ban | MembershipState::Invite | MembershipState::Join
) {
Ok(())
} else {
Err(StateError::forbidden(
"cannot knock if user is banned, invited or joined",
))
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/event_auth/tests.rs | crates/core/src/state/event_auth/tests.rs | use std::collections::BTreeMap;
use serde_json::{json, value::to_raw_value as to_raw_json_value};
mod room_power_levels;
use self::room_power_levels::default_room_power_levels;
use super::check_room_create;
use crate::{
ServerSignatures, UnixMillis, check_state_dependent_auth_rules,
check_state_independent_auth_rules,
event_auth::check_room_redaction,
events::{
RoomCreateEvent, RoomPowerLevelsEvent, TimelineEventType,
room::{
aliases::RoomAliasesEventContent, message::RoomMessageEventContent,
redaction::RoomRedactionEventContent,
},
},
owned_event_id, owned_room_alias_id, owned_room_id,
room_version_rules::AuthorizationRules,
test_utils::{
EventHash, INITIAL_EVENTS, INITIAL_V12_EVENTS, PduEvent, TestStateMap, alice, charlie,
ella, event_id, init_subscriber, member_content_join, room_create_v12_pdu_event, room_id,
room_redaction_pdu_event, room_third_party_invite, to_init_pdu_event, to_pdu_event,
to_v12_pdu_event,
},
user_id,
};
#[test]
fn valid_room_create() {
// Minimal fields valid for room v1.
let content = json!({
"creator": alice(),
});
let event = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V1).unwrap();
// Same, with room version.
let content = json!({
"creator": alice(),
"room_version": "2",
});
let event = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V1).unwrap();
// With a room version that does not need the creator.
let content = json!({
"room_version": "11",
});
let event = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V11).unwrap();
// Check various contents that might not match the definition of `m.room.create` in the
// spec, to ensure that we only care about a few fields.
let contents_to_check = vec![
// With an invalid predecessor, but we don't care about it. Inspired by a real-life
// example.
json!({
"room_version": "11",
"predecessor": "!XPoLiaavxVgyMSiRwK:localhost",
}),
// With an invalid type, but we don't care about it.
json!({
"room_version": "11",
"type": true,
}),
];
for content in contents_to_check {
let event = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V11).unwrap();
}
// Check `additional_creators` is allowed to contain invalid user IDs if the room version
// doesn't acknowledge them.
let content = json!({
"room_version": "11",
"additional_creators": ["@::example.org"]
});
let event = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V11).unwrap();
// Check `additional_creators` only contains valid user IDs.
let content = json!({
"room_version": "12",
"additional_creators": ["@alice:example.org"]
});
let event = room_create_v12_pdu_event("CREATE", alice(), to_raw_json_value(&content).unwrap());
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V12).unwrap();
}
#[test]
fn invalid_room_create() {
// With a prev event.
let content = json!({
"creator": alice(),
});
let event = to_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
&["OTHER_CREATE"],
&["OTHER_CREATE"],
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V1).unwrap_err();
// Sender with a different domain.
let creator = user_id!("@bot:bar");
let content = json!({
"creator": creator,
});
let event = to_init_pdu_event(
"CREATE",
creator,
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V1).unwrap_err();
// No creator in v1.
let content = json!({});
let event = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V1).unwrap_err();
// Check `additional_creators` only contains valid user IDs.
let content = json!({
"room_version": "12",
"additional_creators": ["@::example.org"]
});
let event = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&content).unwrap(),
);
check_room_create(RoomCreateEvent::new(event), &AuthorizationRules::V12).unwrap_err();
}
#[test]
fn redact_higher_power_level() {
let _guard = init_subscriber();
let incoming_event = room_redaction_pdu_event(
"HELLO",
charlie(),
owned_event_id!("$redacted_event:other.server"),
to_raw_json_value(&RoomRedactionEventContent::new_v1()).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let room_power_levels_event = Some(default_room_power_levels());
// Cannot redact if redact level is higher than user's.
check_room_redaction(
incoming_event,
room_power_levels_event,
&AuthorizationRules::V1,
0.into(),
)
.unwrap_err();
}
#[test]
fn redact_same_power_level() {
let _guard = init_subscriber();
let incoming_event = room_redaction_pdu_event(
"HELLO",
charlie(),
owned_event_id!("$redacted_event:other.server"),
to_raw_json_value(&RoomRedactionEventContent::new_v1()).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let room_power_levels_event = Some(RoomPowerLevelsEvent::new(to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100, charlie(): 50 } })).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
)));
// Can redact if redact level is same as user's.
check_room_redaction(
incoming_event,
room_power_levels_event,
&AuthorizationRules::V1,
50.into(),
)
.unwrap();
}
#[test]
fn redact_same_server() {
let _guard = init_subscriber();
let incoming_event = room_redaction_pdu_event(
"HELLO",
charlie(),
event_id("redacted_event"),
to_raw_json_value(&RoomRedactionEventContent::new_v1()).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let room_power_levels_event = Some(default_room_power_levels());
// Can redact if redact level is same as user's.
check_room_redaction(
incoming_event,
room_power_levels_event,
&AuthorizationRules::V1,
0.into(),
)
.unwrap();
}
#[test]
fn missing_room_create_in_state() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
init_events.remove(&event_id("CREATE"));
// Cannot accept event if no `m.room.create` in state.
check_state_independent_auth_rules(&AuthorizationRules::V6, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn reject_missing_room_create_auth_events() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["IMA", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
// Cannot accept event if no `m.room.create` in auth events.
check_state_independent_auth_rules(&AuthorizationRules::V6, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn no_federate_different_server() {
let _guard = init_subscriber();
let sender = user_id!("@aya:other.server");
let incoming_event = to_pdu_event(
"AYA_JOIN",
sender,
TimelineEventType::RoomMember,
Some(sender.as_str()),
member_content_join(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("CREATE")).unwrap() = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&json!({
"creator": alice(),
"m.federate": false,
}))
.unwrap(),
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Cannot accept event if not federating and different server.
check_state_dependent_auth_rules(&AuthorizationRules::V6, incoming_event, fetch_state)
.unwrap_err();
}
#[test]
fn no_federate_same_server() {
let _guard = init_subscriber();
let sender = user_id!("@aya:foo");
let incoming_event = to_pdu_event(
"AYA_JOIN",
sender,
TimelineEventType::RoomMember,
Some(sender.as_str()),
member_content_join(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("CREATE")).unwrap() = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&json!({
"creator": alice(),
"m.federate": false,
}))
.unwrap(),
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Accept event if not federating and same server.
check_state_dependent_auth_rules(&AuthorizationRules::V6, incoming_event, fetch_state).unwrap();
}
#[test]
fn room_aliases_no_state_key() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"ALIASES",
alice(),
TimelineEventType::RoomAliases,
None,
to_raw_json_value(&RoomAliasesEventContent::new(vec![
owned_room_alias_id!("#room:foo"),
owned_room_alias_id!("#room_alt:foo"),
]))
.unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Cannot accept `m.room.aliases` without state key.
check_state_dependent_auth_rules(&AuthorizationRules::V3, &incoming_event, fetch_state)
.unwrap_err();
// `m.room.aliases` is not checked since v6.
check_state_dependent_auth_rules(&AuthorizationRules::V8, &incoming_event, fetch_state)
.unwrap();
}
#[test]
fn room_aliases_other_server() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"ALIASES",
alice(),
TimelineEventType::RoomAliases,
Some("bar"),
to_raw_json_value(&RoomAliasesEventContent::new(vec![
owned_room_alias_id!("#room:bar"),
owned_room_alias_id!("#room_alt:bar"),
]))
.unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Cannot accept `m.room.aliases` with different server name than sender.
check_state_dependent_auth_rules(&AuthorizationRules::V3, &incoming_event, fetch_state)
.unwrap_err();
// `m.room.aliases` is not checked since v6.
check_state_dependent_auth_rules(&AuthorizationRules::V8, &incoming_event, fetch_state)
.unwrap();
}
#[test]
fn room_aliases_same_server() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"ALIASES",
alice(),
TimelineEventType::RoomAliases,
Some("foo"),
to_raw_json_value(&RoomAliasesEventContent::new(vec![
owned_room_alias_id!("#room:foo"),
owned_room_alias_id!("#room_alt:foo"),
]))
.unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Accept `m.room.aliases` with same server name as sender.
check_state_dependent_auth_rules(&AuthorizationRules::V3, &incoming_event, fetch_state)
.unwrap();
// `m.room.aliases` is not checked since v6.
check_state_dependent_auth_rules(&AuthorizationRules::V8, &incoming_event, fetch_state)
.unwrap();
}
#[test]
fn sender_not_in_room() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
ella(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["IMA", "IPOWER", "CREATE"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Cannot accept event if user not in room.
check_state_dependent_auth_rules(&AuthorizationRules::V6, incoming_event, fetch_state)
.unwrap_err();
}
#[test]
fn room_third_party_invite_not_enough_power() {
let _guard = init_subscriber();
let incoming_event = room_third_party_invite(charlie());
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IPOWER")).unwrap() = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({
"users": { alice(): 100 },
"invite": 50,
}))
.unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Cannot accept `m.room.third_party_invite` if not enough power.
check_state_dependent_auth_rules(&AuthorizationRules::V6, incoming_event, fetch_state)
.unwrap_err();
}
#[test]
fn room_third_party_invite_with_enough_power() {
let _guard = init_subscriber();
let incoming_event = room_third_party_invite(charlie());
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Accept `m.room.third_party_invite` if enough power.
check_state_dependent_auth_rules(&AuthorizationRules::V6, incoming_event, fetch_state).unwrap();
}
#[test]
fn event_type_not_enough_power() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IPOWER")).unwrap() = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({
"users": { alice(): 100 },
"events": {
"m.room.message": "50",
},
}))
.unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Cannot send event if not enough power for the event's type.
check_state_dependent_auth_rules(&AuthorizationRules::V6, incoming_event, fetch_state)
.unwrap_err();
}
#[test]
fn user_id_state_key_not_sender() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
"dev.ruma.fake_state_event".into(),
Some(ella().as_str()),
to_raw_json_value(&json!({})).unwrap(),
&["IMA", "IPOWER", "CREATE"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Cannot send state event with a user ID as a state key that doesn't match the sender.
check_state_dependent_auth_rules(&AuthorizationRules::V6, incoming_event, fetch_state)
.unwrap_err();
}
#[test]
fn user_id_state_key_is_sender() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
"dev.ruma.fake_state_event".into(),
Some(alice().as_str()),
to_raw_json_value(&json!({})).unwrap(),
&["IMA", "IPOWER", "CREATE"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
// Can send state event with a user ID as a state key that matches the sender.
check_state_dependent_auth_rules(&AuthorizationRules::V6, incoming_event, fetch_state).unwrap();
}
#[test]
fn auth_event_in_different_room() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
let power_level = PduEvent {
event_id: event_id("IPOWER"),
room_id: Some(owned_room_id!("!wrongroom:foo")),
sender: alice().to_owned(),
origin_server_ts: UnixMillis(3),
state_key: Some(String::new()),
kind: TimelineEventType::RoomPowerLevels,
content: to_raw_json_value(&json!({ "users": { alice(): 100 } })).unwrap(),
redacts: None,
unsigned: BTreeMap::new(),
auth_events: vec![event_id("CREATE"), event_id("IMA")],
prev_events: vec![event_id("IMA")],
depth: 0,
hashes: EventHash {
sha256: "".to_owned(),
},
signatures: ServerSignatures::default(),
rejected: false,
};
init_events
.insert(power_level.event_id.clone(), power_level.into())
.unwrap();
// Cannot accept with auth event in different room.
check_state_independent_auth_rules(&AuthorizationRules::V6, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn duplicate_auth_event_type() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["CREATE", "IMA", "IMA2", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
init_events.insert(
event_id("IMA2"),
to_pdu_event(
"IMA2",
alice(),
TimelineEventType::RoomMember,
Some(alice().as_str()),
member_content_join(),
&["CREATE", "IMA"],
&["IMA"],
),
);
// Cannot accept with two auth events with same (type, state_key) pair.
check_state_independent_auth_rules(&AuthorizationRules::V6, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn unexpected_auth_event_type() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["CREATE", "IMA", "IPOWER", "IMC"],
&["IMC"],
);
let mut init_events = INITIAL_EVENTS();
init_events.insert(
event_id("IMC"),
to_pdu_event(
"IMC",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
),
);
// Cannot accept with auth event with unexpected (type, state_key) pair.
check_state_independent_auth_rules(&AuthorizationRules::V6, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn rejected_auth_event() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
let power_level = PduEvent {
event_id: event_id("IPOWER"),
room_id: Some(room_id().to_owned()),
sender: alice().to_owned(),
origin_server_ts: UnixMillis(3),
state_key: Some(String::new()),
kind: TimelineEventType::RoomPowerLevels,
content: to_raw_json_value(&json!({ "users": { alice(): 100 } })).unwrap(),
redacts: None,
unsigned: BTreeMap::new(),
auth_events: vec![event_id("CREATE"), event_id("IMA")],
prev_events: vec![event_id("IMA")],
depth: 0,
hashes: EventHash {
sha256: "".to_owned(),
},
signatures: ServerSignatures::default(),
rejected: true,
};
init_events
.insert(power_level.event_id.clone(), power_level.into())
.unwrap();
// Cannot accept with auth event that was rejected.
check_state_independent_auth_rules(&AuthorizationRules::V6, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn room_create_with_allowed_or_rejected_room_id() {
// v11, room_id is required.
let v11_content = json!({
"room_version": "11",
});
let event_with_room_id = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&v11_content).unwrap(),
);
check_room_create(
RoomCreateEvent::new(event_with_room_id),
&AuthorizationRules::V11,
)
.unwrap();
let event_no_room_id =
room_create_v12_pdu_event("CREATE", alice(), to_raw_json_value(&v11_content).unwrap());
check_room_create(
RoomCreateEvent::new(event_no_room_id),
&AuthorizationRules::V11,
)
.unwrap_err();
// v12, room_id is rejected.
let v12_content = json!({
"room_version": "12",
});
let event_with_room_id = to_init_pdu_event(
"CREATE",
alice(),
TimelineEventType::RoomCreate,
Some(""),
to_raw_json_value(&v12_content).unwrap(),
);
check_room_create(
RoomCreateEvent::new(event_with_room_id),
&AuthorizationRules::V12,
)
.unwrap_err();
let event_no_room_id =
room_create_v12_pdu_event("CREATE", alice(), to_raw_json_value(&v12_content).unwrap());
check_room_create(
RoomCreateEvent::new(event_no_room_id),
&AuthorizationRules::V12,
)
.unwrap();
}
#[test]
fn event_without_room_id() {
let _guard = init_subscriber();
let incoming_event = PduEvent {
event_id: owned_event_id!("$HELLO"),
room_id: None,
sender: alice().to_owned(),
origin_server_ts: UnixMillis(3),
state_key: None,
kind: TimelineEventType::RoomMessage,
content: to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
redacts: None,
unsigned: BTreeMap::new(),
auth_events: vec![
owned_event_id!("$CREATE"),
owned_event_id!("$IMA"),
owned_event_id!("$IPOWER"),
],
prev_events: vec![owned_event_id!("$IPOWER")],
depth: 0,
hashes: EventHash {
sha256: "".to_owned(),
},
signatures: ServerSignatures::default(),
rejected: false,
};
let init_events = INITIAL_V12_EVENTS();
// Cannot accept event without room ID.
check_state_independent_auth_rules(&AuthorizationRules::V11, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn allow_missing_room_create_auth_events() {
let _guard = init_subscriber();
let incoming_event = to_v12_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["IMA", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_V12_EVENTS();
// Accept event if no `m.room.create` in auth events.
check_state_independent_auth_rules(&AuthorizationRules::V12, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap();
}
#[test]
fn reject_room_create_in_auth_events() {
let _guard = init_subscriber();
let incoming_event = to_v12_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_V12_EVENTS();
// Reject event if `m.room.create` in auth events.
check_state_independent_auth_rules(&AuthorizationRules::V12, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn missing_room_create_in_fetch_event() {
let _guard = init_subscriber();
let incoming_event = to_v12_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_V12_EVENTS();
init_events.remove(&owned_event_id!("$CREATE")).unwrap();
// Reject event if `m.room.create` can't be found.
check_state_independent_auth_rules(&AuthorizationRules::V12, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
#[test]
fn rejected_room_create_in_fetch_event() {
let _guard = init_subscriber();
let incoming_event = to_v12_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMessage,
None,
to_raw_json_value(&RoomMessageEventContent::text_plain("Hi!")).unwrap(),
&["IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_V12_EVENTS();
let create_event_id = owned_event_id!("$CREATE");
let mut create_event =
std::sync::Arc::into_inner(init_events.remove(&create_event_id).unwrap()).unwrap();
create_event.rejected = true;
init_events.insert(create_event_id, create_event.into());
// Reject event if `m.room.create` was rejected.
check_state_independent_auth_rules(&AuthorizationRules::V12, incoming_event, |event_id| {
init_events.get(event_id)
})
.unwrap_err();
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/event_auth/room_member/tests.rs | crates/core/src/state/event_auth/room_member/tests.rs | use crate::events::{
TimelineEventType,
room::{
join_rules::{JoinRule, Restricted, RoomJoinRulesEventContent},
member::{MembershipState, RoomMemberEventContent, SignedContent, ThirdPartyInvite},
third_party_invite::RoomThirdPartyInviteEventContent,
},
};
use palpo_core::{
Signatures, room_version_rules::AuthorizationRules, serde::RawJson,
third_party_invite::IdentityServerBase64PublicKey,
};
use serde_json::{json, value::to_raw_value as to_raw_json_value};
use super::check_room_member;
use crate::{
events::RoomMemberEvent,
test_utils::{
INITIAL_EVENTS, INITIAL_EVENTS_CREATE_ROOM, TestStateMap, alice, bob, charlie, ella,
event_id, init_subscriber, member_content_ban, member_content_join,
room_third_party_invite, to_pdu_event, zara,
},
};
#[tokio::test]
async fn missing_state_key() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
None,
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Event should have a state key.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn missing_membership() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
to_raw_json_value(&json!({})).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Content should at least include `membership`.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_after_create_creator_match() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMember,
Some(alice().as_str()),
member_content_join(),
&["CREATE"],
&["CREATE"],
);
let init_events = INITIAL_EVENTS_CREATE_ROOM();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Before v11, the `creator` of `m.room.create` must be the same as the state key.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap();
}
#[tokio::test]
async fn join_after_create_creator_mismatch() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE"],
&["CREATE"],
);
let init_events = INITIAL_EVENTS_CREATE_ROOM();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Before v11, the `creator` of `m.room.create` must be the same as the state key.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_after_create_sender_match() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
alice(),
TimelineEventType::RoomMember,
Some(alice().as_str()),
member_content_join(),
&["CREATE"],
&["CREATE"],
);
let init_events = INITIAL_EVENTS_CREATE_ROOM();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v11, the `sender` of `m.room.create` must be the same as the state key.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V11,
room_create_event,
fetch_state,
)
.await
.unwrap();
}
#[tokio::test]
async fn join_after_create_sender_mismatch() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE"],
&["CREATE"],
);
let init_events = INITIAL_EVENTS_CREATE_ROOM();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v11, the `sender` of `m.room.create` must be the same as the state key.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V11,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_sender_state_key_mismatch() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(alice().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// For join events, the sender must be the same as the state key.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_banned() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IMC")).unwrap() = to_pdu_event(
"IMC",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_ban(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// A user cannot join if they are banned.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_invite_join_rule_already_joined() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Invite)).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// A user can send a join event in a room with `invite` join rule if they already joined.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap();
}
#[tokio::test]
async fn join_knock_join_rule_already_invited() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IMC")).unwrap() = to_pdu_event(
"IMC",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
to_raw_json_value(&RoomMemberEventContent::new(MembershipState::Invite)).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
);
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Knock)).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v7, a user can send a join event in a room with `knock` join rule if they are were
// invited.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V7,
room_create_event,
fetch_state,
)
.await
.unwrap();
}
#[tokio::test]
async fn join_knock_join_rule_not_supported() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Knock)).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Before v7, a user CANNOT send a join event in a room with `knock` join rule. Servers should
// not allow that join rule if it's not supported by the room version, but this is good
// for coverage.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_restricted_join_rule_not_supported() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Restricted(
Restricted::new(vec![]),
)))
.unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Before v8, a user CANNOT send a join event in a room with `restricted` join rule. Servers
// should not allow that join rule if it's not supported by the room version, but this is good
// for coverage.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_knock_restricted_join_rule_not_supported() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::KnockRestricted(
Restricted::new(vec![]),
)))
.unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Before v10, a user CANNOT send a join event in a room with `knock_restricted` join rule.
// Servers should not allow that join rule if it's not supported by the room version, but
// this is good for coverage.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V6,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_restricted_join_rule_already_joined() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Restricted(
Restricted::new(vec![]),
)))
.unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v8, a user can send a join event in a room with `restricted` join rule if they already
// joined.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap();
}
#[tokio::test]
async fn join_knock_restricted_join_rule_already_invited() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
member_content_join(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IMC")).unwrap() = to_pdu_event(
"IMC",
charlie(),
TimelineEventType::RoomMember,
Some(charlie().as_str()),
to_raw_json_value(&RoomMemberEventContent::new(MembershipState::Invite)).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IMB"],
);
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::KnockRestricted(
Restricted::new(vec![]),
)))
.unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v10, a user can send a join event in a room with `knock_restricted` join rule if they
// were invited.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V10,
room_create_event,
fetch_state,
)
.await
.unwrap();
}
#[tokio::test]
async fn join_restricted_join_rule_missing_join_authorised_via_users_server() {
let _guard = init_subscriber();
let incoming_event = to_pdu_event(
"HELLO",
ella(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
member_content_join(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Restricted(
Restricted::new(vec![]),
)))
.unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v8, a user CANNOT join event in a room with `restricted` join rule if there is no
// `join_authorised_via_users_server` property.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_restricted_join_rule_authorised_via_user_not_in_room() {
let _guard = init_subscriber();
let mut content = RoomMemberEventContent::new(MembershipState::Join);
content.join_authorized_via_users_server = Some(zara().to_owned());
let incoming_event = to_pdu_event(
"HELLO",
ella(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Restricted(
Restricted::new(vec![]),
)))
.unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v8, a user CANNOT join event in a room with `restricted` join rule if they were
// authorized by a user not in the room.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_restricted_join_rule_authorised_via_user_with_not_enough_power() {
let _guard = init_subscriber();
let mut content = RoomMemberEventContent::new(MembershipState::Join);
content.join_authorized_via_users_server = Some(charlie().to_owned());
let incoming_event = to_pdu_event(
"HELLO",
ella(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
*init_events.get_mut(&event_id("IPOWER")).unwrap() = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100 }, "invite": 50 })).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Restricted(
Restricted::new(vec![]),
)))
.unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v8, a user CANNOT join event in a room with `restricted` join rule if they were
// authorized by a user with not enough power.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn join_restricted_join_rule_authorised_via_user() {
let _guard = init_subscriber();
// Check various contents that might not match the definition of `m.room.join_rules` in the
// spec, to ensure that we only care about the `join_rule` field.
let join_rules_to_check = [
// Valid content, but we don't care about the allow rules.
to_raw_json_value(&RoomJoinRulesEventContent::new(JoinRule::Restricted(
Restricted::new(vec![]),
)))
.unwrap(),
// Invalid room ID, real-life example from <https://github.com/ruma/ruma/issues/1867>.
to_raw_json_value(&json!({
"allow": [
{
"room_id": "",
"type": "m.room_membership",
},
],
"join_rule": "restricted",
}))
.unwrap(),
// Missing room ID.
to_raw_json_value(&json!({
"allow": [
{
"type": "m.room_membership",
},
],
"join_rule": "restricted",
}))
.unwrap(),
];
let mut content = RoomMemberEventContent::new(MembershipState::Join);
content.join_authorized_via_users_server = Some(charlie().to_owned());
let incoming_event = to_pdu_event(
"HELLO",
ella(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
);
let mut init_events = INITIAL_EVENTS();
for join_rule_content in join_rules_to_check {
*init_events.get_mut(&event_id("IJR")).unwrap() = to_pdu_event(
"IJR",
alice(),
TimelineEventType::RoomJoinRules,
Some(""),
join_rule_content,
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Since v8, a user can join event in a room with `restricted` join rule if they were
// authorized by a user with enough power.
check_room_member(
RoomMemberEvent::new(&incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap();
}
}
#[tokio::test]
async fn join_public_join_rule() {
let _guard = init_subscriber();
// Check various contents that might not match the definition of `m.room.member` in the
// spec, to ensure that we only care about a few fields.
let contents_to_check = [
// Valid content.
member_content_join(),
// Invalid displayname.
to_raw_json_value(&json!({
"membership": "join",
"displayname": 203,
}))
.unwrap(),
// Invalid is_direct.
to_raw_json_value(&json!({
"membership": "join",
"is_direct": "yes",
}))
.unwrap(),
];
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
for content in contents_to_check {
let incoming_event = to_pdu_event(
"HELLO",
ella(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
content,
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// A user can join a room with a `public` join rule.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event.clone(),
fetch_state,
)
.await
.unwrap();
}
}
#[tokio::test]
async fn invite_via_third_party_invite_banned() {
let _guard = init_subscriber();
let mut content = RoomMemberEventContent::new(MembershipState::Invite);
content.third_party_invite = Some(ThirdPartyInvite::new(
"e..@p..".to_owned(),
SignedContent::new(
Signatures::new(),
ella().to_owned(),
"somerandomtoken".to_owned(),
),
));
let incoming_event = to_pdu_event(
"HELLO",
ella(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "BAN", "IPOWER"],
&["BAN"],
);
let mut init_events = INITIAL_EVENTS();
init_events.insert(
event_id("BAN"),
to_pdu_event(
"BAN",
alice(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
member_content_ban(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
),
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// A user cannot be invited via third party invite if they were banned.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn invite_via_third_party_invite_missing_signed() {
let _guard = init_subscriber();
let content = json!({
"membership": "invite",
"third_party_invite": {
"display_name": "e..@p..",
},
});
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Third party invite content must have a `joined` property.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn invite_via_third_party_invite_missing_mxid() {
let _guard = init_subscriber();
let content = json!({
"membership": "invite",
"third_party_invite": {
"display_name": "e..@p..",
"signed": {
"token": "somerandomtoken",
},
},
});
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Third party invite content must have a `joined.mxid` property.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn invite_via_third_party_invite_missing_token() {
let _guard = init_subscriber();
let content = json!({
"membership": "invite",
"third_party_invite": {
"display_name": "e..@p..",
"signed": {
"mxid": ella(),
},
},
});
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// Third party invite content must have a `joined.token` property.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn invite_via_third_party_invite_mxid_mismatch() {
let _guard = init_subscriber();
let mut content = RoomMemberEventContent::new(MembershipState::Invite);
content.third_party_invite = Some(ThirdPartyInvite::new(
"z..@p..".to_owned(),
SignedContent::new(
Signatures::new(),
zara().to_owned(),
"somerandomtoken".to_owned(),
),
));
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
);
let init_events = INITIAL_EVENTS();
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// `mxid` of third party invite must match state key.
check_room_member(
RoomMemberEvent::new(incoming_event),
&AuthorizationRules::V8,
room_create_event,
fetch_state,
)
.await
.unwrap_err();
}
#[tokio::test]
async fn invite_via_third_party_invite_missing_room_third_party_invite() {
let _guard = init_subscriber();
let mut content = RoomMemberEventContent::new(MembershipState::Invite);
content.third_party_invite = Some(ThirdPartyInvite::new(
"e..@p..".to_owned(),
SignedContent::new(
Signatures::new(),
ella().to_owned(),
"somerandomtoken".to_owned(),
),
));
let incoming_event = to_pdu_event(
"HELLO",
charlie(),
TimelineEventType::RoomMember,
Some(ella().as_str()),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IJR", "IPOWER", "THIRDPARTY"],
&["THIRDPARTY"],
);
let mut init_events = INITIAL_EVENTS();
init_events.insert(
event_id("THIRD_PARTY"),
to_pdu_event(
"THIRDPARTY",
charlie(),
TimelineEventType::RoomThirdPartyInvite,
Some("wrong_token"),
to_raw_json_value(&RoomThirdPartyInviteEventContent::new(
"e..@p..".to_owned(),
"http://host.local/check/public_key".to_owned(),
IdentityServerBase64PublicKey::new(b"public_key"),
))
.unwrap(),
&["CREATE", "IJR", "IPOWER"],
&["IPOWER"],
),
);
let auth_events = TestStateMap::new(&init_events);
let fetch_state = auth_events.fetch_state_fn();
let room_create_event = auth_events.room_create_event();
// There must be an `m.room.third_party_invite` event with the same token in the state.
check_room_member(
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | true |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/event_auth/tests/room_power_levels.rs | crates/core/src/state/event_auth/tests/room_power_levels.rs | use std::{collections::HashSet, sync::Arc};
use crate::events::{TimelineEventType, room::power_levels::UserPowerLevel};
use as_variant::as_variant;
use palpo_core::room_version_rules::AuthorizationRules;
use serde_json::{
Value as JsonValue, json,
value::{Map as JsonMap, to_raw_value as to_raw_json_value},
};
use tracing::info;
use crate::{
event_auth::check_room_power_levels,
events::RoomPowerLevelsEvent,
test_utils::{PduEvent, alice, bob, init_subscriber, to_pdu_event, zara},
};
/// The default `m.room.power_levels` event when creating a public room.
pub(super) fn default_room_power_levels() -> RoomPowerLevelsEvent<Arc<PduEvent>> {
RoomPowerLevelsEvent::new(to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&json!({ "users": { alice(): 100 } })).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
))
}
#[test]
fn not_int_or_string_int_in_content() {
let _guard = init_subscriber();
let original_content = json!({
"users": { alice(): 100 },
});
let original_content_object = as_variant!(original_content, JsonValue::Object).unwrap();
let current_room_power_levels_event = Some(default_room_power_levels());
let int_fields = &[
"users_default",
"events_default",
"state_default",
"ban",
"redact",
"kick",
"invite",
];
// Tuples of (is_string, is_int) booleans.
let combinations = &[(true, false), (true, true), (false, true)];
for field in int_fields {
for (is_string, is_int) in combinations {
info!(?field, ?is_string, ?is_int, "checking field");
let value = match (is_string, is_int) {
(true, false) => "foo".into(),
(true, true) => "50".into(),
(false, true) => 50.into(),
_ => unreachable!(),
};
let mut content_object = original_content_object.clone();
content_object.insert((*field).to_owned(), value);
let incoming_event = to_pdu_event(
"IPOWER2",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&content_object).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// String that is not a number is not accepted.
let v6_result = check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event.clone(),
&AuthorizationRules::V6,
100.into(),
&HashSet::new(),
);
if *is_int {
v6_result.unwrap();
} else {
v6_result.unwrap_err();
}
// String is not accepted.
let v10_result = check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event.clone(),
&AuthorizationRules::V10,
100.into(),
&HashSet::new(),
);
if *is_string {
v10_result.unwrap_err();
} else {
v10_result.unwrap();
}
}
}
}
#[test]
fn not_int_or_string_int_in_events() {
let _guard = init_subscriber();
let original_content = json!({
"users": { alice(): 100 },
});
let original_content_object = as_variant!(original_content, JsonValue::Object).unwrap();
let current_room_power_levels_event = Some(default_room_power_levels());
// Tuples of (is_string, is_int) booleans.
let combinations = &[(true, false), (true, true), (false, true)];
for (is_string, is_int) in combinations {
info!(?is_string, ?is_int, "checking field");
let value = match (is_string, is_int) {
(true, false) => "foo".into(),
(true, true) => "50".into(),
(false, true) => 50.into(),
_ => unreachable!(),
};
let mut events_object = JsonMap::new();
events_object.insert("bar".to_owned(), value);
let mut content_object = original_content_object.clone();
content_object.insert("events".to_owned(), events_object.into());
let incoming_event = to_pdu_event(
"IPOWER2",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&content_object).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// String that is not a number is not accepted.
let v6_result = check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event.clone(),
&AuthorizationRules::V6,
100.into(),
&HashSet::new(),
);
if *is_int {
v6_result.unwrap();
} else {
v6_result.unwrap_err();
}
// String is not accepted.
let v10_result = check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event.clone(),
&AuthorizationRules::V10,
100.into(),
&HashSet::new(),
);
if *is_string {
v10_result.unwrap_err();
} else {
v10_result.unwrap();
}
}
}
#[test]
fn not_int_or_string_int_in_notifications() {
let _guard = init_subscriber();
let original_content = json!({
"users": { alice(): 100 },
});
let original_content_object = as_variant!(original_content, JsonValue::Object).unwrap();
let current_room_power_levels_event = Some(default_room_power_levels());
// Tuples of (is_string, is_int) booleans.
let combinations = &[(true, false), (true, true), (false, true)];
for (is_string, is_int) in combinations {
info!(?is_string, ?is_int, "checking field");
let value = match (is_string, is_int) {
(true, false) => "foo".into(),
(true, true) => "50".into(),
(false, true) => 50.into(),
_ => unreachable!(),
};
let mut notifications_object = JsonMap::new();
notifications_object.insert("room".to_owned(), value);
let mut content_object = original_content_object.clone();
content_object.insert("notifications".to_owned(), notifications_object.into());
let incoming_event = to_pdu_event(
"IPOWER2",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&content_object).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// String that is not a number is not accepted.
let v6_result = check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event.clone(),
&AuthorizationRules::V6,
100.into(),
&HashSet::new(),
);
if *is_int {
v6_result.unwrap();
} else {
v6_result.unwrap_err();
}
// String is not accepted.
let v10_result = check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event.clone(),
&AuthorizationRules::V10,
100.into(),
&HashSet::new(),
);
if *is_string {
v10_result.unwrap_err();
} else {
v10_result.unwrap();
}
}
}
#[test]
fn not_user_id_in_users() {
let _guard = init_subscriber();
let content = json!({
"users": {
alice(): 100,
"spambot": -1,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
let current_room_power_levels_event = Some(default_room_power_levels());
// Key that is not a user ID is not accepted.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event,
&AuthorizationRules::V6,
100.into(),
&HashSet::new(),
)
.unwrap_err();
}
#[test]
fn not_int_or_string_int_in_users() {
let _guard = init_subscriber();
let original_content = json!({
"users": {
alice(): 100,
},
});
let original_content_object = as_variant!(original_content, JsonValue::Object).unwrap();
let current_room_power_levels_event = Some(default_room_power_levels());
// Tuples of (is_string, is_int) booleans.
let combinations = &[(true, false), (true, true), (false, true)];
for (is_string, is_int) in combinations {
info!(?is_string, ?is_int, "checking field");
let value = match (is_string, is_int) {
(true, false) => "foo".into(),
(true, true) => "50".into(),
(false, true) => 50.into(),
_ => unreachable!(),
};
let mut content_object = original_content_object.clone();
let users_object = content_object
.get_mut("users")
.unwrap()
.as_object_mut()
.unwrap();
users_object.insert("@bar:baz".to_owned(), value);
let incoming_event = to_pdu_event(
"IPOWER2",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&content_object).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// String that is not a number is not accepted.
let v6_result = check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event.clone(),
&AuthorizationRules::V6,
100.into(),
&HashSet::new(),
);
if *is_int {
v6_result.unwrap();
} else {
v6_result.unwrap_err();
}
// String is not accepted.
let v10_result = check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event.clone(),
&AuthorizationRules::V10,
100.into(),
&HashSet::new(),
);
if *is_string {
v10_result.unwrap_err();
} else {
v10_result.unwrap();
}
}
}
#[test]
fn first_power_levels_event() {
let _guard = init_subscriber();
let content = json!({
"users": {
alice(): 100,
},
});
let incoming_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let current_room_power_levels_event = None::<RoomPowerLevelsEvent<PduEvent>>;
// First power levels event is accepted.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
current_room_power_levels_event,
&AuthorizationRules::V6,
100.into(),
&HashSet::new(),
)
.unwrap();
}
#[test]
fn change_content_level_with_current_higher_power_level() {
let _guard = init_subscriber();
let original_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
});
let original_content_object = as_variant!(original_content, JsonValue::Object).unwrap();
let int_fields = &[
"users_default",
"events_default",
"state_default",
"ban",
"redact",
"kick",
"invite",
];
for field in int_fields {
info!(?field, "checking field");
let current_value = 60;
let incoming_value = 40;
let mut current_content_object = original_content_object.clone();
current_content_object.insert((*field).to_owned(), current_value.into());
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content_object).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let mut incoming_content_object = original_content_object.clone();
incoming_content_object.insert((*field).to_owned(), incoming_value.into());
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content_object).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Cannot change from a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(current_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
}
#[test]
fn change_content_level_with_new_higher_power_level() {
let _guard = init_subscriber();
let original_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
});
let original_content_object = as_variant!(original_content, JsonValue::Object).unwrap();
let int_fields = &[
"users_default",
"events_default",
"state_default",
"ban",
"redact",
"kick",
"invite",
];
for field in int_fields {
info!(?field, "checking field");
let current_value = 40;
let incoming_value = 60;
let mut current_content_object = original_content_object.clone();
current_content_object.insert((*field).to_owned(), current_value.into());
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content_object).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let mut incoming_content_object = original_content_object.clone();
incoming_content_object.insert((*field).to_owned(), incoming_value.into());
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content_object).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Cannot change to a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(current_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
}
#[test]
fn change_content_level_with_same_power_level() {
let _guard = init_subscriber();
let original_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
});
let original_content_object = as_variant!(original_content, JsonValue::Object).unwrap();
let int_fields = &[
"users_default",
"events_default",
"state_default",
"ban",
"redact",
"kick",
"invite",
];
for field in int_fields {
info!(?field, "checking field");
let current_value = 30;
let incoming_value = 40;
let mut current_content_object = original_content_object.clone();
current_content_object.insert((*field).to_owned(), current_value.into());
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content_object).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let mut incoming_content_object = original_content_object.clone();
incoming_content_object.insert((*field).to_owned(), incoming_value.into());
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content_object).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Can change a power level that is the same or lower than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(current_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap();
}
}
#[test]
fn change_events_level_with_current_higher_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"events": {
"foo": 60,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"events": {
"foo": 40,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Cannot change from a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(current_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
#[test]
fn change_events_level_with_new_higher_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"events": {
"foo": 30,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"events": {
"foo": 60,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Cannot change to a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(current_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
#[test]
fn change_events_level_with_same_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"events": {
"foo": 40,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"events": {
"foo": 10,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Can change a power level that is the same or lower than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(current_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap();
}
#[test]
fn change_notifications_level_with_current_higher_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"notifications": {
"room": 60,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"notifications": {
"room": 40,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Notifications are not checked before v6.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V3,
40.into(),
&HashSet::new(),
)
.unwrap();
// Cannot change from a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
#[test]
fn change_notifications_level_with_new_higher_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"notifications": {
"room": 30,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"notifications": {
"room": 60,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Notifications are not checked before v6.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V3,
40.into(),
&HashSet::new(),
)
.unwrap();
// Cannot change to a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
#[test]
fn change_notifications_level_with_same_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"notifications": {
"room": 30,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
"notifications": {
"room": 31,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Notifications are not checked before v6.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V3,
40.into(),
&HashSet::new(),
)
.unwrap();
// Can change a power level that is the same or lower than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap();
}
#[test]
fn change_other_user_level_with_current_higher_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
zara(): 70,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Cannot change from a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
#[test]
fn change_other_user_level_with_new_higher_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
zara(): 10,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
zara(): 45,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Cannot change to a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
#[test]
fn change_other_user_level_with_same_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
zara(): 20,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 40,
zara(): 40,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Can change a power level that is the same or lower than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap();
}
#[test]
fn change_own_user_level_to_new_higher_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 100,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Cannot change to a power level that is higher than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap_err();
}
#[test]
fn change_own_user_level_to_lower_power_level() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
alice(): 100,
bob(): 40,
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
alice(): 100,
bob(): 20,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
bob(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(&incoming_content).unwrap(),
&["CREATE", "IMA", "IPOWER"],
&["IPOWER"],
);
// Can change own power level to a lower level than the user.
check_room_power_levels(
RoomPowerLevelsEvent::new(&incoming_event),
Some(RoomPowerLevelsEvent::new(¤t_room_power_levels_event)),
&AuthorizationRules::V6,
40.into(),
&HashSet::new(),
)
.unwrap();
}
#[test]
fn creator_has_infinite_power() {
let _guard = init_subscriber();
let current_content = json!({
"users": {
bob(): i64::from(i64::MAX),
},
});
let current_room_power_levels_event = to_pdu_event(
"IPOWER",
alice(),
TimelineEventType::RoomPowerLevels,
Some(""),
to_raw_json_value(¤t_content).unwrap(),
&["CREATE", "IMA"],
&["IMA"],
);
let incoming_content = json!({
"users": {
bob(): 0,
},
});
let incoming_event = to_pdu_event(
"IPOWER2",
alice(),
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | true |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/events/third_party_invite.rs | crates/core/src/state/events/third_party_invite.rs | //! Types to deserialize `m.room.third_party_invite` events.
use std::{collections::BTreeSet, ops::Deref};
use serde::Deserialize;
use crate::state::Event;
use crate::{serde::from_raw_json_value, third_party_invite::IdentityServerBase64PublicKey};
/// A helper type for an [`Event`] of type `m.room.third_party_invite`.
///
/// This is a type that deserializes each field lazily, when requested.
#[derive(Debug, Clone)]
pub struct RoomThirdPartyInviteEvent<E: Event>(E);
impl<E: Event> RoomThirdPartyInviteEvent<E> {
/// Construct a new `RoomThirdPartyInviteEvent` around the given event.
pub fn new(event: E) -> Self {
Self(event)
}
/// The public keys of the identity server that might be used to sign the third-party invite.
pub fn public_keys(&self) -> Result<BTreeSet<IdentityServerBase64PublicKey>, String> {
#[derive(Deserialize)]
struct RoomThirdPartyInviteContentPublicKeys {
public_key: Option<IdentityServerBase64PublicKey>,
#[serde(default)]
public_keys: Vec<PublicKey>,
}
#[derive(Deserialize)]
struct PublicKey {
public_key: IdentityServerBase64PublicKey,
}
let content: RoomThirdPartyInviteContentPublicKeys = from_raw_json_value(self.content())
.map_err(|err: serde_json::Error| {
format!("invalid `public_key` or `public_keys` field in `m.room.third_party_invite` event: {err}")
})?;
Ok(content
.public_key
.into_iter()
.chain(content.public_keys.into_iter().map(|k| k.public_key))
.collect())
}
}
impl<E: Event> Deref for RoomThirdPartyInviteEvent<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.0
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/events/power_levels.rs | crates/core/src/state/events/power_levels.rs | //! Types to deserialize `m.room.power_levels` events.
use std::{
collections::{BTreeMap, HashSet},
ops::Deref,
sync::{Arc, Mutex, OnceLock},
};
use serde::de::DeserializeOwned;
use serde_json::{Error, from_value as from_json_value};
use super::Event;
use crate::events::{TimelineEventType, room::power_levels::UserPowerLevel};
use crate::state::{StateError, StateResult};
use crate::{
OwnedUserId, UserId,
room_version_rules::AuthorizationRules,
serde::{
DebugAsRefStr, DisplayAsRefStr, EqAsRefStr, JsonObject, OrdAsRefStr,
btreemap_deserialize_v1_power_level_values, deserialize_v1_power_level,
from_raw_json_value,
},
};
/// The default value of the creator's power level.
const DEFAULT_CREATOR_POWER_LEVEL: i32 = 100;
/// A helper type for an [`Event`] of type `m.room.power_levels`.
///
/// This is a type that deserializes each field lazily, when requested. Some deserialization results
/// are cached in memory, if they are used often.
#[derive(Debug, Clone)]
pub struct RoomPowerLevelsEvent<E: Event> {
inner: Arc<RoomPowerLevelsEventInner<E>>,
}
#[derive(Debug)]
struct RoomPowerLevelsEventInner<E: Event> {
/// The inner `Event`.
event: E,
/// The deserialized content of the event.
deserialized_content: OnceLock<JsonObject>,
/// The values of fields that should contain an integer.
int_fields: Mutex<BTreeMap<RoomPowerLevelsIntField, Option<i64>>>,
/// The power levels of the users, if any.
users: OnceLock<Option<BTreeMap<OwnedUserId, i64>>>,
}
impl<E: Event> RoomPowerLevelsEvent<E> {
/// Construct a new `RoomPowerLevelsEvent` around the given event.
pub fn new(event: E) -> Self {
Self {
inner: RoomPowerLevelsEventInner {
event,
deserialized_content: OnceLock::new(),
int_fields: Mutex::new(BTreeMap::new()),
users: OnceLock::new(),
}
.into(),
}
}
/// The deserialized content of the event.
fn deserialized_content(&self) -> StateResult<&JsonObject> {
// TODO: Use OnceLock::get_or_try_init when it is stabilized.
if let Some(content) = self.inner.deserialized_content.get() {
Ok(content)
} else {
let content = from_raw_json_value(self.content()).map_err(|error: Error| {
format!("malformed `m.room.power_levels` content: {error}")
})?;
Ok(self.inner.deserialized_content.get_or_init(|| content))
}
}
/// Get the value of a field that should contain an integer, if any.
///
/// The deserialization of this field is cached in memory.
pub fn get_as_int(
&self,
field: RoomPowerLevelsIntField,
auth_rules: &AuthorizationRules,
) -> StateResult<Option<i64>> {
let mut int_fields = self
.inner
.int_fields
.lock()
.expect("we never panic while holding the mutex");
if let Some(power_level) = int_fields.get(&field) {
return Ok(*power_level);
}
let content = self.deserialized_content()?;
let Some(value) = content.get(field.as_str()) else {
int_fields.insert(field, None);
return Ok(None);
};
let res = if auth_rules.integer_power_levels {
from_json_value(value.clone())
} else {
deserialize_v1_power_level(value)
};
let power_level = res.map(Some).map_err(|error| {
format!(
"unexpected format of `{field}` field in `content` \
of `m.room.power_levels` event: {error}"
)
})?;
int_fields.insert(field, power_level);
Ok(power_level)
}
/// Get the value of a field that should contain an integer, or its default value if it is
/// absent.
pub fn get_as_int_or_default(
&self,
field: RoomPowerLevelsIntField,
auth_rules: &AuthorizationRules,
) -> StateResult<i64> {
Ok(self
.get_as_int(field, auth_rules)?
.unwrap_or_else(|| field.default_value()))
}
/// Get the value of a field that should contain a map of any value to integer, if any.
fn get_as_int_map<T: Ord + DeserializeOwned>(
&self,
field: &str,
auth_rules: &AuthorizationRules,
) -> StateResult<Option<BTreeMap<T, i64>>> {
let content = self.deserialized_content()?;
let Some(value) = content.get(field) else {
return Ok(None);
};
let res = if auth_rules.integer_power_levels {
from_json_value(value.clone())
} else {
btreemap_deserialize_v1_power_level_values(value)
};
res.map(Some).map_err(|error| {
StateError::other(format!(
"unexpected format of `{field}` field in `content` \
of `m.room.power_levels` event: {error}"
))
})
}
/// Get the power levels required to send events, if any.
pub fn events(
&self,
auth_rules: &AuthorizationRules,
) -> StateResult<Option<BTreeMap<TimelineEventType, i64>>> {
self.get_as_int_map("events", auth_rules)
}
/// Get the power levels required to trigger notifications, if any.
pub fn notifications(
&self,
auth_rules: &AuthorizationRules,
) -> StateResult<Option<BTreeMap<String, i64>>> {
self.get_as_int_map("notifications", auth_rules)
}
/// Get the power levels of the users, if any.
///
/// The deserialization of this field is cached in memory.
pub fn users(
&self,
auth_rules: &AuthorizationRules,
) -> StateResult<Option<&BTreeMap<OwnedUserId, i64>>> {
// TODO: Use OnceLock::get_or_try_init when it is stabilized.
if let Some(users) = self.inner.users.get() {
Ok(users.as_ref())
} else {
let users = self.get_as_int_map("users", auth_rules)?;
Ok(self.inner.users.get_or_init(|| users).as_ref())
}
}
/// Get the power level of the user with the given ID.
///
/// Calling this method several times should be cheap because the necessary deserialization
/// results are cached.
pub fn user_power_level(
&self,
user_id: &UserId,
auth_rules: &AuthorizationRules,
) -> StateResult<i64> {
if let Some(power_level) = self
.users(auth_rules)?
.as_ref()
.and_then(|users| users.get(user_id))
{
return Ok(*power_level);
}
self.get_as_int_or_default(RoomPowerLevelsIntField::UsersDefault, auth_rules)
}
/// Get the power level required to send an event of the given type.
pub fn event_power_level(
&self,
event_type: &TimelineEventType,
state_key: Option<&str>,
auth_rules: &AuthorizationRules,
) -> StateResult<i64> {
let events = self.events(auth_rules)?;
if let Some(power_level) = events.as_ref().and_then(|events| events.get(event_type)) {
return Ok(*power_level);
}
let default_field = if state_key.is_some() {
RoomPowerLevelsIntField::StateDefault
} else {
RoomPowerLevelsIntField::EventsDefault
};
self.get_as_int_or_default(default_field, auth_rules)
}
/// Get a map of all the fields with an integer value in the `content` of an
/// `m.room.power_levels` event.
pub(crate) fn int_fields_map(
&self,
auth_rules: &AuthorizationRules,
) -> StateResult<BTreeMap<RoomPowerLevelsIntField, i64>> {
RoomPowerLevelsIntField::ALL
.iter()
.copied()
.filter_map(|field| match self.get_as_int(field, auth_rules) {
Ok(value) => value.map(|value| Ok((field, value))),
Err(error) => Some(Err(error)),
})
.collect()
}
}
impl<E: Event> Deref for RoomPowerLevelsEvent<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.inner.event
}
}
/// Helper trait for `Option<RoomPowerLevelsEvent<E>>`.
pub(crate) trait RoomPowerLevelsEventOptionExt {
/// Get the power level of the user with the given ID.
fn user_power_level(
&self,
user_id: &UserId,
creators: &HashSet<OwnedUserId>,
auth_rules: &AuthorizationRules,
) -> StateResult<UserPowerLevel>;
/// Get the value of a field that should contain an integer, or its default value if it is
/// absent.
fn get_as_int_or_default(
&self,
field: RoomPowerLevelsIntField,
auth_rules: &AuthorizationRules,
) -> StateResult<i64>;
/// Get the power level required to send an event of the given type.
fn event_power_level(
&self,
event_type: &TimelineEventType,
state_key: Option<&str>,
auth_rules: &AuthorizationRules,
) -> StateResult<i64>;
}
impl<E: Event> RoomPowerLevelsEventOptionExt for Option<RoomPowerLevelsEvent<E>> {
fn user_power_level(
&self,
user_id: &UserId,
creators: &HashSet<OwnedUserId>,
auth_rules: &AuthorizationRules,
) -> StateResult<UserPowerLevel> {
if auth_rules.explicitly_privilege_room_creators && creators.contains(user_id) {
Ok(UserPowerLevel::Infinite)
} else if let Some(room_power_levels_event) = self {
room_power_levels_event
.user_power_level(user_id, auth_rules)
.map(Into::into)
} else {
let power_level = if creators.contains(user_id) {
DEFAULT_CREATOR_POWER_LEVEL.into()
} else {
RoomPowerLevelsIntField::UsersDefault.default_value()
};
Ok(power_level.into())
}
}
fn get_as_int_or_default(
&self,
field: RoomPowerLevelsIntField,
auth_rules: &AuthorizationRules,
) -> StateResult<i64> {
if let Some(room_power_levels_event) = self {
room_power_levels_event.get_as_int_or_default(field, auth_rules)
} else {
Ok(field.default_value())
}
}
fn event_power_level(
&self,
event_type: &TimelineEventType,
state_key: Option<&str>,
auth_rules: &AuthorizationRules,
) -> StateResult<i64> {
if let Some(room_power_levels_event) = self {
room_power_levels_event.event_power_level(event_type, state_key, auth_rules)
} else {
let default_field = if state_key.is_some() {
RoomPowerLevelsIntField::StateDefault
} else {
RoomPowerLevelsIntField::EventsDefault
};
Ok(default_field.default_value())
}
}
}
/// Fields in the `content` of an `m.room.power_levels` event with an integer value.
#[derive(DebugAsRefStr, Clone, Copy, DisplayAsRefStr, EqAsRefStr, OrdAsRefStr)]
#[non_exhaustive]
pub enum RoomPowerLevelsIntField {
/// `users_default`
UsersDefault,
/// `events_default`
EventsDefault,
/// `state_default`
StateDefault,
/// `ban`
Ban,
/// `redact`
Redact,
/// `kick`
Kick,
/// `invite`
Invite,
}
impl RoomPowerLevelsIntField {
/// A slice containing all the variants.
pub(crate) const ALL: &[RoomPowerLevelsIntField] = &[
Self::UsersDefault,
Self::EventsDefault,
Self::StateDefault,
Self::Ban,
Self::Redact,
Self::Kick,
Self::Invite,
];
/// The string representation of this field.
pub fn as_str(&self) -> &str {
self.as_ref()
}
/// The default value for this field if it is absent.
pub fn default_value(&self) -> i64 {
match self {
Self::UsersDefault | Self::EventsDefault | Self::Invite => 0,
Self::StateDefault | Self::Kick | Self::Ban | Self::Redact => 50,
}
}
}
impl AsRef<str> for RoomPowerLevelsIntField {
fn as_ref(&self) -> &str {
match self {
Self::UsersDefault => "users_default",
Self::EventsDefault => "events_default",
Self::StateDefault => "state_default",
Self::Ban => "ban",
Self::Redact => "redact",
Self::Kick => "kick",
Self::Invite => "invite",
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/events/join_rules.rs | crates/core/src/state/events/join_rules.rs | //! Types to deserialize `m.room.join_rules` events.
use std::ops::Deref;
use serde::Deserialize;
use super::Event;
use crate::state::StateResult;
use crate::{room::JoinRuleKind, serde::from_raw_json_value};
/// A helper type for an [`Event`] of type `m.room.join_rules`.
///
/// This is a type that deserializes each field lazily, when requested.
#[derive(Debug, Clone)]
pub struct RoomJoinRulesEvent<E: Event>(E);
impl<E: Event> RoomJoinRulesEvent<E> {
/// Construct a new `RoomJoinRulesEvent` around the given event.
pub fn new(event: E) -> Self {
Self(event)
}
/// The join rule of the room.
pub fn join_rule(&self) -> StateResult<JoinRuleKind> {
#[derive(Deserialize)]
struct RoomJoinRulesContentJoinRule {
join_rule: JoinRuleKind,
}
let content: RoomJoinRulesContentJoinRule =
from_raw_json_value(self.content()).map_err(|err: serde_json::Error| {
format!("missing or invalid `join_rule` field in `m.room.join_rules` event: {err}")
})?;
Ok(content.join_rule)
}
}
impl<E: Event> Deref for RoomJoinRulesEvent<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.0
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/events/member.rs | crates/core/src/state/events/member.rs | //! Types to deserialize `m.room.member` events.
use std::ops::Deref;
use serde::Deserialize;
use crate::events::room::member::MembershipState;
use crate::serde::{CanonicalJsonObject, RawJsonValue, from_raw_json_value};
use crate::state::{Event, StateResult};
use crate::{identifiers::*, signatures::canonical_json};
/// A helper type for an [`Event`] of type `m.room.member`.
///
/// This is a type that deserializes each field lazily, as requested.
#[derive(Debug, Clone)]
pub struct RoomMemberEvent<E: Event>(E);
impl<E: Event> RoomMemberEvent<E> {
/// Construct a new `RoomMemberEvent` around the given event.
pub fn new(event: E) -> Self {
Self(event)
}
/// The membership of the user.
pub fn membership(&self) -> StateResult<MembershipState> {
RoomMemberEventContent(self.content()).membership()
}
/// If this is a `join` event, the ID of a user on the homeserver that authorized it.
pub fn join_authorised_via_users_server(&self) -> StateResult<Option<OwnedUserId>> {
RoomMemberEventContent(self.content()).join_authorised_via_users_server()
}
/// If this is an `invite` event, details about the third-party invite that resulted in this
/// event.
pub(crate) fn third_party_invite(&self) -> StateResult<Option<ThirdPartyInvite>> {
RoomMemberEventContent(self.content()).third_party_invite()
}
}
impl<E: Event> Deref for RoomMemberEvent<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Helper trait for `Option<RoomMemberEvent<E>>`.
pub(crate) trait RoomMemberEventOptionExt {
/// The membership of the user.
///
/// Defaults to `leave` if there is no `m.room.member` event.
fn membership(&self) -> StateResult<MembershipState>;
}
impl<E: Event> RoomMemberEventOptionExt for Option<RoomMemberEvent<E>> {
fn membership(&self) -> StateResult<MembershipState> {
match self {
Some(event) => event.membership(),
None => Ok(MembershipState::Leave),
}
}
}
/// A helper type for the raw JSON content of an event of type `m.room.member`.
pub(crate) struct RoomMemberEventContent<'a>(&'a RawJsonValue);
impl<'a> RoomMemberEventContent<'a> {
/// Construct a new `RoomMemberEventContent` around the given raw JSON content.
pub(crate) fn new(content: &'a RawJsonValue) -> Self {
Self(content)
}
}
impl RoomMemberEventContent<'_> {
/// The membership of the user.
pub(crate) fn membership(&self) -> StateResult<MembershipState> {
#[derive(Deserialize)]
struct RoomMemberContentMembership {
membership: MembershipState,
}
let content: RoomMemberContentMembership =
from_raw_json_value(self.0).map_err(|err: serde_json::Error| {
format!("missing or invalid `membership` field in `m.room.member` event: {err}")
})?;
Ok(content.membership)
}
/// If this is a `join` event, the ID of a user on the homeserver that authorized it.
pub(crate) fn join_authorised_via_users_server(&self) -> StateResult<Option<OwnedUserId>> {
#[derive(Deserialize, Default)]
struct RoomMemberContentJoinAuthorizedViaUsersServer {
join_authorised_via_users_server: Option<OwnedUserId>,
}
let content: RoomMemberContentJoinAuthorizedViaUsersServer = from_raw_json_value(self.0)
.map_err(|e: serde_json::Error| {
tracing::warn!(
"invalid `join_authorised_via_users_server` field in `m.room.member` event: {e}"
)
})
.unwrap_or_default();
Ok(content.join_authorised_via_users_server)
}
/// If this is an `invite` event, details about the third-party invite that resulted in this
/// event.
pub(crate) fn third_party_invite(&self) -> StateResult<Option<ThirdPartyInvite>> {
#[derive(Deserialize)]
struct RoomMemberContentThirdPartyInvite {
third_party_invite: Option<ThirdPartyInvite>,
}
let content: RoomMemberContentThirdPartyInvite =
from_raw_json_value(self.0).map_err(|err: serde_json::Error| {
format!("invalid `third_party_invite` field in `m.room.member` event: {err}")
})?;
Ok(content.third_party_invite)
}
}
/// Details about a third-party invite.
#[derive(Deserialize)]
pub(crate) struct ThirdPartyInvite {
/// Signed details about the third-party invite.
signed: CanonicalJsonObject,
}
impl ThirdPartyInvite {
/// The unique identifier for the third-party invite.
pub(crate) fn token(&self) -> Result<&str, String> {
let Some(token_value) = self.signed.get("token") else {
return Err("missing `token` field in `third_party_invite.signed` \
of `m.room.member` event"
.into());
};
token_value.as_str().ok_or_else(|| {
format!(
"unexpected format of `token` field in `third_party_invite.signed` \
of `m.room.member` event: expected string, got {token_value:?}"
)
})
}
/// The Matrix ID of the user that was invited.
pub(crate) fn mxid(&self) -> Result<&str, String> {
let Some(mxid_value) = self.signed.get("mxid") else {
return Err("missing `mxid` field in `third_party_invite.signed` \
of `m.room.member` event"
.into());
};
mxid_value.as_str().ok_or_else(|| {
format!(
"unexpected format of `mxid` field in `third_party_invite.signed` \
of `m.room.member` event: expected string, got {mxid_value:?}"
)
})
}
/// The signatures of the event.
pub(crate) fn signatures(&self) -> Result<&CanonicalJsonObject, String> {
let Some(signatures_value) = self.signed.get("signatures") else {
return Err("missing `signatures` field in `third_party_invite.signed` \
of `m.room.member` event"
.into());
};
signatures_value.as_object().ok_or_else(|| {
format!(
"unexpected format of `signatures` field in `third_party_invite.signed` \
of `m.room.member` event: expected object, got {signatures_value:?}"
)
})
}
/// The `signed` object as canonical JSON string to verify the signatures.
pub(crate) fn signed_canonical_json(&self) -> Result<String, String> {
canonical_json(&self.signed).map_err(|error| {
format!("invalid `third_party_invite.signed` field in `m.room.member` event: {error}")
})
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/state/events/create.rs | crates/core/src/state/events/create.rs | //! Types to deserialize `m.room.create` events.
use std::{borrow::Cow, collections::HashSet, ops::Deref};
use serde::{Deserialize, de::IgnoredAny};
use super::Event;
use crate::room_version_rules::RoomVersionRules;
use crate::{OwnedUserId, RoomVersionId, UserId, serde::from_raw_json_value, state::StateResult};
/// A helper type for an [`Event`] of type `m.room.create`.
///
/// This is a type that deserializes each field lazily, when requested.
#[derive(Debug, Clone)]
pub struct RoomCreateEvent<E: Event>(E);
impl<E: Event> RoomCreateEvent<E> {
/// Construct a new `RoomCreateEvent` around the given event.
pub fn new(event: E) -> Self {
Self(event)
}
/// The version of the room.
pub fn room_version(&self) -> StateResult<RoomVersionId> {
#[derive(Deserialize)]
struct RoomCreateContentRoomVersion {
room_version: Option<RoomVersionId>,
}
let content: RoomCreateContentRoomVersion =
from_raw_json_value(self.content()).map_err(|err: serde_json::Error| {
format!("invalid `room_version` field in `m.room.create` event: {err}")
})?;
Ok(content.room_version.unwrap_or(RoomVersionId::V1))
}
pub fn version_rules(&self) -> StateResult<RoomVersionRules> {
let room_version = self.room_version()?;
room_version.rules().ok_or_else(|| {
format!("unsupported room version `{room_version}` in `m.room.create` event").into()
})
}
/// Whether the room is federated.
pub fn federate(&self) -> StateResult<bool> {
#[derive(Deserialize)]
struct RoomCreateContentFederate {
#[serde(rename = "m.federate")]
federate: Option<bool>,
}
let content: RoomCreateContentFederate =
from_raw_json_value(self.content()).map_err(|err: serde_json::Error| {
format!("invalid `m.federate` field in `m.room.create` event: {err}")
})?;
Ok(content.federate.unwrap_or(true))
}
/// The creator of the room.
///
/// If the `use_room_create_sender` field of `AuthorizationRules` is set, the creator is the
/// sender of this `m.room.create` event, otherwise it is deserialized from the `creator`
/// field of this event's content.
///
/// This function ignores any `content.additional_creators`, and should only be used in
/// `check_room_member_join`. Otherwise, you should use `creators` instead.
pub fn creator(&self) -> StateResult<Cow<'_, UserId>> {
#[derive(Deserialize)]
struct RoomCreateContentCreator {
creator: OwnedUserId,
}
let rules = self.version_rules()?.authorization;
if rules.use_room_create_sender {
Ok(Cow::Borrowed(self.sender()))
} else {
let content: RoomCreateContentCreator =
from_raw_json_value(self.content()).map_err(|err: serde_json::Error| {
format!("missing or invalid `creator` field in `m.room.create` event: {err}")
})?;
Ok(Cow::Owned(content.creator))
}
}
/// The additional creators of the room (if any).
///
/// If the `explicitly_privilege_room_creators`
/// field of `AuthorizationRules` is set, any additional user IDs in `additional_creators`, if
/// present, will also be considered creators.
///
/// This function ignores the primary room creator, and should only be used in
/// `check_room_member_join`. Otherwise, you should use `creators` instead.
pub fn additional_creators(&self) -> StateResult<HashSet<OwnedUserId>> {
#[derive(Deserialize)]
struct RoomCreateContentAdditionalCreators {
#[serde(default)]
additional_creators: HashSet<OwnedUserId>,
}
let rules = self.version_rules()?.authorization;
Ok(if rules.additional_room_creators {
let content: RoomCreateContentAdditionalCreators = from_raw_json_value(self.content())
.map_err(|err: serde_json::Error| {
format!("invalid `additional_creators` field in `m.room.create` event: {err}")
})?;
content.additional_creators
} else {
HashSet::new()
})
}
/// The creators of the room.
///
/// If the `use_room_create_sender` field of `AuthorizationRules` is set,
/// the creator is the sender of this `m.room.create` event, otherwise it
/// is deserialized from the `creator` field of this event's content.
/// Additionally if the `explicitly_privilege_room_creators`
/// field of `AuthorizationRules` is set, any additional user IDs in
/// `additional_creators`, if present, will also be considered creators.
pub fn creators(&self) -> StateResult<HashSet<OwnedUserId>> {
let mut creators = self.additional_creators()?;
creators.insert(self.creator()?.into_owned());
Ok(creators)
}
/// Whether the event has a `creator` field.
pub(crate) fn has_creator(&self) -> StateResult<bool> {
#[derive(Deserialize)]
struct RoomCreateContentCreator {
creator: Option<IgnoredAny>,
}
let content: RoomCreateContentCreator =
from_raw_json_value(self.content()).map_err(|err: serde_json::Error| {
format!("invalid `creator` field in `m.room.create` event: {err}")
})?;
Ok(content.creator.is_some())
}
pub fn into_inner(self) -> E {
self.0
}
}
impl<E: Event> Deref for RoomCreateEvent<E> {
type Target = E;
fn deref(&self) -> &Self::Target {
&self.0
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/appservice/event.rs | crates/core/src/appservice/event.rs | //! Endpoint for sending events.
//! `PUT /_matrix/app/*/transactions/{txn_id}`
//!
//! Endpoint to push an event (or batch of events) to the application service.
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/application-service-api/#put_matrixappv1transactionstxnid
use std::borrow::Cow;
use reqwest::Url;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Deserializer, Serialize};
use crate::events::presence::PresenceEvent;
use crate::events::receipt::ReceiptEvent;
use crate::events::typing::TypingEvent;
#[cfg(feature = "unstable-msc4203")]
use crate::events::{AnyToDeviceEvent, AnyToDeviceEventContent, ToDeviceEventType};
use crate::{
OwnedDeviceId, OwnedUserId, UserId,
events::AnyTimelineEvent,
sending::{SendRequest, SendResult},
serde::{JsonCastable, JsonObject, JsonValue, RawJson, RawJsonValue, from_raw_json_value},
};
// /// `PUT /_matrix/app/*/transactions/{txn_id}`
// ///
// /// Endpoint to push an event (or batch of events) to the application service.
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/application-service-api/#put_matrixappv1transactionstxnid
// const METADATA: Metadata = metadata! {
// method: PUT,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/app/v1/transactions/:txn_id",
// }
// };
pub fn push_events_request(
origin: &str,
txn_id: &str,
body: PushEventsReqBody,
) -> SendResult<SendRequest> {
let url = Url::parse(&format!("{origin}/_matrix/app/v1/transactions/{txn_id}"))?;
crate::sending::post(url).stuff(body)
}
/// Request type for the `push_events` endpoint.
#[derive(ToSchema, Deserialize, Serialize, Debug)]
pub struct PushEventsReqBody {
/// The transaction ID for this set of events.
///
/// HomeServers generate these IDs and they are used to ensure idempotency
/// of results.
// #[salvo(parameter(parameter_in = Path))]
// pub txn_id: OwnedTransactionId,
/// A list of events.
pub events: Vec<RawJson<AnyTimelineEvent>>,
// /// Information on E2E device updates.
// #[serde(
// default,
// skip_serializing_if = "DeviceLists::is_empty",
// rename = "org.matrix.msc3202.device_lists"
// )]
// pub device_lists: DeviceLists,
// /// The number of unclaimed one-time keys currently held on the server for this device, for
// /// each algorithm.
// #[serde(
// default,
// skip_serializing_if = "BTreeMap::is_empty",
// rename = "org.matrix.msc3202.device_one_time_keys_count"
// )]
// pub device_one_time_keys_count: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, BTreeMap<DeviceKeyAlgorithm,
// u64>>>,
// /// A list of key algorithms for which the server has an unused fallback key for the
// /// device.
// #[serde(
// default,
// skip_serializing_if = "BTreeMap::is_empty",
// rename = "org.matrix.msc3202.device_unused_fallback_key_types"
// )]
// pub device_unused_fallback_key_types: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, Vec<DeviceKeyAlgorithm>>>,
// /// A list of EDUs.
// #[serde(
// default,
// skip_serializing_if = "<[_]>::is_empty",
// rename = "de.sorunome.msc2409.ephemeral"
// )]
// pub ephemeral: Vec<Edu>,
/// A list of to-device messages.
#[serde(
default,
skip_serializing_if = "<[_]>::is_empty",
rename = "de.sorunome.msc2409.to_device"
)]
pub to_device: Vec<RawJson<AnyAppserviceToDeviceEvent>>,
}
crate::json_body_modifier!(PushEventsReqBody);
/// Information on E2E device updates.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[cfg(feature = "unstable-msc3202")]
pub struct DeviceLists {
/// List of users who have updated their device identity keys or who now
/// share an encrypted room with the client since the previous sync.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub changed: Vec<OwnedUserId>,
/// List of users who no longer share encrypted rooms since the previous sync
/// response.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub left: Vec<OwnedUserId>,
}
#[cfg(feature = "unstable-msc3202")]
impl DeviceLists {
/// Creates an empty `DeviceLists`.
pub fn new() -> Self {
Default::default()
}
/// Returns true if there are no device list updates.
pub fn is_empty(&self) -> bool {
self.changed.is_empty() && self.left.is_empty()
}
}
/// Type for passing ephemeral data to application services.
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum EphemeralData {
/// A presence update for a user.
Presence(PresenceEvent),
/// A receipt update for a room.
Receipt(ReceiptEvent),
/// A typing notification update for a room.
Typing(TypingEvent),
#[doc(hidden)]
_Custom(_CustomEphemeralData),
}
impl EphemeralData {
/// A reference to the `type` string of the data.
pub fn data_type(&self) -> &str {
match self {
Self::Presence(_) => "m.presence",
Self::Receipt(_) => "m.receipt",
Self::Typing(_) => "m.typing",
Self::_Custom(c) => &c.data_type,
}
}
/// The data as a JSON object.
///
/// Prefer to use the public variants of `EphemeralData` where possible; this method is
/// meant to be used for unsupported data types only.
pub fn data(&self) -> Cow<'_, JsonObject> {
fn serialize<T: Serialize>(obj: &T) -> JsonObject {
match serde_json::to_value(obj).expect("ephemeral data serialization to succeed") {
JsonValue::Object(obj) => obj,
_ => panic!("all ephemeral data types must serialize to objects"),
}
}
match self {
Self::Presence(d) => Cow::Owned(serialize(d)),
Self::Receipt(d) => Cow::Owned(serialize(d)),
Self::Typing(d) => Cow::Owned(serialize(d)),
Self::_Custom(c) => Cow::Borrowed(&c.data),
}
}
}
impl<'de> Deserialize<'de> for EphemeralData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct EphemeralDataDeHelper {
/// The data type.
#[serde(rename = "type")]
data_type: String,
}
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let EphemeralDataDeHelper { data_type } = from_raw_json_value(&json)?;
Ok(match data_type.as_ref() {
"m.presence" => Self::Presence(from_raw_json_value(&json)?),
"m.receipt" => Self::Receipt(from_raw_json_value(&json)?),
"m.typing" => Self::Typing(from_raw_json_value(&json)?),
_ => Self::_Custom(_CustomEphemeralData {
data_type,
data: from_raw_json_value(&json)?,
}),
})
}
}
/// Ephemeral data with an unknown type.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct _CustomEphemeralData {
/// The type of the data.
data_type: String,
/// The data.
data: JsonObject,
}
impl Serialize for _CustomEphemeralData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.data.serialize(serializer)
}
}
/// An event sent using send-to-device messaging with additional fields when pushed to an
/// application service.
#[derive(ToSchema, Clone, Debug)]
#[cfg(feature = "unstable-msc4203")]
pub struct AnyAppserviceToDeviceEvent {
/// The to-device event.
pub event: AnyToDeviceEvent,
/// The fully-qualified user ID of the intended recipient.
pub to_user_id: OwnedUserId,
/// The device ID of the intended recipient.
pub to_device_id: OwnedDeviceId,
}
#[cfg(feature = "unstable-msc4203")]
impl AnyAppserviceToDeviceEvent {
/// Construct a new `AnyAppserviceToDeviceEvent` with the given event and recipient
/// information.
pub fn new(
event: AnyToDeviceEvent,
to_user_id: OwnedUserId,
to_device_id: OwnedDeviceId,
) -> Self {
Self {
event,
to_user_id,
to_device_id,
}
}
/// The fully-qualified ID of the user who sent this event.
pub fn sender(&self) -> &UserId {
self.event.sender()
}
/// The event type of the to-device event.
pub fn event_type(&self) -> ToDeviceEventType {
self.event.event_type()
}
/// The content of the to-device event.
pub fn content(&self) -> AnyToDeviceEventContent {
self.event.content()
}
}
#[cfg(feature = "unstable-msc4203")]
impl<'de> Deserialize<'de> for AnyAppserviceToDeviceEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct AppserviceFields {
to_user_id: OwnedUserId,
to_device_id: OwnedDeviceId,
}
let json = Box::<RawJsonValue>::deserialize(deserializer)?;
let event = from_raw_json_value(&json)?;
let AppserviceFields {
to_user_id,
to_device_id,
} = from_raw_json_value(&json)?;
Ok(AnyAppserviceToDeviceEvent::new(
event,
to_user_id,
to_device_id,
))
}
}
#[cfg(feature = "unstable-msc4203")]
impl JsonCastable<JsonObject> for AnyAppserviceToDeviceEvent {}
#[cfg(feature = "unstable-msc4203")]
impl JsonCastable<AnyToDeviceEvent> for AnyAppserviceToDeviceEvent {}
// #[cfg(test)]
// mod tests {
// use crate::{UnixMillis, event_id, room_id, user_id};
// use assert_matches2::assert_matches;
// use js_int::uint;
// use palpo_events::receipt::ReceiptType;
// use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
// use super::EphemeralData;
// #[cfg(feature = "client")]
// #[test]
// fn request_contains_events_field() {
// use crate::api::{OutgoingRequest, auth_scheme::SendAccessToken};
// let dummy_event_json = json!({
// "type": "m.room.message",
// "event_id": "$143273582443PhrSn:example.com",
// "origin_server_ts": 1,
// "room_id": "!roomid:room.com",
// "sender": "@user:example.com",
// "content": {
// "body": "test",
// "msgtype": "m.text",
// },
// });
// let dummy_event = from_json_value(dummy_event_json.clone()).unwrap();
// let events = vec![dummy_event];
// let req = super::Request::new("any_txn_id".into(), events)
// .try_into_http_request::<Vec<u8>>(
// "https://homeserver.tld",
// SendAccessToken::IfRequired("auth_tok"),
// (),
// )
// .unwrap();
// let json_body: serde_json::Value = serde_json::from_slice(req.body()).unwrap();
// assert_eq!(
// json_body,
// json!({
// "events": [
// dummy_event_json,
// ]
// })
// );
// }
// #[test]
// fn serde_ephemeral_data() {
// let room_id = room_id!("!jEsUZKDJdhlrceRyVU:server.local");
// let user_id = user_id!("@alice:server.local");
// let event_id = event_id!("$1435641916114394fHBL");
// // Test m.typing serde.
// let typing_json = json!({
// "type": "m.typing",
// "room_id": room_id,
// "content": {
// "user_ids": [user_id],
// },
// });
// let data = from_json_value::<EphemeralData>(typing_json.clone()).unwrap();
// assert_matches!(&data, EphemeralData::Typing(typing));
// assert_eq!(typing.room_id, room_id);
// assert_eq!(typing.content.user_ids, &[user_id.to_owned()]);
// let serialized_data = to_json_value(data).unwrap();
// assert_eq!(serialized_data, typing_json);
// // Test m.receipt serde.
// let receipt_json = json!({
// "type": "m.receipt",
// "room_id": room_id,
// "content": {
// event_id: {
// "m.read": {
// user_id: {
// "ts": 453,
// },
// },
// },
// },
// });
// let data = from_json_value::<EphemeralData>(receipt_json.clone()).unwrap();
// assert_matches!(&data, EphemeralData::Receipt(receipt));
// assert_eq!(receipt.room_id, room_id);
// let event_receipts = receipt.content.get(event_id).unwrap();
// let event_read_receipts = event_receipts.get(&ReceiptType::Read).unwrap();
// let event_user_read_receipt = event_read_receipts.get(user_id).unwrap();
// assert_eq!(event_user_read_receipt.ts, Some(UnixMillis(uint!(453))));
// let serialized_data = to_json_value(data).unwrap();
// assert_eq!(serialized_data, receipt_json);
// // Test m.presence serde.
// let presence_json = json!({
// "type": "m.presence",
// "sender": user_id,
// "content": {
// "avatar_url": "mxc://localhost/wefuiwegh8742w",
// "currently_active": false,
// "last_active_ago": 785,
// "presence": "online",
// "status_msg": "Making cupcakes",
// },
// });
// let data = from_json_value::<EphemeralData>(presence_json.clone()).unwrap();
// assert_matches!(&data, EphemeralData::Presence(presence));
// assert_eq!(presence.sender, user_id);
// assert_eq!(presence.content.currently_active, Some(false));
// let serialized_data = to_json_value(data).unwrap();
// assert_eq!(serialized_data, presence_json);
// // Test custom serde.
// let custom_json = json!({
// "type": "dev.ruma.custom",
// "key": "value",
// "content": {
// "foo": "bar",
// },
// });
// let data = from_json_value::<EphemeralData>(custom_json.clone()).unwrap();
// let serialized_data = to_json_value(data).unwrap();
// assert_eq!(serialized_data, custom_json);
// }
// #[test]
// #[cfg(feature = "unstable-msc4203")]
// fn serde_any_appservice_to_device_event() {
// use crate::{device_id, user_id};
// use super::AnyAppserviceToDeviceEvent;
// let event_json = json!({
// "type": "m.key.verification.request",
// "sender": "@alice:example.org",
// "content": {
// "from_device": "AliceDevice2",
// "methods": [
// "m.sas.v1"
// ],
// "timestamp": 1_559_598_944_869_i64,
// "transaction_id": "S0meUniqueAndOpaqueString"
// },
// "to_user_id": "@bob:example.org",
// "to_device_id": "DEVICEID"
// });
// // Test deserialization
// let event = from_json_value::<AnyAppserviceToDeviceEvent>(event_json.clone()).unwrap();
// assert_eq!(event.sender(), user_id!("@alice:example.org"));
// assert_eq!(event.to_user_id, user_id!("@bob:example.org"));
// assert_eq!(event.to_device_id, device_id!("DEVICEID"));
// assert_eq!(event.event_type().to_string(), "m.key.verification.request");
// }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/appservice/third_party.rs | crates/core/src/appservice/third_party.rs | //! Endpoints for third party lookups
// `GET /_matrix/app/*/thirdparty/location/{protocol}`
//
// Retrieve a list of Matrix portal rooms that lead to the matched third party
// location. `/v1/` ([spec])
//
// [spec]: https://spec.matrix.org/latest/application-service-api/#get_matrixappv1thirdpartylocationprotocol
use std::collections::BTreeMap;
use salvo::prelude::*;
use serde::{Deserialize, Serialize};
use crate::third_party::{Location, Protocol, User};
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/app/v1/thirdparty/location/:protocol",
// }
// };
/// Request type for the `get_location_for_protocol` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct ForProtocolReqArgs {
/// The protocol used to communicate to the third party network.
#[salvo(parameter(parameter_in = Path))]
pub protocol: String,
/// One or more custom fields to help identify the third party location.
// The specification is incorrect for this parameter. See [matrix-spec#560](https://github.com/matrix-org/matrix-spec/issues/560).
#[salvo(parameter(parameter_in = Query))]
pub fields: BTreeMap<String, String>,
}
impl ForProtocolReqArgs {
/// Creates a new `Request` with the given protocol.
pub fn new(protocol: String) -> Self {
Self {
protocol,
fields: BTreeMap::new(),
}
}
}
// /// Request type for the `get_location_for_room_alias` endpoint.
// #[request]
// pub struct ForRoomAliasReqArgs {
// /// The Matrix room alias to look up.
// pub alias: OwnedRoomAliasId,
// }
// impl ForRoomAliasReqBody {
// /// Creates a new `Request` with the given room alias id.
// pub fn new(alias: OwnedRoomAliasId) -> Self {
// Self { alias }
// }
// }
/// Response type for the `get_location_for_protocol` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct LocationsResBody(
/// List of matched third party locations.
pub Vec<Location>,
);
impl LocationsResBody {
/// Creates a new `Response` with the given locations.
pub fn new(locations: Vec<Location>) -> Self {
Self(locations)
}
}
/// Response type for the `get_user_for_protocol` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct ProtocolResBody {
/// Metadata about the protocol.
pub protocol: Protocol,
}
impl ProtocolResBody {
/// Creates a new `Response` with the given protocol.
pub fn new(protocol: Protocol) -> Self {
Self { protocol }
}
}
/// Response type for the `get_location_for_protocol` endpoint.
#[derive(ToSchema, Serialize, Debug)]
pub struct UsersResBody {
/// List of matched third party users.
pub users: Vec<User>,
}
impl UsersResBody {
/// Creates a new `Response` with the given users.
pub fn new(users: Vec<User>) -> Self {
Self { users }
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/appservice/ping.rs | crates/core/src/appservice/ping.rs | //! Endpoint for pinging the application service.
//! `PUT /_matrix/app/*/ping`
//!
//! Endpoint to ping the application service.
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/latest/application-service-api/#post_matrixappv1ping
use std::time::Duration;
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
OwnedTransactionId,
sending::{SendRequest, SendResult},
};
// const METADATA: Metadata = metadata! {
// method: POST,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// unstable => "/_matrix/app/unstable/fi.mau.msc2659/ping",
// 1.7 => "/_matrix/app/v1/ping",
// }
// };
pub fn send_ping_request(dest: &str, body: SendPingReqBody) -> SendResult<SendRequest> {
let url = Url::parse(dest)?;
crate::sending::post(url).stuff(body)
}
/// Request type for the `send_ping` endpoint.
#[derive(ToSchema, Deserialize, Serialize, Debug)]
pub struct SendPingReqBody {
/// A transaction ID for the ping, copied directly from the `POST
/// /_matrix/client/v1/appservice/{appserviceId}/ping` call.
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction_id: Option<OwnedTransactionId>,
}
crate::json_body_modifier!(SendPingReqBody);
/// Response type for the `request_ping` endpoint.
#[derive(ToSchema, Serialize, Default, Debug)]
pub struct SendPingResBody {
#[serde(with = "crate::serde::duration::ms", rename = "duration_ms")]
pub duration: Duration,
}
impl SendPingResBody {
pub fn new(duration: Duration) -> Self {
Self { duration }
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/appservice/query.rs | crates/core/src/appservice/query.rs | /// Endpoints for querying user IDs and room aliases
///
/// `GET /_matrix/app/*/rooms/{roomAlias}`
///
/// Endpoint to query the existence of a given room alias.
/// `/v1/` ([spec])
///
/// [spec]: https://spec.matrix.org/latest/application-service-api/#get_matrixappv1roomsroomalias
use salvo::oapi::ToParameters;
use serde::Deserialize;
use url::Url;
use crate::{
OwnedRoomAliasId,
sending::{SendRequest, SendResult},
};
// const METADATA: Metadata = metadata! {
// method: GET,
// rate_limited: false,
// authentication: AccessToken,
// history: {
// 1.0 => "/_matrix/app/v1/rooms/:room_alias",
// }
// };
pub fn query_room_alias_request(
origin: &str,
args: QueryRoomAliasReqArgs,
) -> SendResult<SendRequest> {
let url = Url::parse(&format!(
"{origin}/_matrix/app/v1/rooms/{}",
args.room_alias
))?;
Ok(crate::sending::post(url))
}
/// Request type for the `query_room_alias` endpoint.
#[derive(ToParameters, Deserialize, Debug)]
pub struct QueryRoomAliasReqArgs {
/// The room alias being queried.
#[salvo(parameter(parameter_in = Path))]
pub room_alias: OwnedRoomAliasId,
}
// /// `GET /_matrix/app/*/users/{user_id}`
// /// "/_matrix/app/v1/users/:user_id
// ///
// /// Endpoint to query the existence of a given user ID.
// /// `/v1/` ([spec])
// ///
// /// [spec]: https://spec.matrix.org/latest/application-service-api/#get_matrixappv1usersuser_id
// /// Request type for the `query_user_id` endpoint.
// #[derive(ToParameters, Deserialize, Debug)]
// pub struct QueryUseridReqArgs {
// /// The user ID being queried.
// #[salvo(parameter(parameter_in = Path))]
// pub user_id: OwnedUserId,
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/appservice/tests/appservice_registration.rs | crates/core/src/appservice/tests/appservice_registration.rs | use assert_matches2::assert_matches;
use palpo_appservice_api::Registration;
#[test]
fn registration_deserialization() {
let registration_config = r##"
id: "IRC Bridge"
url: "http://127.0.0.1:1234"
as_token: "30c05ae90a248a4188e620216fa72e349803310ec83e2a77b34fe90be6081f46"
hs_token: "312df522183efd404ec1cd22d2ffa4bbc76a8c1ccf541dd692eef281356bb74e"
sender_localpart: "_irc_bot"
namespaces:
users:
- exclusive: true
regex: "@_irc_bridge_.*"
aliases:
- exclusive: false
regex: "#_irc_bridge_.*"
rooms: []
"##;
let observed: Registration = serde_saphyr::from_str(registration_config).unwrap();
assert_eq!(observed.id, "IRC Bridge");
assert_eq!(observed.url.unwrap(), "http://127.0.0.1:1234");
assert_eq!(
observed.as_token,
"30c05ae90a248a4188e620216fa72e349803310ec83e2a77b34fe90be6081f46"
);
assert_eq!(
observed.hs_token,
"312df522183efd404ec1cd22d2ffa4bbc76a8c1ccf541dd692eef281356bb74e"
);
assert_eq!(observed.sender_localpart, "_irc_bot");
assert_eq!(observed.rate_limited, None);
assert_eq!(observed.protocols, None);
assert_eq!(observed.namespaces.users.len(), 1);
assert!(observed.namespaces.users[0].exclusive);
assert_eq!(observed.namespaces.users[0].regex, "@_irc_bridge_.*");
assert_eq!(observed.namespaces.aliases.len(), 1);
assert!(!observed.namespaces.aliases[0].exclusive);
assert_eq!(observed.namespaces.aliases[0].regex, "#_irc_bridge_.*");
assert_eq!(observed.namespaces.rooms.len(), 0);
}
#[test]
fn config_with_optional_url() {
let registration_config = r#"
id: "IRC Bridge"
url: null
as_token: "30c05ae90a248a4188e620216fa72e349803310ec83e2a77b34fe90be6081f46"
hs_token: "312df522183efd404ec1cd22d2ffa4bbc76a8c1ccf541dd692eef281356bb74e"
sender_localpart: "_irc_bot"
namespaces:
users: []
aliases: []
rooms: []
"#;
assert_matches!(serde_saphyr::from_str(registration_config).unwrap(), Registration { url, .. });
assert_eq!(url, None);
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/directory/room_network_serde.rs | crates/core/src/directory/room_network_serde.rs | use std::fmt;
use serde::{
Deserialize, Deserializer, Serialize, Serializer,
de::{Error, MapAccess, Visitor},
ser::SerializeStruct,
};
use serde_json::Value as JsonValue;
use super::RoomNetwork;
impl Serialize for RoomNetwork {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state;
match self {
Self::Matrix => {
state = serializer.serialize_struct("RoomNetwork", 0)?;
}
Self::All => {
state = serializer.serialize_struct("RoomNetwork", 1)?;
state.serialize_field("include_all_networks", &true)?;
}
Self::ThirdParty(network) => {
state = serializer.serialize_struct("RoomNetwork", 1)?;
state.serialize_field("third_party_instance_id", network)?;
}
}
state.end()
}
}
impl<'de> Deserialize<'de> for RoomNetwork {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(RoomNetworkVisitor)
}
}
struct RoomNetworkVisitor;
impl<'de> Visitor<'de> for RoomNetworkVisitor {
type Value = RoomNetwork;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Network selection")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut include_all_networks = false;
let mut third_party_instance_id = None;
while let Some((key, value)) = access.next_entry::<String, JsonValue>()? {
match key.as_str() {
"include_all_networks" => {
include_all_networks = value.as_bool().unwrap_or_default();
}
"third_party_instance_id" => {
third_party_instance_id = value.as_str().map(|v| v.to_owned());
}
_ => {}
};
}
if include_all_networks {
if third_party_instance_id.is_none() {
Ok(RoomNetwork::All)
} else {
Err(M::Error::custom(
"`include_all_networks = true` and `third_party_instance_id` are mutually exclusive.",
))
}
} else {
Ok(match third_party_instance_id {
Some(network) => RoomNetwork::ThirdParty(network),
None => RoomNetwork::Matrix,
})
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/directory/filter_room_type_serde.rs | crates/core/src/directory/filter_room_type_serde.rs | use std::borrow::Cow;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::RoomTypeFilter;
impl Serialize for RoomTypeFilter {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_str().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for RoomTypeFilter {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = Option::<Cow<'_, str>>::deserialize(deserializer)?;
Ok(s.into())
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/metadata/tests.rs | crates/core/src/metadata/tests.rs | use std::collections::{BTreeMap, BTreeSet};
use assert_matches2::assert_matches;
use http::Method;
use super::{
MatrixVersion::{self, V1_0, V1_1, V1_2, V1_3},
StablePathSelector, SupportedVersions, VersionHistory,
};
use crate::AuthScheme;
use crate::error::IntoHttpError;
fn stable_only_metadata(stable_paths: &'static [(StablePathSelector, &'static str)]) -> Metadata {
Metadata {
method: Method::GET,
rate_limited: false,
authentication: AuthScheme::None,
history: VersionHistory {
unstable_paths: &[],
stable_paths,
deprecated: None,
removed: None,
},
}
}
fn version_only_supported(versions: &[MatrixVersion]) -> SupportedVersions {
SupportedVersions {
versions: versions.iter().copied().collect(),
features: BTreeSet::new(),
}
}
// TODO add test that can hook into tracing and verify the deprecation warning is emitted
#[test]
fn make_simple_endpoint_url() {
let meta = stable_only_metadata(&[(StablePathSelector::Version(V1_0), "/s")]);
let url = meta
.make_endpoint_url(
&version_only_supported(&[V1_0]),
"https://example.org",
&[],
"",
)
.unwrap();
assert_eq!(url, "https://example.org/s");
}
#[test]
fn make_endpoint_url_with_path_args() {
let meta = stable_only_metadata(&[(StablePathSelector::Version(V1_0), "/s/{x}")]);
let url = meta
.make_endpoint_url(
&version_only_supported(&[V1_0]),
"https://example.org",
&[&"123"],
"",
)
.unwrap();
assert_eq!(url, "https://example.org/s/123");
}
#[test]
fn make_endpoint_url_with_path_args_with_dash() {
let meta = stable_only_metadata(&[(StablePathSelector::Version(V1_0), "/s/{x}")]);
let url = meta
.make_endpoint_url(
&version_only_supported(&[V1_0]),
"https://example.org",
&[&"my-path"],
"",
)
.unwrap();
assert_eq!(url, "https://example.org/s/my-path");
}
#[test]
fn make_endpoint_url_with_path_args_with_reserved_char() {
let meta = stable_only_metadata(&[(StablePathSelector::Version(V1_0), "/s/{x}")]);
let url = meta
.make_endpoint_url(
&version_only_supported(&[V1_0]),
"https://example.org",
&[&"#path"],
"",
)
.unwrap();
assert_eq!(url, "https://example.org/s/%23path");
}
#[test]
fn make_endpoint_url_with_query() {
let meta = stable_only_metadata(&[(StablePathSelector::Version(V1_0), "/s/")]);
let url = meta
.make_endpoint_url(
&version_only_supported(&[V1_0]),
"https://example.org",
&[],
"foo=bar",
)
.unwrap();
assert_eq!(url, "https://example.org/s/?foo=bar");
}
#[test]
#[should_panic]
fn make_endpoint_url_wrong_num_path_args() {
let meta = stable_only_metadata(&[(StablePathSelector::Version(V1_0), "/s/{x}")]);
_ = meta.make_endpoint_url(
&version_only_supported(&[V1_0]),
"https://example.org",
&[],
"",
);
}
const EMPTY: VersionHistory = VersionHistory {
unstable_paths: &[],
stable_paths: &[],
deprecated: None,
removed: None,
};
#[test]
fn select_version() {
let version_supported = version_only_supported(&[V1_0, V1_1]);
let superset_supported = version_only_supported(&[V1_1]);
// With version only.
let hist = VersionHistory {
stable_paths: &[(StablePathSelector::Version(V1_0), "/s")],
..EMPTY
};
assert_matches!(hist.select_path(&version_supported), Ok("/s"));
assert!(hist.is_supported(&version_supported));
assert_matches!(hist.select_path(&superset_supported), Ok("/s"));
assert!(hist.is_supported(&superset_supported));
// With feature and version.
let hist = VersionHistory {
stable_paths: &[(
StablePathSelector::FeatureAndVersion {
feature: "org.boo.stable",
version: V1_0,
},
"/s",
)],
..EMPTY
};
assert_matches!(hist.select_path(&version_supported), Ok("/s"));
assert!(hist.is_supported(&version_supported));
assert_matches!(hist.select_path(&superset_supported), Ok("/s"));
assert!(hist.is_supported(&superset_supported));
// Select latest stable version.
let hist = VersionHistory {
stable_paths: &[
(StablePathSelector::Version(V1_0), "/s_v1"),
(StablePathSelector::Version(V1_1), "/s_v2"),
],
..EMPTY
};
assert_matches!(hist.select_path(&version_supported), Ok("/s_v2"));
assert!(hist.is_supported(&version_supported));
// With unstable feature.
let unstable_supported = SupportedVersions {
versions: [V1_0].into(),
features: ["org.boo.unstable".into()].into(),
};
let hist = VersionHistory {
unstable_paths: &[(Some("org.boo.unstable"), "/u")],
stable_paths: &[(StablePathSelector::Version(V1_0), "/s")],
..EMPTY
};
assert_matches!(hist.select_path(&unstable_supported), Ok("/s"));
assert!(hist.is_supported(&unstable_supported));
}
#[test]
fn select_stable_feature() {
let supported = SupportedVersions {
versions: [V1_1].into(),
features: ["org.boo.unstable".into(), "org.boo.stable".into()].into(),
};
// With feature only.
let hist = VersionHistory {
unstable_paths: &[(Some("org.boo.unstable"), "/u")],
stable_paths: &[(StablePathSelector::Feature("org.boo.stable"), "/s")],
..EMPTY
};
assert_matches!(hist.select_path(&supported), Ok("/s"));
assert!(hist.is_supported(&supported));
// With feature and version.
let hist = VersionHistory {
unstable_paths: &[(Some("org.boo.unstable"), "/u")],
stable_paths: &[(
StablePathSelector::FeatureAndVersion {
feature: "org.boo.stable",
version: V1_3,
},
"/s",
)],
..EMPTY
};
assert_matches!(hist.select_path(&supported), Ok("/s"));
assert!(hist.is_supported(&supported));
}
#[test]
fn select_unstable_feature() {
let supported = SupportedVersions {
versions: [V1_1].into(),
features: ["org.boo.unstable".into()].into(),
};
let hist = VersionHistory {
unstable_paths: &[(Some("org.boo.unstable"), "/u")],
stable_paths: &[(
StablePathSelector::FeatureAndVersion {
feature: "org.boo.stable",
version: V1_3,
},
"/s",
)],
..EMPTY
};
assert_matches!(hist.select_path(&supported), Ok("/u"));
assert!(hist.is_supported(&supported));
}
#[test]
fn select_unstable_fallback() {
let supported = version_only_supported(&[V1_0]);
let hist = VersionHistory {
unstable_paths: &[(None, "/u")],
..EMPTY
};
assert_matches!(hist.select_path(&supported), Ok("/u"));
assert!(!hist.is_supported(&supported));
}
#[test]
fn select_r0() {
let supported = version_only_supported(&[V1_0]);
let hist = VersionHistory {
stable_paths: &[(StablePathSelector::Version(V1_0), "/r")],
..EMPTY
};
assert_matches!(hist.select_path(&supported), Ok("/r"));
assert!(hist.is_supported(&supported));
}
#[test]
fn select_removed_err() {
let supported = version_only_supported(&[V1_3]);
let hist = VersionHistory {
stable_paths: &[
(StablePathSelector::Version(V1_0), "/r"),
(StablePathSelector::Version(V1_1), "/s"),
],
unstable_paths: &[(None, "/u")],
deprecated: Some(V1_2),
removed: Some(V1_3),
};
assert_matches!(
hist.select_path(&supported),
Err(IntoHttpError::EndpointRemoved(V1_3))
);
assert!(!hist.is_supported(&supported));
}
#[test]
fn partially_removed_but_stable() {
let supported = version_only_supported(&[V1_2]);
let hist = VersionHistory {
stable_paths: &[
(StablePathSelector::Version(V1_0), "/r"),
(StablePathSelector::Version(V1_1), "/s"),
],
unstable_paths: &[],
deprecated: Some(V1_2),
removed: Some(V1_3),
};
assert_matches!(hist.select_path(&supported), Ok("/s"));
assert!(hist.is_supported(&supported));
}
#[test]
fn no_unstable() {
let supported = version_only_supported(&[V1_0]);
let hist = VersionHistory {
stable_paths: &[(StablePathSelector::Version(V1_1), "/s")],
..EMPTY
};
assert_matches!(
hist.select_path(&supported),
Err(IntoHttpError::NoUnstablePath)
);
assert!(!hist.is_supported(&supported));
}
#[test]
fn version_literal() {
const LIT: MatrixVersion = MatrixVersion::from_lit("1.0");
assert_eq!(LIT, V1_0);
}
#[test]
fn parse_as_str_sanity() {
let version = MatrixVersion::try_from("r0.5.0").unwrap();
assert_eq!(version, V1_0);
assert_eq!(version.as_str(), None);
let version = MatrixVersion::try_from("v1.1").unwrap();
assert_eq!(version, V1_1);
assert_eq!(version.as_str(), Some("v1.1"));
}
#[test]
fn supported_versions_from_parts() {
let empty_features = BTreeMap::new();
let none = &[];
let none_supported = SupportedVersions::from_parts(none, &empty_features);
assert_eq!(none_supported.versions, BTreeSet::new());
assert_eq!(none_supported.features, BTreeSet::new());
let single_known = &["r0.6.0".to_owned()];
let single_known_supported = SupportedVersions::from_parts(single_known, &empty_features);
assert_eq!(single_known_supported.versions, BTreeSet::from([V1_0]));
assert_eq!(single_known_supported.features, BTreeSet::new());
let multiple_known = &["v1.1".to_owned(), "r0.6.0".to_owned(), "r0.6.1".to_owned()];
let multiple_known_supported = SupportedVersions::from_parts(multiple_known, &empty_features);
assert_eq!(
multiple_known_supported.versions,
BTreeSet::from([V1_0, V1_1])
);
assert_eq!(multiple_known_supported.features, BTreeSet::new());
let single_unknown = &["v0.0".to_owned()];
let single_unknown_supported = SupportedVersions::from_parts(single_unknown, &empty_features);
assert_eq!(single_unknown_supported.versions, BTreeSet::new());
assert_eq!(single_unknown_supported.features, BTreeSet::new());
let mut features = BTreeMap::new();
features.insert("org.bar.enabled_1".to_owned(), true);
features.insert("org.bar.disabled".to_owned(), false);
features.insert("org.bar.enabled_2".to_owned(), true);
let features_supported = SupportedVersions::from_parts(single_known, &features);
assert_eq!(features_supported.versions, BTreeSet::from([V1_0]));
assert_eq!(
features_supported.features,
["org.bar.enabled_1".into(), "org.bar.enabled_2".into()].into()
);
}
#[test]
fn supported_versions_from_parts_order() {
let empty_features = BTreeMap::new();
let sorted = &[
"r0.0.1".to_owned(),
"r0.5.0".to_owned(),
"r0.6.0".to_owned(),
"r0.6.1".to_owned(),
"v1.1".to_owned(),
"v1.2".to_owned(),
];
let sorted_supported = SupportedVersions::from_parts(sorted, &empty_features);
assert_eq!(
sorted_supported.versions,
BTreeSet::from([V1_0, V1_1, V1_2])
);
let sorted_reverse = &[
"v1.2".to_owned(),
"v1.1".to_owned(),
"r0.6.1".to_owned(),
"r0.6.0".to_owned(),
"r0.5.0".to_owned(),
"r0.0.1".to_owned(),
];
let sorted_reverse_supported = SupportedVersions::from_parts(sorted_reverse, &empty_features);
assert_eq!(
sorted_reverse_supported.versions,
BTreeSet::from([V1_0, V1_1, V1_2])
);
let random_order = &[
"v1.1".to_owned(),
"r0.6.1".to_owned(),
"r0.5.0".to_owned(),
"r0.6.0".to_owned(),
"r0.0.1".to_owned(),
"v1.2".to_owned(),
];
let random_order_supported = SupportedVersions::from_parts(random_order, &empty_features);
assert_eq!(
random_order_supported.versions,
BTreeSet::from([V1_0, V1_1, V1_2])
);
}
#[test]
#[should_panic]
fn make_endpoint_url_with_path_args_old_syntax() {
let meta = stable_only_metadata(&[(StablePathSelector::Version(V1_0), "/s/:x")]);
let url = meta
.make_endpoint_url(
&version_only_supported(&[V1_0]),
"https://example.org",
&[&"123"],
"",
)
.unwrap();
assert_eq!(url, "https://example.org/s/123");
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/metadata/matrix_version.rs | crates/core/src/metadata/matrix_version.rs | use std::{
cmp::Ordering,
fmt::{self, Display},
str::FromStr,
};
use salvo::prelude::*;
use serde::Serialize;
use crate::RoomVersionId;
use crate::error::UnknownVersionError;
/// The Matrix versions Palpo currently understands to exist.
///
/// Matrix, since fall 2021, has a quarterly release schedule, using a global
/// `vX.Y` versioning scheme.
///
/// Every new minor version denotes stable support for endpoints in a
/// *relatively* backwards-compatible manner.
///
/// Matrix has a deprecation policy, read more about it here: <https://spec.matrix.org/latest/#deprecation-policy>.
///
/// Palpo keeps track of when endpoints are added, deprecated, and removed.
/// It'll automatically select the right endpoint stability variation to use
/// depending on which Matrix versions you
/// pass to [`try_into_http_request`](super::OutgoingRequest::try_into_http_request), see its
/// respective documentation for more information.
#[derive(ToSchema, Serialize, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum MatrixVersion {
/// Matrix 1.0 was a release prior to the global versioning system and does not correspond to a
/// version of the Matrix specification.
///
/// It matches the following per-API versions:
///
/// * Client-Server API: r0.5.0 to r0.6.1
/// * Identity Service API: r0.2.0 to r0.3.0
///
/// The other APIs are not supported because they do not have a `GET /versions` endpoint.
///
/// See <https://spec.matrix.org/latest/#legacy-versioning>.
V1_0,
/// Version 1.1 of the Matrix specification, released in Q4 2021.
///
/// See <https://spec.matrix.org/v1.1/>.
V1_1,
/// Version 1.2 of the Matrix specification, released in Q1 2022.
///
/// See <https://spec.matrix.org/v1.2/>.
V1_2,
/// Version 1.3 of the Matrix specification, released in Q2 2022.
///
/// See <https://spec.matrix.org/v1.3/>.
V1_3,
/// Version 1.4 of the Matrix specification, released in Q3 2022.
///
/// See <https://spec.matrix.org/v1.4/>.
V1_4,
/// Version 1.5 of the Matrix specification, released in Q4 2022.
///
/// See <https://spec.matrix.org/v1.5/>.
V1_5,
/// Version 1.6 of the Matrix specification, released in Q1 2023.
///
/// See <https://spec.matrix.org/v1.6/>.
V1_6,
/// Version 1.7 of the Matrix specification, released in Q2 2023.
///
/// See <https://spec.matrix.org/v1.7/>.
V1_7,
/// Version 1.8 of the Matrix specification, released in Q3 2023.
///
/// See <https://spec.matrix.org/v1.8/>.
V1_8,
/// Version 1.9 of the Matrix specification, released in Q4 2023.
///
/// See <https://spec.matrix.org/v1.9/>.
V1_9,
/// Version 1.10 of the Matrix specification, released in Q1 2024.
///
/// See <https://spec.matrix.org/v1.10/>.
V1_10,
/// Version 1.11 of the Matrix specification, released in Q2 2024.
///
/// See <https://spec.matrix.org/v1.11/>.
V1_11,
/// Version 1.12 of the Matrix specification, released in Q3 2024.
///
/// See <https://spec.matrix.org/v1.12/>.
V1_12,
/// Version 1.13 of the Matrix specification, released in Q4 2024.
///
/// See <https://spec.matrix.org/v1.13/>.
V1_13,
/// Version 1.14 of the Matrix specification, released in Q1 2025.
///
/// See <https://spec.matrix.org/v1.14/>.
V1_14,
/// Version 1.15 of the Matrix specification, released in Q2 2025.
///
/// See <https://spec.matrix.org/v1.15/>.
V1_15,
/// Version 1.16 of the Matrix specification, released in Q3 2025.
///
/// See <https://spec.matrix.org/v1.17/>.
V1_16,
/// Version 1.17 of the Matrix specification, released in Q4 2025.
///
/// See <https://spec.matrix.org/v1.17/>.
V1_17,
}
impl TryFrom<&str> for MatrixVersion {
type Error = UnknownVersionError;
fn try_from(value: &str) -> Result<MatrixVersion, Self::Error> {
use MatrixVersion::*;
Ok(match value {
"v1.0" |
// Additional definitions according to https://spec.matrix.org/latest/#legacy-versioning
"r0.5.0" | "r0.6.0" | "r0.6.1" => V1_0,
"v1.1" => V1_1,
"v1.2" => V1_2,
"v1.3" => V1_3,
"v1.4" => V1_4,
"v1.5" => V1_5,
"v1.6" => V1_6,
"v1.7" => V1_7,
"v1.8" => V1_8,
"v1.9" => V1_9,
"v1.10" => V1_10,
"v1.11" => V1_11,
"v1.12" => V1_12,
"v1.13" => V1_13,
"v1.14" => V1_14,
"v1.15" => V1_15,
"v1.16" => V1_16,
"v1.17" => V1_17,
_ => return Err(UnknownVersionError),
})
}
}
impl FromStr for MatrixVersion {
type Err = UnknownVersionError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl MatrixVersion {
/// Checks whether a version is compatible with another.
///
/// A is compatible with B as long as B is equal or less, so long as A and B
/// have the same major versions.
///
/// For example, v1.2 is compatible with v1.1, as it is likely only some
/// additions of endpoints on top of v1.1, but v1.1 would not be
/// compatible with v1.2, as v1.1 cannot represent all of v1.2, in a
/// manner similar to set theory.
///
/// Warning: Matrix has a deprecation policy, and Matrix versioning is not
/// as straight-forward as this function makes it out to be. This
/// function only exists to prune major version differences, and
/// versions too new for `self`.
///
/// This (considering if major versions are the same) is equivalent to a
/// `self >= other` check.
pub fn is_superset_of(self, other: Self) -> bool {
let (major_l, minor_l) = self.into_parts();
let (major_r, minor_r) = other.into_parts();
major_l == major_r && minor_l >= minor_r
}
/// Get a string representation of this Matrix version.
///
/// This is the string that can be found in the response to one of the `GET /versions`
/// endpoints. Parsing this string will give the same variant.
///
/// Returns `None` for [`MatrixVersion::V1_0`] because it can match several per-API versions.
pub const fn as_str(self) -> Option<&'static str> {
let string = match self {
MatrixVersion::V1_0 => return None,
MatrixVersion::V1_1 => "v1.1",
MatrixVersion::V1_2 => "v1.2",
MatrixVersion::V1_3 => "v1.3",
MatrixVersion::V1_4 => "v1.4",
MatrixVersion::V1_5 => "v1.5",
MatrixVersion::V1_6 => "v1.6",
MatrixVersion::V1_7 => "v1.7",
MatrixVersion::V1_8 => "v1.8",
MatrixVersion::V1_9 => "v1.9",
MatrixVersion::V1_10 => "v1.10",
MatrixVersion::V1_11 => "v1.11",
MatrixVersion::V1_12 => "v1.12",
MatrixVersion::V1_13 => "v1.13",
MatrixVersion::V1_14 => "v1.14",
MatrixVersion::V1_15 => "v1.15",
MatrixVersion::V1_16 => "v1.16",
MatrixVersion::V1_17 => "v1.17",
};
Some(string)
}
/// Decompose the Matrix version into its major and minor number.
pub const fn into_parts(self) -> (u8, u8) {
match self {
MatrixVersion::V1_0 => (1, 0),
MatrixVersion::V1_1 => (1, 1),
MatrixVersion::V1_2 => (1, 2),
MatrixVersion::V1_3 => (1, 3),
MatrixVersion::V1_4 => (1, 4),
MatrixVersion::V1_5 => (1, 5),
MatrixVersion::V1_6 => (1, 6),
MatrixVersion::V1_7 => (1, 7),
MatrixVersion::V1_8 => (1, 8),
MatrixVersion::V1_9 => (1, 9),
MatrixVersion::V1_10 => (1, 10),
MatrixVersion::V1_11 => (1, 11),
MatrixVersion::V1_12 => (1, 12),
MatrixVersion::V1_13 => (1, 13),
MatrixVersion::V1_14 => (1, 14),
MatrixVersion::V1_15 => (1, 15),
MatrixVersion::V1_16 => (1, 16),
MatrixVersion::V1_17 => (1, 17),
}
}
/// Try to turn a pair of (major, minor) version components back into a
/// `MatrixVersion`.
pub const fn from_parts(major: u8, minor: u8) -> Result<Self, UnknownVersionError> {
match (major, minor) {
(1, 0) => Ok(MatrixVersion::V1_0),
(1, 1) => Ok(MatrixVersion::V1_1),
(1, 2) => Ok(MatrixVersion::V1_2),
(1, 3) => Ok(MatrixVersion::V1_3),
(1, 4) => Ok(MatrixVersion::V1_4),
(1, 5) => Ok(MatrixVersion::V1_5),
(1, 6) => Ok(MatrixVersion::V1_6),
(1, 7) => Ok(MatrixVersion::V1_7),
(1, 8) => Ok(MatrixVersion::V1_8),
(1, 9) => Ok(MatrixVersion::V1_9),
(1, 10) => Ok(MatrixVersion::V1_10),
(1, 11) => Ok(MatrixVersion::V1_11),
(1, 12) => Ok(MatrixVersion::V1_12),
(1, 13) => Ok(MatrixVersion::V1_13),
(1, 14) => Ok(MatrixVersion::V1_14),
(1, 15) => Ok(MatrixVersion::V1_15),
(1, 16) => Ok(MatrixVersion::V1_16),
(1, 17) => Ok(MatrixVersion::V1_17),
_ => Err(UnknownVersionError),
}
}
/// Constructor for use by the `metadata!` macro.
///
/// Accepts string literals and parses them.
#[doc(hidden)]
pub const fn from_lit(lit: &'static str) -> Self {
use konst::{option, primitive::parse_u8, result, string};
let major: u8;
let minor: u8;
let mut lit_iter = string::split(lit, ".").next();
{
let (checked_first, checked_split) = option::unwrap!(lit_iter); // First iteration always succeeds
major = result::unwrap_or_else!(parse_u8(checked_first), |_| panic!(
"major version is not a valid number"
));
lit_iter = checked_split.next();
}
match lit_iter {
Some((checked_second, checked_split)) => {
minor = result::unwrap_or_else!(parse_u8(checked_second), |_| panic!(
"minor version is not a valid number"
));
lit_iter = checked_split.next();
}
None => panic!("could not find dot to denote second number"),
}
if lit_iter.is_some() {
panic!("version literal contains more than one dot")
}
result::unwrap_or_else!(Self::from_parts(major, minor), |_| panic!(
"not a valid version literal"
))
}
// Internal function to do ordering in const-fn contexts
pub(crate) const fn const_ord(&self, other: &Self) -> Ordering {
let self_parts = self.into_parts();
let other_parts = other.into_parts();
use konst::primitive::cmp::cmp_u8;
let major_ord = cmp_u8(self_parts.0, other_parts.0);
if major_ord.is_ne() {
major_ord
} else {
cmp_u8(self_parts.1, other_parts.1)
}
}
// Internal function to check if this version is the legacy (v1.0) version in
// const-fn contexts
pub(crate) const fn is_legacy(&self) -> bool {
let self_parts = self.into_parts();
use konst::primitive::cmp::cmp_u8;
cmp_u8(self_parts.0, 1).is_eq() && cmp_u8(self_parts.1, 0).is_eq()
}
/// Get the default [`RoomVersionId`] for this `MatrixVersion`.
pub fn default_room_version(&self) -> RoomVersionId {
match self {
// <https://spec.matrix.org/historical/index.html#complete-list-of-room-versions>
MatrixVersion::V1_0
// <https://spec.matrix.org/v1.1/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_1
// <https://spec.matrix.org/v1.2/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_2 => RoomVersionId::V6,
// <https://spec.matrix.org/v1.3/rooms/#complete-list-of-room-versions>
MatrixVersion::V1_3
// <https://spec.matrix.org/v1.4/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_4
// <https://spec.matrix.org/v1.5/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_5 => RoomVersionId::V9,
// <https://spec.matrix.org/v1.6/rooms/#complete-list-of-room-versions>
MatrixVersion::V1_6
// <https://spec.matrix.org/v1.7/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_7
// <https://spec.matrix.org/v1.8/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_8
// <https://spec.matrix.org/v1.9/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_9
// <https://spec.matrix.org/v1.10/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_10
// <https://spec.matrix.org/v1.11/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_11
// <https://spec.matrix.org/v1.12/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_12
// <https://spec.matrix.org/v1.13/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_13 => RoomVersionId::V10,
// <https://spec.matrix.org/v1.14/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_14
// <https://spec.matrix.org/v1.15/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_15 => RoomVersionId::V11,
// <https://spec.matrix.org/v1.17/rooms/#complete-list-of-room-versions>
MatrixVersion::V1_16
// <https://spec.matrix.org/v1.17/rooms/#complete-list-of-room-versions>
| MatrixVersion::V1_17 => RoomVersionId::V12,
}
}
}
impl Display for MatrixVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (major, minor) = self.into_parts();
f.write_str(&format!("v{major}.{minor}"))
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/metadata/supported_versions.rs | crates/core/src/metadata/supported_versions.rs | use std::collections::{BTreeMap, BTreeSet};
use crate::serde::StringEnum;
use crate::{MatrixVersion, PrivOwnedStr};
/// The list of Matrix versions and features supported by a homeserver.
#[derive(Debug, Clone)]
#[allow(clippy::exhaustive_structs)]
pub struct SupportedVersions {
/// The Matrix versions that are supported by the homeserver.
///
/// This set contains only known versions.
pub versions: BTreeSet<MatrixVersion>,
/// The features that are supported by the homeserver.
///
/// This matches the `unstable_features` field of the `/versions` endpoint, without the boolean
/// value.
pub features: BTreeSet<FeatureFlag>,
}
impl SupportedVersions {
/// Construct a `SupportedVersions` from the parts of a `/versions` response.
///
/// Matrix versions that can't be parsed to a `MatrixVersion`, and features with the boolean
/// value set to `false` are discarded.
pub fn from_parts(versions: &[String], unstable_features: &BTreeMap<String, bool>) -> Self {
Self {
versions: versions
.iter()
.flat_map(|s| s.parse::<MatrixVersion>())
.collect(),
features: unstable_features
.iter()
.filter(|(_, enabled)| **enabled)
.map(|(feature, _)| feature.as_str().into())
.collect(),
}
}
}
/// The Matrix features supported by Palpo.
///
/// Features that are not behind a cargo feature are features that are part of the Matrix
/// specification and that Palpo still supports, like the unstable version of an endpoint or a stable
/// feature. Features behind a cargo feature are only supported when this feature is enabled.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum, Hash)]
#[non_exhaustive]
pub enum FeatureFlag {
/// `fi.mau.msc2246` ([MSC])
///
/// Asynchronous media uploads.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2246
#[palpo_enum(rename = "fi.mau.msc2246")]
Msc2246,
/// `org.matrix.msc2432` ([MSC])
///
/// Updated semantics for publishing room aliases.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2432
#[palpo_enum(rename = "org.matrix.msc2432")]
Msc2432,
/// `fi.mau.msc2659` ([MSC])
///
/// Application service ping endpoint.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2659
#[palpo_enum(rename = "fi.mau.msc2659")]
Msc2659,
/// `fi.mau.msc2659` ([MSC])
///
/// Stable version of the application service ping endpoint.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2659
#[palpo_enum(rename = "fi.mau.msc2659.stable")]
Msc2659Stable,
/// `uk.half-shot.msc2666.query_mutual_rooms` ([MSC])
///
/// Get rooms in common with another user.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/2666
#[cfg(feature = "unstable-msc2666")]
#[palpo_enum(rename = "uk.half-shot.msc2666.query_mutual_rooms")]
Msc2666,
/// `org.matrix.msc3030` ([MSC])
///
/// Jump to date API endpoint.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3030
#[palpo_enum(rename = "org.matrix.msc3030")]
Msc3030,
/// `org.matrix.msc3882` ([MSC])
///
/// Allow an existing session to sign in a new session.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3882
#[palpo_enum(rename = "org.matrix.msc3882")]
Msc3882,
/// `org.matrix.msc3916` ([MSC])
///
/// Authentication for media.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916
#[palpo_enum(rename = "org.matrix.msc3916")]
Msc3916,
/// `org.matrix.msc3916.stable` ([MSC])
///
/// Stable version of authentication for media.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916
#[palpo_enum(rename = "org.matrix.msc3916.stable")]
Msc3916Stable,
/// `org.matrix.msc4108` ([MSC])
///
/// Mechanism to allow OIDC sign in and E2EE set up via QR code.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4108
#[cfg(feature = "unstable-msc4108")]
#[palpo_enum(rename = "org.matrix.msc4108")]
Msc4108,
/// `org.matrix.msc4140` ([MSC])
///
/// Delayed events.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4140
#[cfg(feature = "unstable-msc4140")]
#[palpo_enum(rename = "org.matrix.msc4140")]
Msc4140,
/// `org.matrix.simplified_msc3575` ([MSC])
///
/// Simplified Sliding Sync.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186
#[cfg(feature = "unstable-msc4186")]
#[palpo_enum(rename = "org.matrix.simplified_msc3575")]
Msc4186,
/// `org.matrix.msc4380_invite_permission_config` ([MSC])
///
/// Invite Blocking.
///
/// [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4380
#[cfg(feature = "unstable-msc4380")]
#[palpo_enum(rename = "org.matrix.msc4380")]
Msc4380,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/error/kind.rs | crates/core/src/error/kind.rs | //! Errors that can be sent from the homeserver.
use std::collections::BTreeMap;
use serde_json::Value as JsonValue;
use super::{ErrorCode, RetryAfter};
use crate::error::AuthenticateError;
use crate::{PrivOwnedStr, RoomVersionId};
/// An enum for the error kind.
///
/// Items may contain additional information.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
// Please keep the variants sorted alphabetically.
pub enum ErrorKind {
/// `M_APPSERVICE_LOGIN_UNSUPPORTED`
///
/// An application service used the [`m.login.application_service`] type an endpoint from the
/// [legacy authentication API] in a way that is not supported by the homeserver, because the
/// server only supports the [OAuth 2.0 API].
///
/// [`m.login.application_service`]: https://spec.matrix.org/latest/application-service-api/#server-admin-style-permissions
/// [legacy authentication API]: https://spec.matrix.org/latest/client-server-api/#legacy-api
/// [OAuth 2.0 API]: https://spec.matrix.org/latest/client-server-api/#oauth-20-api
AppserviceLoginUnsupported,
/// `M_BAD_ALIAS`
///
/// One or more [room aliases] within the `m.room.canonical_alias` event do
/// not point to the room ID for which the state event is to be sent to.
///
/// [room aliases]: https://spec.matrix.org/latest/client-server-api/#room-aliases
BadAlias,
/// `M_BAD_JSON`
///
/// The request contained valid JSON, but it was malformed in some way, e.g.
/// missing required keys, invalid values for keys.
BadJson,
/// `M_BAD_STATE`
///
/// The state change requested cannot be performed, such as attempting to
/// unban a user who is not banned.
BadState,
/// `M_BAD_STATUS`
///
/// The application service returned a bad status.
BadStatus {
/// The HTTP status code of the response.
status: Option<http::StatusCode>,
/// The body of the response.
body: Option<String>,
},
/// `M_CANNOT_LEAVE_SERVER_NOTICE_ROOM`
///
/// The user is unable to reject an invite to join the [server notices]
/// room.
///
/// [server notices]: https://spec.matrix.org/latest/client-server-api/#server-notices
CannotLeaveServerNoticeRoom,
/// `M_CANNOT_OVERWRITE_MEDIA`
///
/// The [`create_content_async`] endpoint was called with a media ID that
/// already has content.
///
/// [`create_content_async`]: crate::media::create_content_async
CannotOverwriteMedia,
/// `M_CAPTCHA_INVALID`
///
/// The Captcha provided did not match what was expected.
CaptchaInvalid,
/// `M_CAPTCHA_NEEDED`
///
/// A Captcha is required to complete the request.
CaptchaNeeded,
/// `M_CONFLICTING_UNSUBSCRIPTION`
///
/// Part of [MSC4306]: an automatic thread subscription has been skipped by the server, because
/// the user unsubsubscribed after the indicated subscribed-to event.
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
ConflictingUnsubscription,
/// `M_CONNECTION_FAILED`
///
/// The connection to the application service failed.
ConnectionFailed,
/// `M_CONNECTION_TIMEOUT`
///
/// The connection to the application service timed out.
ConnectionTimeout,
/// `M_DUPLICATE_ANNOTATION`
///
/// The request is an attempt to send a [duplicate annotation].
///
/// [duplicate annotation]: https://spec.matrix.org/latest/client-server-api/#avoiding-duplicate-annotations
DuplicateAnnotation,
/// `M_EXCLUSIVE`
///
/// The resource being requested is reserved by an application service, or
/// the application service making the request has not created the
/// resource.
Exclusive,
/// `M_FORBIDDEN`
///
/// Forbidden access, e.g. joining a room without permission, failed login.
#[non_exhaustive]
Forbidden {
/// The `WWW-Authenticate` header error message.
authenticate: Option<AuthenticateError>,
},
/// `M_GUEST_ACCESS_FORBIDDEN`
///
/// The room or resource does not permit [guests] to access it.
///
/// [guests]: https://spec.matrix.org/latest/client-server-api/#guest-access
GuestAccessForbidden,
/// `M_INCOMPATIBLE_ROOM_VERSION`
///
/// The client attempted to join a room that has a version the server does
/// not support.
IncompatibleRoomVersion {
/// The room's version.
room_version: RoomVersionId,
},
/// `M_INVALID_PARAM`
///
/// A parameter that was specified has the wrong value. For example, the
/// server expected an integer and instead received a string.
InvalidParam,
/// `M_INVALID_ROOM_STATE`
///
/// The initial state implied by the parameters to the [`create_room`]
/// request is invalid, e.g. the user's `power_level` is set below that
/// necessary to set the room name.
///
/// [`create_room`]: crate::room::create_room
InvalidRoomState,
/// `M_INVALID_USERNAME`
///
/// The desired user name is not valid.
InvalidUsername,
/// `M_INVITE_BLOCKED`
///
/// The invite was interdicted by moderation tools or configured access controls without having
/// been witnessed by the invitee.
#[cfg(feature = "unstable-msc4380")]
InviteBlocked,
/// `M_LIMIT_EXCEEDED`
///
/// The request has been refused due to [rate limiting]: too many requests
/// have been sent in a short period of time.
///
/// [rate limiting]: https://spec.matrix.org/latest/client-server-api/#rate-limiting
LimitExceeded {
/// How long a client should wait before they can try again.
retry_after: Option<RetryAfter>,
},
/// `M_MISSING_PARAM`
///
/// A required parameter was missing from the request.
MissingParam,
/// `M_MISSING_TOKEN`
///
/// No [access token] was specified for the request, but one is required.
///
/// [access token]: https://spec.matrix.org/latest/client-server-api/#client-authentication
MissingToken,
/// `M_NOT_FOUND`
///
/// No resource was found for this request.
NotFound,
/// `M_NOT_IN_THREAD`
///
/// Part of [MSC4306]: an automatic thread subscription was set to an event ID that isn't part
/// of the subscribed-to thread.
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
NotInThread,
/// `M_NOT_JSON`
///
/// The request did not contain valid JSON.
NotJson,
/// `M_NOT_YET_UPLOADED`
///
/// An `mxc:` URI generated with the [`create_mxc_uri`] endpoint was used
/// and the content is not yet available.
///
/// [`create_mxc_uri`]: crate::media::create_mxc_uri
NotYetUploaded,
/// `M_RESOURCE_LIMIT_EXCEEDED`
///
/// The request cannot be completed because the homeserver has reached a
/// resource limit imposed on it. For example, a homeserver held in a
/// shared hosting environment may reach a resource limit if it starts
/// using too much memory or disk space.
ResourceLimitExceeded {
/// A URI giving a contact method for the server administrator.
admin_contact: String,
},
/// `M_ROOM_IN_USE`
///
/// The [room alias] specified in the [`create_room`] request is already
/// taken.
///
/// [`create_room`]: crate::room::create_room
/// [room alias]: https://spec.matrix.org/latest/client-server-api/#room-aliases
RoomInUse,
/// `M_SERVER_NOT_TRUSTED`
///
/// The client's request used a third-party server, e.g. identity server,
/// that this server does not trust.
ServerNotTrusted,
/// `M_THREEPID_AUTH_FAILED`
///
/// Authentication could not be performed on the [third-party identifier].
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidAuthFailed,
/// `M_THREEPID_DENIED`
///
/// The server does not permit this [third-party identifier]. This may
/// happen if the server only permits, for example, email addresses from
/// a particular domain.
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidDenied,
/// `M_THREEPID_IN_USE`
///
/// The [third-party identifier] is already in use by another user.
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidInUse,
/// `M_THREEPID_MEDIUM_NOT_SUPPORTED`
///
/// The homeserver does not support adding a [third-party identifier] of the
/// given medium.
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidMediumNotSupported,
/// `M_THREEPID_NOT_FOUND`
///
/// No account matching the given [third-party identifier] could be found.
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidNotFound,
/// `M_TOO_LARGE`
///
/// The request or entity was too large.
TooLarge,
/// `M_UNABLE_TO_AUTHORISE_JOIN`
///
/// The room is [restricted] and none of the conditions can be validated by
/// the homeserver. This can happen if the homeserver does not know
/// about any of the rooms listed as conditions, for example.
///
/// [restricted]: https://spec.matrix.org/latest/client-server-api/#restricted-rooms
UnableToAuthorizeJoin,
/// `M_UNABLE_TO_GRANT_JOIN`
///
/// A different server should be attempted for the join. This is typically
/// because the resident server can see that the joining user satisfies
/// one or more conditions, such as in the case of [restricted rooms],
/// but the resident server would be unable to meet the authorization
/// rules.
///
/// [restricted rooms]: https://spec.matrix.org/latest/client-server-api/#restricted-rooms
UnableToGrantJoin,
/// `M_UNACTIONABLE`
///
/// The server does not want to handle the [federated report].
///
/// [federated report]: https://github.com/matrix-org/matrix-spec-proposals/pull/3843
#[cfg(feature = "unstable-msc3843")]
Unactionable,
/// `M_UNAUTHORIZED`
///
/// The request was not correctly authorized. Usually due to login failures.
Unauthorized,
/// `M_UNKNOWN`
///
/// An unknown error has occurred.
Unknown,
/// `M_UNKNOWN_POS`
///
/// The sliding sync ([MSC4186]) connection was expired by the server.
///
/// [MSC4186]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186
#[cfg(feature = "unstable-msc4186")]
UnknownPos,
/// `M_UNKNOWN_TOKEN`
///
/// The [access or refresh token] specified was not recognized.
///
/// [access or refresh token]: https://spec.matrix.org/latest/client-server-api/#client-authentication
UnknownToken {
/// If this is `true`, the client is in a "[soft logout]" state, i.e.
/// the server requires re-authentication but the session is not
/// invalidated. The client can acquire a new access token by
/// specifying the device ID it is already using to the login API.
///
/// [soft logout]: https://spec.matrix.org/latest/client-server-api/#soft-logout
soft_logout: bool,
},
/// `M_UNRECOGNIZED`
///
/// The server did not understand the request.
///
/// This is expected to be returned with a 404 HTTP status code if the
/// endpoint is not implemented or a 405 HTTP status code if the
/// endpoint is implemented, but the incorrect HTTP method is used.
Unrecognized,
/// `M_UNSUPPORTED_ROOM_VERSION`
///
/// The request to [`create_room`] used a room version that the server does
/// not support.
///
/// [`create_room`]: crate::room::create_room
UnsupportedRoomVersion,
/// `M_URL_NOT_SET`
///
/// The application service doesn't have a URL configured.
UrlNotSet,
/// `M_USER_DEACTIVATED`
///
/// The user ID associated with the request has been deactivated.
UserDeactivated,
/// `M_USER_IN_USE`
///
/// The desired user ID is already taken.
UserInUse,
/// `M_USER_LOCKED`
///
/// The account has been [locked] and cannot be used at this time.
///
/// [locked]: https://spec.matrix.org/latest/client-server-api/#account-locking
UserLocked,
/// `M_USER_SUSPENDED`
///
/// The account has been [suspended] and can only be used for limited
/// actions at this time.
///
/// [suspended]: https://spec.matrix.org/latest/client-server-api/#account-suspension
UserSuspended,
/// `M_WEAK_PASSWORD`
///
/// The password was [rejected] by the server for being too weak.
///
/// [rejected]: https://spec.matrix.org/latest/client-server-api/#notes-on-password-management
WeakPassword,
/// `M_WRONG_ROOM_KEYS_VERSION`
///
/// The version of the [room keys backup] provided in the request does not
/// match the current backup version.
///
/// [room keys backup]: https://spec.matrix.org/latest/client-server-api/#server-side-key-backups
WrongRoomKeysVersion {
/// The currently active backup version.
current_version: Option<String>,
},
#[doc(hidden)]
_Custom {
errcode: PrivOwnedStr,
extra: BTreeMap<String, JsonValue>,
},
}
impl ErrorKind {
/// Constructs an empty [`ErrorKind::Forbidden`] variant.
pub fn forbidden() -> Self {
Self::Forbidden { authenticate: None }
}
/// Constructs an [`ErrorKind::Forbidden`] variant with the given
/// `WWW-Authenticate` header error message.
pub fn forbidden_with_authenticate(authenticate: AuthenticateError) -> Self {
Self::Forbidden {
authenticate: Some(authenticate),
}
}
/// Get the [`ErrorCode`] for this `ErrorKind`.
pub fn code(&self) -> ErrorCode {
match self {
ErrorKind::AppserviceLoginUnsupported => ErrorCode::AppserviceLoginUnsupported,
ErrorKind::BadAlias => ErrorCode::BadAlias,
ErrorKind::BadJson => ErrorCode::BadJson,
ErrorKind::BadState => ErrorCode::BadState,
ErrorKind::BadStatus { .. } => ErrorCode::BadStatus,
ErrorKind::CannotLeaveServerNoticeRoom => ErrorCode::CannotLeaveServerNoticeRoom,
ErrorKind::CannotOverwriteMedia => ErrorCode::CannotOverwriteMedia,
ErrorKind::CaptchaInvalid => ErrorCode::CaptchaInvalid,
ErrorKind::CaptchaNeeded => ErrorCode::CaptchaNeeded,
#[cfg(feature = "unstable-msc4306")]
ErrorKind::ConflictingUnsubscription => ErrorCode::ConflictingUnsubscription,
ErrorKind::ConnectionFailed => ErrorCode::ConnectionFailed,
ErrorKind::ConnectionTimeout => ErrorCode::ConnectionTimeout,
ErrorKind::DuplicateAnnotation => ErrorCode::DuplicateAnnotation,
ErrorKind::Exclusive => ErrorCode::Exclusive,
ErrorKind::Forbidden { .. } => ErrorCode::Forbidden,
ErrorKind::GuestAccessForbidden => ErrorCode::GuestAccessForbidden,
ErrorKind::IncompatibleRoomVersion { .. } => ErrorCode::IncompatibleRoomVersion,
ErrorKind::InvalidParam => ErrorCode::InvalidParam,
ErrorKind::InvalidRoomState => ErrorCode::InvalidRoomState,
ErrorKind::InvalidUsername => ErrorCode::InvalidUsername,
#[cfg(feature = "unstable-msc4380")]
ErrorKind::InviteBlocked => ErrorCode::InviteBlocked,
ErrorKind::LimitExceeded { .. } => ErrorCode::LimitExceeded,
ErrorKind::MissingParam => ErrorCode::MissingParam,
ErrorKind::MissingToken => ErrorCode::MissingToken,
ErrorKind::NotFound => ErrorCode::NotFound,
#[cfg(feature = "unstable-msc4306")]
ErrorKind::NotInThread => ErrorCode::NotInThread,
ErrorKind::NotJson => ErrorCode::NotJson,
ErrorKind::NotYetUploaded => ErrorCode::NotYetUploaded,
ErrorKind::ResourceLimitExceeded { .. } => ErrorCode::ResourceLimitExceeded,
ErrorKind::RoomInUse => ErrorCode::RoomInUse,
ErrorKind::ServerNotTrusted => ErrorCode::ServerNotTrusted,
ErrorKind::ThreepidAuthFailed => ErrorCode::ThreepidAuthFailed,
ErrorKind::ThreepidDenied => ErrorCode::ThreepidDenied,
ErrorKind::ThreepidInUse => ErrorCode::ThreepidInUse,
ErrorKind::ThreepidMediumNotSupported => ErrorCode::ThreepidMediumNotSupported,
ErrorKind::ThreepidNotFound => ErrorCode::ThreepidNotFound,
ErrorKind::TooLarge => ErrorCode::TooLarge,
ErrorKind::UnableToAuthorizeJoin => ErrorCode::UnableToAuthorizeJoin,
ErrorKind::UnableToGrantJoin => ErrorCode::UnableToGrantJoin,
#[cfg(feature = "unstable-msc3843")]
ErrorKind::Unactionable => ErrorCode::Unactionable,
ErrorKind::Unauthorized => ErrorCode::Unauthorized,
ErrorKind::Unknown => ErrorCode::Unknown,
#[cfg(feature = "unstable-msc4186")]
ErrorKind::UnknownPos => ErrorCode::UnknownPos,
ErrorKind::UnknownToken { .. } => ErrorCode::UnknownToken,
ErrorKind::Unrecognized => ErrorCode::Unrecognized,
ErrorKind::UnsupportedRoomVersion => ErrorCode::UnsupportedRoomVersion,
ErrorKind::UrlNotSet => ErrorCode::UrlNotSet,
ErrorKind::UserDeactivated => ErrorCode::UserDeactivated,
ErrorKind::UserInUse => ErrorCode::UserInUse,
ErrorKind::UserLocked => ErrorCode::UserLocked,
ErrorKind::UserSuspended => ErrorCode::UserSuspended,
ErrorKind::WeakPassword => ErrorCode::WeakPassword,
ErrorKind::WrongRoomKeysVersion { .. } => ErrorCode::WrongRoomKeysVersion,
ErrorKind::_Custom { errcode, .. } => errcode.0.clone().into(),
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/error/auth.rs | crates/core/src/error/auth.rs | //! Errors that can be sent from the homeserver.
use std::collections::BTreeMap;
use crate::PrivOwnedStr;
/// Errors in the `WWW-Authenticate` header.
///
/// To construct this use `::from_str()`. To get its serialized form, use its
/// `TryInto<http::HeaderValue>` implementation.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthenticateError {
/// insufficient_scope
///
/// Encountered when authentication is handled by OpenID Connect and the
/// current access token isn't authorized for the proper scope for this
/// request. It should be paired with a `401` status code and a
/// `M_FORBIDDEN` error.
InsufficientScope {
/// The new scope to request an authorization for.
scope: String,
},
#[doc(hidden)]
_Custom {
errcode: PrivOwnedStr,
attributes: AuthenticateAttrs,
},
}
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AuthenticateAttrs(BTreeMap<String, String>);
impl AuthenticateError {
/// Construct an `AuthenticateError` from a string.
///
/// Returns `None` if the string doesn't contain an error.
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Option<Self> {
if let Some(val) = s.strip_prefix("Bearer").map(str::trim) {
let mut errcode = None;
let mut attrs = BTreeMap::new();
// Split the attributes separated by commas and optionally spaces, then split
// the keys and the values, with the values optionally surrounded by
// double quotes.
for (key, value) in val
.split(',')
.filter_map(|attr| attr.trim().split_once('='))
.map(|(key, value)| (key, value.trim_matches('"')))
{
if key == "error" {
errcode = Some(value);
} else {
attrs.insert(key.to_owned(), value.to_owned());
}
}
if let Some(errcode) = errcode {
let error = if let Some(scope) = attrs
.get("scope")
.filter(|_| errcode == "insufficient_scope")
{
AuthenticateError::InsufficientScope {
scope: scope.to_owned(),
}
} else {
AuthenticateError::_Custom {
errcode: PrivOwnedStr(errcode.into()),
attributes: AuthenticateAttrs(attrs),
}
};
return Some(error);
}
}
None
}
}
impl TryFrom<&AuthenticateError> for http::HeaderValue {
type Error = http::header::InvalidHeaderValue;
fn try_from(error: &AuthenticateError) -> Result<Self, Self::Error> {
let s = match error {
AuthenticateError::InsufficientScope { scope } => {
format!("Bearer error=\"insufficient_scope\", scope=\"{scope}\"")
}
AuthenticateError::_Custom {
errcode,
attributes,
} => {
let mut s = format!("Bearer error=\"{}\"", errcode.0);
for (key, value) in attributes.0.iter() {
s.push_str(&format!(", {key}=\"{value}\""));
}
s
}
};
s.try_into()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/error/kind_serde.rs | crates/core/src/error/kind_serde.rs | use std::{
borrow::Cow,
collections::btree_map::{BTreeMap, Entry},
fmt,
str::FromStr,
time::{Duration, SystemTime},
};
use serde::{
de::{self, Deserialize, Deserializer, MapAccess, Visitor},
ser::{self, Serialize, SerializeMap, Serializer},
};
use serde_json::from_value as from_json_value;
use super::ErrorKind;
use crate::PrivOwnedStr;
use crate::client::http_header::{http_date_to_system_time, system_time_to_http_date};
use crate::error::{HeaderDeserializationError, HeaderSerializationError};
use crate::macros::StringEnum;
enum Field<'de> {
ErrorCode,
SoftLogout,
RetryAfterMs,
RoomVersion,
AdminContact,
Status,
Body,
CurrentVersion,
Other(Cow<'de, str>),
}
impl<'de> Field<'de> {
fn new(s: Cow<'de, str>) -> Field<'de> {
match s.as_ref() {
"errcode" => Self::ErrorCode,
"soft_logout" => Self::SoftLogout,
"retry_after_ms" => Self::RetryAfterMs,
"room_version" => Self::RoomVersion,
"admin_contact" => Self::AdminContact,
"status" => Self::Status,
"body" => Self::Body,
"current_version" => Self::CurrentVersion,
_ => Self::Other(s),
}
}
}
impl<'de> Deserialize<'de> for Field<'de> {
fn deserialize<D>(deserializer: D) -> Result<Field<'de>, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field<'de>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("any struct field")
}
fn visit_str<E>(self, value: &str) -> Result<Field<'de>, E>
where
E: de::Error,
{
Ok(Field::new(Cow::Owned(value.to_owned())))
}
fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Field<'de>, E>
where
E: de::Error,
{
Ok(Field::new(Cow::Borrowed(value)))
}
fn visit_string<E>(self, value: String) -> Result<Field<'de>, E>
where
E: de::Error,
{
Ok(Field::new(Cow::Owned(value)))
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct ErrorKindVisitor;
impl<'de> Visitor<'de> for ErrorKindVisitor {
type Value = ErrorKind;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("enum ErrorKind")
}
fn visit_map<V>(self, mut map: V) -> Result<ErrorKind, V::Error>
where
V: MapAccess<'de>,
{
let mut errcode = None;
let mut soft_logout = None;
let mut retry_after_ms = None;
let mut room_version = None;
let mut admin_contact = None;
let mut status = None;
let mut body = None;
let mut current_version = None;
let mut extra = BTreeMap::new();
macro_rules! set_field {
(errcode) => {
set_field!(@inner errcode)
};
($field:ident) => {
match errcode {
Some(set_field!(@variant_containing $field)) | None => {
set_field!(@inner $field)
}
// if we already know we're deserializing a different variant to the one
// containing this field, ignore its value.
Some(_) => {
let _ = map.next_value::<de::IgnoredAny>()?;
},
}
};
(@variant_containing soft_logout) => { ErrorCode::UnknownToken };
(@variant_containing retry_after_ms) => { ErrorCode::LimitExceeded };
(@variant_containing room_version) => { ErrorCode::IncompatibleRoomVersion };
(@variant_containing admin_contact) => { ErrorCode::ResourceLimitExceeded };
(@variant_containing status) => { ErrorCode::BadStatus };
(@variant_containing body) => { ErrorCode::BadStatus };
(@variant_containing current_version) => { ErrorCode::WrongRoomKeysVersion };
(@inner $field:ident) => {
{
if $field.is_some() {
return Err(de::Error::duplicate_field(stringify!($field)));
}
$field = Some(map.next_value()?);
}
};
}
while let Some(key) = map.next_key()? {
match key {
Field::ErrorCode => set_field!(errcode),
Field::SoftLogout => set_field!(soft_logout),
Field::RetryAfterMs => set_field!(retry_after_ms),
Field::RoomVersion => set_field!(room_version),
Field::AdminContact => set_field!(admin_contact),
Field::Status => set_field!(status),
Field::Body => set_field!(body),
Field::CurrentVersion => set_field!(current_version),
Field::Other(other) => match extra.entry(other.into_owned()) {
Entry::Vacant(v) => {
v.insert(map.next_value()?);
}
Entry::Occupied(o) => {
return Err(de::Error::custom(format!("duplicate field `{}`", o.key())));
}
},
}
}
let errcode = errcode.ok_or_else(|| de::Error::missing_field("errcode"))?;
Ok(match errcode {
ErrorCode::AppserviceLoginUnsupported => ErrorKind::AppserviceLoginUnsupported,
ErrorCode::BadAlias => ErrorKind::BadAlias,
ErrorCode::BadJson => ErrorKind::BadJson,
ErrorCode::BadState => ErrorKind::BadState,
ErrorCode::BadStatus => ErrorKind::BadStatus {
status: status
.map(|s| {
from_json_value::<u16>(s)
.map_err(de::Error::custom)?
.try_into()
.map_err(de::Error::custom)
})
.transpose()?,
body: body
.map(from_json_value)
.transpose()
.map_err(de::Error::custom)?,
},
ErrorCode::CannotLeaveServerNoticeRoom => ErrorKind::CannotLeaveServerNoticeRoom,
ErrorCode::CannotOverwriteMedia => ErrorKind::CannotOverwriteMedia,
ErrorCode::CaptchaInvalid => ErrorKind::CaptchaInvalid,
ErrorCode::CaptchaNeeded => ErrorKind::CaptchaNeeded,
#[cfg(feature = "unstable-msc4306")]
ErrorCode::ConflictingUnsubscription => ErrorKind::ConflictingUnsubscription,
ErrorCode::ConnectionFailed => ErrorKind::ConnectionFailed,
ErrorCode::ConnectionTimeout => ErrorKind::ConnectionTimeout,
ErrorCode::DuplicateAnnotation => ErrorKind::DuplicateAnnotation,
ErrorCode::Exclusive => ErrorKind::Exclusive,
ErrorCode::Forbidden => ErrorKind::forbidden(),
ErrorCode::GuestAccessForbidden => ErrorKind::GuestAccessForbidden,
ErrorCode::IncompatibleRoomVersion => ErrorKind::IncompatibleRoomVersion {
room_version: from_json_value(
room_version.ok_or_else(|| de::Error::missing_field("room_version"))?,
)
.map_err(de::Error::custom)?,
},
ErrorCode::InvalidParam => ErrorKind::InvalidParam,
ErrorCode::InvalidRoomState => ErrorKind::InvalidRoomState,
ErrorCode::InvalidUsername => ErrorKind::InvalidUsername,
#[cfg(feature = "unstable-msc4380")]
ErrorCode::InviteBlocked => ErrorKind::InviteBlocked,
ErrorCode::LimitExceeded => ErrorKind::LimitExceeded {
retry_after: retry_after_ms
.map(from_json_value::<u64>)
.transpose()
.map_err(de::Error::custom)?
.map(Duration::from_millis)
.map(RetryAfter::Delay),
},
ErrorCode::MissingParam => ErrorKind::MissingParam,
ErrorCode::MissingToken => ErrorKind::MissingToken,
ErrorCode::NotFound => ErrorKind::NotFound,
#[cfg(feature = "unstable-msc4306")]
ErrorCode::NotInThread => ErrorKind::NotInThread,
ErrorCode::NotJson => ErrorKind::NotJson,
ErrorCode::NotYetUploaded => ErrorKind::NotYetUploaded,
ErrorCode::ResourceLimitExceeded => ErrorKind::ResourceLimitExceeded {
admin_contact: from_json_value(
admin_contact.ok_or_else(|| de::Error::missing_field("admin_contact"))?,
)
.map_err(de::Error::custom)?,
},
ErrorCode::RoomInUse => ErrorKind::RoomInUse,
ErrorCode::ServerNotTrusted => ErrorKind::ServerNotTrusted,
ErrorCode::ThreepidAuthFailed => ErrorKind::ThreepidAuthFailed,
ErrorCode::ThreepidDenied => ErrorKind::ThreepidDenied,
ErrorCode::ThreepidInUse => ErrorKind::ThreepidInUse,
ErrorCode::ThreepidMediumNotSupported => ErrorKind::ThreepidMediumNotSupported,
ErrorCode::ThreepidNotFound => ErrorKind::ThreepidNotFound,
ErrorCode::TooLarge => ErrorKind::TooLarge,
ErrorCode::UnableToAuthorizeJoin => ErrorKind::UnableToAuthorizeJoin,
ErrorCode::UnableToGrantJoin => ErrorKind::UnableToGrantJoin,
#[cfg(feature = "unstable-msc3843")]
ErrorCode::Unactionable => ErrorKind::Unactionable,
ErrorCode::Unauthorized => ErrorKind::Unauthorized,
ErrorCode::Unknown => ErrorKind::Unknown,
#[cfg(feature = "unstable-msc4186")]
ErrorCode::UnknownPos => ErrorKind::UnknownPos,
ErrorCode::UnknownToken => ErrorKind::UnknownToken {
soft_logout: soft_logout
.map(from_json_value)
.transpose()
.map_err(de::Error::custom)?
.unwrap_or_default(),
},
ErrorCode::Unrecognized => ErrorKind::Unrecognized,
ErrorCode::UnsupportedRoomVersion => ErrorKind::UnsupportedRoomVersion,
ErrorCode::UrlNotSet => ErrorKind::UrlNotSet,
ErrorCode::UserDeactivated => ErrorKind::UserDeactivated,
ErrorCode::UserInUse => ErrorKind::UserInUse,
ErrorCode::UserLocked => ErrorKind::UserLocked,
ErrorCode::UserSuspended => ErrorKind::UserSuspended,
ErrorCode::WeakPassword => ErrorKind::WeakPassword,
ErrorCode::WrongRoomKeysVersion => ErrorKind::WrongRoomKeysVersion {
current_version: from_json_value(
current_version.ok_or_else(|| de::Error::missing_field("current_version"))?,
)
.map_err(de::Error::custom)?,
},
ErrorCode::_Custom(errcode) => ErrorKind::_Custom { errcode, extra },
})
}
}
/// The possible [error codes] defined in the Matrix spec.
///
/// [error codes]: https://spec.matrix.org/latest/client-server-api/#standard-error-response
#[derive(StringEnum, Clone)]
#[palpo_enum(rename_all(prefix = "M_", rule = "SCREAMING_SNAKE_CASE"))]
// Please keep the variants sorted alphabetically.
pub enum ErrorCode {
/// `M_APPSERVICE_LOGIN_UNSUPPORTED`
///
/// An application service used the [`m.login.application_service`] type an endpoint from the
/// [legacy authentication API] in a way that is not supported by the homeserver, because the
/// server only supports the [OAuth 2.0 API].
///
/// [`m.login.application_service`]: https://spec.matrix.org/latest/application-service-api/#server-admin-style-permissions
/// [legacy authentication API]: https://spec.matrix.org/latest/client-server-api/#legacy-api
/// [OAuth 2.0 API]: https://spec.matrix.org/latest/client-server-api/#oauth-20-api
AppserviceLoginUnsupported,
/// `M_BAD_ALIAS`
///
/// One or more [room aliases] within the `m.room.canonical_alias` event do
/// not point to the room ID for which the state event is to be sent to.
///
/// [room aliases]: https://spec.matrix.org/latest/client-server-api/#room-aliases
BadAlias,
/// `M_BAD_JSON`
///
/// The request contained valid JSON, but it was malformed in some way, e.g.
/// missing required keys, invalid values for keys.
BadJson,
/// `M_BAD_STATE`
///
/// The state change requested cannot be performed, such as attempting to
/// unban a user who is not banned.
BadState,
/// `M_BAD_STATUS`
///
/// The application service returned a bad status.
BadStatus,
/// `M_CANNOT_LEAVE_SERVER_NOTICE_ROOM`
///
/// The user is unable to reject an invite to join the [server notices]
/// room.
///
/// [server notices]: https://spec.matrix.org/latest/client-server-api/#server-notices
CannotLeaveServerNoticeRoom,
/// `M_CANNOT_OVERWRITE_MEDIA`
///
/// The [`create_content_async`] endpoint was called with a media ID that
/// already has content.
///
/// [`create_content_async`]: crate::media::create_content_async
CannotOverwriteMedia,
/// `M_CAPTCHA_INVALID`
///
/// The Captcha provided did not match what was expected.
CaptchaInvalid,
/// `M_CAPTCHA_NEEDED`
///
/// A Captcha is required to complete the request.
CaptchaNeeded,
/// `M_CONFLICTING_UNSUBSCRIPTION`
///
/// Part of [MSC4306]: an automatic thread subscription has been skipped by the server, because
/// the user unsubsubscribed after the indicated subscribed-to event.
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
#[palpo_enum(rename = "IO.ELEMENT.MSC4306.M_CONFLICTING_UNSUBSCRIPTION")]
ConflictingUnsubscription,
/// `M_CONNECTION_FAILED`
///
/// The connection to the application service failed.
ConnectionFailed,
/// `M_CONNECTION_TIMEOUT`
///
/// The connection to the application service timed out.
ConnectionTimeout,
/// `M_DUPLICATE_ANNOTATION`
///
/// The request is an attempt to send a [duplicate annotation].
///
/// [duplicate annotation]: https://spec.matrix.org/latest/client-server-api/#avoiding-duplicate-annotations
DuplicateAnnotation,
/// `M_EXCLUSIVE`
///
/// The resource being requested is reserved by an application service, or
/// the application service making the request has not created the
/// resource.
Exclusive,
/// `M_FORBIDDEN`
///
/// Forbidden access, e.g. joining a room without permission, failed login.
Forbidden,
/// `M_GUEST_ACCESS_FORBIDDEN`
///
/// The room or resource does not permit [guests] to access it.
///
/// [guests]: https://spec.matrix.org/latest/client-server-api/#guest-access
GuestAccessForbidden,
/// `M_INCOMPATIBLE_ROOM_VERSION`
///
/// The client attempted to join a room that has a version the server does
/// not support.
IncompatibleRoomVersion,
/// `M_INVALID_PARAM`
///
/// A parameter that was specified has the wrong value. For example, the
/// server expected an integer and instead received a string.
InvalidParam,
/// `M_INVALID_ROOM_STATE`
///
/// The initial state implied by the parameters to the [`create_room`]
/// request is invalid, e.g. the user's `power_level` is set below that
/// necessary to set the room name.
///
/// [`create_room`]: crate::room::create_room
InvalidRoomState,
/// `M_INVALID_USERNAME`
///
/// The desired user name is not valid.
InvalidUsername,
/// `M_INVITE_BLOCKED`
///
/// The invite was interdicted by moderation tools or configured access controls without having
/// been witnessed by the invitee.
///
/// Unstable prefix intentionally shared with MSC4155 for compatibility.
#[cfg(feature = "unstable-msc4380")]
#[palpo_enum(rename = "ORG.MATRIX.MSC4155.INVITE_BLOCKED")]
InviteBlocked,
/// `M_LIMIT_EXCEEDED`
///
/// The request has been refused due to [rate limiting]: too many requests
/// have been sent in a short period of time.
///
/// [rate limiting]: https://spec.matrix.org/latest/client-server-api/#rate-limiting
LimitExceeded,
/// `M_MISSING_PARAM`
///
/// A required parameter was missing from the request.
MissingParam,
/// `M_MISSING_TOKEN`
///
/// No [access token] was specified for the request, but one is required.
///
/// [access token]: https://spec.matrix.org/latest/client-server-api/#client-authentication
MissingToken,
/// `M_NOT_FOUND`
///
/// No resource was found for this request.
NotFound,
/// `M_NOT_IN_THREAD`
///
/// Part of [MSC4306]: an automatic thread subscription was set to an event ID that isn't part
/// of the subscribed-to thread.
///
/// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
#[cfg(feature = "unstable-msc4306")]
#[palpo_enum(rename = "IO.ELEMENT.MSC4306.M_NOT_IN_THREAD")]
NotInThread,
/// `M_NOT_JSON`
///
/// The request did not contain valid JSON.
NotJson,
/// `M_NOT_YET_UPLOADED`
///
/// An `mxc:` URI generated with the [`create_mxc_uri`] endpoint was used
/// and the content is not yet available.
///
/// [`create_mxc_uri`]: crate::media::create_mxc_uri
NotYetUploaded,
/// `M_RESOURCE_LIMIT_EXCEEDED`
///
/// The request cannot be completed because the homeserver has reached a
/// resource limit imposed on it. For example, a homeserver held in a
/// shared hosting environment may reach a resource limit if it starts
/// using too much memory or disk space.
ResourceLimitExceeded,
/// `M_ROOM_IN_USE`
///
/// The [room alias] specified in the [`create_room`] request is already
/// taken.
///
/// [`create_room`]: crate::room::create_room
/// [room alias]: https://spec.matrix.org/latest/client-server-api/#room-aliases
RoomInUse,
/// `M_SERVER_NOT_TRUSTED`
///
/// The client's request used a third-party server, e.g. identity server,
/// that this server does not trust.
ServerNotTrusted,
/// `M_THREEPID_AUTH_FAILED`
///
/// Authentication could not be performed on the [third-party identifier].
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidAuthFailed,
/// `M_THREEPID_DENIED`
///
/// The server does not permit this [third-party identifier]. This may
/// happen if the server only permits, for example, email addresses from
/// a particular domain.
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidDenied,
/// `M_THREEPID_IN_USE`
///
/// The [third-party identifier] is already in use by another user.
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidInUse,
/// `M_THREEPID_MEDIUM_NOT_SUPPORTED`
///
/// The homeserver does not support adding a [third-party identifier] of the
/// given medium.
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidMediumNotSupported,
/// `M_THREEPID_NOT_FOUND`
///
/// No account matching the given [third-party identifier] could be found.
///
/// [third-party identifier]: https://spec.matrix.org/latest/client-server-api/#adding-account-administrative-contact-information
ThreepidNotFound,
/// `M_TOO_LARGE`
///
/// The request or entity was too large.
TooLarge,
/// `M_UNABLE_TO_AUTHORISE_JOIN`
///
/// The room is [restricted] and none of the conditions can be validated by
/// the homeserver. This can happen if the homeserver does not know
/// about any of the rooms listed as conditions, for example.
///
/// [restricted]: https://spec.matrix.org/latest/client-server-api/#restricted-rooms
#[palpo_enum(rename = "M_UNABLE_TO_AUTHORISE_JOIN")]
UnableToAuthorizeJoin,
/// `M_UNABLE_TO_GRANT_JOIN`
///
/// A different server should be attempted for the join. This is typically
/// because the resident server can see that the joining user satisfies
/// one or more conditions, such as in the case of [restricted rooms],
/// but the resident server would be unable to meet the authorization
/// rules.
///
/// [restricted rooms]: https://spec.matrix.org/latest/client-server-api/#restricted-rooms
UnableToGrantJoin,
/// `M_UNACTIONABLE`
///
/// The server does not want to handle the [federated report].
///
/// [federated report]: https://github.com/matrix-org/matrix-spec-proposals/pull/3843
#[cfg(feature = "unstable-msc3843")]
Unactionable,
/// `M_UNAUTHORIZED`
///
/// The request was not correctly authorized. Usually due to login failures.
Unauthorized,
/// `M_UNKNOWN`
///
/// An unknown error has occurred.
Unknown,
/// `M_UNKNOWN_POS`
///
/// The sliding sync ([MSC4186]) connection was expired by the server.
///
/// [MSC4186]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186
#[cfg(feature = "unstable-msc4186")]
UnknownPos,
/// `M_UNKNOWN_TOKEN`
///
/// The [access or refresh token] specified was not recognized.
///
/// [access or refresh token]: https://spec.matrix.org/latest/client-server-api/#client-authentication
UnknownToken,
/// `M_UNRECOGNIZED`
///
/// The server did not understand the request.
///
/// This is expected to be returned with a 404 HTTP status code if the
/// endpoint is not implemented or a 405 HTTP status code if the
/// endpoint is implemented, but the incorrect HTTP method is used.
Unrecognized,
/// `M_UNSUPPORTED_ROOM_VERSION`
UnsupportedRoomVersion,
/// `M_URL_NOT_SET`
///
/// The application service doesn't have a URL configured.
UrlNotSet,
/// `M_USER_DEACTIVATED`
///
/// The user ID associated with the request has been deactivated.
UserDeactivated,
/// `M_USER_IN_USE`
///
/// The desired user ID is already taken.
UserInUse,
/// `M_USER_LOCKED`
///
/// The account has been [locked] and cannot be used at this time.
///
/// [locked]: https://spec.matrix.org/latest/client-server-api/#account-locking
UserLocked,
/// `M_USER_SUSPENDED`
///
/// The account has been [suspended] and can only be used for limited
/// actions at this time.
///
/// [suspended]: https://spec.matrix.org/latest/client-server-api/#account-suspension
UserSuspended,
/// `M_WEAK_PASSWORD`
///
/// The password was [rejected] by the server for being too weak.
///
/// [rejected]: https://spec.matrix.org/latest/client-server-api/#notes-on-password-management
WeakPassword,
/// `M_WRONG_ROOM_KEYS_VERSION`
///
/// The version of the [room keys backup] provided in the request does not
/// match the current backup version.
///
/// [room keys backup]: https://spec.matrix.org/latest/client-server-api/#server-side-key-backups
WrongRoomKeysVersion,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl<'de> Deserialize<'de> for ErrorKind {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(ErrorKindVisitor)
}
}
impl Serialize for ErrorKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut st = serializer.serialize_map(None)?;
st.serialize_entry("errcode", &self.code())?;
match self {
Self::UnknownToken { soft_logout: true } => {
st.serialize_entry("soft_logout", &true)?;
}
Self::LimitExceeded {
retry_after: Some(RetryAfter::Delay(duration)),
} => {
st.serialize_entry(
"retry_after_ms",
&u64::try_from(duration.as_millis()).map_err(ser::Error::custom)?,
)?;
}
Self::IncompatibleRoomVersion { room_version } => {
st.serialize_entry("room_version", room_version)?;
}
Self::ResourceLimitExceeded { admin_contact } => {
st.serialize_entry("admin_contact", admin_contact)?;
}
Self::_Custom { extra, .. } => {
for (k, v) in extra {
st.serialize_entry(k, v)?;
}
}
_ => {}
}
st.end()
}
}
/// How long a client should wait before it tries again.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(clippy::exhaustive_enums)]
pub enum RetryAfter {
/// The client should wait for the given duration.
///
/// This variant should be preferred for backwards compatibility, as it will
/// also populate the `retry_after_ms` field in the body of the
/// response.
Delay(Duration),
/// The client should wait for the given date and time.
DateTime(SystemTime),
}
impl TryFrom<&http::HeaderValue> for RetryAfter {
type Error = HeaderDeserializationError;
fn try_from(value: &http::HeaderValue) -> Result<Self, Self::Error> {
if value.as_bytes().iter().all(|b| b.is_ascii_digit()) {
// It should be a duration.
Ok(Self::Delay(Duration::from_secs(u64::from_str(
value.to_str()?,
)?)))
} else {
// It should be a date.
Ok(Self::DateTime(http_date_to_system_time(value)?))
}
}
}
impl TryFrom<&RetryAfter> for http::HeaderValue {
type Error = HeaderSerializationError;
fn try_from(value: &RetryAfter) -> Result<Self, Self::Error> {
match value {
RetryAfter::Delay(duration) => Ok(duration.as_secs().into()),
RetryAfter::DateTime(time) => system_time_to_http_date(time),
}
}
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json};
use super::ErrorKind;
use crate::room_version_id;
// #[test]
// fn deserialize_forbidden() {
// let deserialized: ErrorKind = from_json_value(json!({ "errcode": "M_FORBIDDEN" })).unwrap();
// assert_eq!(deserialized, ErrorKind::Forbidden);
// }
// #[test]
// fn deserialize_forbidden_with_extra_fields() {
// let deserialized: ErrorKind = from_json_value(json!({
// "errcode": "M_FORBIDDEN",
// "error": "…",
// }))
// .unwrap();
// assert_eq!(deserialized, ErrorKind::Forbidden);
// }
#[test]
fn deserialize_incompatible_room_version() {
let deserialized: ErrorKind = from_json_value(json!({
"errcode": "M_INCOMPATIBLE_ROOM_VERSION",
"room_version": "7",
}))
.unwrap();
assert_eq!(
deserialized,
ErrorKind::IncompatibleRoomVersion {
room_version: room_version_id!("7")
}
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/signatures/tests.rs | crates/core/src/signatures/tests.rs | use std::collections::BTreeMap;
use crate::{serde::Base64, RoomVersionId, ServerSigningKeyId, SigningKeyAlgorithm};
use palpo_core::signatures::{sign_json, verify_event, Ed25519KeyPair, PublicKeyMap, Verified};
static PKCS8_ED25519_DER: &[u8] = include_bytes!("./keys/ed25519.der");
fn add_key_to_map(public_key_map: &mut PublicKeyMap, name: &str, pair: &Ed25519KeyPair) {
let sender_key_map = public_key_map.entry(name.to_owned()).or_default();
let encoded_public_key = Base64::new(pair.public_key().to_vec());
let version =
ServerSigningKeyId::from_parts(SigningKeyAlgorithm::Ed25519, pair.version().into());
sender_key_map.insert(version.to_string(), encoded_public_key);
}
#[test]
fn verify_event_check_signatures_for_authorized_user() {
let keypair = Ed25519KeyPair::from_der(PKCS8_ED25519_DER, "1".to_owned()).unwrap();
let mut signed_event = serde_json::from_str(
r#"{
"event_id": "$event_id:domain-event",
"auth_events": [],
"content": {},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "m.room.member",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &keypair, &mut signed_event).unwrap();
let mut public_key_map = BTreeMap::new();
add_key_to_map(&mut public_key_map, "domain-sender", &keypair);
let verification = verify_event(&public_key_map, &signed_event, &RoomVersionId::V9).unwrap();
assert_eq!(verification, Verified::Signatures);
let signatures = signed_event.get("signatures").unwrap().as_object().unwrap();
let domain_sender_signatures = signatures.get("domain-sender").unwrap().as_object().unwrap();
let signature = domain_sender_signatures.get("ed25519:1").unwrap().as_str().unwrap();
insta::assert_snapshot!(signature);
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/signatures/verification.rs | crates/core/src/signatures/verification.rs | //! Verification of digital signatures.
use ed25519_dalek::{Verifier as _, VerifyingKey};
use crate::SigningKeyAlgorithm;
use crate::signatures::{Error, ParseError, VerificationError};
/// A digital signature verifier.
pub(crate) trait Verifier {
/// Use a public key to verify a signature against the JSON object that was
/// signed.
///
/// # Parameters
///
/// * public_key: The raw bytes of the public key of the key pair used to
/// sign the message.
/// * signature: The raw bytes of the signature to verify.
/// * message: The raw bytes of the message that was signed.
///
/// # Errors
///
/// Returns an error if verification fails.
fn verify_json(&self, public_key: &[u8], signature: &[u8], message: &[u8])
-> Result<(), Error>;
}
/// A verifier for Ed25519 digital signatures.
#[derive(Debug, Default)]
pub(crate) struct Ed25519Verifier;
impl Verifier for Ed25519Verifier {
fn verify_json(
&self,
public_key: &[u8],
signature: &[u8],
message: &[u8],
) -> Result<(), Error> {
VerifyingKey::from_bytes(
public_key
.try_into()
.map_err(|_| ParseError::PublicKey(ed25519_dalek::SignatureError::new()))?,
)
.map_err(ParseError::PublicKey)?
.verify(
message,
&signature.try_into().map_err(ParseError::Signature)?,
)
.map_err(VerificationError::Signature)
.map_err(Error::from)
}
}
/// A value returned when an event is successfully verified.
///
/// Event verification involves verifying both signatures and a content hash. It
/// is possible for the signatures on an event to be valid, but for the hash to
/// be different than the one calculated during verification. This is not
/// necessarily an error condition, as it may indicate that the event has been
/// redacted. In this case, receiving homeservers should store a redacted
/// version of the event.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
#[allow(clippy::exhaustive_enums)]
pub enum Verified {
/// All signatures are valid and the content hashes match.
All,
/// All signatures are valid but the content hashes don't match.
///
/// This may indicate a redacted event.
Signatures,
}
/// Get the verifier for the given algorithm, if it is supported.
pub(crate) fn verifier_from_algorithm(
algorithm: &SigningKeyAlgorithm,
) -> Option<impl Verifier + use<>> {
match algorithm {
SigningKeyAlgorithm::Ed25519 => Some(Ed25519Verifier),
_ => None,
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/signatures/functions.rs | crates/core/src/signatures/functions.rs | //! Functions for signing and verifying JSON and events.
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet},
mem,
};
use base64::{Engine, alphabet};
use serde_json::to_string as to_json_string;
use sha2::{Sha256, digest::Digest};
#[cfg(test)]
mod tests;
use crate::signatures::{
Error, JsonError, ParseError, VerificationError,
keys::{KeyPair, PublicKeyMap},
verification::{Verified, Verifier, verifier_from_algorithm},
};
use crate::{
AnyKeyName, OwnedEventId, OwnedServerName, OwnedServerSigningKeyId, SigningKeyAlgorithm,
SigningKeyId, UserId,
room_version_rules::{EventIdFormatVersion, RedactionRules, RoomVersionRules, SignaturesRules},
serde::{
Base64, CanonicalJsonObject, CanonicalJsonValue,
base64::Standard,
canonical_json::{JsonType, redact},
},
};
/// The [maximum size allowed] for a PDU.
///
/// [maximum size allowed]: https://spec.matrix.org/latest/client-server-api/#size-limits
const MAX_PDU_BYTES: usize = 65_535;
/// The fields to remove from a JSON object when converting JSON into the "canonical" form.
static CANONICAL_JSON_FIELDS_TO_REMOVE: &[&str] = &["signatures", "unsigned"];
/// The fields to remove from a JSON object when creating a content hash of an event.
static CONTENT_HASH_FIELDS_TO_REMOVE: &[&str] = &["hashes", "signatures", "unsigned"];
/// The fields to remove from a JSON object when creating a reference hash of an event.
static REFERENCE_HASH_FIELDS_TO_REMOVE: &[&str] = &["signatures", "unsigned"];
/// Signs an arbitrary JSON object and adds the signature to an object under the key `signatures`.
///
/// If `signatures` is already present, the new signature will be appended to the existing ones.
///
/// # Parameters
///
/// * `entity_id`: The identifier of the entity creating the signature. Generally this means a
/// homeserver, e.g. `example.com`.
/// * `key_pair`: A cryptographic key pair used to sign the JSON.
/// * `object`: A JSON object to sign according and append a signature to.
///
/// # Errors
///
/// Returns an error if:
///
/// * `object` contains a field called `signatures` that is not a JSON object.
///
/// # Examples
///
/// A homeserver signs JSON with a key pair:
///
/// ```rust
/// # use palpo_core::serde::base64::Base64;
/// #
/// const PKCS8: &str = "\
/// MFECAQEwBQYDK2VwBCIEINjozvdfbsGEt6DD+7Uf4PiJ/YvTNXV2mIPc/\
/// tA0T+6tgSEA3TPraTczVkDPTRaX4K+AfUuyx7Mzq1UafTXypnl0t2k\
/// ";
///
/// let document: Base64 = Base64::parse(PKCS8).unwrap();
///
/// // Create an Ed25519 key pair.
/// let key_pair = palpo_core::signatures::Ed25519KeyPair::from_der(
/// document.as_bytes(),
/// "1".into(), // The "version" of the key.
/// )
/// .unwrap();
///
/// // Deserialize some JSON.
/// let mut value = serde_json::from_str("{}").unwrap();
///
/// // Sign the JSON with the key pair.
/// assert!(palpo_core::signatures::sign_json("domain", &key_pair, &mut value).is_ok());
/// ```
///
/// This will modify the JSON from an empty object to a structure like this:
///
/// ```json
/// {
/// "signatures": {
/// "domain": {
/// "ed25519:1": "K8280/U9SSy9IVtjBuVeLr+HpOB4BQFWbg+UZaADMtTdGYI7Geitb76LTrr5QV/7Xg4ahLwYGYZzuHGZKM5ZAQ"
/// }
/// }
/// }
/// ```
pub fn sign_json<K>(
entity_id: &str,
keypair: &K,
object: &mut CanonicalJsonObject,
) -> Result<(), Error>
where
K: KeyPair,
{
let (signatures_key, mut signature_map) = match object.remove_entry("signatures") {
Some((key, CanonicalJsonValue::Object(signatures))) => (Cow::Owned(key), signatures),
Some(_) => return Err(JsonError::not_of_type("signatures", JsonType::Object)),
None => (Cow::Borrowed("signatures"), BTreeMap::new()),
};
let maybe_unsigned_entry = object.remove_entry("unsigned");
// Get the canonical JSON string.
let json = to_json_string(object).map_err(JsonError::Serde)?;
// Sign the canonical JSON string.
let signature = keypair.sign(json.as_bytes());
// Insert the new signature in the map we pulled out (or created) previously.
let signature_set = signature_map
.entry(entity_id.to_owned())
.or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::new()));
let CanonicalJsonValue::Object(signature_set) = signature_set else {
return Err(JsonError::not_multiples_of_type(
"signatures",
JsonType::Object,
));
};
signature_set.insert(
signature.id(),
CanonicalJsonValue::String(signature.base64()),
);
// Put `signatures` and `unsigned` back in.
object.insert(
signatures_key.into(),
CanonicalJsonValue::Object(signature_map),
);
if let Some((k, v)) = maybe_unsigned_entry {
object.insert(k, v);
}
Ok(())
}
/// Converts an event into the [canonical] string form.
///
/// [canonical]: https://spec.matrix.org/latest/appendices/#canonical-json
///
/// # Parameters
///
/// * `object`: The JSON object to convert.
///
/// # Examples
///
/// ```rust
/// let input = r#"{
/// "本": 2,
/// "日": 1
/// }"#;
///
/// let object = serde_json::from_str(input).unwrap();
/// let canonical = palpo_core::signatures::canonical_json(&object).unwrap();
///
/// assert_eq!(canonical, r#"{"日":1,"本":2}"#);
/// ```
pub fn canonical_json(object: &CanonicalJsonObject) -> Result<String, Error> {
canonical_json_with_fields_to_remove(object, CANONICAL_JSON_FIELDS_TO_REMOVE)
}
/// Uses a set of public keys to verify a signed JSON object.
///
/// Signatures using an unsupported algorithm are ignored, but each entity must have at least one
/// signature from a supported algorithm.
///
/// Unlike `content_hash` and `reference_hash`, this function does not report an error if the
/// canonical JSON is larger than 65535 bytes; this function may be used for requests that are
/// larger than just one PDU's maximum size.
///
/// # Parameters
///
/// * `public_key_map`: A map from entity identifiers to a map from key identifiers to public keys.
/// Generally, entity identifiers are server names — the host/IP/port of a homeserver (e.g.
/// `example.com`) for which a signature must be verified. Key identifiers for each server (e.g.
/// `ed25519:1`) then map to their respective public keys.
/// * `object`: The JSON object that was signed.
///
/// # Errors
///
/// Returns an error if verification fails.
///
/// # Examples
///
/// ```rust
/// use std::collections::BTreeMap;
///
/// use palpo_core::serde::Base64;
///
/// const PUBLIC_KEY: &[u8] = b"XGX0JRS2Af3be3knz2fBiRbApjm2Dh61gXDJA8kcJNI";
///
/// // Deserialize the signed JSON.
/// let object = serde_json::from_str(
/// r#"{
/// "signatures": {
/// "domain": {
/// "ed25519:1": "K8280/U9SSy9IVtjBuVeLr+HpOB4BQFWbg+UZaADMtTdGYI7Geitb76LTrr5QV/7Xg4ahLwYGYZzuHGZKM5ZAQ"
/// }
/// }
/// }"#
/// ).unwrap();
///
/// // Create the `PublicKeyMap` that will inform `verify_json` which signatures to verify.
/// let mut public_key_set = BTreeMap::new();
/// public_key_set.insert("ed25519:1".into(), Base64::parse(PUBLIC_KEY.to_owned()).unwrap());
/// let mut public_key_map = BTreeMap::new();
/// public_key_map.insert("domain".into(), public_key_set);
///
/// // Verify at least one signature for each entity in `public_key_map`.
/// assert!(palpo_core::signatures::verify_json(&public_key_map, &object).is_ok());
/// ```
pub fn verify_json(
public_key_map: &PublicKeyMap,
object: &CanonicalJsonObject,
) -> Result<(), Error> {
let signature_map = match object.get("signatures") {
Some(CanonicalJsonValue::Object(signatures)) => signatures,
Some(_) => return Err(JsonError::not_of_type("signatures", JsonType::Object)),
None => return Err(JsonError::field_missing_from_object("signatures")),
};
let canonical_json = canonical_json(object)?;
for entity_id in signature_map.keys() {
verify_canonical_json_for_entity(
entity_id,
public_key_map,
signature_map,
canonical_json.as_bytes(),
)?;
}
Ok(())
}
/// Uses a set of public keys to verify signed canonical JSON bytes for a given entity.
///
/// Implements the algorithm described in the spec for [checking signatures].
///
/// # Parameters
///
/// * `entity_id`: The entity to check the signatures for.
/// * `public_key_map`: A map from entity identifiers to a map from key identifiers to public keys.
/// * `signature_map`: The map of signatures from the signed JSON object.
/// * `canonical_json`: The signed canonical JSON bytes. Can be obtained by calling
/// [`canonical_json()`].
///
/// # Errors
///
/// Returns an error if verification fails.
///
/// [checking signatures]: https://spec.matrix.org/latest/appendices/#checking-for-a-signature
fn verify_canonical_json_for_entity(
entity_id: &str,
public_key_map: &PublicKeyMap,
signature_map: &CanonicalJsonObject,
canonical_json: &[u8],
) -> Result<(), Error> {
let signature_set = match signature_map.get(entity_id) {
Some(CanonicalJsonValue::Object(set)) => set,
Some(_) => {
return Err(JsonError::not_multiples_of_type(
"signature sets",
JsonType::Object,
));
}
None => return Err(VerificationError::NoSignaturesForEntity(entity_id.to_owned()).into()),
};
let public_keys = public_key_map
.get(entity_id)
.ok_or_else(|| VerificationError::NoPublicKeysForEntity(entity_id.to_owned()))?;
let mut checked = false;
for (key_id, signature) in signature_set {
// If we cannot parse the key ID, ignore.
let Ok(parsed_key_id) = <&SigningKeyId<AnyKeyName>>::try_from(key_id.as_str()) else {
continue;
};
// If the signature uses an unknown algorithm, ignore.
let Some(verifier) = verifier_from_algorithm(&parsed_key_id.algorithm()) else {
continue;
};
let Some(public_key) = public_keys.get(key_id) else {
return Err(VerificationError::PublicKeyNotFound {
entity: entity_id.to_owned(),
key_id: key_id.clone(),
}
.into());
};
let CanonicalJsonValue::String(signature) = signature else {
return Err(JsonError::not_of_type("signature", JsonType::String));
};
let signature = Base64::<Standard>::parse(signature)
.map_err(|e| ParseError::base64("signature", signature, e))?;
verify_canonical_json_with(
&verifier,
public_key.as_bytes(),
signature.as_bytes(),
canonical_json,
)?;
checked = true;
}
if !checked {
return Err(VerificationError::NoSupportedSignatureForEntity(entity_id.to_owned()).into());
}
Ok(())
}
/// Check a signed JSON object using the given public key and signature, all provided as bytes.
///
/// This is a low-level function. In general you will want to use [`verify_event()`] or
/// [`verify_json()`].
///
/// # Parameters
///
/// * `algorithm`: The algorithm used for the signature. Currently this method only supports the
/// ed25519 algorithm.
/// * `public_key`: The raw bytes of the public key used to sign the JSON.
/// * `signature`: The raw bytes of the signature.
/// * `canonical_json`: The signed canonical JSON bytes. Can be obtained by calling
/// [`canonical_json()`].
///
/// # Errors
///
/// Returns an error if verification fails.
pub fn verify_canonical_json_bytes(
algorithm: &SigningKeyAlgorithm,
public_key: &[u8],
signature: &[u8],
canonical_json: &[u8],
) -> Result<(), Error> {
let verifier =
verifier_from_algorithm(algorithm).ok_or(VerificationError::UnsupportedAlgorithm)?;
verify_canonical_json_with(&verifier, public_key, signature, canonical_json)
}
/// Uses a public key to verify signed canonical JSON bytes.
///
/// # Parameters
///
/// * `verifier`: A [`Verifier`] appropriate for the digital signature algorithm that was used.
/// * `public_key`: The raw bytes of the public key used to sign the JSON.
/// * `signature`: The raw bytes of the signature.
/// * `canonical_json`: The signed canonical JSON bytes. Can be obtained by calling
/// [`canonical_json()`].
///
/// # Errors
///
/// Returns an error if verification fails.
fn verify_canonical_json_with<V>(
verifier: &V,
public_key: &[u8],
signature: &[u8],
canonical_json: &[u8],
) -> Result<(), Error>
where
V: Verifier,
{
verifier.verify_json(public_key, signature, canonical_json)
}
/// Creates a *content hash* for an event.
///
/// The content hash of an event covers the complete event including the unredacted contents. It is
/// used during federation and is described in the Matrix server-server specification.
///
/// # Parameters
///
/// * `object`: A JSON object to generate a content hash for.
///
/// # Errors
///
/// Returns an error if the event is too large.
pub fn content_hash(object: &CanonicalJsonObject) -> Result<Base64<Standard, [u8; 32]>, Error> {
let json = canonical_json_with_fields_to_remove(object, CONTENT_HASH_FIELDS_TO_REMOVE)?;
if json.len() > MAX_PDU_BYTES {
return Err(Error::PduSize);
}
let hash = Sha256::digest(json.as_bytes());
Ok(Base64::new(hash.into()))
}
/// Creates a *reference hash* for an event.
///
/// The reference hash of an event covers the essential fields of an event, including content
/// hashes.
///
/// Returns the hash as a base64-encoded string, without padding. The correct character set is used
/// depending on the room version:
///
/// * For room versions 1 and 2, the standard character set is used for sending the reference hash
/// of the `auth_events` and `prev_events`.
/// * For room version 3, the standard character set is used for using the reference hash as the
/// event ID.
/// * For newer versions, the URL-safe character set is used for using the reference hash as the
/// event ID.
///
/// # Parameters
///
/// * `object`: A JSON object to generate a reference hash for.
/// * `rules`: The rules of the version of the current room.
///
/// # Errors
///
/// Returns an error if the event is too large or redaction fails.
pub fn reference_hash(
object: &CanonicalJsonObject,
rules: &RoomVersionRules,
) -> Result<String, Error> {
let redacted_value = redact(object.clone(), &rules.redaction, None)?;
let json =
canonical_json_with_fields_to_remove(&redacted_value, REFERENCE_HASH_FIELDS_TO_REMOVE)?;
if json.len() > MAX_PDU_BYTES {
return Err(Error::PduSize);
}
let hash = Sha256::digest(json.as_bytes());
let base64_alphabet = match rules.event_id_format {
EventIdFormatVersion::V1 | EventIdFormatVersion::V2 => alphabet::STANDARD,
// Room versions higher than version 3 are URL-safe base64 encoded
_ => alphabet::URL_SAFE,
};
let base64_engine = base64::engine::GeneralPurpose::new(
&base64_alphabet,
base64::engine::general_purpose::NO_PAD,
);
Ok(base64_engine.encode(hash))
}
/// Hashes and signs an event and adds the hash and signature to objects under the keys `hashes` and
/// `signatures`, respectively.
///
/// If `hashes` and/or `signatures` are already present, the new data will be appended to the
/// existing data.
///
/// # Parameters
///
/// * `entity_id`: The identifier of the entity creating the signature. Generally this means a
/// homeserver, e.g. "example.com".
/// * `key_pair`: A cryptographic key pair used to sign the event.
/// * `object`: A JSON object to be hashed and signed according to the Matrix specification.
/// * `redaction_rules`: The redaction rules for the version of the event's room.
///
/// # Errors
///
/// Returns an error if:
///
/// * `object` contains a field called `content` that is not a JSON object.
/// * `object` contains a field called `hashes` that is not a JSON object.
/// * `object` contains a field called `signatures` that is not a JSON object.
/// * `object` is missing the `type` field or the field is not a JSON string.
///
/// # Examples
///
/// ```rust
/// # use palpo_core::{RoomVersionId, serde::base64::Base64};
/// # use palpo_core::signatures::{hash_and_sign_event, Ed25519KeyPair};
/// #
/// const PKCS8: &str = "\
/// MFECAQEwBQYDK2VwBCIEINjozvdfbsGEt6DD+7Uf4PiJ/YvTNXV2mIPc/\
/// tA0T+6tgSEA3TPraTczVkDPTRaX4K+AfUuyx7Mzq1UafTXypnl0t2k\
/// ";
///
/// let document: Base64 = Base64::parse(PKCS8).unwrap();
///
/// // Create an Ed25519 key pair.
/// let key_pair = Ed25519KeyPair::from_der(
/// document.as_bytes(),
/// "1".into(), // The "version" of the key.
/// )
/// .unwrap();
///
/// // Deserialize an event from JSON.
/// let mut object = serde_json::from_str(
/// r#"{
/// "room_id": "!x:domain",
/// "sender": "@a:domain",
/// "origin": "domain",
/// "origin_server_ts": 1000000,
/// "signatures": {},
/// "hashes": {},
/// "type": "X",
/// "content": {},
/// "prev_events": [],
/// "auth_events": [],
/// "depth": 3,
/// "unsigned": {
/// "age_ts": 1000000
/// }
/// }"#,
/// )
/// .unwrap();
///
/// // Get the rules for the version of the current room.
/// let rules =
/// RoomVersionId::V1.rules().expect("The rules should be known for a supported room version");
///
/// // Hash and sign the JSON with the key pair.
/// assert!(hash_and_sign_event("domain", &key_pair, &mut object, &rules.redaction).is_ok());
/// ```
///
/// This will modify the JSON from the structure shown to a structure like this:
///
/// ```json
/// {
/// "auth_events": [],
/// "content": {},
/// "depth": 3,
/// "hashes": {
/// "sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
/// },
/// "origin": "domain",
/// "origin_server_ts": 1000000,
/// "prev_events": [],
/// "room_id": "!x:domain",
/// "sender": "@a:domain",
/// "signatures": {
/// "domain": {
/// "ed25519:1": "KxwGjPSDEtvnFgU00fwFz+l6d2pJM6XBIaMEn81SXPTRl16AqLAYqfIReFGZlHi5KLjAWbOoMszkwsQma+lYAg"
/// }
/// },
/// "type": "X",
/// "unsigned": {
/// "age_ts": 1000000
/// }
/// }
/// ```
///
/// Notice the addition of `hashes` and `signatures`.
pub fn hash_and_sign_event<K>(
entity_id: &str,
key_pair: &K,
object: &mut CanonicalJsonObject,
redaction_rules: &RedactionRules,
) -> Result<(), Error>
where
K: KeyPair,
{
let hash = content_hash(object)?;
let hashes_value = object
.entry("hashes".to_owned())
.or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::new()));
match hashes_value {
CanonicalJsonValue::Object(hashes) => {
hashes.insert("sha256".into(), CanonicalJsonValue::String(hash.encode()))
}
_ => return Err(JsonError::not_of_type("hashes", JsonType::Object)),
};
let mut redacted = redact(object.clone(), redaction_rules, None)?;
sign_json(entity_id, key_pair, &mut redacted)?;
object.insert(
"signatures".into(),
mem::take(redacted.get_mut("signatures").unwrap()),
);
Ok(())
}
/// Verifies that the signed event contains all the required valid signatures.
///
/// Some room versions may require signatures from multiple homeservers, so this function takes a
/// map from servers to sets of public keys. Signatures are verified for each required homeserver.
/// All known public keys for a homeserver should be provided. The first one found on the given
/// event will be used.
///
/// If the `Ok` variant is returned by this function, it will contain a [`Verified`] value which
/// distinguishes an event with valid signatures and a matching content hash with an event with
/// only valid signatures. See the documentation for [`Verified`] for details.
///
/// # Parameters
///
/// * `public_key_map`: A map from entity identifiers to a map from key identifiers to public keys.
/// Generally, entity identifiers are server names—the host/IP/port of a homeserver (e.g.
/// "example.com") for which a signature must be verified. Key identifiers for each server (e.g.
/// "ed25519:1") then map to their respective public keys.
/// * `object`: The JSON object of the event that was signed.
/// * `room_version`: The version of the event's room.
///
/// # Examples
///
/// ```rust
/// # use std::collections::BTreeMap;
/// # use palpo_core::RoomVersionId;
/// # use palpo_core::serde::Base64;
/// # use palpo_core::signatures::{verify_event, Verified};
/// #
/// const PUBLIC_KEY: &[u8] = b"XGX0JRS2Af3be3knz2fBiRbApjm2Dh61gXDJA8kcJNI";
///
/// // Deserialize an event from JSON.
/// let object = serde_json::from_str(
/// r#"{
/// "auth_events": [],
/// "content": {},
/// "depth": 3,
/// "hashes": {
/// "sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
/// },
/// "origin": "domain",
/// "origin_server_ts": 1000000,
/// "prev_events": [],
/// "room_id": "!x:domain",
/// "sender": "@a:domain",
/// "signatures": {
/// "domain": {
/// "ed25519:1": "KxwGjPSDEtvnFgU00fwFz+l6d2pJM6XBIaMEn81SXPTRl16AqLAYqfIReFGZlHi5KLjAWbOoMszkwsQma+lYAg"
/// }
/// },
/// "type": "X",
/// "unsigned": {
/// "age_ts": 1000000
/// }
/// }"#
/// ).unwrap();
///
/// // Create the `PublicKeyMap` that will inform `verify_json` which signatures to verify.
/// let mut public_key_set = BTreeMap::new();
/// public_key_set.insert("ed25519:1".into(), Base64::parse(PUBLIC_KEY.to_owned()).unwrap());
/// let mut public_key_map = BTreeMap::new();
/// public_key_map.insert("domain".into(), public_key_set);
///
/// // Get the redaction rules for the version of the current room.
/// let rules =
/// RoomVersionId::V6.rules().expect("The rules should be known for a supported room version");
///
/// // Verify at least one signature for each entity in `public_key_map`.
/// let verification_result = verify_event(&public_key_map, &object, &rules);
/// assert!(verification_result.is_ok());
/// assert_eq!(verification_result.unwrap(), Verified::All);
/// ```
pub fn verify_event(
public_key_map: &PublicKeyMap,
object: &CanonicalJsonObject,
rules: &RoomVersionRules,
) -> Result<Verified, Error> {
let redacted = redact(object.clone(), &rules.redaction, None)?;
let hash = match object.get("hashes") {
Some(hashes_value) => match hashes_value {
CanonicalJsonValue::Object(hashes) => match hashes.get("sha256") {
Some(hash_value) => match hash_value {
CanonicalJsonValue::String(hash) => hash,
_ => return Err(JsonError::not_of_type("sha256 hash", JsonType::String)),
},
None => return Err(JsonError::not_of_type("hashes", JsonType::Object)),
},
_ => return Err(JsonError::field_missing_from_object("sha256")),
},
None => return Err(JsonError::field_missing_from_object("hashes")),
};
let signature_map = match object.get("signatures") {
Some(CanonicalJsonValue::Object(signatures)) => signatures,
Some(_) => return Err(JsonError::not_of_type("signatures", JsonType::Object)),
None => return Err(JsonError::field_missing_from_object("signatures")),
};
let servers_to_check = servers_to_check_signatures(object, &rules.signatures)?;
let canonical_json = canonical_json(&redacted)?;
for entity_id in servers_to_check {
verify_canonical_json_for_entity(
entity_id.as_str(),
public_key_map,
signature_map,
canonical_json.as_bytes(),
)?;
}
let calculated_hash = content_hash(object)?;
if let Ok(hash) = Base64::<Standard>::parse(hash)
&& hash.as_bytes() == calculated_hash.as_bytes()
{
return Ok(Verified::All);
}
Ok(Verified::Signatures)
}
/// Internal implementation detail of the canonical JSON algorithm.
///
/// Allows customization of the fields that will be removed before serializing.
fn canonical_json_with_fields_to_remove(
object: &CanonicalJsonObject,
fields: &[&str],
) -> Result<String, Error> {
let mut owned_object = object.clone();
for field in fields {
owned_object.remove(*field);
}
to_json_string(&owned_object).map_err(|e| Error::Json(e.into()))
}
/// Extracts the server names and key ids to check signatures for given event.
pub fn required_keys(
object: &CanonicalJsonObject,
version: &RoomVersionRules,
) -> Result<BTreeMap<OwnedServerName, Vec<OwnedServerSigningKeyId>>, Error> {
use CanonicalJsonValue::Object;
let mut map = BTreeMap::<OwnedServerName, Vec<OwnedServerSigningKeyId>>::new();
let Some(Object(signatures)) = object.get("signatures") else {
return Ok(map);
};
for server in servers_to_check_signatures(object, &version.signatures)? {
let Some(Object(set)) = signatures.get(server.as_str()) else {
continue;
};
let entry = map.entry(server.clone()).or_default();
set.keys()
.cloned()
.map(TryInto::try_into)
.filter_map(Result::ok)
.for_each(|key_id| entry.push(key_id));
}
Ok(map)
}
/// Extracts the server names to check signatures for given event.
///
/// Respects the rules for [validating signatures on received events] for populating the result:
///
/// - Add the server of the sender, except if it's an invite event that results from a third-party
/// invite.
/// - For room versions 1 and 2, add the server of the `event_id`.
/// - For room versions that support restricted join rules, if it's a join event with a
/// `join_authorised_via_users_server`, add the server of that user.
///
/// [validating signatures on received events]: https://spec.matrix.org/latest/server-server-api/#validating-hashes-and-signatures-on-received-events
fn servers_to_check_signatures(
object: &CanonicalJsonObject,
rules: &SignaturesRules,
) -> Result<BTreeSet<OwnedServerName>, Error> {
let mut servers_to_check = BTreeSet::new();
if !is_invite_via_third_party_id(object)? {
match object.get("sender") {
Some(CanonicalJsonValue::String(raw_sender)) => {
let user_id = <&UserId>::try_from(raw_sender.as_str())
.map_err(|e| Error::from(ParseError::UserId(e)))?;
servers_to_check.insert(user_id.server_name().to_owned());
}
Some(_) => return Err(JsonError::not_of_type("sender", JsonType::String)),
_ => return Err(JsonError::field_missing_from_object("sender")),
}
}
if rules.check_event_id_server {
match object.get("event_id") {
Some(CanonicalJsonValue::String(raw_event_id)) => {
let event_id: OwnedEventId = raw_event_id
.parse()
.map_err(|e| Error::from(ParseError::EventId(e)))?;
let server_name = event_id
.server_name()
.map(ToOwned::to_owned)
.ok_or_else(|| ParseError::server_name_from_event_id(event_id))?;
servers_to_check.insert(server_name);
}
Some(_) => return Err(JsonError::not_of_type("event_id", JsonType::String)),
_ => {
return Err(JsonError::field_missing_from_object("event_id"));
}
}
}
if rules.check_join_authorised_via_users_server
&& let Some(authorized_user) = object
.get("content")
.and_then(|c| c.as_object())
.and_then(|c| c.get("join_authorised_via_users_server"))
{
let authorized_user = authorized_user.as_str().ok_or_else(|| {
JsonError::not_of_type("join_authorised_via_users_server", JsonType::String)
})?;
match <&UserId>::try_from(authorized_user) {
Ok(user_id) => {
servers_to_check.insert(user_id.server_name().to_owned());
}
Err(e) => {
tracing::warn!(
"failed to parse join_authorised_via_users_server: {authorized_user:?}: {e}"
);
}
}
}
Ok(servers_to_check)
}
/// Whether the given event is an `m.room.member` invite that was created as the result of a
/// third-party invite.
///
/// Returns an error if the object has not the expected format of an `m.room.member` event.
fn is_invite_via_third_party_id(object: &CanonicalJsonObject) -> Result<bool, Error> {
let Some(CanonicalJsonValue::String(raw_type)) = object.get("type") else {
return Err(JsonError::not_of_type("type", JsonType::String));
};
if raw_type != "m.room.member" {
return Ok(false);
}
let Some(CanonicalJsonValue::Object(content)) = object.get("content") else {
return Err(JsonError::not_of_type("content", JsonType::Object));
};
let Some(CanonicalJsonValue::String(membership)) = content.get("membership") else {
return Err(JsonError::not_of_type("membership", JsonType::String));
};
if membership != "invite" {
return Ok(false);
}
match content.get("third_party_invite") {
Some(CanonicalJsonValue::Object(_)) => Ok(true),
None => Ok(false),
_ => Err(JsonError::not_of_type(
"third_party_invite",
JsonType::Object,
)),
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/signatures/error.rs | crates/core/src/signatures/error.rs | use thiserror::Error;
use crate::{
EventId, OwnedEventId, RoomVersionId,
serde::{
Base64DecodeError,
canonical_json::{JsonType, RedactionError},
},
};
/// `palpo-signature`'s error type, wraps a number of other error types.
#[derive(Debug, Error)]
#[non_exhaustive]
#[allow(clippy::enum_variant_names)]
pub enum Error {
/// [`JsonError`] wrapper.
#[error("json error: {0}")]
Json(#[from] JsonError),
/// [`VerificationError`] wrapper.
#[error("verification error: {0}")]
Verification(#[from] VerificationError),
/// [`ParseError`] wrapper.
#[error("parse error: {0}")]
Parse(#[from] ParseError),
/// Wrapper for [`pkcs8::Error`].
#[error("der parse error: {0}")]
DerParse(ed25519_dalek::pkcs8::Error),
/// The signature's ID does not have exactly two components separated by a
/// colon.
#[error("malformed signature ID: expected exactly 2 segment separated by a colon, found {0}")]
InvalidLength(usize),
/// The signature's ID contains invalid characters in its version.
#[error(
"malformed signature ID: expected version to contain only characters in the character set `[a-zA-Z0-9_]`, found `{0}`"
)]
InvalidVersion(String),
/// The signature uses an unsupported algorithm.
#[error("signature uses an unsupported algorithm: {0}")]
UnsupportedAlgorithm(String),
/// PDU was too large
#[error("pdu is larger than maximum of 65535 bytes")]
PduSize,
}
impl From<RedactionError> for Error {
fn from(err: RedactionError) -> Self {
match err {
RedactionError::NotOfType {
field: target,
of_type,
..
} => JsonError::NotOfType { target, of_type }.into(),
RedactionError::JsonFieldMissingFromObject(field) => {
JsonError::JsonFieldMissingFromObject(field).into()
}
#[allow(unreachable_patterns)]
_ => unreachable!(),
}
}
}
/// All errors related to JSON validation/parsing.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum JsonError {
/// `target` is not of the correct type `of_type` ([`JsonType`]).
#[error("Value in {target:?} must be a JSON {of_type:?}")]
NotOfType {
/// An arbitrary "target" that doesn't have the required type.
target: String,
/// The JSON type the target was expected to be.
of_type: JsonType,
},
/// Like [`JsonError::NotOfType`], only called when the `target` is a
/// multiple; array, set, etc.
#[error("Values in {target:?} must be JSON {of_type:?}s")]
NotMultiplesOfType {
/// An arbitrary "target" where
/// each or one of it's elements doesn't have the required type.
target: String,
/// The JSON type the element was expected to be.
of_type: JsonType,
},
/// The given required field is missing from a JSON object.
#[error("JSON object must contain the field {0:?}")]
JsonFieldMissingFromObject(String),
/// A key is missing from a JSON object.
///
/// Note that this is different from
/// [`JsonError::JsonFieldMissingFromObject`], this error talks about an
/// expected identifying key (`"ed25519:abcd"`) missing from a target,
/// where the key has a specific "type"/name.
#[error("JSON object {for_target:?} does not have {type_of} key {with_key:?}")]
JsonKeyMissing {
/// The target from which the key is missing.
for_target: String,
/// The kind of thing the key indicates.
type_of: String,
/// The key that is missing.
with_key: String,
},
/// A more generic JSON error from [`serde_json`].
#[error(transparent)]
Serde(#[from] serde_json::Error),
}
// TODO: make macro for this
impl JsonError {
pub(crate) fn not_of_type<T: Into<String>>(target: T, of_type: JsonType) -> Error {
Self::NotOfType {
target: target.into(),
of_type,
}
.into()
}
pub(crate) fn not_multiples_of_type<T: Into<String>>(target: T, of_type: JsonType) -> Error {
Self::NotMultiplesOfType {
target: target.into(),
of_type,
}
.into()
}
pub(crate) fn field_missing_from_object<T: Into<String>>(target: T) -> Error {
Self::JsonFieldMissingFromObject(target.into()).into()
}
pub(crate) fn key_missing<T1: Into<String>, T2: Into<String>, T3: Into<String>>(
for_target: T1,
type_of: T2,
with_key: T3,
) -> Error {
Self::JsonKeyMissing {
for_target: for_target.into(),
type_of: type_of.into(),
with_key: with_key.into(),
}
.into()
}
}
/// Errors relating to verification of events and signatures.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum VerificationError {
/// The signature uses an unsupported algorithm.
#[error("signature uses an unsupported algorithm")]
UnsupportedAlgorithm,
/// The signatures for an entity cannot be found in the signatures map.
#[error("could not find signatures for entity {0:?}")]
NoSignaturesForEntity(String),
/// The public keys for an entity cannot be found in the public keys map.
#[error("could not find public keys for entity {0:?}")]
NoPublicKeysForEntity(String),
/// For when a public key cannot be found for a `target`.
#[error("could not find public key for {entity:?}")]
PublicKeyNotFound {
/// The entity for which the key is missing.
entity: String,
/// The identifier of the key that is missing.
key_id: String,
},
/// No signature with a supported algorithm was found for the given entity.
#[error("could not find supported signature for entity {0:?}")]
NoSupportedSignatureForEntity(String),
/// The signature verification failed.
#[error("could not verify signature: {0}")]
Signature(#[source] ed25519_dalek::SignatureError),
}
impl VerificationError {
pub(crate) fn public_key_not_found(
entity: impl Into<String>,
key_id: impl Into<String>,
) -> Self {
Self::PublicKeyNotFound {
entity: entity.into(),
key_id: key_id.into(),
}
}
}
/// Errors relating to parsing of all sorts.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ParseError {
/// For user ID parsing errors.
#[error("could not parse user id: {0}")]
UserId(#[source] palpo_core::IdParseError),
/// For event ID parsing errors.
#[error("could not parse Event id: {0}")]
EventId(#[source] palpo_core::IdParseError),
/// For when an event ID, coupled with a specific room version, doesn't have a server name
/// embedded.
#[error("event id {0:?} should have a server name for the given room version")]
ServerNameFromEventId(OwnedEventId),
/// For when an event ID, coupled with a specific room version, doesn't have
/// a server name embedded.
#[error("event id {0:?} should have a server name for the given room version {1:?}")]
ServerNameFromEventIdByRoomVersion(OwnedEventId, RoomVersionId),
/// For when the extracted/"parsed" public key from a PKCS#8 v2 document
/// doesn't match the public key derived from it's private key.
#[error("PKCS#8 Document public key does not match public key derived from private key; derived: {0:X?} (len {}), parsed: {1:X?} (len {})", .derived_key.len(), .parsed_key.len())]
DerivedPublicKeyDoesNotMatchParsedKey {
/// The parsed key.
parsed_key: Vec<u8>,
/// The derived key.
derived_key: Vec<u8>,
},
/// For when the ASN.1 Object Identifier on a PKCS#8 document doesn't match
/// the expected one.
///
/// e.g. the document describes a RSA key, while an ed25519 key was
/// expected.
#[error("algorithm OID does not match ed25519, expected {expected}, found {found}")]
Oid {
/// The expected OID.
expected: ed25519_dalek::pkcs8::ObjectIdentifier,
/// The OID that was found instead.
found: ed25519_dalek::pkcs8::ObjectIdentifier,
},
/// For when [`ed25519_dalek`] cannot parse a secret/private key.
#[error("could not parse secret key")]
SecretKey,
/// For when [`ed25519_dalek`] cannot parse a public key.
#[error("could not parse public key: {0}")]
PublicKey(#[source] ed25519_dalek::SignatureError),
/// For when [`ed25519_dalek`] cannot parse a signature.
#[error("could not parse signature: {0}")]
Signature(#[source] ed25519_dalek::SignatureError),
/// For when parsing base64 gives an error.
#[error("could not parse {of_type} base64 string {string:?}: {source}")]
Base64 {
/// The "type"/name of the base64 string
of_type: String,
/// The string itself.
string: String,
/// The originating error.
#[source]
source: Base64DecodeError,
},
}
impl ParseError {
pub(crate) fn server_name_from_event_id(event_id: OwnedEventId) -> Error {
Self::ServerNameFromEventId(event_id).into()
}
pub(crate) fn from_event_id_by_room_version(
event_id: &EventId,
room_version: &RoomVersionId,
) -> Error {
Self::ServerNameFromEventIdByRoomVersion(event_id.to_owned(), room_version.clone()).into()
}
pub(crate) fn derived_vs_parsed_mismatch<P: Into<Vec<u8>>, D: Into<Vec<u8>>>(
parsed: P,
derived: D,
) -> Error {
Self::DerivedPublicKeyDoesNotMatchParsedKey {
parsed_key: parsed.into(),
derived_key: derived.into(),
}
.into()
}
pub(crate) fn base64<T1: Into<String>, T2: Into<String>>(
of_type: T1,
string: T2,
source: Base64DecodeError,
) -> Error {
Self::Base64 {
of_type: of_type.into(),
string: string.into(),
source,
}
.into()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/signatures/keys.rs | crates/core/src/signatures/keys.rs | //! Public and private key pairs.
use std::{
collections::BTreeMap,
fmt::{Debug, Formatter, Result as FmtResult},
};
use ed25519_dalek::{PUBLIC_KEY_LENGTH, SecretKey, Signer, SigningKey, pkcs8::ALGORITHM_OID};
use pkcs8::{
DecodePrivateKey, EncodePrivateKey, ObjectIdentifier, PrivateKeyInfo, der::zeroize::Zeroizing,
};
use crate::{
SigningKeyAlgorithm, SigningKeyId,
serde::Base64,
signatures::{Error, ParseError, Signature},
};
#[cfg(feature = "ring-compat")]
mod compat;
/// A cryptographic key pair for digitally signing data.
pub trait KeyPair: Sized {
/// Signs a JSON object.
///
/// # Parameters
///
/// * message: An arbitrary series of bytes to sign.
fn sign(&self, message: &[u8]) -> Signature;
}
/// An Ed25519 key pair.
#[derive(PartialEq, Eq, Clone)]
pub struct Ed25519KeyPair {
signing_key: SigningKey,
/// The specific name of the key pair.
version: String,
}
// impl<'de> Deserialize<'de> for Ed25519KeyPair {
// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
// where
// D: Deserializer<'de>,
// {
// let bytes =
//
// base64::decode(String::deserialize(deserializer).map_err(de::Error::custom)?
// ).map_err(de::Error::custom)?; let mut parts = bytes.splitn(2, |&b| b
// == 0xff); let (version, signing_key) = match (parts.next(),
// parts.next()) { (Some(version), Some(signing_key)) =>{(
//
// String::from_utf8(version.to_vec()).map_err(de::Error::custom)?,
// signing_key, )
// } ,
// (Some(signing_key), None) => ("".into(), signing_key),
// _ => return Err(de::Error::custom("Invalid keypair format in
// database.")), };
// Ok(Self {
// signing_key: SigningKey::from_bytes(
//
// Self::correct_privkey_from_octolet(signing_key).map_err(de::Error::custom)?,
// ),
// version,
// })
// }
// }
impl Ed25519KeyPair {
/// Create a key pair from its constituent parts.
pub fn new(
oid: ObjectIdentifier,
privkey: &[u8],
pubkey: Option<&[u8]>,
version: String,
) -> Result<Self, Error> {
if oid != ALGORITHM_OID {
return Err(ParseError::Oid {
expected: ALGORITHM_OID,
found: oid,
}
.into());
}
let secret_key = Self::correct_privkey_from_octolet(privkey)?;
let signing_key = SigningKey::from_bytes(secret_key);
if let Some(oak_key) = pubkey {
// If the document had a public key, we're verifying it.
let verifying_key = signing_key.verifying_key();
if oak_key != verifying_key.as_bytes() {
return Err(ParseError::derived_vs_parsed_mismatch(
oak_key,
verifying_key.as_bytes().to_vec(),
));
}
}
Ok(Self {
signing_key,
version,
})
}
/// Initializes a new key pair.
///
/// # Parameters
///
/// * document: PKCS#8 v1/v2 DER-formatted document containing the private
/// (and optionally public) key.
/// * version: The "version" of the key used for this signature. Versions
/// are used as an identifier to distinguish signatures generated from
/// different keys but using the same algorithm on the same homeserver.
///
/// # Errors
///
/// Returns an error if the public and private keys provided are invalid for
/// the implementing algorithm.
///
/// Returns an error when the PKCS#8 document had a public key, but it
/// doesn't match the one generated from the private key. This is a
/// fallback and extra validation against corruption or
pub fn from_der(document: &[u8], version: String) -> Result<Self, Error> {
let signing_key = SigningKey::from_pkcs8_der(document).map_err(Error::DerParse)?;
Ok(Self {
signing_key,
version,
})
}
/// Constructs a key pair from [`pkcs8::PrivateKeyInfo`].
pub fn from_pkcs8_oak(oak: PrivateKeyInfo<'_>, version: String) -> Result<Self, Error> {
Self::new(oak.algorithm.oid, oak.private_key, oak.public_key, version)
}
/// Constructs a key pair from [`pkcs8::PrivateKeyInfo`].
pub fn from_pkcs8_pki(oak: PrivateKeyInfo<'_>, version: String) -> Result<Self, Error> {
Self::new(oak.algorithm.oid, oak.private_key, None, version)
}
/// PKCS#8's "private key" is not yet actually the entire key,
/// so convert it if it is wrongly formatted.
///
/// See [RFC 8310 10.3](https://datatracker.ietf.org/doc/html/rfc8410#section-10.3) for more details
fn correct_privkey_from_octolet(key: &[u8]) -> Result<&SecretKey, ParseError> {
if key.len() == 34 && key[..2] == [0x04, 0x20] {
Ok(key[2..].try_into().unwrap())
} else {
key.try_into().map_err(|_| ParseError::SecretKey)
}
}
/// Generates a new key pair.
///
/// # Returns
///
/// Returns a `Vec<u8>` representing a DER-encoded PKCS#8 v2 document (with
/// public key)
///
/// # Errors
///
/// Returns an error if the generation failed.
pub fn generate() -> Result<Zeroizing<Vec<u8>>, Error> {
let signing_key = SigningKey::generate(&mut rand_core::OsRng);
Ok(signing_key
.to_pkcs8_der()
.map_err(Error::DerParse)?
.to_bytes())
}
/// Returns the version string for this keypair.
pub fn version(&self) -> &str {
&self.version
}
/// Returns the public key.
pub fn public_key(&self) -> [u8; PUBLIC_KEY_LENGTH] {
self.signing_key.verifying_key().to_bytes()
}
}
impl KeyPair for Ed25519KeyPair {
fn sign(&self, message: &[u8]) -> Signature {
Signature {
key_id: SigningKeyId::from_parts(
SigningKeyAlgorithm::Ed25519,
self.version.as_str().into(),
),
signature: self.signing_key.sign(message).to_bytes().to_vec(),
}
}
}
impl Debug for Ed25519KeyPair {
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
formatter
.debug_struct("Ed25519KeyPair")
.field(
"verifying_key",
&self.signing_key.verifying_key().as_bytes(),
)
.field("version", &self.version)
.finish()
}
}
/// A map from entity names to sets of public keys for that entity.
///
/// "Entity" is generally a homeserver, e.g. "example.com".
pub type PublicKeyMap = BTreeMap<String, PublicKeySet>;
/// A set of public keys for a single homeserver.
///
/// This is represented as a map from key ID to base64-encoded signature.
pub type PublicKeySet = BTreeMap<String, Base64>;
#[cfg(test)]
mod tests {
use super::Ed25519KeyPair;
const WELL_FORMED_DOC: &[u8] = &[
0x30, 0x72, 0x02, 0x01, 0x01, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, 0x04, 0x22, 0x04,
0x20, 0xD4, 0xEE, 0x72, 0xDB, 0xF9, 0x13, 0x58, 0x4A, 0xD5, 0xB6, 0xD8, 0xF1, 0xF7, 0x69,
0xF8, 0xAD, 0x3A, 0xFE, 0x7C, 0x28, 0xCB, 0xF1, 0xD4, 0xFB, 0xE0, 0x97, 0xA8, 0x8F, 0x44,
0x75, 0x58, 0x42, 0xA0, 0x1F, 0x30, 0x1D, 0x06, 0x0A, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D,
0x01, 0x09, 0x09, 0x14, 0x31, 0x0F, 0x0C, 0x0D, 0x43, 0x75, 0x72, 0x64, 0x6C, 0x65, 0x20,
0x43, 0x68, 0x61, 0x69, 0x72, 0x73, 0x81, 0x21, 0x00, 0x19, 0xBF, 0x44, 0x09, 0x69, 0x84,
0xCD, 0xFE, 0x85, 0x41, 0xBA, 0xC1, 0x67, 0xDC, 0x3B, 0x96, 0xC8, 0x50, 0x86, 0xAA, 0x30,
0xB6, 0xB6, 0xCB, 0x0C, 0x5C, 0x38, 0xAD, 0x70, 0x31, 0x66, 0xE1,
];
const WELL_FORMED_PUBKEY: &[u8] = &[
0x19, 0xBF, 0x44, 0x09, 0x69, 0x84, 0xCD, 0xFE, 0x85, 0x41, 0xBA, 0xC1, 0x67, 0xDC, 0x3B,
0x96, 0xC8, 0x50, 0x86, 0xAA, 0x30, 0xB6, 0xB6, 0xCB, 0x0C, 0x5C, 0x38, 0xAD, 0x70, 0x31,
0x66, 0xE1,
];
#[test]
fn generate_key() {
Ed25519KeyPair::generate().unwrap();
}
#[test]
fn well_formed_key() {
let keypair = Ed25519KeyPair::from_der(WELL_FORMED_DOC, "".to_owned()).unwrap();
assert_eq!(keypair.public_key(), WELL_FORMED_PUBKEY);
}
// #[cfg(feature = "ring-compat")]
// mod ring_compat {
// use super::Ed25519KeyPair;
// const RING_DOC: &[u8] = &[
// 0x30, 0x53, 0x02, 0x01, 0x01, 0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70, 0x04, 0x22,
// 0x04, 0x20, 0x61, 0x9E, 0xD8, 0x25, 0xA6, 0x1D, 0x32, 0x29, 0xD7, 0xD8, 0x22, 0x03,
// 0xC6, 0x0E, 0x37, 0x48, 0xE9, 0xC9, 0x11, 0x96, 0x3B, 0x03, 0x15, 0x94, 0x19, 0x3A,
// 0x86, 0xEC, 0xE6, 0x2D, 0x73, 0xC0, 0xA1, 0x23, 0x03, 0x21, 0x00, 0x3D, 0xA6, 0xC8,
// 0xD1, 0x76, 0x2F, 0xD6, 0x49, 0xB8, 0x4F, 0xF6, 0xC6, 0x1D, 0x04, 0xEA, 0x4A, 0x70,
// 0xA8, 0xC9, 0xF0, 0x8F, 0x96, 0x7F, 0x6B, 0xD7, 0xDA, 0xE5, 0x2E, 0x88, 0x8D, 0xBA,
// 0x3E,
// ];
// const RING_PUBKEY: &[u8] = &[
// 0x3D, 0xA6, 0xC8, 0xD1, 0x76, 0x2F, 0xD6, 0x49, 0xB8, 0x4F, 0xF6, 0xC6, 0x1D, 0x04,
// 0xEA, 0x4A, 0x70, 0xA8, 0xC9, 0xF0, 0x8F, 0x96, 0x7F, 0x6B, 0xD7, 0xDA, 0xE5, 0x2E,
// 0x88, 0x8D, 0xBA, 0x3E,
// ];
// #[test]
// fn ring_key() {
// let keypair = Ed25519KeyPair::from_der(RING_DOC, "".to_owned()).unwrap();
// assert_eq!(keypair.public_key(), RING_PUBKEY);
// }
// }
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/signatures/functions/tests.rs | crates/core/src/signatures/functions/tests.rs | use std::collections::BTreeMap;
use assert_matches2::assert_matches;
use serde_json::json;
use super::{
canonical_json, servers_to_check_signatures, sign_json, verify_canonical_json_bytes,
verify_event,
};
use crate::signatures::{
Ed25519KeyPair, Error, KeyPair, PublicKeyMap, PublicKeySet, VerificationError, Verified,
};
use crate::{
ServerSigningKeyId, SigningKeyAlgorithm,
room_version_rules::{RoomVersionRules, SignaturesRules},
serde::Base64,
serde::CanonicalJsonValue,
server_name,
};
fn generate_key_pair(name: &str) -> Ed25519KeyPair {
let key_content = Ed25519KeyPair::generate().unwrap();
Ed25519KeyPair::from_der(&key_content, name.to_owned())
.unwrap_or_else(|_| panic!("{:?}", &key_content))
}
fn add_key_to_map(public_key_map: &mut PublicKeyMap, name: &str, pair: &Ed25519KeyPair) {
let sender_key_map = public_key_map.entry(name.to_owned()).or_default();
let encoded_public_key = Base64::new(pair.public_key().to_vec());
let version = ServerSigningKeyId::from_parts(
SigningKeyAlgorithm::Ed25519,
pair.version().try_into().unwrap(),
);
sender_key_map.insert(version.to_string(), encoded_public_key);
}
fn add_invalid_key_to_map(public_key_map: &mut PublicKeyMap, name: &str, pair: &Ed25519KeyPair) {
let sender_key_map = public_key_map.entry(name.to_owned()).or_default();
let encoded_public_key = Base64::new(pair.public_key().to_vec());
let version = ServerSigningKeyId::from_parts(
SigningKeyAlgorithm::from("an-unknown-algorithm"),
pair.version().try_into().unwrap(),
);
sender_key_map.insert(version.to_string(), encoded_public_key);
}
#[test]
fn canonical_json_complex() {
let data = json!({
"auth": {
"success": true,
"mxid": "@john.doe:example.com",
"profile": {
"display_name": "John Doe",
"three_pids": [
{
"medium": "email",
"address": "john.doe@example.org"
},
{
"medium": "msisdn",
"address": "123456789"
}
]
}
}
});
let canonical = r#"{"auth":{"mxid":"@john.doe:example.com","profile":{"display_name":"John Doe","three_pids":[{"address":"john.doe@example.org","medium":"email"},{"address":"123456789","medium":"msisdn"}]},"success":true}}"#;
let CanonicalJsonValue::Object(object) = CanonicalJsonValue::try_from(data).unwrap() else {
unreachable!();
};
assert_eq!(canonical_json(&object).unwrap(), canonical);
}
#[test]
fn verify_event_does_not_check_signatures_invite_via_third_party_id() {
let signed_event = serde_json::from_str(
r#"{
"auth_events": [],
"content": {
"membership": "invite",
"third_party_invite": {
"display_name": "alice",
"signed": {
"mxid": "@alice:example.org",
"signatures": {
"magic.forest": {
"ed25519:3": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg"
}
},
"token": "abc123"
}
}
},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@a:domain",
"signatures": {
"domain": {
"ed25519:1": "KxwGjPSDEtvnFgU00fwFz+l6d2pJM6XBIaMEn81SXPTRl16AqLAYqfIReFGZlHi5KLjAWbOoMszkwsQma+lYAg"
}
},
"type": "m.room.member",
"unsigned": {
"age_ts": 1000000
}
}"#
).unwrap();
let public_key_map = BTreeMap::new();
let verification = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V6).unwrap();
assert_eq!(verification, Verified::Signatures);
}
#[test]
fn verify_event_check_signatures_for_both_sender_and_event_id() {
let key_pair_sender = generate_key_pair("1");
let key_pair_event = generate_key_pair("2");
let mut signed_event = serde_json::from_str(
r#"{
"event_id": "$event_id:domain-event",
"auth_events": [],
"content": {},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "X",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &key_pair_sender, &mut signed_event).unwrap();
sign_json("domain-event", &key_pair_event, &mut signed_event).unwrap();
let mut public_key_map = BTreeMap::new();
add_key_to_map(&mut public_key_map, "domain-sender", &key_pair_sender);
add_key_to_map(&mut public_key_map, "domain-event", &key_pair_event);
let verification = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V1).unwrap();
assert_eq!(verification, Verified::Signatures);
}
#[test]
fn verify_event_check_signatures_for_authorized_user() {
let key_pair_sender = generate_key_pair("1");
let key_pair_authorized = generate_key_pair("2");
let mut signed_event = serde_json::from_str(
r#"{
"event_id": "$event_id:domain-event",
"auth_events": [],
"content": {
"membership": "join",
"join_authorised_via_users_server": "@authorized:domain-authorized"
},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "m.room.member",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &key_pair_sender, &mut signed_event).unwrap();
sign_json("domain-authorized", &key_pair_authorized, &mut signed_event).unwrap();
let mut public_key_map = BTreeMap::new();
add_key_to_map(&mut public_key_map, "domain-sender", &key_pair_sender);
add_key_to_map(
&mut public_key_map,
"domain-authorized",
&key_pair_authorized,
);
let verification = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V9).unwrap();
assert_eq!(verification, Verified::Signatures);
}
#[test]
fn verification_fails_if_missing_signatures_for_authorized_user() {
let key_pair_sender = generate_key_pair("1");
let mut signed_event = serde_json::from_str(
r#"{
"event_id": "$event_id:domain-event",
"auth_events": [],
"content": {"join_authorised_via_users_server": "@authorized:domain-authorized"},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "X",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &key_pair_sender, &mut signed_event).unwrap();
let mut public_key_map = BTreeMap::new();
add_key_to_map(&mut public_key_map, "domain-sender", &key_pair_sender);
let verification_result = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V9);
assert_matches!(
verification_result,
Err(Error::Verification(
VerificationError::NoSignaturesForEntity(server)
))
);
assert_eq!(server, "domain-authorized");
}
#[test]
fn verification_fails_if_required_keys_are_not_given() {
let key_pair_sender = generate_key_pair("1");
let mut signed_event = serde_json::from_str(
r#"{
"auth_events": [],
"content": {},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "X",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &key_pair_sender, &mut signed_event).unwrap();
// Verify with an empty public key map should fail due to missing public keys
let public_key_map = BTreeMap::new();
let verification_result = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V6);
assert_matches!(
verification_result,
Err(Error::Verification(
VerificationError::NoPublicKeysForEntity(entity)
))
);
assert_eq!(entity, "domain-sender");
}
#[test]
fn verify_event_fails_if_public_key_is_invalid() {
let key_pair_sender = generate_key_pair("1");
let mut signed_event = serde_json::from_str(
r#"{
"auth_events": [],
"content": {},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "X",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &key_pair_sender, &mut signed_event).unwrap();
let mut public_key_map = PublicKeyMap::new();
let mut sender_key_map = PublicKeySet::new();
let newly_generated_key_pair = generate_key_pair("2");
let encoded_public_key = Base64::new(newly_generated_key_pair.public_key().to_vec());
let version = ServerSigningKeyId::from_parts(
SigningKeyAlgorithm::Ed25519,
key_pair_sender.version().try_into().unwrap(),
);
sender_key_map.insert(version.to_string(), encoded_public_key);
public_key_map.insert("domain-sender".to_owned(), sender_key_map);
let verification_result = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V6);
assert_matches!(
verification_result,
Err(Error::Verification(VerificationError::Signature(error)))
);
// dalek doesn't expose InternalError :(
// https://github.com/dalek-cryptography/ed25519-dalek/issues/174
assert!(format!("{error:?}").contains("Some(Verification equation was not satisfied)"));
}
#[test]
fn verify_event_check_signatures_for_sender_is_allowed_with_unknown_algorithms_in_key_map() {
let key_pair_sender = generate_key_pair("1");
let mut signed_event = serde_json::from_str(
r#"{
"auth_events": [],
"content": {},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "X",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &key_pair_sender, &mut signed_event).unwrap();
let mut public_key_map = BTreeMap::new();
add_key_to_map(&mut public_key_map, "domain-sender", &key_pair_sender);
add_invalid_key_to_map(
&mut public_key_map,
"domain-sender",
&generate_key_pair("2"),
);
let verification = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V6).unwrap();
assert_eq!(verification, Verified::Signatures);
}
#[test]
fn verify_event_fails_with_missing_key_when_event_is_signed_multiple_times_by_same_entity() {
let key_pair_sender = generate_key_pair("1");
let secondary_key_pair_sender = generate_key_pair("2");
let mut signed_event = serde_json::from_str(
r#"{
"auth_events": [],
"content": {},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "X",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &key_pair_sender, &mut signed_event).unwrap();
sign_json(
"domain-sender",
&secondary_key_pair_sender,
&mut signed_event,
)
.unwrap();
let mut public_key_map = BTreeMap::new();
add_key_to_map(&mut public_key_map, "domain-sender", &key_pair_sender);
let verification_result = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V6);
assert_matches!(
verification_result,
Err(Error::Verification(VerificationError::PublicKeyNotFound {
entity,
key_id
}))
);
assert_eq!(entity, "domain-sender");
assert_eq!(key_id, "ed25519:2");
}
#[test]
fn verify_event_checks_all_signatures_from_sender_entity() {
let key_pair_sender = generate_key_pair("1");
let secondary_key_pair_sender = generate_key_pair("2");
let mut signed_event = serde_json::from_str(
r#"{
"auth_events": [],
"content": {},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "X",
"unsigned": {
"age_ts": 1000000
}
}"#,
)
.unwrap();
sign_json("domain-sender", &key_pair_sender, &mut signed_event).unwrap();
sign_json(
"domain-sender",
&secondary_key_pair_sender,
&mut signed_event,
)
.unwrap();
let mut public_key_map = BTreeMap::new();
add_key_to_map(&mut public_key_map, "domain-sender", &key_pair_sender);
add_key_to_map(
&mut public_key_map,
"domain-sender",
&secondary_key_pair_sender,
);
let verification = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V6).unwrap();
assert_eq!(verification, Verified::Signatures);
}
#[test]
fn verify_event_with_single_key_with_unknown_algorithm_should_not_accept_event() {
let key_pair_sender = generate_key_pair("1");
let signed_event = serde_json::from_str(
r#"{
"auth_events": [],
"content": {},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1000000,
"prev_events": [],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "X",
"unsigned": {
"age_ts": 1000000
},
"signatures": {
"domain-sender": {
"an-unknown-algorithm:1": "pE5UT/4JiY7YZDtZDOsEaxc0wblurdoYqNQx4bCXORA3vLFOGOK10Q/xXVLPWWgIKo15LNvWwWd/2YjmdPvYCg"
}
}
}"#,
)
.unwrap();
let mut public_key_map = BTreeMap::new();
add_invalid_key_to_map(&mut public_key_map, "domain-sender", &key_pair_sender);
let verification_result = verify_event(&public_key_map, &signed_event, &RoomVersionRules::V6);
assert_matches!(
verification_result,
Err(Error::Verification(
VerificationError::NoSupportedSignatureForEntity(entity)
))
);
assert_eq!(entity, "domain-sender");
}
#[test]
fn servers_to_check_signatures_message() {
let message_event_json = json!({
"event_id": "$event_id:domain-event",
"auth_events": [
"$room_create",
"$power_levels",
"$sender_room_member",
],
"content": {
"msgtype": "text",
"body": "Hello world!",
},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1_000_000,
"prev_events": [
"$another_message",
],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"type": "m.room.message",
"unsigned": {
"age_ts": 1_000_000,
}
});
let object = serde_json::from_value(message_event_json).unwrap();
// Check for room v1.
let servers = servers_to_check_signatures(&object, &SignaturesRules::V1).unwrap();
assert_eq!(servers.len(), 2);
assert!(servers.contains(server_name!("domain-sender")));
assert!(servers.contains(server_name!("domain-event")));
// Check for room v3.
let servers = servers_to_check_signatures(&object, &SignaturesRules::V3).unwrap();
assert_eq!(servers.len(), 1);
assert!(servers.contains(server_name!("domain-sender")));
}
#[test]
fn servers_to_check_signatures_invite_via_third_party() {
let message_event_json = json!({
"event_id": "$event_id:domain-event",
"auth_events": [
"$room_create",
"$power_levels",
"$sender_room_member",
],
"content": {
"membership": "invite",
"third_party_invite": {},
},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1_000_000,
"prev_events": [
"$another_message",
],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"state_key": "@name:domain-target-user",
"type": "m.room.member",
"unsigned": {
"age_ts": 1_000_000,
}
});
let object = serde_json::from_value(message_event_json).unwrap();
// Check for room v1.
let servers = servers_to_check_signatures(&object, &SignaturesRules::V1).unwrap();
assert_eq!(servers.len(), 1);
assert!(servers.contains(server_name!("domain-event")));
// Check for room v3.
let servers = servers_to_check_signatures(&object, &SignaturesRules::V3).unwrap();
assert_eq!(servers.len(), 0);
}
#[test]
fn servers_to_check_signatures_restricted() {
let message_event_json = json!({
"event_id": "$event_id:domain-event",
"auth_events": [
"$room_create",
"$power_levels",
"$sender_room_member",
],
"content": {
"membership": "join",
"join_authorised_via_users_server": "@name:domain-authorize-user",
},
"depth": 3,
"hashes": {
"sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
},
"origin": "domain",
"origin_server_ts": 1_000_000,
"prev_events": [
"$another_message",
],
"room_id": "!x:domain",
"sender": "@name:domain-sender",
"state_key": "@name:domain-sender",
"type": "m.room.member",
"unsigned": {
"age_ts": 1_000_000,
}
});
let object = serde_json::from_value(message_event_json).unwrap();
// Check for room v1.
let servers = servers_to_check_signatures(&object, &SignaturesRules::V1).unwrap();
assert_eq!(servers.len(), 2);
assert!(servers.contains(server_name!("domain-sender")));
assert!(servers.contains(server_name!("domain-event")));
// Check for room v3.
let servers = servers_to_check_signatures(&object, &SignaturesRules::V3).unwrap();
assert_eq!(servers.len(), 1);
assert!(servers.contains(server_name!("domain-sender")));
// Check for room v8.
let servers = servers_to_check_signatures(&object, &SignaturesRules::V8).unwrap();
assert_eq!(servers.len(), 2);
assert!(servers.contains(server_name!("domain-sender")));
assert!(servers.contains(server_name!("domain-authorize-user")));
}
#[test]
fn verify_canonical_json_bytes_success() {
let json = serde_json::from_value(json!({
"foo": "bar",
"bat": "baz",
}))
.unwrap();
let canonical_json = canonical_json(&json).unwrap();
let key_pair = generate_key_pair("1");
let signature = key_pair.sign(canonical_json.as_bytes());
verify_canonical_json_bytes(
&signature.algorithm(),
key_pair.public_key().as_slice(),
signature.as_bytes(),
canonical_json.as_bytes(),
)
.unwrap();
}
#[test]
fn verify_canonical_json_bytes_unsupported_algorithm() {
let json = serde_json::from_value(json!({
"foo": "bar",
"bat": "baz",
}))
.unwrap();
let canonical_json = canonical_json(&json).unwrap();
let key_pair = generate_key_pair("1");
let signature = key_pair.sign(canonical_json.as_bytes());
let err = verify_canonical_json_bytes(
&"unknown".into(),
key_pair.public_key().as_slice(),
signature.as_bytes(),
canonical_json.as_bytes(),
)
.unwrap_err();
assert_matches!(
err,
Error::Verification(VerificationError::UnsupportedAlgorithm)
);
}
#[test]
fn verify_canonical_json_bytes_wrong_key() {
let json = serde_json::from_value(json!({
"foo": "bar",
"bat": "baz",
}))
.unwrap();
let canonical_json = canonical_json(&json).unwrap();
let valid_key_pair = generate_key_pair("1");
let signature = valid_key_pair.sign(canonical_json.as_bytes());
let wrong_key_pair = generate_key_pair("2");
let err = verify_canonical_json_bytes(
&"ed25519".into(),
wrong_key_pair.public_key().as_slice(),
signature.as_bytes(),
canonical_json.as_bytes(),
)
.unwrap_err();
assert_matches!(err, Error::Verification(VerificationError::Signature(_)));
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/signatures/keys/compat.rs | crates/core/src/signatures/keys/compat.rs | use subslice::SubsliceExt as _;
#[derive(Debug)]
pub(super) enum CompatibleDocument<'a> {
WellFormed(&'a [u8]),
CleanedFromRing(Vec<u8>),
}
impl<'a> CompatibleDocument<'a> {
pub(super) fn from_bytes(bytes: &'a [u8]) -> Self {
if is_ring(bytes) {
Self::CleanedFromRing(fix_ring_doc(bytes.to_vec()))
} else {
Self::WellFormed(bytes)
}
}
}
// Ring uses a very specific template to generate its documents,
// and so this is essentially a sentinel value of that.
//
// It corresponds to CONTEXT-SPECIFIC[1](35) { BIT-STRING(32) {...} } in ASN.1
//
// A well-formed bit would look like just CONTEXT-SPECIFIC[1](32) { ... }
//
// Note: this is purely a sentinel value, don't take these bytes out of context
// to detect or fiddle with the document.
const RING_TEMPLATE_CONTEXT_SPECIFIC: &[u8] = &[0xA1, 0x23, 0x03, 0x21];
// A checked well-formed context-specific[1] prefix.
const WELL_FORMED_CONTEXT_ONE_PREFIX: &[u8] = &[0x81, 0x21];
// If present, removes a malfunctioning pubkey suffix and adjusts the length at
// the start.
fn fix_ring_doc(mut doc: Vec<u8>) -> Vec<u8> {
assert!(!doc.is_empty());
// Check if first tag is ASN.1 SEQUENCE
assert_eq!(doc[0], 0x30);
// Second byte asserts the length for the rest of the document
assert_eq!(doc[1] as usize, doc.len() - 2);
let idx = doc
.find(RING_TEMPLATE_CONTEXT_SPECIFIC)
.expect("Expected to find ring template in doc, but found none.");
// Snip off the malformed bit.
let suffix = doc.split_off(idx);
// Feed back an actual well-formed prefix.
doc.extend(WELL_FORMED_CONTEXT_ONE_PREFIX);
// Then give it the actual public key.
doc.extend(&suffix[4..]);
doc[1] = doc.len() as u8 - 2;
doc
}
fn is_ring(bytes: &[u8]) -> bool {
bytes.find(RING_TEMPLATE_CONTEXT_SPECIFIC).is_some()
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/html/helpers.rs | crates/core/src/html/helpers.rs | //! Convenience methods and types to sanitize HTML messages.
use crate::html::{Html, HtmlSanitizerMode, SanitizerConfig};
/// Sanitize the given HTML string.
///
/// This removes the [tags and attributes] that are not listed in the Matrix specification.
///
/// It can also optionally remove the [rich reply] fallback.
///
/// [tags and attributes]: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes
/// [rich reply]: https://spec.matrix.org/latest/client-server-api/#rich-replies
pub fn sanitize_html(
s: &str,
mode: HtmlSanitizerMode,
remove_reply_fallback: RemoveReplyFallback,
) -> String {
let mut conf = match mode {
HtmlSanitizerMode::Strict => SanitizerConfig::strict(),
HtmlSanitizerMode::Compat => SanitizerConfig::compat(),
};
if remove_reply_fallback == RemoveReplyFallback::Yes {
conf = conf.remove_reply_fallback();
}
sanitize_inner(s, &conf)
}
/// Whether to remove the [rich reply] fallback while sanitizing.
///
/// [rich reply]: https://spec.matrix.org/latest/client-server-api/#rich-replies
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(clippy::exhaustive_enums)]
pub enum RemoveReplyFallback {
/// Remove the rich reply fallback.
Yes,
/// Don't remove the rich reply fallback.
No,
}
/// Remove the [rich reply] fallback of the given HTML string.
///
/// Due to the fact that the HTML is parsed, note that malformed HTML and comments will be stripped
/// from the output.
///
/// [rich reply]: https://spec.matrix.org/latest/client-server-api/#rich-replies
pub fn remove_html_reply_fallback(s: &str) -> String {
let conf = SanitizerConfig::new().remove_reply_fallback();
sanitize_inner(s, &conf)
}
fn sanitize_inner(s: &str, conf: &SanitizerConfig) -> String {
let html = Html::parse(s);
html.sanitize_with(conf);
html.to_string()
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/html/sanitizer_config.rs | crates/core/src/html/sanitizer_config.rs | #![allow(clippy::disallowed_types)]
use std::collections::{HashMap, HashSet};
pub(crate) mod clean;
use crate::html::HtmlSanitizerMode;
/// Configuration to sanitize HTML elements and attributes.
#[derive(Debug, Default, Clone)]
pub struct SanitizerConfig {
/// The mode of the sanitizer, if any.
mode: Option<HtmlSanitizerMode>,
/// Change to the list of elements to replace.
///
/// The content is a map of element name to their replacement's element name.
replace_elements: Option<List<HashMap<&'static str, &'static str>>>,
/// Elements to remove.
remove_elements: Option<HashSet<&'static str>>,
/// Whether to remove the rich reply fallback.
remove_reply_fallback: bool,
/// Elements to ignore.
ignore_elements: Option<HashSet<&'static str>>,
/// Change to the list of elements to allow.
allow_elements: Option<List<HashSet<&'static str>>>,
/// Change to the list of attributes to replace per element.
///
/// The content is a map of element name to a map of attribute name to their replacement's
/// attribute name.
replace_attrs: Option<List<HashMap<&'static str, HashMap<&'static str, &'static str>>>>,
/// Removed attributes per element.
remove_attrs: Option<HashMap<&'static str, HashSet<&'static str>>>,
/// Change to the list of allowed attributes per element.
allow_attrs: Option<List<HashMap<&'static str, HashSet<&'static str>>>>,
/// Denied URI schemes per attribute per element.
///
/// The content is a map of element name to a map of attribute name to a set of schemes.
deny_schemes: Option<HashMap<&'static str, HashMap<&'static str, HashSet<&'static str>>>>,
/// Change to the list of allowed URI schemes per attribute per element.
///
/// The content is a map of element name to a map of attribute name to a set of schemes.
#[allow(clippy::type_complexity)]
allow_schemes:
Option<List<HashMap<&'static str, HashMap<&'static str, HashSet<&'static str>>>>>,
/// Removed classes per element.
///
/// The content is a map of element name to a set of classes.
remove_classes: Option<HashMap<&'static str, HashSet<&'static str>>>,
/// Change to the list of allowed classes per element.
///
/// The content is a map of element name to a set of classes.
allow_classes: Option<List<HashMap<&'static str, HashSet<&'static str>>>>,
/// Maximum nesting level of the elements.
max_depth: Option<u32>,
}
impl SanitizerConfig {
/// Constructs an empty `SanitizerConfig` that will not filter any element or attribute.
///
/// The list of allowed and replaced elements can be changed with [`Self::allow_elements()`],
/// [`Self::replace_elements()`], [`Self::ignore_elements()`], [`Self::remove_elements()`],
/// [`Self::remove_reply_fallback()`].
///
/// The list of allowed and replaced attributes can be changed with
/// [`Self::allow_attributes()`], [`Self::replace_attributes()`],
/// [`Self::remove_attributes()`], [`Self::allow_schemes()`], [`Self::deny_schemes()`],
/// [`Self::allow_classes()`], [`Self::remove_classes()`].
pub fn new() -> Self {
Self::default()
}
/// Constructs a `SanitizerConfig` with the given mode for filtering elements and attributes.
///
/// The mode defines the basic list of allowed and replaced elements and attributes and the
/// maximum nesting level of elements.
///
/// The list of allowed and replaced elements can be changed with [`Self::allow_elements()`],
/// [`Self::replace_elements()`], [`Self::ignore_elements()`], [`Self::remove_elements()`],
/// [`Self::remove_reply_fallback()`].
///
/// The list of allowed and replaced attributes can be changed with
/// [`Self::allow_attributes()`], [`Self::replace_attributes()`],
/// [`Self::remove_attributes()`], [`Self::allow_schemes()`], [`Self::deny_schemes()`],
/// [`Self::allow_classes()`], [`Self::remove_classes()`].
pub fn with_mode(mode: HtmlSanitizerMode) -> Self {
Self {
mode: Some(mode),
..Default::default()
}
}
/// Constructs a `SanitizerConfig` that will filter elements and attributes not [suggested in
/// the Matrix specification].
///
/// The list of allowed and replaced elements can be changed with [`Self::allow_elements()`],
/// [`Self::replace_elements()`], [`Self::ignore_elements()`], [`Self::remove_elements()`],
/// [`Self::remove_reply_fallback()`].
///
/// The list of allowed and replaced attributes can be changed with
/// [`Self::allow_attributes()`], [`Self::replace_attributes()`],
/// [`Self::remove_attributes()`], [`Self::allow_schemes()`], [`Self::deny_schemes()`],
/// [`Self::allow_classes()`], [`Self::remove_classes()`].
///
/// This is the same as calling `SanitizerConfig::with_mode(HtmlSanitizerMode::Strict)`.
///
/// [suggested in the Matrix specification]: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes
pub fn strict() -> Self {
Self::with_mode(HtmlSanitizerMode::Strict)
}
/// Constructs a `SanitizerConfig` that will filter elements and attributes not [suggested in
/// the Matrix specification], except a few for improved compatibility:
///
/// * The `matrix` scheme is allowed in links.
///
/// The list of allowed elements can be changed with [`Self::allow_elements()`],
/// [`Self::replace_elements()`], [`Self::ignore_elements()`], [`Self::remove_elements()`],
/// [`Self::remove_reply_fallback()`].
///
/// The list of allowed attributes can be changed with [`Self::allow_attributes()`],
/// [`Self::replace_attributes()`], [`Self::remove_attributes()`], [`Self::allow_schemes()`],
/// [`Self::deny_schemes()`], [`Self::allow_classes()`], [`Self::remove_classes()`].
///
/// This is the same as calling `SanitizerConfig::with_mode(HtmlSanitizerMode::Compat)`.
///
/// [listed in the Matrix specification]: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes
pub fn compat() -> Self {
Self::with_mode(HtmlSanitizerMode::Compat)
}
/// Change the list of replaced HTML elements.
///
/// The given list is added to or replaces the list of replacements of the current mode,
/// depending on the [`ListBehavior`].
///
/// The replacement occurs before the removal, so the replaced element should not be in
/// the allowed list of elements, but the replacement element should.
///
/// # Parameters
///
/// * `elements`: The list of element names replacements.
pub fn replace_elements(
mut self,
elements: impl IntoIterator<Item = NameReplacement>,
behavior: ListBehavior,
) -> Self {
let content = elements.into_iter().map(|r| r.to_tuple()).collect();
self.replace_elements = Some(List { content, behavior });
self
}
/// Remove the given HTML elements.
///
/// When an element is removed, the element and its children are dropped. If you want to remove
/// an element but keep its children, use [`SanitizerConfig::ignore_elements`] or
/// [`SanitizerConfig::allow_elements`].
///
/// Removing elements has a higher priority than ignoring or allowing. So if an element is in
/// this list, it will always be removed.
///
/// # Parameters
///
/// * `elements`: The list of element names to remove.
pub fn remove_elements(mut self, elements: impl IntoIterator<Item = &'static str>) -> Self {
self.remove_elements = Some(elements.into_iter().collect());
self
}
/// Remove the [rich reply] fallback.
///
/// Calling this allows to remove the `mx-reply` element in addition to the list of elements to
/// remove.
///
/// Removing elements has a higher priority than ignoring or allowing. So if this settings is
/// set, `mx-reply` will always be removed.
///
/// [rich reply]: https://spec.matrix.org/latest/client-server-api/#rich-replies
pub fn remove_reply_fallback(mut self) -> Self {
self.remove_reply_fallback = true;
self
}
/// Ignore the given HTML elements.
///
/// When an element is ignored, the element is dropped and replaced by its children. If you want
/// to drop an element and its children, use [`SanitizerConfig::remove_elements`].
///
/// Removing elements has a lower priority than removing but a higher priority than allowing.
///
/// # Parameters
///
/// * `elements`: The list of element names to ignore.
pub fn ignore_elements(mut self, elements: impl IntoIterator<Item = &'static str>) -> Self {
self.ignore_elements = Some(elements.into_iter().collect());
self
}
/// Change the list of allowed HTML elements.
///
/// The given list is added to or replaces the list of allowed elements of the current
/// mode, depending on the [`ListBehavior`].
///
/// If an element is not allowed, it is ignored. If no mode is set and no elements are
/// explicitly allowed, all elements are allowed.
///
/// # Parameters
///
/// * `elements`: The list of element names.
pub fn allow_elements(
mut self,
elements: impl IntoIterator<Item = &'static str>,
behavior: ListBehavior,
) -> Self {
let content = elements.into_iter().collect();
self.allow_elements = Some(List { content, behavior });
self
}
/// Change the list of replaced attributes per HTML element.
///
/// The given list is added to or replaces the list of replacements of the current mode,
/// depending on the [`ListBehavior`].
///
/// The replacement occurs before the removal, so the replaced attribute should not be in the
/// list of allowed attributes, but the replacement attribute should. Attribute replacement
/// occurs before element replacement, so if you want to replace an attribute on an element
/// that is set to be replaced, you must use the replaced element's name, not the name of its
/// replacement.
///
/// # Parameters
///
/// * `attrs`: The list of element's attributes replacements.
pub fn replace_attributes<'a>(
mut self,
attrs: impl IntoIterator<Item = ElementAttributesReplacement<'a>>,
behavior: ListBehavior,
) -> Self {
let content = attrs.into_iter().map(|r| r.to_tuple()).collect();
self.replace_attrs = Some(List { content, behavior });
self
}
/// Remove the given attributes per HTML element.
///
/// Removing attributes has a higher priority than allowing. So if an attribute is in
/// this list, it will always be removed.
///
/// # Parameters
///
/// * `attrs`: The list of attributes per element. The value of `parent` is the element name,
/// and `properties` contains attribute names.
pub fn remove_attributes<'a>(
mut self,
attrs: impl IntoIterator<Item = PropertiesNames<'a>>,
) -> Self {
self.remove_attrs = Some(attrs.into_iter().map(|a| a.to_tuple()).collect());
self
}
/// Change the list of allowed attributes per HTML element.
///
/// The given list is added to or replaces the list of allowed attributes of the current
/// mode, depending on the [`ListBehavior`].
///
/// If an attribute is not allowed, it is removed. If no mode is set and no attributes are
/// explicitly allowed, all attributes are allowed.
///
/// # Parameters
///
/// * `attrs`: The list of attributes per element. The value of `parent` is the element name,
/// and `properties` contains attribute names.
pub fn allow_attributes<'a>(
mut self,
attrs: impl IntoIterator<Item = PropertiesNames<'a>>,
behavior: ListBehavior,
) -> Self {
let content = attrs.into_iter().map(|a| a.to_tuple()).collect();
self.allow_attrs = Some(List { content, behavior });
self
}
/// Deny the given URI schemes per attribute per HTML element.
///
/// Denying schemes has a higher priority than allowing. So if a scheme is in
/// this list, it will always be denied.
///
/// If a scheme is denied, its element is removed, because it is deemed that the element will
/// not be usable without it URI.
///
/// # Parameters
///
/// * `schemes`: The list of schemes per attribute per element.
pub fn deny_schemes<'a>(
mut self,
schemes: impl IntoIterator<Item = ElementAttributesSchemes<'a>>,
) -> Self {
self.deny_schemes = Some(schemes.into_iter().map(|s| s.to_tuple()).collect());
self
}
/// Change the list of allowed schemes per attribute per HTML element.
///
/// The given list is added to or replaces the list of allowed schemes of the current
/// mode, depending on the [`ListBehavior`].
///
/// If a scheme is not allowed, it is denied. If a scheme is denied, its element is ignored,
/// because it is deemed that the element will not be usable without it URI. If no mode is set
/// and no schemes are explicitly allowed, all schemes are allowed.
///
/// # Parameters
///
/// * `schemes`: The list of schemes per attribute per element.
pub fn allow_schemes<'a>(
mut self,
schemes: impl IntoIterator<Item = ElementAttributesSchemes<'a>>,
behavior: ListBehavior,
) -> Self {
let content = schemes.into_iter().map(|s| s.to_tuple()).collect();
self.allow_schemes = Some(List { content, behavior });
self
}
/// Deny the given classes per HTML element.
///
/// Removing classes has a higher priority than allowing. So if a class is in
/// this list, it will always be removed.
///
/// If all the classes of a `class` attribute are removed, the whole attribute is removed.
///
/// In the list of classes, the names must match the full class name. `*` can be used as a
/// wildcard for any number of characters. So `language` will only match a class named
/// `language`, and `language-*` will match any class name starting with `language-`.
///
/// # Parameters
///
/// * `attrs`: The list of classes per element. The value of `parent` is the element name, and
/// `properties` contains classes.
pub fn remove_classes<'a>(
mut self,
classes: impl IntoIterator<Item = PropertiesNames<'a>>,
) -> Self {
self.remove_classes = Some(classes.into_iter().map(|c| c.to_tuple()).collect());
self
}
/// Change the list of allowed classes per HTML element.
///
/// The given list is added, removed or replaces the list of allowed classes of the current
/// mode, depending on the [`ListBehavior`].
///
/// If a class is not allowed, it is removed. If all the classes of a `class` attribute are
/// removed, the whole attribute is removed. If no mode is set and no classes are explicitly
/// allowed, all classes are allowed.
///
/// In the list of classes, the names must match the full class name. `*` can be used as a
/// wildcard for any number of characters. So `language` will only match a class named
/// `language`, and `language-*` will match any class name starting with `language-`.
///
/// # Parameters
///
/// * `attrs`: The list of classes per element. The value of `parent` is the element name, and
/// `properties` contains classes.
pub fn allow_classes<'a>(
mut self,
classes: impl IntoIterator<Item = PropertiesNames<'a>>,
behavior: ListBehavior,
) -> Self {
let content = classes.into_iter().map(|c| c.to_tuple()).collect();
self.allow_classes = Some(List { content, behavior });
self
}
/// The maximum nesting level of HTML elements.
///
/// This overrides the maximum depth set by the mode, if one is set.
///
/// All elements that are deeper than the maximum depth will be removed. If no mode is set and
/// no maximum depth is explicitly set, elements are not filtered by their nesting level.
///
/// # Parameters
///
/// * `depth`: The maximum nesting level allowed.
pub fn max_depth(mut self, depth: u32) -> Self {
self.max_depth = Some(depth);
self
}
}
/// A list with a behavior.
#[derive(Debug, Clone)]
struct List<T> {
/// The content of this list.
content: T,
/// The behavior of this list.
behavior: ListBehavior,
}
impl<T> List<T> {
/// Whether this is `ListBehavior::Override`.
fn is_override(&self) -> bool {
self.behavior == ListBehavior::Override
}
}
/// The behavior of the setting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(clippy::exhaustive_enums)]
pub enum ListBehavior {
/// The list replaces the default list of the current mode, if one is set.
///
/// If no mode is set, this is the full allow list.
Override,
/// The list is added to the default list of the current mode, if one is set.
///
/// If no mode is set, this is the full allow list.
Add,
}
/// The replacement of a name.
#[derive(Debug, Clone, Copy)]
#[allow(clippy::exhaustive_structs)]
pub struct NameReplacement {
/// The name to replace.
pub old: &'static str,
/// The name of the replacement.
pub new: &'static str,
}
impl NameReplacement {
fn to_tuple(self) -> (&'static str, &'static str) {
(self.old, self.new)
}
}
/// A list of properties names for a parent.
#[allow(clippy::exhaustive_structs)]
#[derive(Debug, Clone, Copy)]
pub struct PropertiesNames<'a> {
/// The name of the parent.
pub parent: &'static str,
/// The list of properties names.
pub properties: &'a [&'static str],
}
impl PropertiesNames<'_> {
fn to_tuple(self) -> (&'static str, HashSet<&'static str>) {
let set = self.properties.iter().copied().collect();
(self.parent, set)
}
}
/// The replacement of an element's attributes.
#[allow(clippy::exhaustive_structs)]
#[derive(Debug, Clone, Copy)]
pub struct ElementAttributesReplacement<'a> {
/// The name of the element.
pub element: &'static str,
/// The list of attributes replacements.
pub replacements: &'a [NameReplacement],
}
impl ElementAttributesReplacement<'_> {
fn to_tuple(self) -> (&'static str, HashMap<&'static str, &'static str>) {
let map = self.replacements.iter().map(|r| r.to_tuple()).collect();
(self.element, map)
}
}
/// An element's attributes' URI schemes.
#[allow(clippy::exhaustive_structs)]
#[derive(Debug, Clone, Copy)]
pub struct ElementAttributesSchemes<'a> {
/// The name of the element.
pub element: &'static str,
/// The list of allowed URI schemes per attribute name.
///
/// The value of the `parent` is the attribute name and the properties are schemes.
pub attr_schemes: &'a [PropertiesNames<'a>],
}
impl ElementAttributesSchemes<'_> {
fn to_tuple(self) -> (&'static str, HashMap<&'static str, HashSet<&'static str>>) {
let map = self.attr_schemes.iter().map(|s| s.to_tuple()).collect();
(self.element, map)
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/html/matrix.rs | crates/core/src/html/matrix.rs | //! Types to work with HTML elements and attributes [suggested by the Matrix Specification][spec].
//!
//! [spec]: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes
use std::collections::BTreeSet;
use html5ever::{Attribute, QualName, ns, tendril::StrTendril};
use crate::html::sanitizer_config::clean::{
ALLOWED_SCHEMES_A_HREF_COMPAT, ALLOWED_SCHEMES_A_HREF_STRICT,
};
use crate::{
IdParseError, MatrixToError, MatrixToUri, MatrixUri, MatrixUriError, MxcUri, OwnedMxcUri,
};
const CLASS_LANGUAGE_PREFIX: &str = "language-";
/// The data of a Matrix HTML element.
///
/// This is a helper type to work with elements [suggested by the Matrix Specification][spec].
///
/// This performs a lossless conversion from [`ElementData`]. Unsupported elements are represented
/// by [`MatrixElement::Other`] and unsupported attributes are listed in the `attrs` field.
///
/// [`ElementData`]: crate::ElementData
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes
#[derive(Debug, Clone)]
#[allow(clippy::exhaustive_structs)]
pub struct MatrixElementData {
/// The HTML element and its supported data.
pub element: MatrixElement,
/// The unsupported attributes found on the element.
pub attrs: BTreeSet<Attribute>,
}
impl MatrixElementData {
/// Parse a `MatrixElementData` from the given qualified name and attributes.
#[allow(clippy::mutable_key_type)]
pub(super) fn parse(name: &QualName, attrs: &BTreeSet<Attribute>) -> Self {
let (element, attrs) = MatrixElement::parse(name, attrs);
Self { element, attrs }
}
}
/// A Matrix HTML element.
///
/// All the elements [suggested by the Matrix Specification][spec] have a variant. The others are
/// handled by the fallback `Other` variant.
///
/// Suggested attributes are represented as optional fields on the variants structs.
///
/// [spec]: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum MatrixElement {
/// [`<del>`], a deleted text element.
///
/// [`<del>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del
Del,
/// [`<h1>-<h6>`], a section heading element.
///
/// [`<h1>-<h6>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements
H(HeadingData),
/// [`<blockquote>`], a block quotation element.
///
/// [`<blockquote>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote
Blockquote,
/// [`<p>`], a paragraph element.
///
/// [`<p>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p
P,
/// [`<a>`], an anchor element.
///
/// [`<a>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
A(AnchorData),
/// [`<ul>`], an unordered list element.
///
/// [`<ul>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul
Ul,
/// [`<ol>`], an ordered list element.
///
/// [`<ol>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol
Ol(OrderedListData),
/// [`<sup>`], a superscript element.
///
/// [`<sup>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup
Sup,
/// [`<sub>`], a subscript element.
///
/// [`<sub>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub
Sub,
/// [`<li>`], a list item element.
///
/// [`<li>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li
Li,
/// [`<b>`], a bring attention to element.
///
/// [`<b>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b
B,
/// [`<i>`], an idiomatic text element.
///
/// [`<i>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i
I,
/// [`<u>`], an unarticulated annotation element.
///
/// [`<u>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/u
U,
/// [`<strong>`], a strong importance element.
///
/// [`<strong>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong
Strong,
/// [`<em>`], an emphasis element.
///
/// [`<em>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em
Em,
/// [`<s>`], a strikethrough element.
///
/// [`<s>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/s
S,
/// [`<code>`], an inline code element.
///
/// [`<code>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code
Code(CodeData),
/// [`<hr>`], a thematic break element.
///
/// [`<hr>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr
Hr,
/// [`<br>`], a line break element.
///
/// [`<br>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br
Br,
/// [`<div>`], a content division element.
///
/// [`<div>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div
Div(DivData),
/// [`<table>`], a table element.
///
/// [`<table>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
Table,
/// [`<thead>`], a table head element.
///
/// [`<thead>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead
Thead,
/// [`<tbody>`], a table body element.
///
/// [`<tbody>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody
Tbody,
/// [`<tr>`], a table row element.
///
/// [`<tr>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr
Tr,
/// [`<th>`], a table header element.
///
/// [`<th>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th
Th,
/// [`<td>`], a table data cell element.
///
/// [`<td>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td
Td,
/// [`<caption>`], a table caption element.
///
/// [`<caption>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption
Caption,
/// [`<pre>`], a preformatted text element.
///
/// [`<pre>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
Pre,
/// [`<span>`], a content span element.
///
/// [`<span>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
Span(SpanData),
/// [`<img>`], an image embed element.
///
/// [`<img>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
Img(ImageData),
/// [`<details>`], a details disclosure element.
///
/// [`<details>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
Details,
/// [`<summary>`], a disclosure summary element.
///
/// [`<summary>`]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary
Summary,
/// [`mx-reply`], a Matrix rich reply fallback element.
///
/// [`mx-reply`]: https://spec.matrix.org/latest/client-server-api/#rich-replies
MatrixReply,
/// An HTML element that is not in the suggested list.
Other(QualName),
}
impl MatrixElement {
/// Parse a `MatrixElement` from the given qualified name and attributes.
///
/// Returns a tuple containing the constructed `Element` and the list of remaining unsupported
/// attributes.
#[allow(clippy::mutable_key_type)]
fn parse(name: &QualName, attrs: &BTreeSet<Attribute>) -> (Self, BTreeSet<Attribute>) {
if name.ns != ns!(html) {
return (Self::Other(name.clone()), attrs.clone());
}
match name.local.as_bytes() {
b"del" => (Self::Del, attrs.clone()),
b"h1" => (Self::H(HeadingData::new(1)), attrs.clone()),
b"h2" => (Self::H(HeadingData::new(2)), attrs.clone()),
b"h3" => (Self::H(HeadingData::new(3)), attrs.clone()),
b"h4" => (Self::H(HeadingData::new(4)), attrs.clone()),
b"h5" => (Self::H(HeadingData::new(5)), attrs.clone()),
b"h6" => (Self::H(HeadingData::new(6)), attrs.clone()),
b"blockquote" => (Self::Blockquote, attrs.clone()),
b"p" => (Self::P, attrs.clone()),
b"a" => {
let (data, attrs) = AnchorData::parse(attrs);
(Self::A(data), attrs)
}
b"ul" => (Self::Ul, attrs.clone()),
b"ol" => {
let (data, attrs) = OrderedListData::parse(attrs);
(Self::Ol(data), attrs)
}
b"sup" => (Self::Sup, attrs.clone()),
b"sub" => (Self::Sub, attrs.clone()),
b"li" => (Self::Li, attrs.clone()),
b"b" => (Self::B, attrs.clone()),
b"i" => (Self::I, attrs.clone()),
b"u" => (Self::U, attrs.clone()),
b"strong" => (Self::Strong, attrs.clone()),
b"em" => (Self::Em, attrs.clone()),
b"s" => (Self::S, attrs.clone()),
b"code" => {
let (data, attrs) = CodeData::parse(attrs);
(Self::Code(data), attrs)
}
b"hr" => (Self::Hr, attrs.clone()),
b"br" => (Self::Br, attrs.clone()),
b"div" => {
let (data, attrs) = DivData::parse(attrs);
(Self::Div(data), attrs)
}
b"table" => (Self::Table, attrs.clone()),
b"thead" => (Self::Thead, attrs.clone()),
b"tbody" => (Self::Tbody, attrs.clone()),
b"tr" => (Self::Tr, attrs.clone()),
b"th" => (Self::Th, attrs.clone()),
b"td" => (Self::Td, attrs.clone()),
b"caption" => (Self::Caption, attrs.clone()),
b"pre" => (Self::Pre, attrs.clone()),
b"span" => {
let (data, attrs) = SpanData::parse(attrs);
(Self::Span(data), attrs)
}
b"img" => {
let (data, attrs) = ImageData::parse(attrs);
(Self::Img(data), attrs)
}
b"details" => (Self::Details, attrs.clone()),
b"summary" => (Self::Summary, attrs.clone()),
b"mx-reply" => (Self::MatrixReply, attrs.clone()),
_ => (Self::Other(name.clone()), attrs.clone()),
}
}
}
/// The supported data of a `<h1>-<h6>` HTML element.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct HeadingData {
/// The level of the heading.
pub level: HeadingLevel,
}
impl HeadingData {
/// Constructs a new `HeadingData` with the given heading level.
fn new(level: u8) -> Self {
Self {
level: HeadingLevel(level),
}
}
}
/// The level of a heading element.
///
/// The supported levels range from 1 (highest) to 6 (lowest). Other levels cannot construct this
/// and do not use the [`MatrixElement::H`] variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeadingLevel(u8);
impl HeadingLevel {
/// The value of the level.
///
/// Can only be a value between 1 and 6 included.
pub fn value(&self) -> u8 {
self.0
}
}
impl PartialEq<u8> for HeadingLevel {
fn eq(&self, other: &u8) -> bool {
self.0.eq(other)
}
}
/// The supported data of a `<a>` HTML element.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AnchorData {
/// Where to display the linked URL.
pub target: Option<StrTendril>,
/// The URL that the hyperlink points to.
pub href: Option<AnchorUri>,
}
impl AnchorData {
/// Construct an empty `AnchorData`.
fn new() -> Self {
Self {
target: None,
href: None,
}
}
/// Parse the given attributes to construct a new `AnchorData`.
///
/// Returns a tuple containing the constructed data and the remaining unsupported attributes.
#[allow(clippy::mutable_key_type)]
fn parse(attrs: &BTreeSet<Attribute>) -> (Self, BTreeSet<Attribute>) {
let mut data = Self::new();
let mut remaining_attrs = BTreeSet::new();
for attr in attrs {
if attr.name.ns != ns!() {
remaining_attrs.insert(attr.clone());
continue;
}
match attr.name.local.as_bytes() {
b"target" => {
data.target = Some(attr.value.clone());
}
b"href" => {
if let Some(uri) = AnchorUri::parse(&attr.value) {
data.href = Some(uri);
} else {
remaining_attrs.insert(attr.clone());
}
}
_ => {
remaining_attrs.insert(attr.clone());
}
}
}
(data, remaining_attrs)
}
}
/// A URI as a value for the `href` attribute of a `<a>` HTML element.
///
/// This is a helper type that recognizes `matrix:` and `https://matrix.to` URIs to detect mentions.
///
/// If the URI is an invalid Matrix URI or does not use one of the suggested schemes, the `href`
/// attribute will be in the `attrs` list of [`MatrixElementData`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum AnchorUri {
/// A `matrix:` URI.
Matrix(MatrixUri),
/// A `https://matrix.to` URI.
MatrixTo(MatrixToUri),
/// An other URL using one of the suggested schemes.
///
/// Those schemes are:
///
/// * `https`
/// * `http`
/// * `ftp`
/// * `mailto`
/// * `magnet`
Other(StrTendril),
}
impl AnchorUri {
/// Parse the given string to construct a new `AnchorUri`.
fn parse(value: &StrTendril) -> Option<Self> {
let s = value.as_ref();
// Check if it starts with a supported scheme.
let mut allowed_schemes = ALLOWED_SCHEMES_A_HREF_STRICT
.iter()
.chain(ALLOWED_SCHEMES_A_HREF_COMPAT.iter());
if !allowed_schemes.any(|scheme| s.starts_with(&format!("{scheme}:"))) {
return None;
}
match MatrixUri::parse(s) {
Ok(uri) => return Some(Self::Matrix(uri)),
// It's not a `matrix:` URI, continue.
Err(IdParseError::InvalidMatrixUri(MatrixUriError::WrongScheme)) => {}
// The URI is invalid.
_ => return None,
}
match MatrixToUri::parse(s) {
Ok(uri) => return Some(Self::MatrixTo(uri)),
// It's not a `https://matrix.to` URI, continue.
Err(IdParseError::InvalidMatrixToUri(MatrixToError::WrongBaseUrl)) => {}
// The URI is invalid.
_ => return None,
}
Some(Self::Other(value.clone()))
}
}
/// The supported data of a `<ol>` HTML element.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OrderedListData {
/// An integer to start counting from for the list items.
///
/// If parsing the integer from a string fails, the attribute will be in the `attrs` list of
/// [`MatrixElementData`].
pub start: Option<i64>,
}
impl OrderedListData {
/// Construct an empty `OrderedListData`.
fn new() -> Self {
Self { start: None }
}
/// Parse the given attributes to construct a new `OrderedListData`.
///
/// Returns a tuple containing the constructed data and the remaining unsupported attributes.
#[allow(clippy::mutable_key_type)]
fn parse(attrs: &BTreeSet<Attribute>) -> (Self, BTreeSet<Attribute>) {
let mut data = Self::new();
let mut remaining_attrs = BTreeSet::new();
for attr in attrs {
if attr.name.ns != ns!() {
remaining_attrs.insert(attr.clone());
continue;
}
match attr.name.local.as_bytes() {
b"start" => {
if let Ok(start) = attr.value.parse() {
data.start = Some(start);
} else {
remaining_attrs.insert(attr.clone());
}
}
_ => {
remaining_attrs.insert(attr.clone());
}
}
}
(data, remaining_attrs)
}
}
/// The supported data of a `<code>` HTML element.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CodeData {
/// The language of the code, for syntax highlighting.
///
/// This corresponds to the `class` attribute with a value that starts with the
/// `language-` prefix. The prefix is stripped from the value.
///
/// If there are other classes in the `class` attribute, the whole attribute will be in the
/// `attrs` list of [`MatrixElementData`].
pub language: Option<StrTendril>,
}
impl CodeData {
/// Construct an empty `CodeData`.
fn new() -> Self {
Self { language: None }
}
/// Parse the given attributes to construct a new `CodeData`.
///
/// Returns a tuple containing the constructed data and the remaining unsupported attributes.
#[allow(clippy::mutable_key_type)]
fn parse(attrs: &BTreeSet<Attribute>) -> (Self, BTreeSet<Attribute>) {
let mut data = Self::new();
let mut remaining_attrs = BTreeSet::new();
for attr in attrs {
if attr.name.ns != ns!() {
remaining_attrs.insert(attr.clone());
continue;
}
match attr.name.local.as_bytes() {
b"class" => {
let value_str = attr.value.as_ref();
// The attribute could contain several classes separated by spaces, so let's
// find the first class starting with `language-`.
for (match_start, _) in value_str.match_indices(CLASS_LANGUAGE_PREFIX) {
// The class name must either be at the start of the string or preceded by a
// space.
if match_start != 0
&& !value_str.as_bytes()[match_start - 1].is_ascii_whitespace()
{
continue;
}
let language_start = match_start + CLASS_LANGUAGE_PREFIX.len();
let str_end = &value_str[language_start..];
let language_end = str_end
.find(|c: char| c.is_ascii_whitespace())
.map(|pos| language_start + pos)
.unwrap_or(value_str.len());
if language_end == language_start {
continue;
}
let sub_len = (language_end - language_start) as u32;
data.language = Some(attr.value.subtendril(language_start as u32, sub_len));
if match_start != 0 || language_end != value_str.len() {
// There are other classes, keep the whole attribute for the conversion
// to be lossless.
remaining_attrs.insert(attr.clone());
}
break;
}
if data.language.is_none() {
// We didn't find the class we want, keep the whole attribute.
remaining_attrs.insert(attr.clone());
}
}
_ => {
remaining_attrs.insert(attr.clone());
}
}
}
(data, remaining_attrs)
}
}
/// The supported data of a `<span>` HTML element.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SpanData {
/// `data-mx-bg-color`, the background color of the text.
pub bg_color: Option<StrTendril>,
/// `data-mx-color`, the foreground color of the text.
pub color: Option<StrTendril>,
/// `data-mx-spoiler`, a Matrix [spoiler message].
///
/// The value is the reason of the spoiler. If the string is empty, this is a spoiler
/// without a reason.
///
/// [spoiler message]: https://spec.matrix.org/latest/client-server-api/#spoiler-messages
pub spoiler: Option<StrTendril>,
/// `data-mx-maths`, an inline Matrix [mathematical message].
///
/// The value is the mathematical notation in [LaTeX] format.
///
/// If this attribute is present, the content of the span is the fallback representation of the
/// mathematical notation.
///
/// [mathematical message]: https://spec.matrix.org/latest/client-server-api/#mathematical-messages
/// [LaTeX]: https://www.latex-project.org/
pub maths: Option<StrTendril>,
}
impl SpanData {
/// Construct an empty `SpanData`.
fn new() -> Self {
Self {
bg_color: None,
color: None,
spoiler: None,
maths: None,
}
}
/// Parse the given attributes to construct a new `SpanData`.
///
/// Returns a tuple containing the constructed data and the remaining unsupported attributes.
#[allow(clippy::mutable_key_type)]
fn parse(attrs: &BTreeSet<Attribute>) -> (Self, BTreeSet<Attribute>) {
let mut data = Self::new();
let mut remaining_attrs = BTreeSet::new();
for attr in attrs {
if attr.name.ns != ns!() {
remaining_attrs.insert(attr.clone());
continue;
}
match attr.name.local.as_bytes() {
b"data-mx-bg-color" => {
data.bg_color = Some(attr.value.clone());
}
b"data-mx-color" => data.color = Some(attr.value.clone()),
b"data-mx-spoiler" => {
data.spoiler = Some(attr.value.clone());
}
b"data-mx-maths" => {
data.maths = Some(attr.value.clone());
}
_ => {
remaining_attrs.insert(attr.clone());
}
}
}
(data, remaining_attrs)
}
}
/// The supported data of a `<img>` HTML element.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ImageData {
/// The intrinsic width of the image, in pixels.
///
/// If parsing the integer from a string fails, the attribute will be in the `attrs` list of
/// `MatrixElementData`.
pub width: Option<i64>,
/// The intrinsic height of the image, in pixels.
///
/// If parsing the integer from a string fails, the attribute will be in the `attrs` list of
/// [`MatrixElementData`].
pub height: Option<i64>,
/// Text that can replace the image.
pub alt: Option<StrTendril>,
/// Text representing advisory information about the image.
pub title: Option<StrTendril>,
/// The image URL.
///
/// It this is not a valid `mxc:` URI, the attribute will be in the `attrs` list of
/// [`MatrixElementData`].
pub src: Option<OwnedMxcUri>,
}
impl ImageData {
/// Construct an empty `ImageData`.
fn new() -> Self {
Self {
width: None,
height: None,
alt: None,
title: None,
src: None,
}
}
/// Parse the given attributes to construct a new `ImageData`.
///
/// Returns a tuple containing the constructed data and the remaining unsupported attributes.
#[allow(clippy::mutable_key_type)]
fn parse(attrs: &BTreeSet<Attribute>) -> (Self, BTreeSet<Attribute>) {
let mut data = Self::new();
let mut remaining_attrs = BTreeSet::new();
for attr in attrs {
if attr.name.ns != ns!() {
remaining_attrs.insert(attr.clone());
continue;
}
match attr.name.local.as_bytes() {
b"width" => {
if let Ok(width) = attr.value.parse() {
data.width = Some(width);
} else {
remaining_attrs.insert(attr.clone());
}
}
b"height" => {
if let Ok(height) = attr.value.parse() {
data.height = Some(height);
} else {
remaining_attrs.insert(attr.clone());
}
}
b"alt" => data.alt = Some(attr.value.clone()),
b"title" => data.title = Some(attr.value.clone()),
b"src" => {
let uri = <&MxcUri>::from(attr.value.as_ref());
if uri.validate().is_ok() {
data.src = Some(uri.to_owned());
} else {
remaining_attrs.insert(attr.clone());
}
}
_ => {
remaining_attrs.insert(attr.clone());
}
}
}
(data, remaining_attrs)
}
}
/// The supported data of a `<div>` HTML element.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DivData {
/// `data-mx-maths`, a Matrix [mathematical message] block.
///
/// The value is the mathematical notation in [LaTeX] format.
///
/// If this attribute is present, the content of the div is the fallback representation of the
/// mathematical notation.
///
/// [mathematical message]: https://spec.matrix.org/latest/client-server-api/#mathematical-messages
/// [LaTeX]: https://www.latex-project.org/
pub maths: Option<StrTendril>,
}
impl DivData {
/// Construct an empty `DivData`.
fn new() -> Self {
Self { maths: None }
}
/// Parse the given attributes to construct a new `SpanData`.
///
/// Returns a tuple containing the constructed data and the remaining unsupported attributes.
#[allow(clippy::mutable_key_type)]
fn parse(attrs: &BTreeSet<Attribute>) -> (Self, BTreeSet<Attribute>) {
let mut data = Self::new();
let mut remaining_attrs = BTreeSet::new();
for attr in attrs {
if attr.name.ns != ns!() {
remaining_attrs.insert(attr.clone());
continue;
}
match attr.name.local.as_bytes() {
b"data-mx-maths" => {
data.maths = Some(attr.value.clone());
}
_ => {
remaining_attrs.insert(attr.clone());
}
}
}
(data, remaining_attrs)
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/html/sanitizer_config/clean.rs | crates/core/src/html/sanitizer_config/clean.rs | use html5ever::{Attribute, LocalName, tendril::StrTendril};
use phf::{Map, Set, phf_map, phf_set};
use wildmatch::WildMatch;
use crate::html::{ElementData, Html, HtmlSanitizerMode, NodeData, NodeRef, SanitizerConfig};
/// HTML elements allowed in the Matrix specification.
static ALLOWED_ELEMENTS_STRICT: Set<&str> = phf_set! {
"del", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "p", "a",
"ul", "ol", "sup", "sub", "li", "b", "i", "u", "strong", "em", "s",
"code", "hr", "br", "div", "table", "thead", "tbody", "tr", "th", "td",
"caption", "pre", "span", "img", "details", "summary", "mx-reply",
};
/// The HTML element name for a rich reply fallback.
const RICH_REPLY_ELEMENT_NAME: &str = "mx-reply";
/// HTML elements that were previously allowed in the Matrix specification, with their replacement.
static DEPRECATED_ELEMENTS: Map<&str, &str> = phf_map! {
"font" => "span",
"strike" => "s",
};
/// Allowed attributes per HTML element according to the Matrix specification.
static ALLOWED_ATTRIBUTES_STRICT: Map<&str, &Set<&str>> = phf_map! {
"span" => &ALLOWED_ATTRIBUTES_SPAN_STRICT,
"a" => &ALLOWED_ATTRIBUTES_A_STRICT,
"img" => &ALLOWED_ATTRIBUTES_IMG_STRICT,
"ol" => &ALLOWED_ATTRIBUTES_OL_STRICT,
"code" => &ALLOWED_ATTRIBUTES_CODE_STRICT,
"div" => &ALLOWED_ATTRIBUTES_DIV_STRICT,
};
static ALLOWED_ATTRIBUTES_SPAN_STRICT: Set<&str> =
phf_set! { "data-mx-bg-color", "data-mx-color", "data-mx-spoiler", "data-mx-maths" };
static ALLOWED_ATTRIBUTES_A_STRICT: Set<&str> = phf_set! { "target", "href" };
static ALLOWED_ATTRIBUTES_IMG_STRICT: Set<&str> =
phf_set! { "width", "height", "alt", "title", "src" };
static ALLOWED_ATTRIBUTES_OL_STRICT: Set<&str> = phf_set! { "start" };
static ALLOWED_ATTRIBUTES_CODE_STRICT: Set<&str> = phf_set! { "class" };
static ALLOWED_ATTRIBUTES_DIV_STRICT: Set<&str> = phf_set! { "data-mx-maths" };
/// Attributes that were previously allowed on HTML elements according to the Matrix specification,
/// with their replacement.
static DEPRECATED_ATTRS: Map<&str, &Map<&str, &str>> = phf_map! {
"font" => &DEPRECATED_ATTRIBUTES_FONT,
};
static DEPRECATED_ATTRIBUTES_FONT: Map<&str, &str> = phf_map! { "color" => "data-mx-color" };
/// Allowed schemes of URIs per attribute per HTML element according to the Matrix specification.
static ALLOWED_SCHEMES_STRICT: Map<&str, &Map<&str, &Set<&str>>> = phf_map! {
"a" => &ALLOWED_SCHEMES_A_STRICT,
"img" => &ALLOWED_SCHEMES_IMG_STRICT,
};
static ALLOWED_SCHEMES_A_STRICT: Map<&str, &Set<&str>> = phf_map! {
"href" => &ALLOWED_SCHEMES_A_HREF_STRICT,
};
pub(crate) static ALLOWED_SCHEMES_A_HREF_STRICT: Set<&str> =
phf_set! { "http", "https", "ftp", "mailto", "magnet" };
static ALLOWED_SCHEMES_IMG_STRICT: Map<&str, &Set<&str>> = phf_map! {
"src" => &ALLOWED_SCHEMES_IMG_SRC_STRICT,
};
static ALLOWED_SCHEMES_IMG_SRC_STRICT: Set<&str> = phf_set! { "mxc" };
/// Extra allowed schemes of URIs per attribute per HTML element.
///
/// This is a convenience list to add schemes that can be encountered but are not listed in the
/// Matrix specification. It consists of:
///
/// * The `matrix` scheme for `a` elements (see [matrix-org/matrix-spec#1108]).
///
/// To get a complete list, add these to `ALLOWED_SCHEMES_STRICT`.
///
/// [matrix-org/matrix-spec#1108]: https://github.com/matrix-org/matrix-spec/issues/1108
static ALLOWED_SCHEMES_COMPAT: Map<&str, &Map<&str, &Set<&str>>> = phf_map! {
"a" => &ALLOWED_SCHEMES_A_COMPAT,
};
static ALLOWED_SCHEMES_A_COMPAT: Map<&str, &Set<&str>> = phf_map! {
"href" => &ALLOWED_SCHEMES_A_HREF_COMPAT,
};
pub(crate) static ALLOWED_SCHEMES_A_HREF_COMPAT: Set<&str> = phf_set! { "matrix" };
/// Allowed classes per HTML element according to the Matrix specification.
static ALLOWED_CLASSES_STRICT: Map<&str, &Set<&str>> =
phf_map! { "code" => &ALLOWED_CLASSES_CODE_STRICT };
static ALLOWED_CLASSES_CODE_STRICT: Set<&str> = phf_set! { "language-*" };
/// Max depth of nested HTML elements allowed by the Matrix specification.
const MAX_DEPTH_STRICT: u32 = 100;
impl SanitizerConfig {
/// Whether the current mode uses the values of the strict mode.
fn use_strict(&self) -> bool {
self.mode.is_some()
}
/// Whether the current mode uses the values of the compat mode.
fn use_compat(&self) -> bool {
self.mode.is_some_and(|m| m == HtmlSanitizerMode::Compat)
}
/// The maximum nesting level allowed by the config.
fn max_depth_value(&self) -> Option<u32> {
self.max_depth
.or_else(|| self.use_strict().then_some(MAX_DEPTH_STRICT))
}
/// Clean the given HTML with this sanitizer.
pub(crate) fn clean(&self, html: &Html) {
for child in html.children() {
self.clean_node(child, 0);
}
}
fn clean_node(&self, node: NodeRef, depth: u32) {
let node = self.apply_replacements(node);
let action = self.node_action(&node, depth);
if action != NodeAction::Remove {
for child in node.children() {
if action == NodeAction::Ignore {
child.insert_before_sibling(&node);
}
self.clean_node(child, depth + 1);
}
}
if matches!(action, NodeAction::Ignore | NodeAction::Remove) {
node.detach();
} else if let Some(data) = node.as_element() {
self.clean_element_attributes(data);
}
}
/// Apply the attributes and element name replacements to the given node.
///
/// This might return a different node than the one provided.
fn apply_replacements(&self, node: NodeRef) -> NodeRef {
let mut element_replacement = None;
if let NodeData::Element(ElementData { name, attrs, .. }) = node.data() {
let element_name = name.local.as_ref();
// Replace attributes.
let list_replacements = self
.replace_attrs
.as_ref()
.and_then(|list| list.content.get(element_name));
let list_is_override = self
.replace_attrs
.as_ref()
.map(|list| list.is_override())
.unwrap_or_default();
let mode_replacements = (!list_is_override && self.use_strict())
.then(|| DEPRECATED_ATTRS.get(element_name))
.flatten();
if list_replacements.is_some() || mode_replacements.is_some() {
let mut attrs = attrs.borrow_mut();
*attrs = attrs
.clone()
.into_iter()
.map(|mut attr| {
let attr_name = attr.name.local.as_ref();
let attr_replacement = list_replacements
.and_then(|s| s.get(attr_name))
.or_else(|| mode_replacements.and_then(|s| s.get(attr_name)))
.copied();
if let Some(attr_replacement) = attr_replacement {
attr.name.local = LocalName::from(attr_replacement);
}
attr
})
.collect();
}
// Replace element.
element_replacement = self
.replace_elements
.as_ref()
.and_then(|list| list.content.get(element_name))
.copied();
if element_replacement.is_none() {
let list_is_override = self
.replace_elements
.as_ref()
.map(|list| list.is_override())
.unwrap_or_default();
element_replacement = (!list_is_override && self.use_strict())
.then(|| DEPRECATED_ELEMENTS.get(element_name))
.flatten()
.copied();
}
}
if let Some(element_replacement) = element_replacement {
node.replace_with_element_name(LocalName::from(element_replacement))
} else {
node
}
}
fn node_action(&self, node: &NodeRef, depth: u32) -> NodeAction {
match node.data() {
NodeData::Element(ElementData { name, attrs, .. }) => {
let element_name = name.local.as_ref();
let attrs = attrs.borrow();
// Check if element should be removed.
if self
.remove_elements
.as_ref()
.is_some_and(|set| set.contains(element_name))
{
return NodeAction::Remove;
}
if self.remove_reply_fallback && element_name == RICH_REPLY_ELEMENT_NAME {
return NodeAction::Remove;
}
if self.max_depth_value().is_some_and(|max| depth >= max) {
return NodeAction::Remove;
}
// Check if element should be ignored.
if self
.ignore_elements
.as_ref()
.is_some_and(|set| set.contains(element_name))
{
return NodeAction::Ignore;
}
// Check if element should be allowed.
if self.allow_elements.is_some() || self.use_strict() {
let list_allowed = self
.allow_elements
.as_ref()
.is_some_and(|list| list.content.contains(element_name));
let list_is_override = self
.allow_elements
.as_ref()
.map(|list| list.is_override())
.unwrap_or_default();
let mode_allowed = !list_is_override
&& self.use_strict()
&& ALLOWED_ELEMENTS_STRICT.contains(element_name);
if !list_allowed && !mode_allowed {
return NodeAction::Ignore;
}
}
// Check if element contains scheme that should be denied.
if let Some(deny_schemes) = self
.deny_schemes
.as_ref()
.and_then(|map| map.get(element_name))
{
for attr in attrs.iter() {
let value = &attr.value;
let attr_name = attr.name.local.as_ref();
if let Some(schemes) = deny_schemes.get(attr_name) {
// Check if the scheme is denied.
if schemes
.iter()
.any(|scheme| value.starts_with(&format!("{scheme}:")))
{
return NodeAction::Ignore;
}
}
}
}
if self.allow_schemes.is_none() && !self.use_strict() {
// All schemes are allowed.
return NodeAction::None;
}
// Check if element contains scheme that should be allowed.
let list_element_schemes = self
.allow_schemes
.as_ref()
.and_then(|list| list.content.get(element_name));
let list_is_override = self
.allow_schemes
.as_ref()
.map(|list| list.is_override())
.unwrap_or_default();
let strict_mode_element_schemes = (!list_is_override && self.use_strict())
.then(|| ALLOWED_SCHEMES_STRICT.get(element_name))
.flatten();
let compat_mode_element_schemes = (!list_is_override && self.use_compat())
.then(|| ALLOWED_SCHEMES_COMPAT.get(element_name))
.flatten();
if list_element_schemes.is_none()
&& strict_mode_element_schemes.is_none()
&& compat_mode_element_schemes.is_none()
{
// We don't check schemes for this element.
return NodeAction::None;
}
for attr in attrs.iter() {
let value = &attr.value;
let attr_name = attr.name.local.as_ref();
let list_attr_schemes = list_element_schemes.and_then(|map| map.get(attr_name));
let strict_mode_attr_schemes =
strict_mode_element_schemes.and_then(|map| map.get(attr_name));
let compat_mode_attr_schemes =
compat_mode_element_schemes.and_then(|map| map.get(attr_name));
if list_attr_schemes.is_none()
&& strict_mode_attr_schemes.is_none()
&& compat_mode_attr_schemes.is_none()
{
// We don't check schemes for this attribute.
return NodeAction::None;
}
let mut allowed_schemes = list_attr_schemes
.into_iter()
.flatten()
.chain(
strict_mode_attr_schemes
.map(|set| set.iter())
.into_iter()
.flatten(),
)
.chain(
compat_mode_attr_schemes
.map(|set| set.iter())
.into_iter()
.flatten(),
);
// Check if the scheme is allowed.
if !allowed_schemes.any(|scheme| value.starts_with(&format!("{scheme}:"))) {
return NodeAction::Ignore;
}
}
NodeAction::None
}
NodeData::Text(_) => NodeAction::None,
_ => NodeAction::Remove,
}
}
fn clean_element_attributes(&self, data: &ElementData) {
let ElementData { name, attrs } = data;
let element_name = name.local.as_ref();
let mut attrs = attrs.borrow_mut();
let list_remove_attrs = self
.remove_attrs
.as_ref()
.and_then(|map| map.get(element_name));
let whitelist_attrs = self.allow_attrs.is_some() || self.use_strict();
let list_allow_attrs = self
.allow_attrs
.as_ref()
.and_then(|list| list.content.get(element_name));
let list_is_override = self
.allow_attrs
.as_ref()
.map(|list| list.is_override())
.unwrap_or_default();
let mode_allow_attrs = (!list_is_override && self.use_strict())
.then(|| ALLOWED_ATTRIBUTES_STRICT.get(element_name))
.flatten();
let list_remove_classes = self
.remove_classes
.as_ref()
.and_then(|map| map.get(element_name));
let whitelist_classes = self.allow_classes.is_some() || self.use_strict();
let list_allow_classes = self
.allow_classes
.as_ref()
.and_then(|list| list.content.get(element_name));
let list_is_override = self
.allow_classes
.as_ref()
.map(|list| list.is_override())
.unwrap_or_default();
let mode_allow_classes = (!list_is_override && self.use_strict())
.then(|| ALLOWED_CLASSES_STRICT.get(element_name))
.flatten();
let actions: Vec<_> = attrs
.iter()
.filter_map(|attr| {
let value = &attr.value;
let attr_name = attr.name.local.as_ref();
// Check if the attribute should be removed.
if list_remove_attrs.is_some_and(|set| set.contains(attr_name)) {
return Some(AttributeAction::Remove(attr.to_owned()));
}
// Check if the attribute is allowed.
if whitelist_attrs {
let list_allowed = list_allow_attrs.is_some_and(|set| set.contains(attr_name));
let mode_allowed = mode_allow_attrs.is_some_and(|set| set.contains(attr_name));
if !list_allowed && !mode_allowed {
return Some(AttributeAction::Remove(attr.to_owned()));
}
}
// Filter classes.
if attr_name == "class" {
let mut classes = value.split_whitespace().collect::<Vec<_>>();
let initial_len = classes.len();
// Process classes to remove.
if let Some(remove_classes) = list_remove_classes {
classes.retain(|class| {
for remove_class in remove_classes {
if WildMatch::new(remove_class).matches(class) {
return false;
}
}
true
});
}
// Process classes to allow.
if whitelist_classes {
classes.retain(|class| {
let allow_classes = list_allow_classes
.map(|set| set.iter())
.into_iter()
.flatten()
.chain(
mode_allow_classes
.map(|set| set.iter())
.into_iter()
.flatten(),
);
for allow_class in allow_classes {
if WildMatch::new(allow_class).matches(class) {
return true;
}
}
false
});
}
if classes.len() == initial_len {
// The list has not changed, no action necessary.
return None;
}
if classes.is_empty() {
return Some(AttributeAction::Remove(attr.to_owned()));
} else {
let new_class = classes.join(" ");
return Some(AttributeAction::ReplaceValue(
attr.to_owned(),
new_class.into(),
));
}
}
None
})
.collect();
for action in actions {
match action {
AttributeAction::ReplaceValue(attr, value) => {
if let Some(mut attr) = attrs.take(&attr) {
attr.value = value;
attrs.insert(attr);
}
}
AttributeAction::Remove(attr) => {
attrs.remove(&attr);
}
}
}
}
}
/// The possible actions to apply to an element node.
#[derive(Debug, PartialEq, Eq)]
enum NodeAction {
/// Don't do anything.
None,
/// Remove the element but keep its children.
Ignore,
/// Remove the element and its children.
Remove,
}
/// The possible actions to apply to an attribute.
#[derive(Debug)]
enum AttributeAction {
/// Replace the value of the attribute.
ReplaceValue(Attribute, StrTendril),
/// Remove the attribute.
Remove(Attribute),
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/room_id.rs | crates/core/src/identifiers/room_id.rs | //! Matrix room identifiers.
use diesel::expression::AsExpression;
use super::{
MatrixToUri, MatrixUri, OwnedEventId, OwnedServerName, ServerName, matrix_uri::UriAction,
};
use crate::macros::IdDst;
use crate::{IdParseError, RoomOrAliasId};
/// A Matrix [room ID].
///
/// A `RoomId` is generated randomly or converted from a string slice, and can
/// be converted back into a string as needed.
///
/// ```
/// # use palpo_core::RoomId;
/// assert_eq!(<&RoomId>::try_from("!n8f893n9:example.com").unwrap(), "!n8f893n9:example.com");
/// ```
///
/// [room ID]: https://spec.matrix.org/latest/appendices/#room-ids
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
#[palpo_id(validate = palpo_identifiers_validation::room_id::validate)]
pub struct RoomId(str);
impl RoomId {
/// Attempts to generate a `RoomId` for the given origin server with a localpart consisting of
/// 18 random ASCII alphanumeric characters, as recommended in the spec.
///
/// This generates a room ID matching the [`RoomIdFormatVersion::V1`] variant of the
/// `room_id_format` field of [`RoomVersionRules`]. To construct a room ID matching the
/// [`RoomIdFormatVersion::V2`] variant, use [`RoomId::new_v2()`] instead.
///
/// [`RoomIdFormatVersion::V1`]: crate::room_version_rules::RoomIdFormatVersion::V1
/// [`RoomIdFormatVersion::V2`]: crate::room_version_rules::RoomIdFormatVersion::V2
/// [`RoomVersionRules`]: crate::room_version_rules::RoomVersionRules
pub fn new_v1(server_name: &ServerName) -> OwnedRoomId {
Self::from_borrowed(&format!("!{}:{server_name}", super::generate_localpart(18))).to_owned()
}
/// Construct an `OwnedRoomId` using the reference hash of the `m.room.create` event of the
/// room.
///
/// This generates a room ID matching the [`RoomIdFormatVersion::V2`] variant of the
/// `room_id_format` field of [`RoomVersionRules`]. To construct a room ID matching the
/// [`RoomIdFormatVersion::V1`] variant, use [`RoomId::new_v1()`] instead.
///
/// Returns an error if the given string contains a NUL byte or is too long.
///
/// [`RoomIdFormatVersion::V1`]: crate::room_version_rules::RoomIdFormatVersion::V1
/// [`RoomIdFormatVersion::V2`]: crate::room_version_rules::RoomIdFormatVersion::V2
/// [`RoomVersionRules`]: crate::room_version_rules::RoomVersionRules
pub fn new_v2(room_create_reference_hash: &str) -> Result<OwnedRoomId, IdParseError> {
Self::parse(format!("!{room_create_reference_hash}"))
}
/// Returns the room ID without the initial `!` sigil.
///
/// For room versions using [`RoomIdFormatVersion::V2`], this is the reference hash of the
/// `m.room.create` event of the room.
///
/// [`RoomIdFormatVersion::V2`]: crate::room_version_rules::RoomIdFormatVersion::V2
pub fn strip_sigil(&self) -> &str {
self.as_str()
.strip_prefix('!')
.expect("sigil should be checked during construction")
}
/// Returns the server name of the room ID.
pub fn server_name(&self) -> Result<&ServerName, &str> {
<&RoomOrAliasId>::from(self).server_name()
}
/// Create a `matrix.to` URI for this room ID.
///
/// Note that it is recommended to provide servers that should know the room
/// to be able to find it with its room ID. For that use
/// [`RoomId::matrix_to_uri_via()`].
///
/// # Example
///
/// ```
/// use palpo_core::{room_id, server_name};
///
/// assert_eq!(
/// room_id!("!somewhere:example.org").matrix_to_uri().to_string(),
/// "https://matrix.to/#/!somewhere:example.org"
/// );
/// ```
pub fn matrix_to_uri(&self) -> MatrixToUri {
MatrixToUri::new(self.into(), vec![])
}
/// Create a `matrix.to` URI for this room ID with a list of servers that
/// should know it.
///
/// To get the list of servers, it is recommended to use the [routing
/// algorithm] from the spec.
///
/// If you don't have a list of servers, you can use
/// [`RoomId::matrix_to_uri()`] instead.
///
/// # Example
///
/// ```
/// use palpo_core::{room_id, server_name};
///
/// assert_eq!(
/// room_id!("!somewhere:example.org")
/// .matrix_to_uri_via([&*server_name!("example.org"), &*server_name!("alt.example.org")])
/// .to_string(),
/// "https://matrix.to/#/!somewhere:example.org?via=example.org&via=alt.example.org"
/// );
/// ```
///
/// [routing algorithm]: https://spec.matrix.org/latest/appendices/#routing
pub fn matrix_to_uri_via<T>(&self, via: T) -> MatrixToUri
where
T: IntoIterator,
T::Item: Into<OwnedServerName>,
{
MatrixToUri::new(self.into(), via.into_iter().map(Into::into).collect())
}
/// Create a `matrix.to` URI for an event scoped under this room ID.
///
/// Note that it is recommended to provide servers that should know the room
/// to be able to find it with its room ID. For that use
/// [`RoomId::matrix_to_event_uri_via()`].
pub fn matrix_to_event_uri(&self, ev_id: impl Into<OwnedEventId>) -> MatrixToUri {
MatrixToUri::new((self.to_owned(), ev_id.into()).into(), vec![])
}
/// Create a `matrix.to` URI for an event scoped under this room ID with a
/// list of servers that should know it.
///
/// To get the list of servers, it is recommended to use the [routing
/// algorithm] from the spec.
///
/// If you don't have a list of servers, you can use
/// [`RoomId::matrix_to_event_uri()`] instead.
///
/// [routing algorithm]: https://spec.matrix.org/latest/appendices/#routing
pub fn matrix_to_event_uri_via<T>(&self, ev_id: impl Into<OwnedEventId>, via: T) -> MatrixToUri
where
T: IntoIterator,
T::Item: Into<OwnedServerName>,
{
MatrixToUri::new(
(self.to_owned(), ev_id.into()).into(),
via.into_iter().map(Into::into).collect(),
)
}
/// Create a `matrix:` URI for this room ID.
///
/// If `join` is `true`, a click on the URI should join the room.
///
/// Note that it is recommended to provide servers that should know the room
/// to be able to find it with its room ID. For that use
/// [`RoomId::matrix_uri_via()`].
///
/// # Example
///
/// ```
/// use palpo_core::{room_id, server_name};
///
/// assert_eq!(
/// room_id!("!somewhere:example.org").matrix_uri(false).to_string(),
/// "matrix:roomid/somewhere:example.org"
/// );
/// ```
pub fn matrix_uri(&self, join: bool) -> MatrixUri {
MatrixUri::new(self.into(), vec![], Some(UriAction::Join).filter(|_| join))
}
/// Create a `matrix:` URI for this room ID with a list of servers that
/// should know it.
///
/// To get the list of servers, it is recommended to use the [routing
/// algorithm] from the spec.
///
/// If you don't have a list of servers, you can use
/// [`RoomId::matrix_uri()`] instead.
///
/// If `join` is `true`, a click on the URI should join the room.
///
/// # Example
///
/// ```
/// use palpo_core::{room_id, server_name};
///
/// assert_eq!(
/// room_id!("!somewhere:example.org")
/// .matrix_uri_via(
/// [&*server_name!("example.org"), &*server_name!("alt.example.org")],
/// true
/// )
/// .to_string(),
/// "matrix:roomid/somewhere:example.org?via=example.org&via=alt.example.org&action=join"
/// );
/// ```
///
/// [routing algorithm]: https://spec.matrix.org/latest/appendices/#routing
pub fn matrix_uri_via<T>(&self, via: T, join: bool) -> MatrixUri
where
T: IntoIterator,
T::Item: Into<OwnedServerName>,
{
MatrixUri::new(
self.into(),
via.into_iter().map(Into::into).collect(),
Some(UriAction::Join).filter(|_| join),
)
}
/// Create a `matrix:` URI for an event scoped under this room ID.
///
/// Note that it is recommended to provide servers that should know the room
/// to be able to find it with its room ID. For that use
/// [`RoomId::matrix_event_uri_via()`].
pub fn matrix_event_uri(&self, ev_id: impl Into<OwnedEventId>) -> MatrixUri {
MatrixUri::new((self.to_owned(), ev_id.into()).into(), vec![], None)
}
/// Create a `matrix:` URI for an event scoped under this room ID with a
/// list of servers that should know it.
///
/// To get the list of servers, it is recommended to use the [routing
/// algorithm] from the spec.
///
/// If you don't have a list of servers, you can use
/// [`RoomId::matrix_event_uri()`] instead.
///
/// [routing algorithm]: https://spec.matrix.org/latest/appendices/#routing
pub fn matrix_event_uri_via<T>(&self, ev_id: impl Into<OwnedEventId>, via: T) -> MatrixUri
where
T: IntoIterator,
T::Item: Into<OwnedServerName>,
{
MatrixUri::new(
(self.to_owned(), ev_id.into()).into(),
via.into_iter().map(Into::into).collect(),
None,
)
}
}
// #[cfg(test)]
// mod tests {
// use super::{OwnedRoomId, RoomId};
// use crate::{server_name, IdParseError};
// #[test]
// fn valid_room_id() {
// let room_id =
// <&RoomId>::try_from("!29fhd83h92h0:example.com").expect("Failed to create
// RoomId."); assert_eq!(room_id, "!29fhd83h92h0:example.com");
// }
// #[test]
// fn empty_localpart() {
// let room_id = <&RoomId>::try_from("!:example.com").expect("Failed to
// create RoomId."); assert_eq!(room_id, "!:example.com");
// assert_eq!(room_id.server_name(), Some(server_name!("example.com")));
// }
// #[test]
// fn generate_random_valid_room_id() {
// let room_id = RoomId::new(server_name!("example.com"));
// let id_str = room_id.as_str();
// assert!(id_str.starts_with('!'));
// assert_eq!(id_str.len(), 31);
// }
// #[test]
// fn serialize_valid_room_id() {
// assert_eq!(
//
// serde_json::to_string(<&RoomId>::try_from("!29fhd83h92h0:example.com").
// expect("Failed to create RoomId.")) .expect("Failed to
// convert RoomId to JSON."), r#""!29fhd83h92h0:example.com""#
// );
// }
// #[test]
// fn deserialize_valid_room_id() {
// assert_eq!(
//
// serde_json::from_str::<OwnedRoomId>(r#""!29fhd83h92h0:example.com""#)
// .expect("Failed to convert JSON to RoomId"),
// <&RoomId>::try_from("!29fhd83h92h0:example.com").expect("Failed
// to create RoomId.") );
// }
// #[test]
// fn valid_room_id_with_explicit_standard_port() {
// let room_id =
// <&RoomId>::try_from("!29fhd83h92h0:example.com:443").expect("Failed to create
// RoomId."); assert_eq!(room_id, "!29fhd83h92h0:example.com:443");
// assert_eq!(room_id.server_name(),
// Some(server_name!("example.com:443"))); }
// #[test]
// fn valid_room_id_with_non_standard_port() {
// assert_eq!(
//
// <&RoomId>::try_from("!29fhd83h92h0:example.com:5000").expect("Failed to
// create RoomId."), "!29fhd83h92h0:example.com:5000"
// );
// }
// #[test]
// fn missing_room_id_sigil() {
// assert_eq!(
// <&RoomId>::try_from("carl:example.com").unwrap_err(),
// IdParseError::MissingLeadingSigil
// );
// }
// #[test]
// fn missing_server_name() {
// let room_id = <&RoomId>::try_from("!29fhd83h92h0").expect("Failed to
// create RoomId."); assert_eq!(room_id, "!29fhd83h92h0");
// assert_eq!(room_id.server_name(), None);
// }
// #[test]
// fn invalid_room_id_host() {
// let room_id = <&RoomId>::try_from("!29fhd83h92h0:/").expect("Failed
// to create RoomId."); assert_eq!(room_id, "!29fhd83h92h0:/");
// assert_eq!(room_id.server_name(), None);
// }
// #[test]
// fn invalid_room_id_port() {
// let room_id =
// <&RoomId>::try_from("!29fhd83h92h0:example.com:notaport").expect("Failed to
// create RoomId."); assert_eq!(room_id,
// "!29fhd83h92h0:example.com:notaport"); assert_eq!(room_id.
// server_name(), None); }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/matrix_uri.rs | crates/core/src/identifiers/matrix_uri.rs | //! Matrix URIs.
use std::{fmt, str::FromStr};
use palpo_identifiers_validation::{
Error,
error::{MatrixIdError, MatrixToError, MatrixUriError},
};
use percent_encoding::{percent_decode_str, percent_encode};
use url::Url;
use super::{
EventId, OwnedEventId, OwnedRoomAliasId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName,
OwnedUserId, RoomAliasId, RoomId, RoomOrAliasId, UserId,
};
use crate::{PrivOwnedStr, ServerName, percent_encode::PATH_PERCENT_ENCODE_SET};
const MATRIX_TO_BASE_URL: &str = "https://matrix.to/#/";
const MATRIX_SCHEME: &str = "matrix";
/// All Matrix Identifiers that can be represented as a Matrix URI.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MatrixId {
/// A room ID.
Room(OwnedRoomId),
/// A room alias.
RoomAlias(OwnedRoomAliasId),
/// A user ID.
User(OwnedUserId),
/// An event ID.
Event(OwnedRoomOrAliasId, OwnedEventId),
}
impl MatrixId {
/// Try parsing a `&str` with sigils into a `MatrixId`.
///
/// The identifiers are expected to start with a sigil and to be percent
/// encoded. Slashes at the beginning and the end are stripped.
///
/// For events, the room ID or alias and the event ID should be separated by
/// a slash and they can be in any order.
pub(crate) fn parse_with_sigil(s: &str) -> Result<Self, Error> {
let s = if let Some(stripped) = s.strip_prefix('/') {
stripped
} else {
s
};
let s = if let Some(stripped) = s.strip_suffix('/') {
stripped
} else {
s
};
if s.is_empty() {
return Err(MatrixIdError::NoIdentifier.into());
}
if s.matches('/').count() > 1 {
return Err(MatrixIdError::TooManyIdentifiers.into());
}
if let Some((first_raw, second_raw)) = s.split_once('/') {
let first = percent_decode_str(first_raw).decode_utf8()?;
let second = percent_decode_str(second_raw).decode_utf8()?;
match first.as_bytes()[0] {
b'!' | b'#' if second.as_bytes()[0] == b'$' => {
let room_id = <&RoomOrAliasId>::try_from(first.as_ref())?;
let event_id = <&EventId>::try_from(second.as_ref())?;
Ok((room_id, event_id).into())
}
b'$' if matches!(second.as_bytes()[0], b'!' | b'#') => {
let room_id = <&RoomOrAliasId>::try_from(second.as_ref())?;
let event_id = <&EventId>::try_from(first.as_ref())?;
Ok((room_id, event_id).into())
}
_ => Err(MatrixIdError::UnknownIdentifierPair.into()),
}
} else {
let id = percent_decode_str(s).decode_utf8()?;
match id.as_bytes()[0] {
b'@' => Ok(<&UserId>::try_from(id.as_ref())?.into()),
b'!' => Ok(<&RoomId>::try_from(id.as_ref())?.into()),
b'#' => Ok(<&RoomAliasId>::try_from(id.as_ref())?.into()),
b'$' => Err(MatrixIdError::MissingRoom.into()),
_ => Err(MatrixIdError::UnknownIdentifier.into()),
}
}
}
/// Try parsing a `&str` with types into a `MatrixId`.
///
/// The identifiers are expected to be in the format
/// `type/identifier_without_sigil` and the identifier part is expected to
/// be percent encoded. Slashes at the beginning and the end are stripped.
///
/// For events, the room ID or alias and the event ID should be separated by
/// a slash and they can be in any order.
pub(crate) fn parse_with_type(s: &str) -> Result<Self, Error> {
let s = if let Some(stripped) = s.strip_prefix('/') {
stripped
} else {
s
};
let s = if let Some(stripped) = s.strip_suffix('/') {
stripped
} else {
s
};
if s.is_empty() {
return Err(MatrixIdError::NoIdentifier.into());
}
if ![1, 3].contains(&s.matches('/').count()) {
return Err(MatrixIdError::InvalidPartsNumber.into());
}
let mut id = String::new();
let mut split = s.split('/');
while let (Some(type_), Some(id_without_sigil)) = (split.next(), split.next()) {
let sigil = match type_ {
"u" | "user" => '@',
"r" | "room" => '#',
"e" | "event" => '$',
"roomid" => '!',
_ => return Err(MatrixIdError::UnknownType.into()),
};
id = format!("{id}/{sigil}{id_without_sigil}");
}
Self::parse_with_sigil(&id)
}
/// Construct a string with sigils from `self`.
///
/// The identifiers will start with a sigil and be percent encoded.
///
/// For events, the room ID or alias and the event ID will be separated by
/// a slash.
pub(crate) fn to_string_with_sigil(&self) -> String {
match self {
Self::Room(room_id) => {
percent_encode(room_id.as_bytes(), PATH_PERCENT_ENCODE_SET).to_string()
}
Self::RoomAlias(room_alias) => {
percent_encode(room_alias.as_bytes(), PATH_PERCENT_ENCODE_SET).to_string()
}
Self::User(user_id) => {
percent_encode(user_id.as_bytes(), PATH_PERCENT_ENCODE_SET).to_string()
}
Self::Event(room_id, event_id) => format!(
"{}/{}",
percent_encode(room_id.as_bytes(), PATH_PERCENT_ENCODE_SET),
percent_encode(event_id.as_bytes(), PATH_PERCENT_ENCODE_SET),
),
}
}
/// Construct a string with types from `self`.
///
/// The identifiers will be in the format `type/identifier_without_sigil`
/// and the identifier part will be percent encoded.
///
/// For events, the room ID or alias and the event ID will be separated by
/// a slash.
pub(crate) fn to_string_with_type(&self) -> String {
match self {
Self::Room(room_id) => {
format!(
"roomid/{}",
percent_encode(&room_id.as_bytes()[1..], PATH_PERCENT_ENCODE_SET)
)
}
Self::RoomAlias(room_alias) => {
format!(
"r/{}",
percent_encode(&room_alias.as_bytes()[1..], PATH_PERCENT_ENCODE_SET)
)
}
Self::User(user_id) => {
format!(
"u/{}",
percent_encode(&user_id.as_bytes()[1..], PATH_PERCENT_ENCODE_SET)
)
}
Self::Event(room_id, event_id) => {
let room_type = if room_id.is_room_id() { "roomid" } else { "r" };
format!(
"{}/{}/e/{}",
room_type,
percent_encode(&room_id.as_bytes()[1..], PATH_PERCENT_ENCODE_SET),
percent_encode(&event_id.as_bytes()[1..], PATH_PERCENT_ENCODE_SET),
)
}
}
}
}
impl From<OwnedRoomId> for MatrixId {
fn from(room_id: OwnedRoomId) -> Self {
Self::Room(room_id)
}
}
impl From<&RoomId> for MatrixId {
fn from(room_id: &RoomId) -> Self {
room_id.to_owned().into()
}
}
impl From<OwnedRoomAliasId> for MatrixId {
fn from(room_alias: OwnedRoomAliasId) -> Self {
Self::RoomAlias(room_alias)
}
}
impl From<&RoomAliasId> for MatrixId {
fn from(room_alias: &RoomAliasId) -> Self {
room_alias.to_owned().into()
}
}
impl From<OwnedUserId> for MatrixId {
fn from(user_id: OwnedUserId) -> Self {
Self::User(user_id)
}
}
impl From<&UserId> for MatrixId {
fn from(user_id: &UserId) -> Self {
user_id.to_owned().into()
}
}
impl From<(OwnedRoomOrAliasId, OwnedEventId)> for MatrixId {
fn from(ids: (OwnedRoomOrAliasId, OwnedEventId)) -> Self {
Self::Event(ids.0, ids.1)
}
}
impl From<(&RoomOrAliasId, &EventId)> for MatrixId {
fn from(ids: (&RoomOrAliasId, &EventId)) -> Self {
(ids.0.to_owned(), ids.1.to_owned()).into()
}
}
impl From<(OwnedRoomId, OwnedEventId)> for MatrixId {
fn from(ids: (OwnedRoomId, OwnedEventId)) -> Self {
Self::Event(ids.0.into(), ids.1)
}
}
impl From<(&RoomId, &EventId)> for MatrixId {
fn from(ids: (&RoomId, &EventId)) -> Self {
(ids.0.to_owned(), ids.1.to_owned()).into()
}
}
impl From<(OwnedRoomAliasId, OwnedEventId)> for MatrixId {
fn from(ids: (OwnedRoomAliasId, OwnedEventId)) -> Self {
Self::Event(ids.0.into(), ids.1)
}
}
impl From<(&RoomAliasId, &EventId)> for MatrixId {
fn from(ids: (&RoomAliasId, &EventId)) -> Self {
(ids.0.to_owned(), ids.1.to_owned()).into()
}
}
/// The [`matrix.to` URI] representation of a user, room or event.
///
/// Get the URI through its `Display` implementation (i.e. by interpolating it
/// in a formatting macro or via `.to_string()`).
///
/// [`matrix.to` URI]: https://spec.matrix.org/latest/appendices/#matrixto-navigation
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct MatrixToUri {
id: MatrixId,
via: Vec<OwnedServerName>,
}
impl MatrixToUri {
pub(crate) fn new(id: MatrixId, via: Vec<OwnedServerName>) -> Self {
Self { id, via }
}
/// The identifier represented by this `matrix.to` URI.
pub fn id(&self) -> &MatrixId {
&self.id
}
/// Matrix servers usable to route a `RoomId`.
pub fn via(&self) -> &[OwnedServerName] {
&self.via
}
/// Try parsing a `&str` into a `MatrixToUri`.
pub fn parse(s: &str) -> Result<Self, Error> {
// We do not rely on parsing with `url::Url` because the meaningful part
// of the URI is in its fragment part.
//
// Even if the fragment part looks like parts of a URI, non-url-encoded
// room aliases (starting with `#`) could be detected as fragments,
// messing up the URI parsing.
//
// A matrix.to URI looks like this: https://matrix.to/#/{MatrixId}?{query};
// where the MatrixId should be percent-encoded, but might not, and the query
// should also be percent-encoded.
let s = s
.strip_prefix(MATRIX_TO_BASE_URL)
.ok_or(MatrixToError::WrongBaseUrl)?;
let s = s.strip_suffix('/').unwrap_or(s);
// Separate the identifiers and the query.
let mut parts = s.split('?');
let ids_part = parts
.next()
.expect("a split iterator yields at least one value");
let id = MatrixId::parse_with_sigil(ids_part)?;
// Parse the query for routing arguments.
let via = parts
.next()
.map(|query| {
// `form_urlencoded` takes care of percent-decoding the query.
let query_parts = form_urlencoded::parse(query.as_bytes());
query_parts
.map(|(key, value)| {
if key == "via" {
ServerName::parse(&value)
} else {
Err(MatrixToError::UnknownArgument.into())
}
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?
.unwrap_or_default();
// That would mean there are two `?` in the URL which is not valid.
if parts.next().is_some() {
return Err(MatrixToError::InvalidUrl.into());
}
Ok(Self { id, via })
}
}
impl fmt::Display for MatrixToUri {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(MATRIX_TO_BASE_URL)?;
write!(f, "{}", self.id().to_string_with_sigil())?;
let mut first = true;
for server_name in &self.via {
f.write_str(if first { "?via=" } else { "&via=" })?;
f.write_str(server_name.as_str())?;
first = false;
}
Ok(())
}
}
impl TryFrom<&str> for MatrixToUri {
type Error = Error;
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::parse(s)
}
}
impl FromStr for MatrixToUri {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
/// The intent of a Matrix URI.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum UriAction {
/// Join the room referenced by the URI.
///
/// The client should prompt for confirmation prior to joining the room, if
/// the user isn’t already part of the room.
Join,
/// Start a direct chat with the user referenced by the URI.
///
/// Clients supporting a form of Canonical DMs should reuse existing DMs
/// instead of creating new ones if available. The client should prompt for
/// confirmation prior to creating the DM, if the user isn’t being
/// redirected to an existing canonical DM.
Chat,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl UriAction {
/// Creates a string slice from this `UriAction`.
pub fn as_str(&self) -> &str {
self.as_ref()
}
fn from<T>(s: T) -> Self
where
T: AsRef<str> + Into<Box<str>>,
{
match s.as_ref() {
"join" => UriAction::Join,
"chat" => UriAction::Chat,
_ => UriAction::_Custom(PrivOwnedStr(s.into())),
}
}
}
impl AsRef<str> for UriAction {
fn as_ref(&self) -> &str {
match self {
UriAction::Join => "join",
UriAction::Chat => "chat",
UriAction::_Custom(s) => s.0.as_ref(),
}
}
}
impl fmt::Display for UriAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_ref())?;
Ok(())
}
}
impl From<&str> for UriAction {
fn from(s: &str) -> Self {
Self::from(s)
}
}
impl From<String> for UriAction {
fn from(s: String) -> Self {
Self::from(s)
}
}
impl From<Box<str>> for UriAction {
fn from(s: Box<str>) -> Self {
Self::from(s)
}
}
/// The [`matrix:` URI] representation of a user, room or event.
///
/// Get the URI through its `Display` implementation (i.e. by interpolating it
/// in a formatting macro or via `.to_string()`).
///
/// [`matrix:` URI]: https://spec.matrix.org/latest/appendices/#matrix-uri-scheme
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct MatrixUri {
id: MatrixId,
via: Vec<OwnedServerName>,
action: Option<UriAction>,
}
impl MatrixUri {
pub(crate) fn new(id: MatrixId, via: Vec<OwnedServerName>, action: Option<UriAction>) -> Self {
Self { id, via, action }
}
/// The identifier represented by this `matrix:` URI.
pub fn id(&self) -> &MatrixId {
&self.id
}
/// Matrix servers usable to route a `RoomId`.
pub fn via(&self) -> &[OwnedServerName] {
&self.via
}
/// The intent of this URI.
pub fn action(&self) -> Option<&UriAction> {
self.action.as_ref()
}
/// Try parsing a `&str` into a `MatrixUri`.
pub fn parse(s: &str) -> Result<Self, Error> {
let url = Url::parse(s).map_err(|_| MatrixToError::InvalidUrl)?;
if url.scheme() != MATRIX_SCHEME {
return Err(MatrixUriError::WrongScheme.into());
}
let id = MatrixId::parse_with_type(url.path())?;
let mut via = vec![];
let mut action = None;
for (key, value) in url.query_pairs() {
if key.as_ref() == "via" {
via.push(value.parse()?);
} else if key.as_ref() == "action" {
if action.is_some() {
return Err(MatrixUriError::TooManyActions.into());
};
action = Some(value.as_ref().into());
} else {
return Err(MatrixUriError::UnknownQueryItem.into());
}
}
Ok(Self { id, via, action })
}
}
impl fmt::Display for MatrixUri {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{MATRIX_SCHEME}:{}", self.id().to_string_with_type())?;
let mut first = true;
for server_name in &self.via {
f.write_str(if first { "?via=" } else { "&via=" })?;
f.write_str(server_name.as_str())?;
first = false;
}
if let Some(action) = self.action() {
f.write_str(if first { "?action=" } else { "&action=" })?;
f.write_str(action.as_str())?;
}
Ok(())
}
}
impl TryFrom<&str> for MatrixUri {
type Error = Error;
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::parse(s)
}
}
impl FromStr for MatrixUri {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use palpo_identifiers_validation::{
// error::{MatrixIdError, MatrixToError, MatrixUriError},
// Error,
// };
// use super::{MatrixId, MatrixToUri, MatrixUri};
// use crate::{event_id, matrix_uri::UriAction, room_alias_id, room_id,
// server_name, user_id, RoomOrAliasId};
// #[test]
// fn display_matrixtouri() {
// assert_eq!(
// user_id!("@jplatte:notareal.hs").matrix_to_uri().to_string(),
// "https://matrix.to/#/@jplatte:notareal.hs"
// );
// assert_eq!(
// room_alias_id!("#palpo:notareal.hs").matrix_to_uri().to_string(),
// "https://matrix.to/#/%23palpo:notareal.hs"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs").matrix_to_uri().to_string(),
// "https://matrix.to/#/!palpo:notareal.hs"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs")
// .matrix_to_uri_via(vec![server_name!("notareal.hs")])
// .to_string(),
// "https://matrix.to/#/!palpo:notareal.hs?via=notareal.hs"
// );
// assert_eq!(
// room_alias_id!("#palpo:notareal.hs")
// .matrix_to_event_uri(event_id!("$event:notareal.hs"))
// .to_string(),
// "https://matrix.to/#/%23palpo:notareal.hs/$event:notareal.hs"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs")
// .matrix_to_event_uri(event_id!("$event:notareal.hs"))
// .to_string(),
// "https://matrix.to/#/!palpo:notareal.hs/$event:notareal.hs"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs")
// .matrix_to_event_uri_via(event_id!("$event:notareal.hs"),
// vec![server_name!("notareal.hs")]) .to_string(),
// "https://matrix.to/#/!palpo:notareal.hs/$event:notareal.hs?via=notareal.hs"
// );
// }
// #[test]
// fn parse_valid_matrixid_with_sigil() {
// assert_eq!(
// MatrixId::parse_with_sigil("@user:imaginary.hs").expect("Failed
// to create MatrixId."),
// MatrixId::User(user_id!("@user:imaginary.hs").into()) );
// assert_eq!(
// MatrixId::parse_with_sigil("!roomid:imaginary.hs").expect("Failed
// to create MatrixId."),
// MatrixId::Room(room_id!("!roomid:imaginary.hs").into()) );
// assert_eq!(
//
// MatrixId::parse_with_sigil("#roomalias:imaginary.hs").expect("Failed to
// create MatrixId."),
// MatrixId::RoomAlias(room_alias_id!("#roomalias:imaginary.hs").into())
// );
// assert_eq!(
//
// MatrixId::parse_with_sigil("!roomid:imaginary.hs/$event:imaginary.hs").
// expect("Failed to create MatrixId."), MatrixId::Event(
//
// <&RoomOrAliasId>::from(room_id!("!roomid:imaginary.hs")).into(),
// event_id!("$event:imaginary.hs").into() )
// );
// assert_eq!(
//
// MatrixId::parse_with_sigil("#roomalias:imaginary.hs/$event:imaginary.hs")
// .expect("Failed to create MatrixId."),
// MatrixId::Event(
//
// <&RoomOrAliasId>::from(room_alias_id!("#roomalias:imaginary.hs")).into(),
// event_id!("$event:imaginary.hs").into()
// )
// );
// // Invert the order of the event and the room.
// assert_eq!(
//
// MatrixId::parse_with_sigil("$event:imaginary.hs/!roomid:imaginary.hs").
// expect("Failed to create MatrixId."), MatrixId::Event(
//
// <&RoomOrAliasId>::from(room_id!("!roomid:imaginary.hs")).into(),
// event_id!("$event:imaginary.hs").into() )
// );
// assert_eq!(
//
// MatrixId::parse_with_sigil("$event:imaginary.hs/#roomalias:imaginary.hs")
// .expect("Failed to create MatrixId."),
// MatrixId::Event(
//
// <&RoomOrAliasId>::from(room_alias_id!("#roomalias:imaginary.hs")).into(),
// event_id!("$event:imaginary.hs").into()
// )
// );
// // Starting with a slash
// assert_eq!(
// MatrixId::parse_with_sigil("/@user:imaginary.hs").expect("Failed
// to create MatrixId."),
// MatrixId::User(user_id!("@user:imaginary.hs").into()) );
// // Ending with a slash
// assert_eq!(
//
// MatrixId::parse_with_sigil("!roomid:imaginary.hs/").expect("Failed to create
// MatrixId."),
// MatrixId::Room(room_id!("!roomid:imaginary.hs").into()) );
// // Starting and ending with a slash
// assert_eq!(
//
// MatrixId::parse_with_sigil("/#roomalias:imaginary.hs/").expect("Failed to
// create MatrixId."),
// MatrixId::RoomAlias(room_alias_id!("#roomalias:imaginary.hs").into())
// );
// }
// #[test]
// fn parse_matrixid_no_identifier() {
// assert_eq!(
// MatrixId::parse_with_sigil("").unwrap_err(),
// MatrixIdError::NoIdentifier.into()
// );
// assert_eq!(
// MatrixId::parse_with_sigil("/").unwrap_err(),
// MatrixIdError::NoIdentifier.into()
// );
// }
// #[test]
// fn parse_matrixid_too_many_identifiers() {
// assert_eq!(
//
// MatrixId::parse_with_sigil("@user:imaginary.hs/#room:imaginary.hs/$event1:
// imaginary.hs").unwrap_err(),
// MatrixIdError::TooManyIdentifiers.into() );
// }
// #[test]
// fn parse_matrixid_unknown_identifier_pair() {
// assert_eq!(
//
// MatrixId::parse_with_sigil("!roomid:imaginary.hs/@user:imaginary.hs").
// unwrap_err(), MatrixIdError::UnknownIdentifierPair.into()
// );
// assert_eq!(
//
// MatrixId::parse_with_sigil("#roomalias:imaginary.hs/notanidentifier").
// unwrap_err(), MatrixIdError::UnknownIdentifierPair.into()
// );
// assert_eq!(
//
// MatrixId::parse_with_sigil("$event:imaginary.hs/$otherevent:imaginary.hs").
// unwrap_err(), MatrixIdError::UnknownIdentifierPair.into()
// );
// assert_eq!(
//
// MatrixId::parse_with_sigil("notanidentifier/neitheristhis").unwrap_err(),
// MatrixIdError::UnknownIdentifierPair.into()
// );
// }
// #[test]
// fn parse_matrixid_missing_room() {
// assert_eq!(
// MatrixId::parse_with_sigil("$event:imaginary.hs").unwrap_err(),
// MatrixIdError::MissingRoom.into()
// );
// }
// #[test]
// fn parse_matrixid_unknown_identifier() {
// assert_eq!(
// MatrixId::parse_with_sigil("event:imaginary.hs").unwrap_err(),
// MatrixIdError::UnknownIdentifier.into()
// );
// assert_eq!(
// MatrixId::parse_with_sigil("notanidentifier").unwrap_err(),
// MatrixIdError::UnknownIdentifier.into()
// );
// }
// #[test]
// fn parse_matrixtouri_valid_uris() {
// let matrix_to =
// MatrixToUri::parse("https://matrix.to/#/%40jplatte%3Anotareal.hs").expect("Failed to create MatrixToUri.");
// assert_eq!(matrix_to.id(), &user_id!("@jplatte:notareal.hs").into());
// let matrix_to =
// MatrixToUri::parse("https://matrix.to/#/%23palpo%3Anotareal.hs").expect("Failed to create MatrixToUri.");
// assert_eq!(matrix_to.id(),
// &room_alias_id!("#palpo:notareal.hs").into());
// let matrix_to =
// MatrixToUri::parse("https://matrix.to/#/%21palpo%3Anotareal.hs?via=notareal.hs&via=anotherunreal.hs")
// .expect("Failed to create MatrixToUri.");
// assert_eq!(matrix_to.id(), &room_id!("!palpo:notareal.hs").into());
// assert_eq!(
// matrix_to.via(),
// &[
// server_name!("notareal.hs").to_owned(),
// server_name!("anotherunreal.hs").to_owned(),
// ]
// );
// let matrix_to = MatrixToUri::parse("https://matrix.to/#/%23palpo%3Anotareal.hs/%24event%3Anotareal.hs")
// .expect("Failed to create MatrixToUri.");
// assert_eq!(
// matrix_to.id(),
// &(room_alias_id!("#palpo:notareal.hs"),
// event_id!("$event:notareal.hs")).into() );
// let matrix_to = MatrixToUri::parse("https://matrix.to/#/%21palpo%3Anotareal.hs/%24event%3Anotareal.hs")
// .expect("Failed to create MatrixToUri.");
// assert_eq!(
// matrix_to.id(),
// &(room_id!("!palpo:notareal.hs"),
// event_id!("$event:notareal.hs")).into() );
// assert_eq!(matrix_to.via().len(), 0);
// }
// #[test]
// fn parse_matrixtouri_valid_uris_not_urlencoded() {
// let matrix_to =
// MatrixToUri::parse("https://matrix.to/#/@jplatte:notareal.hs").expect("Failed to create MatrixToUri.");
// assert_eq!(matrix_to.id(), &user_id!("@jplatte:notareal.hs").into());
// let matrix_to =
// MatrixToUri::parse("https://matrix.to/#/#palpo:notareal.hs").expect("Failed to create MatrixToUri.");
// assert_eq!(matrix_to.id(),
// &room_alias_id!("#palpo:notareal.hs").into());
// let matrix_to = MatrixToUri::parse("https://matrix.to/#/!palpo:notareal.hs?via=notareal.hs")
// .expect("Failed to create MatrixToUri.");
// assert_eq!(matrix_to.id(), &room_id!("!palpo:notareal.hs").into());
// assert_eq!(matrix_to.via(),
// &[server_name!("notareal.hs").to_owned()]);
// let matrix_to = MatrixToUri::parse("https://matrix.to/#/#palpo:notareal.hs/$event:notareal.hs")
// .expect("Failed to create MatrixToUri.");
// assert_eq!(
// matrix_to.id(),
// &(room_alias_id!("#palpo:notareal.hs"),
// event_id!("$event:notareal.hs")).into() );
// let matrix_to = MatrixToUri::parse("https://matrix.to/#/!palpo:notareal.hs/$event:notareal.hs")
// .expect("Failed to create MatrixToUri.");
// assert_eq!(
// matrix_to.id(),
// &(room_id!("!palpo:notareal.hs"),
// event_id!("$event:notareal.hs")).into() );
// assert_eq!(matrix_to.via().len(), 0);
// }
// #[test]
// fn parse_matrixtouri_wrong_base_url() {
// assert_eq!(MatrixToUri::parse("").unwrap_err(),
// MatrixToError::WrongBaseUrl.into()); assert_eq!(
// MatrixToUri::parse("https://notreal.to/#/").unwrap_err(),
// MatrixToError::WrongBaseUrl.into()
// );
// }
// #[test]
// fn parse_matrixtouri_wrong_identifier() {
// assert_matches!(
// MatrixToUri::parse("https://matrix.to/#/notanidentifier").unwrap_err(),
// Error::InvalidMatrixId(_)
// );
// assert_matches!(
// MatrixToUri::parse("https://matrix.to/#/").unwrap_err(),
// Error::InvalidMatrixId(_)
// );
// assert_matches!(
// MatrixToUri::parse("https://matrix.to/#/%40jplatte%3Anotareal.hs/%24event%3Anotareal.hs").unwrap_err(),
// Error::InvalidMatrixId(_)
// );
// }
// #[test]
// fn parse_matrixtouri_unknown_arguments() {
// assert_eq!(
// MatrixToUri::parse("https://matrix.to/#/%21palpo%3Anotareal.hs?via=notareal.hs&custom=data").unwrap_err(),
// MatrixToError::UnknownArgument.into()
// );
// }
// #[test]
// fn display_matrixuri() {
// assert_eq!(
// user_id!("@jplatte:notareal.hs").matrix_uri(false).to_string(),
// "matrix:u/jplatte:notareal.hs"
// );
// assert_eq!(
// user_id!("@jplatte:notareal.hs").matrix_uri(true).to_string(),
// "matrix:u/jplatte:notareal.hs?action=chat"
// );
// assert_eq!(
//
// room_alias_id!("#palpo:notareal.hs").matrix_uri(false).to_string(),
// "matrix:r/palpo:notareal.hs"
// );
// assert_eq!(
//
// room_alias_id!("#palpo:notareal.hs").matrix_uri(true).to_string(),
// "matrix:r/palpo:notareal.hs?action=join"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs").matrix_uri(false).to_string(),
// "matrix:roomid/palpo:notareal.hs"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs")
// .matrix_uri_via(vec![server_name!("notareal.hs")], false)
// .to_string(),
// "matrix:roomid/palpo:notareal.hs?via=notareal.hs"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs")
// .matrix_uri_via(
// vec![server_name!("notareal.hs"),
// server_name!("anotherunreal.hs")], true
// )
// .to_string(),
//
// "matrix:roomid/palpo:notareal.hs?via=notareal.hs&via=anotherunreal.hs&
// action=join" );
// assert_eq!(
// room_alias_id!("#palpo:notareal.hs")
// .matrix_event_uri(event_id!("$event:notareal.hs"))
// .to_string(),
// "matrix:r/palpo:notareal.hs/e/event:notareal.hs"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs")
// .matrix_event_uri(event_id!("$event:notareal.hs"))
// .to_string(),
// "matrix:roomid/palpo:notareal.hs/e/event:notareal.hs"
// );
// assert_eq!(
// room_id!("!palpo:notareal.hs")
// .matrix_event_uri_via(event_id!("$event:notareal.hs"),
// vec![server_name!("notareal.hs")]) .to_string(),
//
// "matrix:roomid/palpo:notareal.hs/e/event:notareal.hs?via=notareal.hs"
// );
// }
// #[test]
// fn parse_valid_matrixid_with_type() {
// assert_eq!(
// MatrixId::parse_with_type("u/user:imaginary.hs").expect("Failed
// to create MatrixId."),
// MatrixId::User(user_id!("@user:imaginary.hs").into()) );
// assert_eq!(
//
// MatrixId::parse_with_type("user/user:imaginary.hs").expect("Failed to create
// MatrixId."),
// MatrixId::User(user_id!("@user:imaginary.hs").into()) );
// assert_eq!(
//
// MatrixId::parse_with_type("roomid/roomid:imaginary.hs").expect("Failed to
// create MatrixId."),
// MatrixId::Room(room_id!("!roomid:imaginary.hs").into()) );
// assert_eq!(
//
// MatrixId::parse_with_type("r/roomalias:imaginary.hs").expect("Failed to
// create MatrixId."),
// MatrixId::RoomAlias(room_alias_id!("#roomalias:imaginary.hs").into())
// );
// assert_eq!(
//
// MatrixId::parse_with_type("room/roomalias:imaginary.hs").expect("Failed to
// create MatrixId."),
// MatrixId::RoomAlias(room_alias_id!("#roomalias:imaginary.hs").into())
// );
// assert_eq!(
//
// MatrixId::parse_with_type("roomid/roomid:imaginary.hs/e/event:imaginary.hs")
// .expect("Failed to create MatrixId."),
// MatrixId::Event(
//
// <&RoomOrAliasId>::from(room_id!("!roomid:imaginary.hs")).into(),
// event_id!("$event:imaginary.hs").into() )
// );
// assert_eq!(
//
// MatrixId::parse_with_type("r/roomalias:imaginary.hs/e/event:imaginary.hs")
// .expect("Failed to create MatrixId."),
// MatrixId::Event(
//
// <&RoomOrAliasId>::from(room_alias_id!("#roomalias:imaginary.hs")).into(),
// event_id!("$event:imaginary.hs").into()
// )
// );
// assert_eq!(
//
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | true |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/user_id.rs | crates/core/src/identifiers/user_id.rs | //! Matrix user identifiers.
use std::{rc::Rc, sync::Arc};
use diesel::expression::AsExpression;
use palpo_identifiers_validation::MAX_BYTES;
pub use palpo_identifiers_validation::user_id::localpart_is_fully_conforming;
use super::{IdParseError, MatrixToUri, MatrixUri, ServerName, matrix_uri::UriAction};
use crate::macros::IdDst;
/// A Matrix [user ID].
///
/// A `UserId` is generated randomly or converted from a string slice, and can
/// be converted back into a string as needed.
///
/// ```
/// # use palpo_core::UserId;
/// assert_eq!(<&UserId>::try_from("@carl:example.com").unwrap(), "@carl:example.com");
/// ```
///
/// [user ID]: https://spec.matrix.org/latest/appendices/#user-identifiers
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
#[palpo_id(validate = palpo_identifiers_validation::user_id::validate)]
pub struct UserId(str);
impl UserId {
/// Attempts to generate a `UserId` for the given origin server with a
/// localpart consisting of 12 random ASCII characters.
#[allow(clippy::new_ret_no_self)]
pub fn new(server_name: &ServerName) -> OwnedUserId {
Self::from_borrowed(&format!(
"@{}:{}",
super::generate_localpart(12).to_lowercase(),
server_name
))
.to_owned()
}
/// Attempts to complete a user ID, by adding the colon + server name and
/// `@` prefix, if not present already.
///
/// This is a convenience function for the login API, where a user can
/// supply either their full user ID or just the localpart. It only
/// supports a valid user ID or a valid user ID localpart, not the
/// localpart plus the `@` prefix, or the localpart plus server name without
/// the `@` prefix.
pub fn parse_with_server_name(
id: impl AsRef<str> + Into<Box<str>>,
server_name: &ServerName,
) -> Result<OwnedUserId, IdParseError> {
let id_str = id.as_ref();
if id_str.starts_with('@') {
Self::parse(id)
} else {
let _ = localpart_is_fully_conforming(id_str)?;
Ok(Self::from_borrowed(&format!("@{id_str}:{server_name}")).to_owned())
}
}
/// Variation of [`parse_with_server_name`] that returns `Rc<Self>`.
///
/// [`parse_with_server_name`]: Self::parse_with_server_name
pub fn parse_with_server_name_rc(
id: impl AsRef<str> + Into<Rc<str>>,
server_name: &ServerName,
) -> Result<Rc<Self>, IdParseError> {
let id_str = id.as_ref();
if id_str.starts_with('@') {
Self::parse_rc(id)
} else {
let _ = localpart_is_fully_conforming(id_str)?;
Ok(Self::from_rc(format!("@{id_str}:{server_name}").into()))
}
}
/// Variation of [`parse_with_server_name`] that returns `Arc<Self>`.
///
/// [`parse_with_server_name`]: Self::parse_with_server_name
pub fn parse_with_server_name_arc(
id: impl AsRef<str> + Into<Arc<str>>,
server_name: &ServerName,
) -> Result<Arc<Self>, IdParseError> {
let id_str = id.as_ref();
if id_str.starts_with('@') {
Self::parse_arc(id)
} else {
let _ = localpart_is_fully_conforming(id_str)?;
Ok(Self::from_arc(format!("@{id_str}:{server_name}").into()))
}
}
/// Returns the user's localpart.
pub fn localpart(&self) -> &str {
&self.as_str()[1..self.colon_idx()]
}
/// Returns the server name of the user ID.
pub fn server_name(&self) -> &ServerName {
ServerName::from_borrowed(&self.as_str()[self.colon_idx() + 1..])
}
/// Validate this user ID against the strict or historical grammar.
///
/// Returns an `Err` for invalid user IDs, `Ok(false)` for historical user IDs
/// and `Ok(true)` for fully conforming user IDs.
fn validate_fully_conforming(&self) -> Result<bool, IdParseError> {
// Since the length check can be disabled with `compat-arbitrary-length-ids`, check it again
// here.
if self.as_bytes().len() > MAX_BYTES {
return Err(IdParseError::MaximumLengthExceeded);
}
localpart_is_fully_conforming(self.localpart())
}
/// Validate this user ID against the [strict grammar].
///
/// This should be used to validate newly created user IDs as historical user IDs are
/// deprecated.
///
/// [strict grammar]: https://spec.matrix.org/latest/appendices/#user-identifiers
pub fn validate_strict(&self) -> Result<(), IdParseError> {
let is_fully_conforming = self.validate_fully_conforming()?;
if is_fully_conforming {
Ok(())
} else {
Err(IdParseError::InvalidCharacters)
}
}
/// Validate this user ID against the [historical grammar].
///
/// According to the spec, servers should check events received over federation that contain
/// user IDs with this method, and those that fail should not be forwarded to their users.
///
/// Contrary to [`UserId::is_historical()`] this method also includes user IDs that conform to
/// the latest grammar.
///
/// [historical grammar]: https://spec.matrix.org/latest/appendices/#historical-user-ids
pub fn validate_historical(&self) -> Result<(), IdParseError> {
self.validate_fully_conforming()?;
Ok(())
}
/// Whether this user ID is a historical one.
///
/// A historical user ID is one that doesn't conform to the latest
/// specification of the user ID grammar but is still accepted because
/// it was previously allowed.
pub fn is_historical(&self) -> bool {
!localpart_is_fully_conforming(self.localpart()).unwrap()
}
/// Create a `matrix.to` URI for this user ID.
///
/// # Example
///
/// ```
/// use palpo_core::user_id;
///
/// let message = format!(
/// r#"Thanks for the update <a href="{link}">{display_name}</a>."#,
/// link = user_id!("@jplatte:notareal.hs").matrix_to_uri(),
/// display_name = "jplatte",
/// );
/// ```
pub fn matrix_to_uri(&self) -> MatrixToUri {
MatrixToUri::new(self.into(), Vec::new())
}
/// Create a `matrix:` URI for this user ID.
///
/// If `chat` is `true`, a click on the URI should start a direct message
/// with the user.
///
/// # Example
///
/// ```
/// use palpo_core::user_id;
///
/// let message = format!(
/// r#"Thanks for the update <a href="{link}">{display_name}</a>."#,
/// link = user_id!("@jplatte:notareal.hs").matrix_uri(false),
/// display_name = "jplatte",
/// );
/// ```
pub fn matrix_uri(&self, chat: bool) -> MatrixUri {
MatrixUri::new(
self.into(),
Vec::new(),
Some(UriAction::Chat).filter(|_| chat),
)
}
fn colon_idx(&self) -> usize {
self.as_str().find(':').unwrap()
}
}
#[cfg(test)]
mod tests {
use super::{OwnedUserId, UserId};
use crate::{IdParseError, server_name};
#[test]
fn valid_user_id_from_str() {
let user_id = <&UserId>::try_from("@carl:example.com").expect("Failed to create UserId.");
assert_eq!(user_id.as_str(), "@carl:example.com");
assert_eq!(user_id.localpart(), "carl");
assert_eq!(user_id.server_name(), "example.com");
assert!(!user_id.is_historical());
}
#[test]
fn parse_valid_user_id() {
let server_name = server_name!("example.com");
let user_id = UserId::parse_with_server_name("@carl:example.com", server_name)
.expect("Failed to create UserId.");
assert_eq!(user_id.as_str(), "@carl:example.com");
assert_eq!(user_id.localpart(), "carl");
assert_eq!(user_id.server_name(), "example.com");
assert!(!user_id.is_historical());
}
#[test]
fn parse_valid_user_id_parts() {
let server_name = server_name!("example.com");
let user_id =
UserId::parse_with_server_name("carl", server_name).expect("Failed to create UserId.");
assert_eq!(user_id.as_str(), "@carl:example.com");
assert_eq!(user_id.localpart(), "carl");
assert_eq!(user_id.server_name(), "example.com");
assert!(!user_id.is_historical());
}
// #[cfg(not(feature = "compat-user-id"))]
// #[test]
// fn invalid_user_id() {
// let localpart = "τ";
// let user_id = "@τ:example.com";
// let server_name = server_name!("example.com");
// <&UserId>::try_from(user_id).unwrap_err();
// UserId::parse_with_server_name(user_id, server_name).unwrap_err();
// UserId::parse_with_server_name(localpart, server_name).unwrap_err();
// UserId::parse_with_server_name_rc(user_id, server_name).unwrap_err();
// UserId::parse_with_server_name_rc(localpart, server_name).unwrap_err();
// UserId::parse_with_server_name_arc(user_id, server_name).unwrap_err();
// UserId::parse_with_server_name_arc(localpart, server_name).unwrap_err();
// UserId::parse_rc(user_id).unwrap_err();
// UserId::parse_arc(user_id).unwrap_err();
// }
#[test]
fn definitely_invalid_user_id() {
UserId::parse_with_server_name("a:b", server_name!("example.com")).unwrap_err();
}
#[test]
fn valid_historical_user_id() {
let user_id =
<&UserId>::try_from("@a%b[irc]:example.com").expect("Failed to create UserId.");
assert_eq!(user_id.as_str(), "@a%b[irc]:example.com");
assert_eq!(user_id.localpart(), "a%b[irc]");
assert_eq!(user_id.server_name(), "example.com");
assert!(user_id.is_historical());
}
#[test]
fn parse_valid_historical_user_id() {
let server_name = server_name!("example.com");
let user_id = UserId::parse_with_server_name("@a%b[irc]:example.com", server_name)
.expect("Failed to create UserId.");
assert_eq!(user_id.as_str(), "@a%b[irc]:example.com");
assert_eq!(user_id.localpart(), "a%b[irc]");
assert_eq!(user_id.server_name(), "example.com");
assert!(user_id.is_historical());
}
#[test]
fn parse_valid_historical_user_id_parts() {
let server_name = server_name!("example.com");
let user_id = UserId::parse_with_server_name("a%b[irc]", server_name)
.expect("Failed to create UserId.");
assert_eq!(user_id.as_str(), "@a%b[irc]:example.com");
assert_eq!(user_id.localpart(), "a%b[irc]");
assert_eq!(user_id.server_name(), "example.com");
assert!(user_id.is_historical());
}
#[test]
fn uppercase_user_id() {
let user_id = <&UserId>::try_from("@CARL:example.com").expect("Failed to create UserId.");
assert_eq!(user_id.as_str(), "@CARL:example.com");
assert!(user_id.is_historical());
}
#[test]
fn generate_random_valid_user_id() {
let server_name = server_name!("example.com");
let user_id = UserId::new(server_name);
assert_eq!(user_id.localpart().len(), 12);
assert_eq!(user_id.server_name(), "example.com");
let id_str = user_id.as_str();
assert!(id_str.starts_with('@'));
assert_eq!(id_str.len(), 25);
}
#[test]
fn serialize_valid_user_id() {
assert_eq!(
serde_json::to_string(
<&UserId>::try_from("@carl:example.com").expect("Failed to create UserId.")
)
.expect("Failed to convert UserId to JSON."),
r#""@carl:example.com""#
);
}
#[test]
fn deserialize_valid_user_id() {
assert_eq!(
serde_json::from_str::<OwnedUserId>(r#""@carl:example.com""#)
.expect("Failed to convert JSON to UserId"),
<&UserId>::try_from("@carl:example.com").expect("Failed to create UserId.")
);
}
#[test]
fn valid_user_id_with_explicit_standard_port() {
assert_eq!(
<&UserId>::try_from("@carl:example.com:443")
.expect("Failed to create UserId.")
.as_str(),
"@carl:example.com:443"
);
assert_eq!(
<&UserId>::try_from("@carl:127.0.0.1:443")
.expect("Failed to create UserId.")
.as_str(),
"@carl:127.0.0.1:443"
);
}
#[test]
fn valid_user_id_with_non_standard_port() {
let user_id =
<&UserId>::try_from("@carl:example.com:5000").expect("Failed to create UserId.");
assert_eq!(user_id.as_str(), "@carl:example.com:5000");
assert!(!user_id.is_historical());
}
// #[test]
// #[cfg(not(feature = "compat-user-id"))]
// fn invalid_characters_in_user_id_localpart() {
// assert_eq!(
// <&UserId>::try_from("@te\nst:example.com").unwrap_err(),
// IdParseError::InvalidCharacters
// );
// }
#[test]
fn missing_user_id_sigil() {
assert_eq!(
<&UserId>::try_from("carl:example.com").unwrap_err(),
IdParseError::MissingLeadingSigil
);
}
#[test]
fn missing_user_id_delimiter() {
assert_eq!(
<&UserId>::try_from("@carl").unwrap_err(),
IdParseError::MissingColon
);
}
#[test]
fn invalid_user_id_host() {
assert_eq!(
<&UserId>::try_from("@carl:/").unwrap_err(),
IdParseError::InvalidServerName
);
}
#[test]
fn invalid_user_id_port() {
assert_eq!(
<&UserId>::try_from("@carl:example.com:notaport").unwrap_err(),
IdParseError::InvalidServerName
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/room_or_alias_id.rs | crates/core/src/identifiers/room_or_alias_id.rs | //! Matrix identifiers for places where a room ID or room alias ID are used
//! interchangeably.
use std::hint::unreachable_unchecked;
use crate::macros::IdDst;
use diesel::expression::AsExpression;
use super::{OwnedRoomAliasId, OwnedRoomId, RoomAliasId, RoomId, server_name::ServerName};
/// A Matrix [room ID] or a Matrix [room alias ID].
///
/// `RoomOrAliasId` is useful for APIs that accept either kind of room
/// identifier. It is converted from a string slice, and can be converted back
/// into a string as needed. When converted from a string slice, the variant is
/// determined by the leading sigil character.
///
/// ```
/// # use palpo_core::RoomOrAliasId;
/// assert_eq!(<&RoomOrAliasId>::try_from("#palpo:example.com").unwrap(), "#palpo:example.com");
///
/// assert_eq!(
/// <&RoomOrAliasId>::try_from("!n8f893n9:example.com").unwrap(),
/// "!n8f893n9:example.com"
/// );
/// ```
///
/// [room ID]: https://spec.matrix.org/latest/appendices/#room-ids
/// [room alias ID]: https://spec.matrix.org/latest/appendices/#room-aliases
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
#[palpo_id(validate = palpo_identifiers_validation::room_id_or_alias_id::validate)]
pub struct RoomOrAliasId(str);
impl RoomOrAliasId {
/// Returns the server name of the room (alias) ID.
pub fn server_name(&self) -> Result<&ServerName, &str> {
let colon_idx = self.as_str().find(':').ok_or(self.as_str())?;
if let Ok(server_name) = (&self.as_str()[colon_idx + 1..]).try_into() {
Ok(server_name)
} else {
Err(self.as_str())
}
}
/// Whether this is a room id (starts with `'!'`)
pub fn is_room_id(&self) -> bool {
self.variant() == Variant::RoomId
}
/// Whether this is a room alias id (starts with `'#'`)
pub fn is_room_alias_id(&self) -> bool {
self.variant() == Variant::RoomAliasId
}
fn variant(&self) -> Variant {
match self.as_bytes().first() {
Some(b'!') => Variant::RoomId,
Some(b'#') => Variant::RoomAliasId,
_ => unsafe { unreachable_unchecked() },
}
}
}
#[derive(PartialEq, Eq)]
enum Variant {
RoomId,
RoomAliasId,
}
impl<'a> From<&'a RoomId> for &'a RoomOrAliasId {
fn from(room_id: &'a RoomId) -> Self {
RoomOrAliasId::from_borrowed(room_id.as_str())
}
}
impl<'a> From<&'a RoomAliasId> for &'a RoomOrAliasId {
fn from(room_alias_id: &'a RoomAliasId) -> Self {
RoomOrAliasId::from_borrowed(room_alias_id.as_str())
}
}
impl From<OwnedRoomId> for OwnedRoomOrAliasId {
fn from(room_id: OwnedRoomId) -> Self {
// FIXME: Don't allocate
RoomOrAliasId::from_borrowed(room_id.as_str()).to_owned()
}
}
impl From<OwnedRoomAliasId> for OwnedRoomOrAliasId {
fn from(room_alias_id: OwnedRoomAliasId) -> Self {
// FIXME: Don't allocate
RoomOrAliasId::from_borrowed(room_alias_id.as_str()).to_owned()
}
}
impl<'a> TryFrom<&'a RoomOrAliasId> for &'a RoomId {
type Error = &'a RoomAliasId;
fn try_from(id: &'a RoomOrAliasId) -> Result<&'a RoomId, &'a RoomAliasId> {
match id.variant() {
Variant::RoomId => Ok(RoomId::from_borrowed(id.as_str())),
Variant::RoomAliasId => Err(RoomAliasId::from_borrowed(id.as_str())),
}
}
}
impl<'a> TryFrom<&'a RoomOrAliasId> for &'a RoomAliasId {
type Error = &'a RoomId;
fn try_from(id: &'a RoomOrAliasId) -> Result<&'a RoomAliasId, &'a RoomId> {
match id.variant() {
Variant::RoomAliasId => Ok(RoomAliasId::from_borrowed(id.as_str())),
Variant::RoomId => Err(RoomId::from_borrowed(id.as_str())),
}
}
}
impl TryFrom<OwnedRoomOrAliasId> for OwnedRoomId {
type Error = OwnedRoomAliasId;
fn try_from(id: OwnedRoomOrAliasId) -> Result<OwnedRoomId, OwnedRoomAliasId> {
// FIXME: Don't allocate
match id.variant() {
Variant::RoomId => Ok(RoomId::from_borrowed(id.as_str()).to_owned()),
Variant::RoomAliasId => Err(RoomAliasId::from_borrowed(id.as_str()).to_owned()),
}
}
}
impl TryFrom<OwnedRoomOrAliasId> for OwnedRoomAliasId {
type Error = OwnedRoomId;
fn try_from(id: OwnedRoomOrAliasId) -> Result<OwnedRoomAliasId, OwnedRoomId> {
// FIXME: Don't allocate
match id.variant() {
Variant::RoomAliasId => Ok(RoomAliasId::from_borrowed(id.as_str()).to_owned()),
Variant::RoomId => Err(RoomId::from_borrowed(id.as_str()).to_owned()),
}
}
}
#[cfg(test)]
mod tests {
use super::{OwnedRoomOrAliasId, RoomOrAliasId};
use crate::IdParseError;
#[test]
fn valid_room_id_or_alias_id_with_a_room_alias_id() {
assert_eq!(
<&RoomOrAliasId>::try_from("#palpo:example.com")
.expect("Failed to create RoomAliasId.")
.as_str(),
"#palpo:example.com"
);
}
#[test]
fn valid_room_id_or_alias_id_with_a_room_id() {
assert_eq!(
<&RoomOrAliasId>::try_from("!29fhd83h92h0:example.com")
.expect("Failed to create RoomId.")
.as_str(),
"!29fhd83h92h0:example.com"
);
}
#[test]
fn missing_sigil_for_room_id_or_alias_id() {
assert_eq!(
<&RoomOrAliasId>::try_from("palpo:example.com").unwrap_err(),
IdParseError::MissingLeadingSigil
);
}
#[test]
fn serialize_valid_room_id_or_alias_id_with_a_room_alias_id() {
assert_eq!(
serde_json::to_string(
<&RoomOrAliasId>::try_from("#palpo:example.com")
.expect("Failed to create RoomAliasId.")
)
.expect("Failed to convert RoomAliasId to JSON."),
r##""#palpo:example.com""##
);
}
#[test]
fn serialize_valid_room_id_or_alias_id_with_a_room_id() {
assert_eq!(
serde_json::to_string(
<&RoomOrAliasId>::try_from("!29fhd83h92h0:example.com")
.expect("Failed to create RoomId.")
)
.expect("Failed to convert RoomId to JSON."),
r#""!29fhd83h92h0:example.com""#
);
}
#[test]
fn deserialize_valid_room_id_or_alias_id_with_a_room_alias_id() {
assert_eq!(
serde_json::from_str::<OwnedRoomOrAliasId>(r##""#palpo:example.com""##)
.expect("Failed to convert JSON to RoomAliasId"),
<&RoomOrAliasId>::try_from("#palpo:example.com")
.expect("Failed to create RoomAliasId.")
);
}
#[test]
fn deserialize_valid_room_id_or_alias_id_with_a_room_id() {
assert_eq!(
serde_json::from_str::<OwnedRoomOrAliasId>(r#""!29fhd83h92h0:example.com""#)
.expect("Failed to convert JSON to RoomId"),
<&RoomOrAliasId>::try_from("!29fhd83h92h0:example.com")
.expect("Failed to create RoomAliasId.")
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/one_time_key_name.rs | crates/core/src/identifiers/one_time_key_name.rs | use super::{IdParseError, KeyName};
use crate::macros::IdDst;
/// The name of a [one-time or fallback key].
///
/// One-time and fallback key names in Matrix are completely opaque character sequences. This
/// type is provided simply for its semantic value.
///
/// [one-time or fallback key]: https://spec.matrix.org/latest/client-server-api/#one-time-and-fallback-keys
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
pub struct OneTimeKeyName(str);
impl KeyName for OneTimeKeyName {
fn validate(_s: &str) -> Result<(), IdParseError> {
Ok(())
}
}
impl KeyName for OwnedOneTimeKeyName {
fn validate(_s: &str) -> Result<(), IdParseError> {
Ok(())
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/server_name.rs | crates/core/src/identifiers/server_name.rs | //! Matrix-spec compliant server names.
use std::net::Ipv4Addr;
use diesel::expression::AsExpression;
use crate::macros::IdDst;
/// A Matrix-spec compliant [server name].
///
/// It consists of a host and an optional port (separated by a colon if
/// present).
///
/// [server name]: https://spec.matrix.org/latest/appendices/#server-name
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
#[palpo_id(validate = palpo_identifiers_validation::server_name::validate)]
pub struct ServerName(str);
impl ServerName {
/// Returns the host of the server name.
///
/// That is: Return the part of the server name before `:<port>` or the full
/// server name if there is no port.
pub fn host(&self) -> &str {
if let Some(end_of_ipv6) = self.0.find(']') {
&self.0[..=end_of_ipv6]
} else {
// It's not ipv6, so ':' means the port starts
let end_of_host = self.0.find(':').unwrap_or(self.0.len());
&self.0[..end_of_host]
}
}
/// Returns the port of the server name, if any.
pub fn port(&self) -> Option<u16> {
#[allow(clippy::unnecessary_lazy_evaluations)]
let end_of_host = self
.0
.find(']')
.map(|i| i + 1)
.or_else(|| self.0.find(':'))
.unwrap_or_else(|| self.0.len());
(self.0.len() != end_of_host).then(|| {
assert!(self.as_bytes()[end_of_host] == b':');
self.0[end_of_host + 1..].parse().unwrap()
})
}
/// Returns true if and only if the server name is an IPv4 or IPv6 address.
pub fn is_ip_literal(&self) -> bool {
self.host().parse::<Ipv4Addr>().is_ok() || self.0.starts_with('[')
}
pub fn is_valid(&self) -> bool {
!((self.0.starts_with('[') && !self.0.contains(']')) || self.0.ends_with('.'))
}
}
#[cfg(test)]
mod tests {
use super::ServerName;
#[test]
fn ipv4_host() {
<&ServerName>::try_from("127.0.0.1").unwrap();
}
#[test]
fn ipv4_host_and_port() {
<&ServerName>::try_from("1.1.1.1:12000").unwrap();
}
#[test]
fn ipv6() {
<&ServerName>::try_from("[::1]").unwrap();
}
#[test]
fn ipv6_with_port() {
<&ServerName>::try_from("[1234:5678::abcd]:5678").unwrap();
}
#[test]
fn dns_name() {
<&ServerName>::try_from("example.com").unwrap();
}
#[test]
fn dns_name_with_port() {
<&ServerName>::try_from("palpo.io:8080").unwrap();
}
#[test]
fn empty_string() {
<&ServerName>::try_from("").unwrap_err();
}
#[test]
fn invalid_ipv6() {
<&ServerName>::try_from("[test::1]").unwrap_err();
}
#[test]
fn ipv4_with_invalid_port() {
<&ServerName>::try_from("127.0.0.1:").unwrap_err();
}
#[test]
fn ipv6_with_invalid_port() {
<&ServerName>::try_from("[fe80::1]:100000").unwrap_err();
<&ServerName>::try_from("[fe80::1]!").unwrap_err();
}
#[test]
fn dns_name_with_invalid_port() {
<&ServerName>::try_from("matrix.org:hello").unwrap_err();
}
#[test]
fn parse_ipv4_host() {
let server_name = <&ServerName>::try_from("127.0.0.1").unwrap();
assert!(server_name.is_ip_literal());
assert_eq!(server_name.host(), "127.0.0.1");
}
#[test]
fn parse_ipv4_host_and_port() {
let server_name = <&ServerName>::try_from("1.1.1.1:12000").unwrap();
assert!(server_name.is_ip_literal());
assert_eq!(server_name.host(), "1.1.1.1");
}
#[test]
fn parse_ipv6() {
let server_name = <&ServerName>::try_from("[::1]").unwrap();
assert!(server_name.is_ip_literal());
assert_eq!(server_name.host(), "[::1]");
}
#[test]
fn parse_ipv6_with_port() {
let server_name = <&ServerName>::try_from("[1234:5678::abcd]:5678").unwrap();
assert!(server_name.is_ip_literal());
assert_eq!(server_name.host(), "[1234:5678::abcd]");
}
#[test]
fn parse_dns_name() {
let server_name = <&ServerName>::try_from("example.com").unwrap();
assert!(!server_name.is_ip_literal());
assert_eq!(server_name.host(), "example.com");
}
#[test]
fn parse_dns_name_with_port() {
let server_name = <&ServerName>::try_from("palpo.io:8080").unwrap();
assert!(!server_name.is_ip_literal());
assert_eq!(server_name.host(), "palpo.io");
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/base64_public_key.rs | crates/core/src/identifiers/base64_public_key.rs | use super::{IdParseError, KeyName};
use crate::macros::IdDst;
use crate::serde::{Base64, Base64DecodeError, base64::Standard};
/// A public key encoded using unpadded base64, used as an identifier for [cross-signing] keys.
///
/// This string is validated using the set `[a-zA-Z0-9+/=]`, but it is not validated to be decodable
/// as base64. This type is provided simply for its semantic value.
///
/// [cross-signing]: https://spec.matrix.org/latest/client-server-api/#cross-signing
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
#[palpo_id(validate = palpo_identifiers_validation::base64_public_key::validate)]
pub struct Base64PublicKey(str);
impl OwnedBase64PublicKey {
/// Construct a new `OwnedBase64PublicKey` by encoding the given bytes using unpadded base64.
pub fn with_bytes<B: AsRef<[u8]>>(bytes: B) -> OwnedBase64PublicKey {
Base64::<Standard, B>::new(bytes).into()
}
}
impl KeyName for Base64PublicKey {
fn validate(s: &str) -> Result<(), IdParseError> {
palpo_identifiers_validation::base64_public_key::validate(s)
}
}
impl KeyName for OwnedBase64PublicKey {
fn validate(s: &str) -> Result<(), IdParseError> {
palpo_identifiers_validation::base64_public_key::validate(s)
}
}
impl<B: AsRef<[u8]>> From<Base64<Standard, B>> for OwnedBase64PublicKey {
fn from(value: Base64<Standard, B>) -> Self {
value
.to_string()
.try_into()
.unwrap_or_else(|_| unreachable!())
}
}
impl TryFrom<&Base64PublicKey> for Base64<Standard, Vec<u8>> {
type Error = Base64DecodeError;
fn try_from(value: &Base64PublicKey) -> Result<Self, Self::Error> {
Base64::parse(value)
}
}
impl TryFrom<&OwnedBase64PublicKey> for Base64<Standard, Vec<u8>> {
type Error = Base64DecodeError;
fn try_from(value: &OwnedBase64PublicKey) -> Result<Self, Self::Error> {
Base64::parse(value)
}
}
impl TryFrom<OwnedBase64PublicKey> for Base64<Standard, Vec<u8>> {
type Error = Base64DecodeError;
fn try_from(value: OwnedBase64PublicKey) -> Result<Self, Self::Error> {
Base64::parse(value)
}
}
#[cfg(test)]
mod tests {
use super::{Base64PublicKey, OwnedBase64PublicKey};
#[test]
fn valid_string() {
<&Base64PublicKey>::try_from("base64+master+public+key").unwrap();
}
#[test]
fn invalid_string() {
<&Base64PublicKey>::try_from("not@base@64").unwrap_err();
}
#[test]
fn constructor() {
_ = OwnedBase64PublicKey::with_bytes(b"self-signing master public key");
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/voip_version_id.rs | crates/core/src/identifiers/voip_version_id.rs | //! Matrix VoIP version identifier.
use std::fmt;
use crate::macros::DisplayAsRefStr;
use salvo::oapi::ToSchema;
use serde::{
Deserialize, Deserializer, Serialize,
de::{self, Visitor},
};
use crate::{IdParseError, PrivOwnedStr};
/// A Matrix VoIP version ID.
///
/// A `VoipVersionId` representing VoIP version 0 can be converted or
/// deserialized from a `i64`, and can be converted or serialized back into a
/// `i64` as needed.
///
/// Custom room versions or ones that were introduced into the specification
/// after this code was written are represented by a hidden enum variant. They
/// can be converted or deserialized from a string slice, and can be converted
/// or serialized back into a string as needed.
///
/// ```
/// # use palpo_core::VoipVersionId;
/// assert_eq!(VoipVersionId::try_from("1").unwrap().as_ref(), "1");
/// ```
///
/// For simplicity, version 0 has a string representation, but trying to
/// construct a `VoipVersionId` from a `"0"` string will not result in the `V0`
/// variant.
#[derive(ToSchema, Clone, Debug, PartialEq, Eq, Hash, DisplayAsRefStr)]
pub enum VoipVersionId {
/// A version 0 VoIP call.
V0,
/// A version 1 VoIP call.
V1,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
impl VoipVersionId {
/// Creates a string slice from this `VoipVersionId`.
pub fn as_str(&self) -> &str {
match &self {
Self::V0 => "0",
Self::V1 => "1",
Self::_Custom(PrivOwnedStr(s)) => s,
}
}
/// Creates a byte slice from this `VoipVersionId`.
pub fn as_bytes(&self) -> &[u8] {
self.as_str().as_bytes()
}
}
impl From<VoipVersionId> for String {
fn from(id: VoipVersionId) -> Self {
match id {
VoipVersionId::_Custom(PrivOwnedStr(version)) => version.into(),
_ => id.as_str().to_owned(),
}
}
}
impl AsRef<str> for VoipVersionId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl<'de> Deserialize<'de> for VoipVersionId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct CallVersionVisitor;
impl<'de> Visitor<'de> for CallVersionVisitor {
type Value = VoipVersionId;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("0 or string")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(value.into())
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Self::Value::try_from(value).map_err(de::Error::custom)
}
}
deserializer.deserialize_any(CallVersionVisitor)
}
}
impl Serialize for VoipVersionId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Self::V0 => serializer.serialize_u64(0),
_ => serializer.serialize_str(self.as_str()),
}
}
}
impl TryFrom<u64> for VoipVersionId {
type Error = IdParseError;
fn try_from(u: u64) -> Result<Self, Self::Error> {
palpo_identifiers_validation::voip_version_id::validate(u)?;
Ok(Self::V0)
}
}
fn from<T>(s: T) -> VoipVersionId
where
T: AsRef<str> + Into<Box<str>>,
{
match s.as_ref() {
"1" => VoipVersionId::V1,
_ => VoipVersionId::_Custom(PrivOwnedStr(s.into())),
}
}
impl From<&str> for VoipVersionId {
fn from(s: &str) -> Self {
from(s)
}
}
impl From<String> for VoipVersionId {
fn from(s: String) -> Self {
from(s)
}
}
// #[cfg(test)]
// mod tests {
// use assert_matches2::assert_matches;
// use serde_json::{from_value as from_json_value, json, to_value as
// to_json_value};
// use super::VoipVersionId;
// use crate::IdParseError;
// #[test]
// fn valid_version_0() {
// assert_eq!(VoipVersionId::try_from(u0), Ok(VoipVersionId::V0));
// }
// #[test]
// fn invalid_uint_version() {
// assert_matches!(VoipVersionId::try_from(u1),
// Err(IdParseError::InvalidVoipVersionId(_))); }
// #[test]
// fn valid_version_1() {
// assert_eq!(VoipVersionId::from("1"), VoipVersionId::V1);
// }
// #[test]
// fn valid_custom_string_version() {
// assert_matches!(VoipVersionId::from("io.palpo.2"), version);
// assert_eq!(version.as_ref(), "io.palpo.2");
// }
// #[test]
// fn serialize_version_0() {
// assert_eq!(to_json_value(&VoipVersionId::V0).unwrap(), json!(0));
// }
// #[test]
// fn deserialize_version_0() {
// assert_eq!(from_json_value::<VoipVersionId>(json!(0)).unwrap(),
// VoipVersionId::V0); }
// #[test]
// fn serialize_version_1() {
// assert_eq!(to_json_value(&VoipVersionId::V1).unwrap(), json!("1"));
// }
// #[test]
// fn deserialize_version_1() {
// assert_eq!(from_json_value::<VoipVersionId>(json!("1")).unwrap(),
// VoipVersionId::V1); }
// #[test]
// fn serialize_custom_string() {
// let version = VoipVersionId::from("io.palpo.1");
// assert_eq!(to_json_value(&version).unwrap(), json!("io.palpo.1"));
// }
// #[test]
// fn deserialize_custom_string() {
// let version = VoipVersionId::from("io.palpo.1");
// assert_eq!(from_json_value::<VoipVersionId>(json!("io.palpo.1")).
// unwrap(), version); }
// }
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/signatures.rs | crates/core/src/identifiers/signatures.rs | use std::{
borrow::Borrow,
collections::BTreeMap,
ops::{Deref, DerefMut},
};
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use super::{
Base64PublicKeyOrDeviceId, DeviceId, KeyName, OwnedServerName, OwnedSigningKeyId, OwnedUserId,
ServerSigningKeyVersion,
};
/// Map of key identifier to signature values.
pub type EntitySignatures<K> = BTreeMap<OwnedSigningKeyId<K>, String>;
/// Map of all signatures, grouped by entity
///
/// ```
/// # use palpo_core::{server_name, server_signing_key_version, ServerSigningKeyId, Signatures, SigningKeyAlgorithm};
/// let key_identifier = ServerSigningKeyId::from_parts(
/// SigningKeyAlgorithm::Ed25519,
/// server_signing_key_version!("1")
/// );
/// let mut signatures = Signatures::new();
/// let server_name = server_name!("example.org");
/// let signature =
/// "YbJva03ihSj5mPk+CHMJKUKlCXCPFXjXOK6VqBnN9nA2evksQcTGn6hwQfrgRHIDDXO2le49x7jnWJHMJrJoBQ";
/// signatures.insert(server_name, key_identifier, signature.into());
/// ```
#[derive(ToSchema, Debug, Serialize, Deserialize)]
#[serde(
transparent,
bound(
serialize = "E: Serialize",
deserialize = "E: serde::de::DeserializeOwned"
)
)]
pub struct Signatures<E: Ord, K: KeyName + ?Sized>(BTreeMap<E, EntitySignatures<K>>);
impl<E: Ord, K: KeyName + ?Sized> Signatures<E, K> {
/// Creates an empty signature map.
pub fn new() -> Self {
Self(BTreeMap::new())
}
/// Add a signature for the given server name and key identifier.
///
/// If there was already one, it is returned.
pub fn insert(
&mut self,
entity: E,
key_identifier: OwnedSigningKeyId<K>,
value: String,
) -> Option<String> {
self.0
.entry(entity)
.or_default()
.insert(key_identifier, value)
}
/// Returns a reference to the signatures corresponding to the entities.
pub fn get<Q>(&self, entity: &Q) -> Option<&EntitySignatures<K>>
where
E: Borrow<Q>,
Q: Ord + ?Sized,
{
self.0.get(entity)
}
}
/// Map of server signatures, grouped by server.
pub type ServerSignatures = Signatures<OwnedServerName, ServerSigningKeyVersion>;
/// Map of device signatures, grouped by user.
pub type DeviceSignatures = Signatures<OwnedUserId, DeviceId>;
/// Map of cross-signing or device signatures, grouped by user.
pub type CrossSigningOrDeviceSignatures = Signatures<OwnedUserId, Base64PublicKeyOrDeviceId>;
impl<E, K> Clone for Signatures<E, K>
where
E: Ord + Clone,
K: KeyName + ?Sized,
{
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<E: Ord, K: KeyName + ?Sized> Default for Signatures<E, K> {
fn default() -> Self {
Self(Default::default())
}
}
impl<E: Ord, K: KeyName + ?Sized> Deref for Signatures<E, K> {
type Target = BTreeMap<E, EntitySignatures<K>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<E: Ord, K: KeyName + ?Sized> DerefMut for Signatures<E, K> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<E: Ord, K: KeyName + ?Sized, const N: usize> From<[(E, OwnedSigningKeyId<K>, String); N]>
for Signatures<E, K>
{
fn from(value: [(E, OwnedSigningKeyId<K>, String); N]) -> Self {
value.into_iter().collect()
}
}
impl<E: Ord, K: KeyName + ?Sized> FromIterator<(E, OwnedSigningKeyId<K>, String)>
for Signatures<E, K>
{
fn from_iter<T: IntoIterator<Item = (E, OwnedSigningKeyId<K>, String)>>(iter: T) -> Self {
iter.into_iter()
.fold(Self::new(), |mut acc, (entity, key_identifier, value)| {
acc.insert(entity, key_identifier, value);
acc
})
}
}
impl<E: Ord, K: KeyName + ?Sized> Extend<(E, OwnedSigningKeyId<K>, String)> for Signatures<E, K> {
fn extend<T: IntoIterator<Item = (E, OwnedSigningKeyId<K>, String)>>(&mut self, iter: T) {
for (entity, key_identifier, value) in iter {
self.insert(entity, key_identifier, value);
}
}
}
impl<E: Ord + Clone, K: KeyName + ?Sized> IntoIterator for Signatures<E, K> {
type Item = (E, OwnedSigningKeyId<K>, String);
type IntoIter = IntoIter<E, K>;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
outer: self.0.into_iter(),
inner: None,
entity: None,
}
}
}
pub struct IntoIter<E: Clone, K: KeyName + ?Sized> {
outer: std::collections::btree_map::IntoIter<E, BTreeMap<OwnedSigningKeyId<K>, String>>,
inner: Option<std::collections::btree_map::IntoIter<OwnedSigningKeyId<K>, String>>,
entity: Option<E>,
}
impl<E: Clone, K: KeyName + ?Sized> Iterator for IntoIter<E, K> {
type Item = (E, OwnedSigningKeyId<K>, String);
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(inner) = &mut self.inner
&& let Some((k, v)) = inner.next()
&& let Some(entity) = self.entity.clone()
{
return Some((entity, k, v));
}
if let Some((e, map)) = self.outer.next() {
self.inner = Some(map.into_iter());
self.entity = Some(e);
} else {
return None;
}
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn signatures_into_iter() {
use crate::{
ServerSigningKeyId, Signatures, SigningKeyAlgorithm, owned_server_name,
server_signing_key_version,
};
let key_identifier = ServerSigningKeyId::from_parts(
SigningKeyAlgorithm::Ed25519,
server_signing_key_version!("1"),
);
let mut signatures = Signatures::new();
let server_name = owned_server_name!("example.org");
let signature = "YbJva03ihSj5mPk+CHMJKUKlCXCPFXjXOK6VqBnN9nA2evksQcTGn6hwQfrgRHIDDXO2le49x7jnWJHMJrJoBQ";
signatures.insert(server_name, key_identifier, signature.into());
let mut more_signatures = Signatures::new();
more_signatures.extend(signatures.clone());
assert_eq!(more_signatures.0, signatures.0);
let mut iter = more_signatures.into_iter();
assert!(iter.next().is_some());
assert!(iter.next().is_none());
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/session_id.rs | crates/core/src/identifiers/session_id.rs | //! Matrix session ID.
use crate::macros::IdDst;
use diesel::expression::AsExpression;
use super::IdParseError;
/// A session ID.
///
/// Session IDs in Matrix are opaque character sequences of `[0-9a-zA-Z.=_-]`.
/// Their length must must not exceed 255 characters.
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
#[palpo_id(validate = validate_session_id)]
pub struct SessionId(str);
impl SessionId {
#[doc(hidden)]
pub const fn _priv_const_new(s: &str) -> Result<&Self, &'static str> {
match validate_session_id(s) {
Ok(()) => Ok(Self::from_borrowed(s)),
Err(IdParseError::MaximumLengthExceeded) => {
Err("Invalid Session ID: exceeds 255 bytes")
}
Err(IdParseError::InvalidCharacters) => {
Err("Invalid Session ID: contains invalid characters")
}
Err(IdParseError::Empty) => Err("Invalid Session ID: empty"),
Err(_) => unreachable!(),
}
}
}
const fn validate_session_id(s: &str) -> Result<(), IdParseError> {
if s.len() > 255 {
return Err(IdParseError::MaximumLengthExceeded);
} else if contains_invalid_byte(s.as_bytes()) {
return Err(IdParseError::InvalidCharacters);
} else if s.is_empty() {
return Err(IdParseError::Empty);
}
Ok(())
}
const fn contains_invalid_byte(mut bytes: &[u8]) -> bool {
// non-const form:
//
// bytes.iter().all(|b| b.is_ascii_alphanumeric() || b".=_-".contains(&b))
loop {
if let Some((byte, rest)) = bytes.split_first() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'=' | b'_' | b'-') {
bytes = rest;
} else {
break true;
}
} else {
break false;
}
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/server_signing_key_version.rs | crates/core/src/identifiers/server_signing_key_version.rs | use crate::macros::IdDst;
use crate::{IdParseError, KeyName};
/// The version of a [homeserver signing key].
///
/// This is an opaque character sequences of `[a-zA-Z0-9_]`. This type is
/// provided simply for its semantic value.
///
/// With the `compat-server-signing-key-version` cargo feature, the validation
/// of this type is relaxed to accept any string.
///
/// [homeserver signing key]: https://spec.matrix.org/latest/server-server-api/#retrieving-server-keys
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
#[palpo_id(
validate = palpo_identifiers_validation::server_signing_key_version::validate,
)]
pub struct ServerSigningKeyVersion(str);
impl KeyName for ServerSigningKeyVersion {
fn validate(s: &str) -> Result<(), IdParseError> {
palpo_identifiers_validation::server_signing_key_version::validate(s)
}
}
impl KeyName for OwnedServerSigningKeyVersion {
fn validate(s: &str) -> Result<(), IdParseError> {
palpo_identifiers_validation::server_signing_key_version::validate(s)
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/room_alias_id.rs | crates/core/src/identifiers/room_alias_id.rs | //! Matrix room alias identifiers.
use crate::macros::IdDst;
use diesel::expression::AsExpression;
use super::{MatrixToUri, MatrixUri, OwnedEventId, matrix_uri::UriAction, server_name::ServerName};
/// A Matrix [room alias ID].
///
/// A `RoomAliasId` is converted from a string slice, and can be converted back
/// into a string as needed.
///
/// ```
/// # use palpo_core::RoomAliasId;
/// assert_eq!(<&RoomAliasId>::try_from("#palpo:example.com").unwrap(), "#palpo:example.com");
/// ```
///
/// [room alias ID]: https://spec.matrix.org/latest/appendices/#room-aliases
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
#[palpo_id(validate = palpo_identifiers_validation::room_alias_id::validate)]
pub struct RoomAliasId(str);
impl RoomAliasId {
/// Returns the room's alias.
pub fn alias(&self) -> &str {
&self.as_str()[1..self.colon_idx()]
}
/// Returns the server name of the room alias ID.
pub fn server_name(&self) -> &ServerName {
ServerName::from_borrowed(&self.as_str()[self.colon_idx() + 1..])
}
/// Create a `matrix.to` URI for this room alias ID.
pub fn matrix_to_uri(&self) -> MatrixToUri {
MatrixToUri::new(self.into(), Vec::new())
}
/// Create a `matrix.to` URI for an event scoped under this room alias ID.
pub fn matrix_to_event_uri(&self, ev_id: impl Into<OwnedEventId>) -> MatrixToUri {
MatrixToUri::new((self.to_owned(), ev_id.into()).into(), Vec::new())
}
/// Create a `matrix:` URI for this room alias ID.
///
/// If `join` is `true`, a click on the URI should join the room.
pub fn matrix_uri(&self, join: bool) -> MatrixUri {
MatrixUri::new(
self.into(),
Vec::new(),
Some(UriAction::Join).filter(|_| join),
)
}
/// Create a `matrix:` URI for an event scoped under this room alias ID.
pub fn matrix_event_uri(&self, ev_id: impl Into<OwnedEventId>) -> MatrixUri {
MatrixUri::new((self.to_owned(), ev_id.into()).into(), Vec::new(), None)
}
fn colon_idx(&self) -> usize {
self.as_str().find(':').unwrap()
}
}
#[cfg(test)]
mod tests {
use super::{OwnedRoomAliasId, RoomAliasId};
use crate::IdParseError;
#[test]
fn valid_room_alias_id() {
assert_eq!(
<&RoomAliasId>::try_from("#palpo:example.com").expect("Failed to create RoomAliasId."),
"#palpo:example.com"
);
}
#[test]
fn empty_localpart() {
assert_eq!(
<&RoomAliasId>::try_from("#:myhomeserver.io").expect("Failed to create RoomAliasId."),
"#:myhomeserver.io"
);
}
#[test]
fn serialize_valid_room_alias_id() {
assert_eq!(
serde_json::to_string(
<&RoomAliasId>::try_from("#palpo:example.com")
.expect("Failed to create RoomAliasId.")
)
.expect("Failed to convert RoomAliasId to JSON."),
r##""#palpo:example.com""##
);
}
#[test]
fn deserialize_valid_room_alias_id() {
assert_eq!(
serde_json::from_str::<OwnedRoomAliasId>(r##""#palpo:example.com""##)
.expect("Failed to convert JSON to RoomAliasId"),
<&RoomAliasId>::try_from("#palpo:example.com").expect("Failed to create RoomAliasId.")
);
}
#[test]
fn valid_room_alias_id_with_explicit_standard_port() {
assert_eq!(
<&RoomAliasId>::try_from("#palpo:example.com:443")
.expect("Failed to create RoomAliasId."),
"#palpo:example.com:443"
);
}
#[test]
fn valid_room_alias_id_with_non_standard_port() {
assert_eq!(
<&RoomAliasId>::try_from("#palpo:example.com:5000")
.expect("Failed to create RoomAliasId."),
"#palpo:example.com:5000"
);
}
#[test]
fn valid_room_alias_id_unicode() {
assert_eq!(
<&RoomAliasId>::try_from("#老虎£я:example.com")
.expect("Failed to create RoomAliasId."),
"#老虎£я:example.com"
);
}
#[test]
fn missing_room_alias_id_sigil() {
assert_eq!(
<&RoomAliasId>::try_from("39hvsi03hlne:example.com").unwrap_err(),
IdParseError::MissingLeadingSigil
);
}
#[test]
fn missing_room_alias_id_delimiter() {
assert_eq!(
<&RoomAliasId>::try_from("#palpo").unwrap_err(),
IdParseError::MissingColon
);
}
#[test]
fn invalid_leading_sigil() {
assert_eq!(
<&RoomAliasId>::try_from("!room_id:foo.bar").unwrap_err(),
IdParseError::MissingLeadingSigil
);
}
#[test]
fn invalid_room_alias_id_host() {
assert_eq!(
<&RoomAliasId>::try_from("#palpo:/").unwrap_err(),
IdParseError::InvalidServerName
);
}
#[test]
fn invalid_room_alias_id_port() {
assert_eq!(
<&RoomAliasId>::try_from("#palpo:example.com:notaport").unwrap_err(),
IdParseError::InvalidServerName
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/space_child_order.rs | crates/core/src/identifiers/space_child_order.rs | //! `m.space.child` order.
use crate::macros::IdDst;
/// The order of an [`m.space.child`] event.
///
/// Space child orders in Matrix are opaque character sequences consisting of ASCII characters
/// within the range `\x20` (space) and `\x7E` (~), inclusive. Their length must must not exceed 50
/// characters.
///
/// [`m.space.child`]: https://spec.matrix.org/latest/client-server-api/#mspacechild
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
#[palpo_id(validate = palpo_identifiers_validation::space_child_order::validate)]
pub struct SpaceChildOrder(str);
#[cfg(test)]
mod tests {
use std::iter::repeat_n;
use palpo_identifiers_validation::Error;
use super::SpaceChildOrder;
#[test]
fn validate_space_child_order() {
// Valid string.
SpaceChildOrder::parse("aaa").unwrap();
// String too long.
let order = repeat_n('a', 60).collect::<String>();
assert_eq!(
SpaceChildOrder::parse(&order),
Err(Error::MaximumLengthExceeded)
);
// Invalid character.
assert_eq!(SpaceChildOrder::parse("🔝"), Err(Error::InvalidCharacters));
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/client_secret.rs | crates/core/src/identifiers/client_secret.rs | //! Client secret identifier.
use crate::macros::IdDst;
/// A client secret.
///
/// Client secrets in Matrix are opaque character sequences of
/// `[0-9a-zA-Z.=_-]`. Their length must must not exceed 255 characters.
///
/// You can create one from a string (using `ClientSecret::parse()`) but the
/// recommended way is to use `ClientSecret::new()` to generate a random one. If
/// that function is not available for you, you need to activate this crate's
/// `rand` Cargo feature.
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
#[palpo_id(validate = palpo_identifiers_validation::client_secret::validate)]
pub struct ClientSecret(str);
impl ClientSecret {
/// Creates a random client secret.
///
/// This will currently be a UUID without hyphens, but no guarantees are
/// made about the structure of client secrets generated from this
/// function.
#[allow(clippy::new_ret_no_self)]
pub fn new() -> OwnedClientSecret {
let id = uuid::Uuid::new_v4();
ClientSecret::from_borrowed(&id.simple().to_string()).to_owned()
}
}
#[cfg(test)]
mod tests {
use super::ClientSecret;
#[test]
fn valid_secret() {
<&ClientSecret>::try_from("this_=_a_valid_secret_1337").unwrap();
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/transaction_id.rs | crates/core/src/identifiers/transaction_id.rs | use crate::macros::IdDst;
use diesel::expression::AsExpression;
/// A Matrix transaction ID.
///
/// Transaction IDs in Matrix are opaque strings. This type is provided simply
/// for its semantic value.
///
/// You can create one from a string (using `.into()`) but the recommended way
/// is to use `TransactionId::new()` to generate a random one. If that function
/// is not available for you, you need to activate this crate's `rand` Cargo
/// feature.
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
pub struct TransactionId(str);
impl TransactionId {
/// Creates a random transaction ID.
///
/// This will currently be a UUID without hyphens, but no guarantees are
/// made about the structure of transaction IDs generated from this
/// function.
#[allow(clippy::new_ret_no_self)]
pub fn new() -> OwnedTransactionId {
let id = uuid::Uuid::new_v4();
Self::from_borrowed(&id.simple().to_string()).to_owned()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/event_id.rs | crates/core/src/identifiers/event_id.rs | //! Matrix event identifiers.
use diesel::expression::AsExpression;
use super::ServerName;
use crate::macros::IdDst;
/// A Matrix [event ID].
///
/// An `EventId` is generated randomly or converted from a string slice, and can
/// be converted back into a string as needed.
///
/// # Room versions
///
/// Matrix specifies multiple [room versions] and the format of event
/// identifiers differ between them. The original format used by room versions 1
/// and 2 uses a short pseudorandom "localpart" followed by the hostname and
/// port of the originating homeserver. Later room versions change
/// event identifiers to be a hash of the event encoded with Base64. Some of the
/// methods provided by `EventId` are only relevant to the original event
/// format.
///
/// ```
/// # use palpo_core::EventId;
/// // Original format
/// assert_eq!(<&EventId>::try_from("$h29iv0s8:example.com").unwrap(), "$h29iv0s8:example.com");
/// // Room version 3 format
/// assert_eq!(
/// <&EventId>::try_from("$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk").unwrap(),
/// "$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk"
/// );
/// // Room version 4 format
/// assert_eq!(
/// <&EventId>::try_from("$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg").unwrap(),
/// "$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg"
/// );
/// ```
///
/// [event ID]: https://spec.matrix.org/latest/appendices/#event-ids
/// [room versions]: https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
#[palpo_id(validate = palpo_identifiers_validation::event_id::validate)]
pub struct EventId(str);
impl EventId {
/// Attempts to generate an `EventId` for the given origin server with a
/// localpart consisting of 18 random ASCII characters.
///
/// This should only be used for events in the original format as used by
/// Matrix room versions 1 and 2.
#[allow(clippy::new_ret_no_self)]
pub fn new(server_name: &ServerName) -> OwnedEventId {
Self::from_borrowed(&format!("${}:{server_name}", super::generate_localpart(18))).to_owned()
}
/// Returns the event's unique ID.
///
/// For the original event format as used by Matrix room versions 1 and 2,
/// this is the "localpart" that precedes the homeserver. For later
/// formats, this is the entire ID without the leading `$` sigil.
pub fn localpart(&self) -> &str {
let idx = self.colon_idx().unwrap_or_else(|| self.as_str().len());
&self.as_str()[1..idx]
}
/// Returns the server name of the event ID.
///
/// Only applicable to events in the original format as used by Matrix room
/// versions 1 and 2.
pub fn server_name(&self) -> Option<&ServerName> {
self.colon_idx()
.map(|idx| ServerName::from_borrowed(&self.as_str()[idx + 1..]))
}
fn colon_idx(&self) -> Option<usize> {
self.as_str().find(':')
}
}
#[cfg(test)]
mod tests {
use super::{EventId, OwnedEventId};
use crate::IdParseError;
#[test]
fn valid_original_event_id() {
assert_eq!(
<&EventId>::try_from("$39hvsi03hlne:example.com").expect("Failed to create EventId."),
"$39hvsi03hlne:example.com"
);
}
#[test]
fn valid_base64_event_id() {
assert_eq!(
<&EventId>::try_from("$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk")
.expect("Failed to create EventId."),
"$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk"
);
}
#[test]
fn valid_url_safe_base64_event_id() {
assert_eq!(
<&EventId>::try_from("$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg")
.expect("Failed to create EventId."),
"$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg"
);
}
#[test]
fn generate_random_valid_event_id() {
use crate::server_name;
let event_id = EventId::new(server_name!("example.com"));
let id_str = event_id.as_str();
assert!(id_str.starts_with('$'));
assert_eq!(id_str.len(), 31);
}
#[test]
fn serialize_valid_original_event_id() {
assert_eq!(
serde_json::to_string(
<&EventId>::try_from("$39hvsi03hlne:example.com")
.expect("Failed to create EventId.")
)
.expect("Failed to convert EventId to JSON."),
r#""$39hvsi03hlne:example.com""#
);
}
#[test]
fn serialize_valid_base64_event_id() {
assert_eq!(
serde_json::to_string(
<&EventId>::try_from("$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk")
.expect("Failed to create EventId.")
)
.expect("Failed to convert EventId to JSON."),
r#""$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk""#
);
}
#[test]
fn serialize_valid_url_safe_base64_event_id() {
assert_eq!(
serde_json::to_string(
<&EventId>::try_from("$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg")
.expect("Failed to create EventId.")
)
.expect("Failed to convert EventId to JSON."),
r#""$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg""#
);
}
#[test]
fn deserialize_valid_original_event_id() {
assert_eq!(
serde_json::from_str::<OwnedEventId>(r#""$39hvsi03hlne:example.com""#)
.expect("Failed to convert JSON to EventId"),
<&EventId>::try_from("$39hvsi03hlne:example.com").expect("Failed to create EventId.")
);
}
#[test]
fn deserialize_valid_base64_event_id() {
assert_eq!(
serde_json::from_str::<OwnedEventId>(
r#""$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk""#
)
.expect("Failed to convert JSON to EventId"),
<&EventId>::try_from("$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk")
.expect("Failed to create EventId.")
);
}
#[test]
fn deserialize_valid_url_safe_base64_event_id() {
assert_eq!(
serde_json::from_str::<OwnedEventId>(
r#""$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg""#
)
.expect("Failed to convert JSON to EventId"),
<&EventId>::try_from("$Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg")
.expect("Failed to create EventId.")
);
}
#[test]
fn valid_original_event_id_with_explicit_standard_port() {
assert_eq!(
<&EventId>::try_from("$39hvsi03hlne:example.com:443")
.expect("Failed to create EventId."),
"$39hvsi03hlne:example.com:443"
);
}
#[test]
fn valid_original_event_id_with_non_standard_port() {
assert_eq!(
<&EventId>::try_from("$39hvsi03hlne:example.com:5000")
.expect("Failed to create EventId."),
"$39hvsi03hlne:example.com:5000"
);
}
#[test]
fn missing_original_event_id_sigil() {
assert_eq!(
<&EventId>::try_from("39hvsi03hlne:example.com").unwrap_err(),
IdParseError::MissingLeadingSigil
);
}
#[test]
fn missing_base64_event_id_sigil() {
assert_eq!(
<&EventId>::try_from("acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk").unwrap_err(),
IdParseError::MissingLeadingSigil
);
}
#[test]
fn missing_url_safe_base64_event_id_sigil() {
assert_eq!(
<&EventId>::try_from("Rqnc-F-dvnEYJTyHq_iKxU2bZ1CI92-kuZq3a5lr5Zg").unwrap_err(),
IdParseError::MissingLeadingSigil
);
}
#[test]
fn invalid_event_id_host() {
assert_eq!(
<&EventId>::try_from("$39hvsi03hlne:/").unwrap_err(),
IdParseError::InvalidServerName
);
}
#[test]
fn invalid_event_id_port() {
assert_eq!(
<&EventId>::try_from("$39hvsi03hlne:example.com:notaport").unwrap_err(),
IdParseError::InvalidServerName
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/device_id.rs | crates/core/src/identifiers/device_id.rs | use diesel::expression::AsExpression;
use super::generate_localpart;
use crate::macros::IdDst;
use crate::{IdParseError, KeyName};
/// A Matrix key ID.
///
/// Device identifiers in Matrix are completely opaque character sequences. This
/// type is provided simply for its semantic value.
///
/// # Example
///
/// ```
/// use palpo_core::{DeviceId, OwnedDeviceId, device_id};
///
/// let random_id = DeviceId::new();
/// assert_eq!(random_id.as_str().len(), 10);
///
/// let static_id = device_id!("01234567");
/// assert_eq!(static_id.as_str(), "01234567");
///
/// let ref_id: &DeviceId = "abcdefghi".into();
/// assert_eq!(ref_id.as_str(), "abcdefghi");
///
/// let owned_id: OwnedDeviceId = "ijklmnop".into();
/// assert_eq!(owned_id.as_str(), "ijklmnop");
/// ```
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
pub struct DeviceId(str);
impl DeviceId {
/// Generates a random `DeviceId`, suitable for assignment to a new device.
#[allow(clippy::new_ret_no_self)]
pub fn new() -> OwnedDeviceId {
Self::from_borrowed(&generate_localpart(10)).to_owned()
}
}
impl KeyName for DeviceId {
fn validate(_s: &str) -> Result<(), IdParseError> {
Ok(())
}
}
impl KeyName for OwnedDeviceId {
fn validate(_s: &str) -> Result<(), IdParseError> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{DeviceId, OwnedDeviceId};
#[test]
fn generate_device_id() {
assert_eq!(DeviceId::new().as_str().len(), 10);
}
#[test]
fn create_device_id_from_str() {
let ref_id: &DeviceId = "abcdefgh".into();
assert_eq!(ref_id.as_str(), "abcdefgh");
}
#[test]
fn create_boxed_device_id_from_str() {
let box_id: OwnedDeviceId = "12345678".into();
assert_eq!(box_id.as_str(), "12345678");
}
#[test]
fn create_device_id_from_box() {
let box_str: Box<str> = "ijklmnop".into();
let device_id: OwnedDeviceId = box_str.into();
assert_eq!(device_id.as_str(), "ijklmnop");
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/crypto_algorithms.rs | crates/core/src/identifiers/crypto_algorithms.rs | //! Key algorithms used in Matrix spec.
use crate::macros::StringEnum;
use salvo::prelude::*;
use crate::PrivOwnedStr;
/// The basic key algorithms in the specification.
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
#[palpo_enum(rename_all = "snake_case")]
pub enum DeviceKeyAlgorithm {
/// The Ed25519 signature algorithm.
Ed25519,
/// The Curve25519 ECDH algorithm.
Curve25519,
/// The Curve25519 ECDH algorithm, but the key also contains signatures
SignedCurve25519,
#[doc(hidden)]
#[salvo(schema(value_type = String))]
_Custom(PrivOwnedStr),
}
/// The signing key algorithms defined in the Matrix spec.
#[derive(Clone, Hash, StringEnum)]
#[non_exhaustive]
#[palpo_enum(rename_all = "snake_case")]
pub enum SigningKeyAlgorithm {
/// The Ed25519 signature algorithm.
Ed25519,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// An encryption algorithm to be used to encrypt messages sent to a room.
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum EventEncryptionAlgorithm {
/// Olm version 1 using Curve25519, AES-256, and SHA-256.
#[palpo_enum(rename = "m.olm.v1.curve25519-aes-sha2")]
OlmV1Curve25519AesSha2,
/// Megolm version 1 using AES-256 and SHA-256.
#[palpo_enum(rename = "m.megolm.v1.aes-sha2")]
MegolmV1AesSha2,
#[doc(hidden)]
#[salvo(schema(skip))]
_Custom(PrivOwnedStr),
}
/// A key algorithm to be used to generate a key from a passphrase.
#[derive(ToSchema, Clone, StringEnum)]
#[non_exhaustive]
pub enum KeyDerivationAlgorithm {
/// PBKDF2
#[palpo_enum(rename = "m.pbkdf2")]
Pbkfd2,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
/// The algorithms for [one-time and fallback keys] defined in the Matrix spec.
///
/// [one-time and fallback keys]: https://spec.matrix.org/latest/client-server-api/#one-time-and-fallback-keys
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, StringEnum)]
#[non_exhaustive]
#[palpo_enum(rename_all = "snake_case")]
pub enum OneTimeKeyAlgorithm {
/// The Curve25519 ECDH algorithm, but the key also contains signatures.
SignedCurve25519,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
#[cfg(test)]
mod tests {
use super::{DeviceKeyAlgorithm, SigningKeyAlgorithm};
#[test]
fn parse_device_key_algorithm() {
assert_eq!(
DeviceKeyAlgorithm::from("ed25519"),
DeviceKeyAlgorithm::Ed25519
);
assert_eq!(
DeviceKeyAlgorithm::from("curve25519"),
DeviceKeyAlgorithm::Curve25519
);
assert_eq!(
DeviceKeyAlgorithm::from("signed_curve25519"),
DeviceKeyAlgorithm::SignedCurve25519
);
}
#[test]
fn parse_signing_key_algorithm() {
assert_eq!(
SigningKeyAlgorithm::from("ed25519"),
SigningKeyAlgorithm::Ed25519
);
}
#[test]
fn event_encryption_algorithm_serde() {
use serde_json::json;
use super::EventEncryptionAlgorithm;
use crate::serde::test::serde_json_eq;
serde_json_eq(
EventEncryptionAlgorithm::MegolmV1AesSha2,
json!("m.megolm.v1.aes-sha2"),
);
serde_json_eq(
EventEncryptionAlgorithm::OlmV1Curve25519AesSha2,
json!("m.olm.v1.curve25519-aes-sha2"),
);
serde_json_eq(
EventEncryptionAlgorithm::from("io.palpo.test"),
json!("io.palpo.test"),
);
}
#[test]
fn key_derivation_algorithm_serde() {
use serde_json::json;
use super::KeyDerivationAlgorithm;
use crate::serde::test::serde_json_eq;
serde_json_eq(KeyDerivationAlgorithm::Pbkfd2, json!("m.pbkdf2"));
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/key_id.rs | crates/core/src/identifiers/key_id.rs | use std::{
cmp::Ordering,
hash::{Hash, Hasher},
marker::PhantomData,
};
use super::{
Base64PublicKey, Base64PublicKeyOrDeviceId, DeviceId, DeviceKeyAlgorithm, KeyName,
OneTimeKeyAlgorithm, OneTimeKeyName, ServerSigningKeyVersion,
crypto_algorithms::SigningKeyAlgorithm,
};
use crate::macros::IdDst;
/// A key algorithm and key name delimited by a colon.
///
/// Examples of the use of this struct are [`DeviceKeyId`], which identifies a Ed25519 or Curve25519
/// [device key](https://spec.matrix.org/latest/client-server-api/#device-keys), and
/// [`CrossSigningKeyId`], which identifies a user's
/// [cross signing key](https://spec.matrix.org/latest/client-server-api/#cross-signing).
///
/// This format of identifier is often used in the `signatures` field of
/// [signed JSON](https://spec.matrix.org/latest/appendices/#signing-details)
/// where it is referred to as a "signing key identifier".
///
/// This struct is rarely used directly - instead you should expect to use one of the type aliases
/// that rely on it like [`CrossSigningKeyId`] or [`DeviceSigningKeyId`].
///
/// # Examples
///
/// To parse a colon-separated identifier:
///
/// ```
/// use palpo_core::DeviceKeyId;
///
/// let k = DeviceKeyId::parse("ed25519:1").unwrap();
/// assert_eq!(k.algorithm().as_str(), "ed25519");
/// assert_eq!(k.key_name(), "1");
/// ```
///
/// To construct a colon-separated identifier from its parts:
///
/// ```
/// use palpo_core::{DeviceKeyAlgorithm, DeviceKeyId};
///
/// let k = DeviceKeyId::from_parts(DeviceKeyAlgorithm::Curve25519, "MYDEVICE".into());
/// assert_eq!(k.as_str(), "curve25519:MYDEVICE");
/// ```
#[repr(transparent)]
#[derive(IdDst)]
#[palpo_id(validate = palpo_identifiers_validation::key_id::validate::<K>)]
pub struct KeyId<A: KeyAlgorithm, K: KeyName + ?Sized>(PhantomData<(A, K)>, str);
impl<A: KeyAlgorithm, K: KeyName + ?Sized> KeyId<A, K> {
/// Creates a new `KeyId` from an algorithm and key name.
pub fn from_parts(algorithm: A, key_name: &K) -> OwnedKeyId<A, K>
where
A: AsRef<str>,
K: AsRef<str>,
{
let algorithm = algorithm.as_ref();
let key_name = key_name.as_ref();
let mut res = String::with_capacity(algorithm.len() + 1 + key_name.len());
res.push_str(algorithm);
res.push(':');
res.push_str(key_name);
Self::from_borrowed(&res).to_owned()
}
/// Returns key algorithm of the key ID - the part that comes before the colon.
///
/// # Example
///
/// ```
/// use palpo_core::{DeviceKeyAlgorithm, DeviceKeyId};
///
/// let k = DeviceKeyId::parse("ed25519:1").unwrap();
/// assert_eq!(k.algorithm(), DeviceKeyAlgorithm::Ed25519);
/// ```
pub fn algorithm(&self) -> A {
A::from(&self.as_str()[..self.colon_idx()])
}
/// Returns the key name of the key ID - the part that comes after the colon.
///
/// # Example
///
/// ```
/// use palpo_core::{device_id, DeviceKeyId};
///
/// let k = DeviceKeyId::parse("ed25519:DEV1").unwrap();
/// assert_eq!(k.key_name(), device_id!("DEV1"));
/// ```
pub fn key_name<'a>(&'a self) -> &'a K
where
&'a K: TryFrom<&'a str>,
{
<&'a K>::try_from(&self.as_str()[(self.colon_idx() + 1)..])
.unwrap_or_else(|_| unreachable!())
}
fn colon_idx(&self) -> usize {
self.as_str().find(':').unwrap()
}
}
/// Algorithm + key name for signing keys.
pub type SigningKeyId<K> = KeyId<SigningKeyAlgorithm, K>;
/// Algorithm + key name for signing keys.
pub type OwnedSigningKeyId<K> = OwnedKeyId<SigningKeyAlgorithm, K>;
/// Algorithm + key name for homeserver signing keys.
pub type ServerSigningKeyId = SigningKeyId<ServerSigningKeyVersion>;
/// Algorithm + key name for homeserver signing keys.
pub type OwnedServerSigningKeyId = OwnedSigningKeyId<ServerSigningKeyVersion>;
/// Algorithm + key name for [device signing keys].
///
/// [device signing keys]: https://spec.matrix.org/latest/client-server-api/#device-keys
pub type DeviceSigningKeyId = SigningKeyId<DeviceId>;
/// Algorithm + key name for [device signing] keys.
///
/// [device signing keys]: https://spec.matrix.org/latest/client-server-api/#device-keys
pub type OwnedDeviceSigningKeyId = OwnedSigningKeyId<DeviceId>;
/// Algorithm + key name for [cross-signing] keys.
///
/// [cross-signing]: https://spec.matrix.org/latest/client-server-api/#cross-signing
pub type CrossSigningKeyId = SigningKeyId<Base64PublicKey>;
/// Algorithm + key name for [cross-signing] keys.
///
/// [cross-signing]: https://spec.matrix.org/latest/client-server-api/#cross-signing
pub type OwnedCrossSigningKeyId = OwnedSigningKeyId<Base64PublicKey>;
/// Algorithm + key name for [cross-signing] or [device signing] keys.
///
/// [cross-signing]: https://spec.matrix.org/latest/client-server-api/#cross-signing
/// [device signing]: https://spec.matrix.org/latest/client-server-api/#device-keys
pub type CrossSigningOrDeviceSigningKeyId = SigningKeyId<Base64PublicKeyOrDeviceId>;
/// Algorithm + key name for [cross-signing] or [device signing] keys.
///
/// [cross-signing]: https://spec.matrix.org/latest/client-server-api/#cross-signing
/// [device signing]: https://spec.matrix.org/latest/client-server-api/#device-keys
pub type OwnedCrossSigningOrDeviceSigningKeyId = OwnedSigningKeyId<Base64PublicKeyOrDeviceId>;
/// Algorithm + key name for [device keys].
///
/// [device keys]: https://spec.matrix.org/latest/client-server-api/#device-keys
pub type DeviceKeyId = KeyId<DeviceKeyAlgorithm, DeviceId>;
/// Algorithm + key name for [device keys].
///
/// [device keys]: https://spec.matrix.org/latest/client-server-api/#device-keys
pub type OwnedDeviceKeyId = OwnedKeyId<DeviceKeyAlgorithm, DeviceId>;
/// Algorithm + key name for [one-time and fallback keys].
///
/// [one-time and fallback keys]: https://spec.matrix.org/latest/client-server-api/#one-time-and-fallback-keys
pub type OneTimeKeyId = KeyId<OneTimeKeyAlgorithm, OneTimeKeyName>;
/// Algorithm + key name for [one-time and fallback keys].
///
/// [one-time and fallback keys]: https://spec.matrix.org/latest/client-server-api/#one-time-and-fallback-keys
pub type OwnedOneTimeKeyId = OwnedKeyId<OneTimeKeyAlgorithm, OneTimeKeyName>;
// The following impls are usually derived using the std macros.
// They are implemented manually here to avoid unnecessary bounds.
impl<A: KeyAlgorithm, K: KeyName + ?Sized> PartialEq for KeyId<A, K> {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl<A: KeyAlgorithm, K: KeyName + ?Sized> Eq for KeyId<A, K> {}
impl<A: KeyAlgorithm, K: KeyName + ?Sized> PartialOrd for KeyId<A, K> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<A: KeyAlgorithm, K: KeyName + ?Sized> Ord for KeyId<A, K> {
fn cmp(&self, other: &Self) -> Ordering {
Ord::cmp(self.as_str(), other.as_str())
}
}
impl<A: KeyAlgorithm, K: KeyName + ?Sized> Hash for KeyId<A, K> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
/// The algorithm of a key.
pub trait KeyAlgorithm: for<'a> From<&'a str> + AsRef<str> {}
impl KeyAlgorithm for SigningKeyAlgorithm {}
impl KeyAlgorithm for DeviceKeyAlgorithm {}
impl KeyAlgorithm for OneTimeKeyAlgorithm {}
/// An opaque identifier type to use with [`KeyId`].
///
/// This type has no semantic value and no validation is done. It is meant to be able to use the
/// [`KeyId`] API without validating the key name.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
pub struct AnyKeyName(str);
impl KeyName for AnyKeyName {
fn validate(_s: &str) -> Result<(), crate::IdParseError> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use assert_matches2::assert_matches;
use palpo_identifiers_validation::Error;
use super::DeviceKeyId;
#[test]
fn algorithm_and_key_name_are_correctly_extracted() {
let key_id = DeviceKeyId::parse("ed25519:MYDEVICE").expect("Should parse correctly");
assert_eq!(key_id.algorithm().as_str(), "ed25519");
assert_eq!(key_id.key_name(), "MYDEVICE");
}
#[test]
fn empty_key_name_is_correctly_extracted() {
let key_id = DeviceKeyId::parse("ed25519:").expect("Should parse correctly");
assert_eq!(key_id.algorithm().as_str(), "ed25519");
assert_eq!(key_id.key_name(), "");
}
#[test]
fn missing_colon_fails_to_parse() {
let error = DeviceKeyId::parse("ed25519_MYDEVICE").expect_err("Should fail to parse");
assert_matches!(error, Error::MissingColon);
}
#[test]
fn empty_algorithm_fails_to_parse() {
let error = DeviceKeyId::parse(":MYDEVICE").expect_err("Should fail to parse");
// Weirdly, this also reports MissingColon
assert_matches!(error, Error::MissingColon);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/voip_id.rs | crates/core/src/identifiers/voip_id.rs | //! VoIP identifier.
use crate::macros::IdDst;
use diesel::expression::AsExpression;
/// A VoIP identifier.
///
/// VoIP IDs in Matrix are opaque strings. This type is provided simply for its
/// semantic value.
///
/// You can create one from a string (using `VoipId::parse()`) but the
/// recommended way is to use `VoipId::new()` to generate a random one. If that
/// function is not available for you, you need to activate this crate's `rand`
/// Cargo feature.
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst, AsExpression)]
#[diesel(not_sized, sql_type = diesel::sql_types::Text)]
pub struct VoipId(str);
impl VoipId {
/// Creates a random VoIP identifier.
///
/// This will currently be a UUID without hyphens, but no guarantees are
/// made about the structure of client secrets generated from this
/// function.
#[allow(clippy::new_ret_no_self)]
pub fn new() -> OwnedVoipId {
let id = uuid::Uuid::new_v4();
VoipId::from_borrowed(&id.simple().to_string()).to_owned()
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/base64_public_key_or_device_id.rs | crates/core/src/identifiers/base64_public_key_or_device_id.rs | use palpo_core_macros::IdDst;
use super::{
Base64PublicKey, DeviceId, IdParseError, KeyName, OwnedBase64PublicKey, OwnedDeviceId,
};
/// A Matrix ID that can be either a [`DeviceId`] or a [`Base64PublicKey`].
///
/// Device identifiers in Matrix are completely opaque character sequences and cross-signing keys
/// are identified by their base64-encoded public key. This type is provided simply for its semantic
/// value.
///
/// It is not recommended to construct this type directly, it should instead be converted from a
/// [`DeviceId`] or a [`Base64PublicKey`].
///
/// # Example
///
/// ```
/// use palpo_core::{Base64PublicKeyOrDeviceId, OwnedBase64PublicKeyOrDeviceId};
///
/// let ref_id: &Base64PublicKeyOrDeviceId = "abcdefghi".into();
/// assert_eq!(ref_id.as_str(), "abcdefghi");
///
/// let owned_id: OwnedBase64PublicKeyOrDeviceId = "ijklmnop".into();
/// assert_eq!(owned_id.as_str(), "ijklmnop");
/// ```
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
pub struct Base64PublicKeyOrDeviceId(str);
impl KeyName for Base64PublicKeyOrDeviceId {
fn validate(_s: &str) -> Result<(), IdParseError> {
Ok(())
}
}
impl KeyName for OwnedBase64PublicKeyOrDeviceId {
fn validate(_s: &str) -> Result<(), IdParseError> {
Ok(())
}
}
impl<'a> From<&'a DeviceId> for &'a Base64PublicKeyOrDeviceId {
fn from(value: &'a DeviceId) -> Self {
Self::from(value.as_str())
}
}
impl From<OwnedDeviceId> for OwnedBase64PublicKeyOrDeviceId {
fn from(value: OwnedDeviceId) -> Self {
Self::from(value.as_str())
}
}
impl<'a> From<&'a Base64PublicKey> for &'a Base64PublicKeyOrDeviceId {
fn from(value: &'a Base64PublicKey) -> Self {
Self::from(value.as_str())
}
}
impl From<OwnedBase64PublicKey> for OwnedBase64PublicKeyOrDeviceId {
fn from(value: OwnedBase64PublicKey) -> Self {
Self::from(value.as_str())
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/room_version_id.rs | crates/core/src/identifiers/room_version_id.rs | //! Matrix room version identifiers.
use std::{cmp::Ordering, str::FromStr};
use salvo::oapi::{Components, RefOr, Schema, ToSchema};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::IdParseError;
use crate::macros::DisplayAsRefStr;
use crate::room_version_rules::RoomVersionRules;
/// A Matrix [room version] ID.
///
/// A `RoomVersionId` can be or converted or deserialized from a string slice,
/// and can be converted or serialized back into a string as needed.
///
/// ```
/// # use palpo_core::RoomVersionId;
/// assert_eq!(RoomVersionId::try_from("1").unwrap().as_str(), "1");
/// ```
///
/// Any string consisting of at minimum 1, at maximum 32 unicode codepoints is a
/// room version ID. Custom room versions or ones that were introduced into the
/// specification after this code was written are represented by a hidden enum
/// variant. You can still construct them the same, and check for them using one
/// of `RoomVersionId`s `PartialEq` implementations or through `.as_str()`.
///
/// [room version]: https://spec.matrix.org/latest/rooms/
#[derive(Clone, Debug, PartialEq, Eq, Hash, DisplayAsRefStr)]
pub enum RoomVersionId {
/// A version 1 room.
V1,
/// A version 2 room.
V2,
/// A version 3 room.
V3,
/// A version 4 room.
V4,
/// A version 5 room.
V5,
/// A version 6 room.
V6,
/// A version 7 room.
V7,
/// A version 8 room.
V8,
/// A version 9 room.
V9,
/// A version 10 room.
V10,
/// A version 11 room.
V11,
/// A version 12 room.
V12,
/// `org.matrix.msc2870` ([MSC2870]).
///
/// [MSC2870]: https://github.com/matrix-org/matrix-spec-proposals/pull/2870
#[cfg(feature = "unstable-msc2870")]
MSC2870,
#[doc(hidden)]
_Custom(CustomRoomVersion),
}
impl RoomVersionId {
/// Creates a string slice from this `RoomVersionId`.
pub fn as_str(&self) -> &str {
// FIXME: Add support for non-`str`-deref'ing types for fallback to AsRefStr
// derive and implement this function in terms of `AsRef<str>`
match &self {
Self::V1 => "1",
Self::V2 => "2",
Self::V3 => "3",
Self::V4 => "4",
Self::V5 => "5",
Self::V6 => "6",
Self::V7 => "7",
Self::V8 => "8",
Self::V9 => "9",
Self::V10 => "10",
Self::V11 => "11",
Self::V12 => "12",
#[cfg(feature = "unstable-msc2870")]
Self::MSC2870 => "org.matrix.msc2870",
Self::_Custom(version) => version.as_str(),
}
}
/// Creates a byte slice from this `RoomVersionId`.
pub fn as_bytes(&self) -> &[u8] {
self.as_str().as_bytes()
}
/// Get the [`RoomVersionRules`] for this `RoomVersionId`, if it matches a supported room
/// version.
///
/// All known variants are guaranteed to return `Some(_)`.
pub fn rules(&self) -> Option<RoomVersionRules> {
Some(match self {
Self::V1 => RoomVersionRules::V1,
Self::V2 => RoomVersionRules::V2,
Self::V3 => RoomVersionRules::V3,
Self::V4 => RoomVersionRules::V4,
Self::V5 => RoomVersionRules::V5,
Self::V6 => RoomVersionRules::V6,
Self::V7 => RoomVersionRules::V7,
Self::V8 => RoomVersionRules::V8,
Self::V9 => RoomVersionRules::V9,
Self::V10 => RoomVersionRules::V10,
Self::V11 => RoomVersionRules::V11,
Self::V12 => RoomVersionRules::V12,
#[cfg(feature = "unstable-msc2870")]
Self::MSC2870 => RoomVersionRules::MSC2870,
Self::_Custom(_) => return None,
})
}
}
impl From<RoomVersionId> for String {
fn from(id: RoomVersionId) -> Self {
match id {
RoomVersionId::_Custom(version) => version.into(),
id => id.as_str().to_owned(),
}
}
}
impl AsRef<str> for RoomVersionId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<[u8]> for RoomVersionId {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl PartialOrd for RoomVersionId {
/// Compare the two given room version IDs by comparing their string
/// representations.
///
/// Please be aware that room version IDs don't have a defined ordering in
/// the Matrix specification. This implementation only exists to be able
/// to use `RoomVersionId`s or types containing `RoomVersionId`s as
/// `BTreeMap` keys.
fn partial_cmp(&self, other: &RoomVersionId) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for RoomVersionId {
/// Compare the two given room version IDs by comparing their string
/// representations.
///
/// Please be aware that room version IDs don't have a defined ordering in
/// the Matrix specification. This implementation only exists to be able
/// to use `RoomVersionId`s or types containing `RoomVersionId`s as
/// `BTreeMap` keys.
fn cmp(&self, other: &Self) -> Ordering {
self.as_str().cmp(other.as_str())
}
}
impl Serialize for RoomVersionId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for RoomVersionId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
super::deserialize_id(deserializer, "a Matrix room version ID as a string")
}
}
impl ToSchema for RoomVersionId {
fn to_schema(components: &mut Components) -> RefOr<Schema> {
<String>::to_schema(components)
}
}
/// Attempts to create a new Matrix room version ID from a string
/// representation.
fn try_from<S>(room_version_id: S) -> Result<RoomVersionId, IdParseError>
where
S: AsRef<str> + Into<Box<str>>,
{
let version = match room_version_id.as_ref() {
"1" => RoomVersionId::V1,
"2" => RoomVersionId::V2,
"3" => RoomVersionId::V3,
"4" => RoomVersionId::V4,
"5" => RoomVersionId::V5,
"6" => RoomVersionId::V6,
"7" => RoomVersionId::V7,
"8" => RoomVersionId::V8,
"9" => RoomVersionId::V9,
"10" => RoomVersionId::V10,
"11" => RoomVersionId::V11,
"12" => RoomVersionId::V12,
custom => {
palpo_identifiers_validation::room_version_id::validate(custom)?;
RoomVersionId::_Custom(CustomRoomVersion(room_version_id.into()))
}
};
Ok(version)
}
impl FromStr for RoomVersionId {
type Err = IdParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
try_from(s)
}
}
impl TryFrom<&str> for RoomVersionId {
type Error = IdParseError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
try_from(s)
}
}
impl TryFrom<String> for RoomVersionId {
type Error = IdParseError;
fn try_from(s: String) -> Result<Self, Self::Error> {
try_from(s)
}
}
impl PartialEq<&str> for RoomVersionId {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl PartialEq<RoomVersionId> for &str {
fn eq(&self, other: &RoomVersionId) -> bool {
*self == other.as_str()
}
}
impl PartialEq<String> for RoomVersionId {
fn eq(&self, other: &String) -> bool {
self.as_str() == other
}
}
impl PartialEq<RoomVersionId> for String {
fn eq(&self, other: &RoomVersionId) -> bool {
self == other.as_str()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[doc(hidden)]
#[allow(unknown_lints, unnameable_types)]
pub struct CustomRoomVersion(Box<str>);
#[doc(hidden)]
impl CustomRoomVersion {
/// Creates a string slice from this `CustomRoomVersion`
pub fn as_str(&self) -> &str {
&self.0
}
}
#[doc(hidden)]
impl From<CustomRoomVersion> for String {
fn from(v: CustomRoomVersion) -> Self {
v.0.into()
}
}
#[doc(hidden)]
impl AsRef<str> for CustomRoomVersion {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[cfg(test)]
mod tests {
use super::RoomVersionId;
use crate::IdParseError;
#[test]
fn valid_version_1_room_version_id() {
assert_eq!(
RoomVersionId::try_from("1")
.expect("Failed to create RoomVersionId.")
.as_str(),
"1"
);
}
#[test]
fn valid_version_2_room_version_id() {
assert_eq!(
RoomVersionId::try_from("2")
.expect("Failed to create RoomVersionId.")
.as_str(),
"2"
);
}
#[test]
fn valid_version_3_room_version_id() {
assert_eq!(
RoomVersionId::try_from("3")
.expect("Failed to create RoomVersionId.")
.as_str(),
"3"
);
}
#[test]
fn valid_version_4_room_version_id() {
assert_eq!(
RoomVersionId::try_from("4")
.expect("Failed to create RoomVersionId.")
.as_str(),
"4"
);
}
#[test]
fn valid_version_5_room_version_id() {
assert_eq!(
RoomVersionId::try_from("5")
.expect("Failed to create RoomVersionId.")
.as_str(),
"5"
);
}
#[test]
fn valid_version_6_room_version_id() {
assert_eq!(
RoomVersionId::try_from("6")
.expect("Failed to create RoomVersionId.")
.as_str(),
"6"
);
}
#[test]
fn valid_custom_room_version_id() {
assert_eq!(
RoomVersionId::try_from("io.palpo.1")
.expect("Failed to create RoomVersionId.")
.as_str(),
"io.palpo.1"
);
}
#[test]
fn empty_room_version_id() {
assert_eq!(RoomVersionId::try_from(""), Err(IdParseError::Empty));
}
#[test]
fn over_max_code_point_room_version_id() {
assert_eq!(
RoomVersionId::try_from("0123456789012345678901234567890123456789"),
Err(IdParseError::MaximumLengthExceeded)
);
}
#[test]
fn serialize_official_room_id() {
assert_eq!(
serde_json::to_string(
&RoomVersionId::try_from("1").expect("Failed to create RoomVersionId.")
)
.expect("Failed to convert RoomVersionId to JSON."),
r#""1""#
);
}
#[test]
fn deserialize_official_room_id() {
let deserialized = serde_json::from_str::<RoomVersionId>(r#""1""#)
.expect("Failed to convert RoomVersionId to JSON.");
assert_eq!(deserialized, RoomVersionId::V1);
assert_eq!(
deserialized,
RoomVersionId::try_from("1").expect("Failed to create RoomVersionId.")
);
}
#[test]
fn serialize_custom_room_id() {
assert_eq!(
serde_json::to_string(
&RoomVersionId::try_from("io.palpo.1").expect("Failed to create RoomVersionId.")
)
.expect("Failed to convert RoomVersionId to JSON."),
r#""io.palpo.1""#
);
}
#[test]
fn deserialize_custom_room_id() {
let deserialized = serde_json::from_str::<RoomVersionId>(r#""io.palpo.1""#)
.expect("Failed to convert RoomVersionId to JSON.");
assert_eq!(
deserialized,
RoomVersionId::try_from("io.palpo.1").expect("Failed to create RoomVersionId.")
);
}
#[test]
fn custom_room_id_invalid_character() {
assert!(serde_json::from_str::<RoomVersionId>(r#""io_palpo_1""#).is_err());
assert!(serde_json::from_str::<RoomVersionId>(r#""=""#).is_err());
assert!(serde_json::from_str::<RoomVersionId>(r#""/""#).is_err());
assert!(serde_json::from_str::<RoomVersionId>(r#"".""#).is_ok());
assert!(serde_json::from_str::<RoomVersionId>(r#""-""#).is_ok());
assert_eq!(
RoomVersionId::try_from("io_palpo_1").unwrap_err(),
IdParseError::InvalidCharacters
);
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identifiers/mxc_uri.rs | crates/core/src/identifiers/mxc_uri.rs | //! A URI that should be a Matrix-spec compliant [MXC URI].
//!
//! [MXC URI]: https://spec.matrix.org/latest/client-server-api/#matrix-content-mxc-uris
use std::{fmt, num::NonZeroU8};
use crate::macros::IdDst;
use palpo_identifiers_validation::{error::MxcUriError, mxc_uri::validate};
use serde::{Serialize, Serializer};
use super::ServerName;
type Result<T, E = MxcUriError> = std::result::Result<T, E>;
/// A URI that should be a Matrix-spec compliant [MXC URI].
///
/// [MXC URI]: https://spec.matrix.org/latest/client-server-api/#matrix-content-mxc-uris
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdDst)]
pub struct MxcUri(str);
impl MxcUri {
/// If this is a valid MXC URI, returns the media ID.
pub fn media_id(&self) -> Result<&str> {
self.parts().map(|mxc| mxc.media_id)
}
/// If this is a valid MXC URI, returns the server name.
pub fn server_name(&self) -> Result<&ServerName> {
self.parts().map(|mxc| mxc.server_name)
}
/// If this is a valid MXC URI, returns a `(server_name, media_id)` tuple,
/// else it returns the error.
pub fn parts(&self) -> Result<Mxc<'_>> {
self.extract_slash_idx().map(|idx| Mxc::<'_> {
server_name: ServerName::from_borrowed(&self.as_str()[6..idx.get() as usize]),
media_id: &self.as_str()[idx.get() as usize + 1..],
})
}
/// Validates the URI and returns an error if it failed.
pub fn validate(&self) -> Result<()> {
self.extract_slash_idx().map(|_| ())
}
/// Convenience method for `.validate().is_ok()`.
#[inline(always)]
pub fn is_valid(&self) -> bool {
self.validate().is_ok()
}
// convenience method for calling validate(self)
#[inline(always)]
fn extract_slash_idx(&self) -> Result<NonZeroU8> {
validate(self.as_str())
}
}
/// Structured MXC URI which may reference strings from separate sources without
/// serialization
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(clippy::exhaustive_structs)]
pub struct Mxc<'a> {
/// ServerName part of the MXC URI
pub server_name: &'a ServerName,
/// MediaId part of the MXC URI
pub media_id: &'a str,
}
impl fmt::Display for Mxc<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "mxc://{}/{}", self.server_name, self.media_id)
}
}
impl<'a> TryFrom<&'a MxcUri> for Mxc<'a> {
type Error = MxcUriError;
fn try_from(s: &'a MxcUri) -> Result<Self, Self::Error> {
s.parts()
}
}
impl<'a> TryFrom<&'a str> for Mxc<'a> {
type Error = MxcUriError;
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
let s: &MxcUri = s.into();
s.try_into()
}
}
impl<'a> TryFrom<&'a OwnedMxcUri> for Mxc<'a> {
type Error = MxcUriError;
fn try_from(s: &'a OwnedMxcUri) -> Result<Self, Self::Error> {
let s: &MxcUri = s.as_ref();
s.try_into()
}
}
impl Serialize for Mxc<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.to_string().as_str())
}
}
#[cfg(test)]
mod tests {
use palpo_identifiers_validation::error::MxcUriError;
use super::MxcUri;
// #[test]
// fn parse_mxc_uri() {
// let mxc = Box::<MxcUri>::from("mxc://127.0.0.1/asd32asdfasdsd");
// assert!(mxc.is_valid());
// assert_eq!(
// mxc.parts(),
// Ok((
// "127.0.0.1".try_into().expect("Failed to create ServerName"),
// "asd32asdfasdsd"
// ))
// );
// }
#[test]
fn parse_mxc_uri_without_media_id() {
let mxc = Box::<MxcUri>::from("mxc://127.0.0.1");
assert!(!mxc.is_valid());
assert_eq!(mxc.parts(), Err(MxcUriError::MissingSlash));
}
#[test]
fn parse_mxc_uri_without_protocol() {
assert!(!Box::<MxcUri>::from("127.0.0.1/asd32asdfasdsd").is_valid());
}
#[test]
fn serialize_mxc_uri() {
assert_eq!(
serde_json::to_string(&Box::<MxcUri>::from("mxc://server/1234id"))
.expect("Failed to convert MxcUri to JSON."),
r#""mxc://server/1234id""#
);
}
// #[test]
// fn deserialize_mxc_uri() {
// let mxc =
// serde_json::from_str::<OwnedMxcUri>(r#""mxc://server/1234id""#).expect("Failed to convert JSON to MxcUri");
// assert_eq!(mxc.as_str(), "mxc://server/1234id");
// assert!(mxc.is_valid());
// assert_eq!(
// mxc.parts(),
// Ok(("server".try_into().expect("Failed to create ServerName"), "1234id"))
// );
// }
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/json_string.rs | crates/core/src/serde/json_string.rs | //! De-/serialization functions to and from json strings, allows the type to be
//! used as a query string.
use serde::{
de::{DeserializeOwned, Deserializer, Error as _},
ser::{Error as _, Serialize, Serializer},
};
/// Serialize the given value as a JSON string.
pub fn serialize<T, S>(value: T, serializer: S) -> Result<S::Ok, S::Error>
where
T: Serialize,
S: Serializer,
{
let json = serde_json::to_string(&value).map_err(S::Error::custom)?;
serializer.serialize_str(&json)
}
/// Read a string from the input and deserialize it as a `T`.
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: DeserializeOwned,
D: Deserializer<'de>,
{
let s = super::deserialize_cow_str(deserializer)?;
serde_json::from_str(&s).map_err(D::Error::custom)
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/test.rs | crates/core/src/serde/test.rs | //! Helpers for tests
use std::fmt::Debug;
use serde::{Serialize, de::DeserializeOwned};
/// Assert that serialization of `de` results in `se` and deserialization of
/// `se` results in `de`.
pub fn serde_json_eq<T>(de: T, se: serde_json::Value)
where
T: Clone + Debug + PartialEq + Serialize + DeserializeOwned,
{
assert_eq!(se, serde_json::to_value(de.clone()).unwrap());
assert_eq!(de, serde_json::from_value(se).unwrap());
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/raw_json.rs | crates/core/src/serde/raw_json.rs | use std::{
clone::Clone,
fmt::{self, Debug},
marker::PhantomData,
mem,
};
use salvo::{
oapi::{Components, RefOr, Schema},
prelude::*,
};
use serde::{
de::{self, Deserialize, DeserializeSeed, Deserializer, IgnoredAny, MapAccess, Visitor},
ser::{Serialize, Serializer},
};
use serde_json::value::to_raw_value as to_raw_json_value;
use crate::serde::{JsonValue, RawJsonValue};
/// A wrapper around `Box<RawValue>`, to be used in place of any type in the
/// Matrix endpoint definition to allow request and response types to contain
/// that said type represented by the generic argument `Ev`.
///
/// Palpo offers the `RawJson` wrapper to enable passing around JSON text that
/// is only partially validated. This is useful when a client receives events
/// that do not follow the spec perfectly or a server needs to generate
/// reference hashes with the original canonical JSON string. All event structs
/// and enums implement `Serialize` / `Deserialize`, `Raw` should be used
/// to pass around events in a lossless way.
///
/// ```no_run
/// # use serde::Deserialize;
/// # use palpo_core::serde::RawJson;
/// # #[derive(Deserialize)]
/// # struct AnyTimelineEvent;
///
/// let json = r#"{ "type": "imagine a full event", "content": {...} }"#;
///
/// let deser = serde_json::from_str::<RawJson<AnyTimelineEvent>>(json)
/// .unwrap() // the first Result from serde_json::from_str, will not fail
/// .deserialize() // deserialize to the inner type
/// .unwrap(); // finally get to the AnyTimelineEvent
/// ```
#[repr(transparent)]
pub struct RawJson<T> {
inner: Box<RawJsonValue>,
_ev: PhantomData<T>,
}
impl<T> ToSchema for RawJson<T>
where
T: ToSchema + 'static,
{
fn to_schema(components: &mut Components) -> RefOr<Schema> {
T::to_schema(components)
}
}
impl<T> RawJson<T> {
/// Create a `Raw` by serializing the given `T`.
///
/// Shorthand for
/// `serde_json::value::to_raw_value(val).map(RawJson::from_json)`, but
/// specialized to `T`.
///
/// # Errors
///
/// Fails if `T`s [`Serialize`] implementation fails.
pub fn new(val: &T) -> serde_json::Result<Self>
where
T: Serialize,
{
to_raw_json_value(val).map(Self::from_raw_value)
}
/// Create a `Raw` from a boxed `RawValue`.
pub fn from_value(val: &JsonValue) -> serde_json::Result<Self> {
to_raw_json_value(val).map(Self::from_raw_value)
}
pub fn from_raw_value(inner: Box<RawJsonValue>) -> Self {
Self {
inner,
_ev: PhantomData,
}
}
/// Convert an owned `String` of JSON data to `RawJson<T>`.
///
/// This function is equivalent to `serde_json::from_str::<RawJson<T>>`
/// except that an allocation and copy is avoided if both of the
/// following are true:
///
/// * the input has no leading or trailing whitespace, and
/// * the input has capacity equal to its length.
pub fn from_string(json: String) -> serde_json::Result<Self> {
RawJsonValue::from_string(json).map(Self::from_raw_value)
}
/// Access the underlying json value.
pub fn inner(&self) -> &RawJsonValue {
&self.inner
}
pub fn as_str(&self) -> &str {
self.inner.get()
}
/// Convert `self` into the underlying json value.
pub fn into_inner(self) -> Box<RawJsonValue> {
self.inner
}
/// Try to access a given field inside this `Raw`, assuming it contains an
/// object.
///
/// Returns `Err(_)` when the contained value is not an object, or the field
/// exists but is fails to deserialize to the expected type.
///
/// Returns `Ok(None)` when the field doesn't exist or is `null`.
///
/// # Example
///
/// ```no_run
/// # type CustomMatrixEvent = ();
/// # fn foo() -> serde_json::Result<()> {
/// # let raw_event: palpo_core::serde::RawJson<()> = todo!();
/// if raw_event.get_field::<String>("type")?.as_deref() == Some("org.custom.matrix.event") {
/// let event = raw_event.deserialize_as::<CustomMatrixEvent>()?;
/// // ...
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_field<'a, U>(&'a self, field_name: &str) -> serde_json::Result<Option<U>>
where
U: Deserialize<'a>,
{
struct FieldVisitor<'b>(&'b str);
impl<'b, 'de> Visitor<'de> for FieldVisitor<'b> {
type Value = bool;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "`{}`", self.0)
}
fn visit_str<E>(self, value: &str) -> Result<bool, E>
where
E: de::Error,
{
Ok(value == self.0)
}
}
struct Field<'b>(&'b str);
impl<'b, 'de> DeserializeSeed<'de> for Field<'b> {
type Value = bool;
fn deserialize<D>(self, deserializer: D) -> Result<bool, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_identifier(FieldVisitor(self.0))
}
}
struct SingleFieldVisitor<'b, T> {
field_name: &'b str,
_phantom: PhantomData<T>,
}
impl<'b, T> SingleFieldVisitor<'b, T> {
fn new(field_name: &'b str) -> Self {
Self {
field_name,
_phantom: PhantomData,
}
}
}
impl<'b, 'de, T> Visitor<'de> for SingleFieldVisitor<'b, T>
where
T: Deserialize<'de>,
{
type Value = Option<T>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a string")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut res = None;
while let Some(is_right_field) = map.next_key_seed(Field(self.field_name))? {
if is_right_field {
res = Some(map.next_value()?);
} else {
map.next_value::<IgnoredAny>()?;
}
}
Ok(res)
}
}
let mut deserializer = serde_json::Deserializer::from_str(self.inner().get());
deserializer.deserialize_map(SingleFieldVisitor::new(field_name))
}
/// Try to deserialize the JSON as the expected type.
pub fn deserialize<'a>(&'a self) -> serde_json::Result<T>
where
T: Deserialize<'a>,
{
serde_json::from_str(self.inner.get())
}
/// Try to deserialize the JSON as a custom type.
pub fn deserialize_as<'a, U>(&'a self) -> serde_json::Result<U>
where
U: Deserialize<'a>,
{
serde_json::from_str(self.inner.get())
}
/// Turns `RawJson<T>` into `RawJson<U>` without changing the underlying
/// JSON.
///
/// This is useful for turning raw specific event types into raw event enum
/// types.
pub fn cast<U>(self) -> RawJson<U> {
RawJson::from_raw_value(self.into_inner())
}
/// Turns `&RawJson<T>` into `&RawJson<U>` without changing the underlying
/// JSON.
///
/// This is useful for turning raw specific event types into raw event enum
/// types.
pub fn cast_ref<U>(&self) -> &RawJson<U> {
unsafe { mem::transmute(self) }
}
}
impl<T> Clone for RawJson<T> {
fn clone(&self) -> Self {
Self::from_raw_value(self.inner.clone())
}
}
impl<T> Debug for RawJson<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use std::any::type_name;
f.debug_struct(&format!("RawJson::<{}>", type_name::<T>()))
.field("json", &self.inner)
.finish()
}
}
impl<'de, T> Deserialize<'de> for RawJson<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Box::<RawJsonValue>::deserialize(deserializer).map(Self::from_raw_value)
}
}
impl<T> Serialize for RawJson<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.inner.serialize(serializer)
}
}
/// Marker trait for restricting the types [`Raw::deserialize_as`], [`Raw::cast`] and
/// [`Raw::cast_ref`] can be called with.
///
/// Implementing this trait for a type `U` means that it is safe to cast from `U` to `T` because `T`
/// can be deserialized from the same JSON as `U`.
pub trait JsonCastable<T> {}
impl<T> JsonCastable<JsonValue> for T {}
#[cfg(test)]
mod tests {
use serde::Deserialize;
use serde_json::from_str as from_json_str;
use crate::serde::{RawJson, RawJsonValue};
#[test]
fn get_field() -> serde_json::Result<()> {
#[derive(Debug, PartialEq, Deserialize)]
struct A<'a> {
#[serde(borrow)]
b: Vec<&'a str>,
}
const OBJ: &str = r#"{ "a": { "b": [ "c"] }, "z": 5 }"#;
let raw: RawJson<()> = from_json_str(OBJ)?;
assert_eq!(raw.get_field::<u8>("z")?, Some(5));
assert_eq!(
raw.get_field::<&RawJsonValue>("a")?.unwrap().get(),
r#"{ "b": [ "c"] }"#
);
assert_eq!(raw.get_field::<A<'_>>("a")?, Some(A { b: vec!["c"] }));
assert_eq!(raw.get_field::<u8>("b")?, None);
raw.get_field::<u8>("a").unwrap_err();
Ok(())
}
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
palpo-im/palpo | https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/serde/single_element_seq.rs | crates/core/src/serde/single_element_seq.rs | //! De-/serialization functions to and from single element sequences.
use serde::{
de::{Deserialize, Deserializer},
ser::{Serialize, Serializer},
};
/// Serialize the given value as a list of just that value.
pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
T: Serialize,
S: Serializer,
{
[value].serialize(serializer)
}
/// Deserialize a list of one item and return that item.
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: Deserialize<'de>,
D: Deserializer<'de>,
{
<[_; 1]>::deserialize(deserializer).map(|[first]| first)
}
| rust | Apache-2.0 | 066b5b15ce094d4e9f6d28484cbc9cb8bd913e67 | 2026-01-04T20:22:21.242775Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.