feat(server): protocol v2 with signed handshake, secure voice relay, media broadcast and channel authorization
Revoke voice access on channel delete, kick and permission change, and acknowledge the sender's own chat messages.
This commit is contained in:
parent
bc5157046e
commit
3e7f5b22dc
44 changed files with 2825 additions and 386 deletions
|
|
@ -5,10 +5,7 @@ use tracing::{info, warn};
|
|||
|
||||
use crate::{
|
||||
domain::{channels, session},
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
net::{io, state::State},
|
||||
proto::{
|
||||
ChannelCreatePayload, ChannelDeletePayload, ChannelListItem, ChannelListPayload,
|
||||
ChannelStatePayload, PacketId, SessionCrypto, encode_packet, to_payload,
|
||||
|
|
@ -62,7 +59,12 @@ pub async fn handle_channel_create(
|
|||
req.channel_name.trim().to_string()
|
||||
};
|
||||
|
||||
if channel_id.is_empty() {
|
||||
if channel_id.is_empty()
|
||||
|| channel_id.len() > 128
|
||||
|| channel_name.chars().count() > 100
|
||||
|| channel_id.chars().any(char::is_control)
|
||||
|| channel_name.chars().any(char::is_control)
|
||||
{
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
|
|
@ -96,6 +98,13 @@ pub async fn handle_channel_create(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !super::may_manage(state, &sess.user_id, req.guild_id.as_deref()).await? {
|
||||
drop(access);
|
||||
super::denied(stream, seq, crypto).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let guild_id = req.guild_id.clone();
|
||||
|
||||
let created = channels::create(
|
||||
|
|
@ -107,10 +116,8 @@ pub async fn handle_channel_create(
|
|||
)
|
||||
.await;
|
||||
|
||||
// Persist to DB (best-effort, log and continue on failure).
|
||||
#[allow(clippy::collapsible_if)]
|
||||
if created {
|
||||
if let Err(e) = state
|
||||
if created
|
||||
&& let Err(error) = state
|
||||
.storage
|
||||
.create_channel(
|
||||
&channel_id,
|
||||
|
|
@ -119,11 +126,12 @@ pub async fn handle_channel_create(
|
|||
guild_id.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("failed to persist channel to storage: {e}");
|
||||
}
|
||||
{
|
||||
channels::delete(&state.channels, &channel_id).await;
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
drop(access);
|
||||
if !created {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
@ -165,22 +173,22 @@ pub async fn handle_channel_create(
|
|||
)
|
||||
.await?;
|
||||
|
||||
// Broadcast a ChannelCreate event to all other sessions so their sidebars update.
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(
|
||||
super::notify_guild(
|
||||
state,
|
||||
guild_id.as_deref(),
|
||||
Some(session_id),
|
||||
encode_packet(
|
||||
PacketId::ChannelCreate,
|
||||
0,
|
||||
&to_payload(&ChannelCreatePayload {
|
||||
channel_id: channel_id.clone(),
|
||||
channel_name: channel_name.clone(),
|
||||
kind: kind.as_str().into(),
|
||||
guild_id: req.guild_id.clone(),
|
||||
guild_id: guild_id.clone(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -217,15 +225,23 @@ pub async fn handle_channel_delete(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let existed = channels::delete(&state.channels, &req.channel_id).await;
|
||||
|
||||
// Remove from DB (best-effort).
|
||||
#[allow(clippy::collapsible_if)]
|
||||
if existed {
|
||||
if let Err(e) = state.storage.delete_channel(&req.channel_id).await {
|
||||
warn!("failed to remove channel from storage: {e}");
|
||||
}
|
||||
let access = state.access.write().await;
|
||||
let channel = channels::get_channel(&state.channels, &req.channel_id).await;
|
||||
if !super::may_manage(
|
||||
state,
|
||||
&sess.user_id,
|
||||
channel.as_ref().and_then(|c| c.guild_id.as_deref()),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
super::denied(stream, seq, crypto).await?;
|
||||
return Ok(());
|
||||
}
|
||||
state.storage.delete_channel(&req.channel_id).await?;
|
||||
super::revoke_channel(state, &req.channel_id).await;
|
||||
let existed = channels::delete(&state.channels, &req.channel_id).await;
|
||||
drop(access);
|
||||
|
||||
if !existed {
|
||||
io::send_encrypted(
|
||||
|
|
@ -247,19 +263,21 @@ pub async fn handle_channel_delete(
|
|||
req.channel_id, sess.nickname
|
||||
);
|
||||
|
||||
// Broadcast deletion to all sessions.
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(
|
||||
super::notify_guild(
|
||||
state,
|
||||
channel
|
||||
.as_ref()
|
||||
.and_then(|channel| channel.guild_id.as_deref()),
|
||||
None,
|
||||
encode_packet(
|
||||
PacketId::ChannelDelete,
|
||||
0,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: req.channel_id.clone(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -273,7 +291,10 @@ pub async fn handle_channel_list(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let _sess = session::get(&state.sessions, session_id).await;
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
let guilds = state.storage.list_user_guilds(&sess.user_id).await?;
|
||||
|
||||
// Decode optional guild_id filter from request.
|
||||
let filter_guild_id = if !payload.is_empty() {
|
||||
|
|
@ -286,6 +307,11 @@ pub async fn handle_channel_list(
|
|||
let channels = channels::list(&state.channels).await;
|
||||
let items: Vec<ChannelListItem> = channels
|
||||
.iter()
|
||||
.filter(|c| {
|
||||
c.guild_id
|
||||
.as_ref()
|
||||
.is_none_or(|guild| guilds.iter().any(|g| &g.id == guild))
|
||||
})
|
||||
.filter(|c| {
|
||||
filter_guild_id
|
||||
.as_ref()
|
||||
|
|
|
|||
|
|
@ -1,14 +1,11 @@
|
|||
use anyhow::Result;
|
||||
use prost::Message;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tracing::{info, warn};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
domain::{channels, session},
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
net::{io, state::State},
|
||||
proto::{ChannelEditPayload, PacketId, SessionCrypto, encode_packet, to_payload},
|
||||
};
|
||||
|
||||
|
|
@ -29,7 +26,12 @@ pub async fn handle_channel_edit(
|
|||
let channel_id = req.channel_id.trim().to_string();
|
||||
let channel_name = req.channel_name.trim().to_string();
|
||||
|
||||
if channel_id.is_empty() || channel_name.is_empty() {
|
||||
if channel_id.is_empty()
|
||||
|| channel_name.is_empty()
|
||||
|| channel_id.len() > 128
|
||||
|| channel_name.chars().count() > 100
|
||||
|| channel_name.chars().any(char::is_control)
|
||||
{
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
|
|
@ -44,8 +46,26 @@ pub async fn handle_channel_edit(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let access = state.access.write().await;
|
||||
let channel = channels::get_channel(&state.channels, &channel_id).await;
|
||||
if !super::may_manage(
|
||||
state,
|
||||
&sess.user_id,
|
||||
channel.as_ref().and_then(|c| c.guild_id.as_deref()),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
super::denied(stream, seq, crypto).await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.update_channel(&channel_id, &channel_name)
|
||||
.await?;
|
||||
let renamed = channels::rename(&state.channels, &channel_id, &channel_name).await;
|
||||
|
||||
drop(access);
|
||||
if !renamed {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
@ -61,24 +81,18 @@ pub async fn handle_channel_edit(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
if let Err(e) = state
|
||||
.storage
|
||||
.update_channel(&channel_id, &channel_name)
|
||||
.await
|
||||
{
|
||||
warn!("failed to update channel in storage: {e}");
|
||||
}
|
||||
|
||||
info!(
|
||||
"channel_edit: '{}' renamed to '{}' by {}",
|
||||
channel_id, channel_name, sess.nickname
|
||||
);
|
||||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.clone()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(
|
||||
super::notify_guild(
|
||||
state,
|
||||
channel
|
||||
.as_ref()
|
||||
.and_then(|channel| channel.guild_id.as_deref()),
|
||||
None,
|
||||
encode_packet(
|
||||
PacketId::ChannelEdit,
|
||||
0,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
|
|
@ -86,7 +100,8 @@ pub async fn handle_channel_edit(
|
|||
channel_name: channel_name.clone(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,4 @@
|
|||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tracing::info;
|
||||
|
||||
use super::{broadcast_leave, set_channel, set_voice_channel};
|
||||
use crate::{
|
||||
domain::{channels, session},
|
||||
net::{
|
||||
|
|
@ -15,11 +10,11 @@ use crate::{
|
|||
UserJoinPayload, encode_packet, to_payload,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{broadcast_leave, set_channel};
|
||||
|
||||
use anyhow::Result;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
const HISTORY_LIMIT: i64 = 50;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn join(
|
||||
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
|
|
@ -27,135 +22,224 @@ pub async fn join(
|
|||
channel_id: &str,
|
||||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
addr: SocketAddr,
|
||||
_addr: SocketAddr,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.read().await;
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
let prev_channel = sess.channel_id;
|
||||
|
||||
let ch = match channels::get_channel(&state.channels, channel_id).await {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::ChannelNotFound as u32,
|
||||
message: "not found".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
let Some(ch) = channels::get_channel(&state.channels, channel_id).await else {
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::ChannelNotFound as u32,
|
||||
message: "not found".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
};
|
||||
|
||||
// Validate the destination before changing membership or exposing its history.
|
||||
// Role assignments alone are insufficient: a kicked user can retain stale roles.
|
||||
if let Some(guild_id) = ch.guild_id.as_deref() {
|
||||
let is_member = state
|
||||
if let Some(guild) = &ch.guild_id
|
||||
&& !state
|
||||
.storage
|
||||
.list_user_guilds(&sess.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|guild| guild.id == guild_id);
|
||||
if !is_member {
|
||||
io::send_encrypted(
|
||||
.any(|g| g.id == *guild)
|
||||
{
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::PermissionDenied as u32,
|
||||
message: "guild membership required".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let is_voice = ch.kind == channels::ChannelKind::Voice;
|
||||
if is_voice && state.voice_member_tx.is_none() {
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::NodeUnavailable as u32,
|
||||
message: "voice requires the combined server process".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if is_voice && let Some(guild) = &ch.guild_id {
|
||||
let owner = state
|
||||
.storage
|
||||
.get_guild(guild)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == sess.user_id);
|
||||
let perms = state
|
||||
.storage
|
||||
.get_user_role_perms(guild, &sess.user_id)
|
||||
.await?;
|
||||
if !owner
|
||||
&& !crate::domain::permissions::Permissions::from_role_perms(&perms)
|
||||
.has(crate::domain::permissions::Permissions::VOICE_SPEAK)
|
||||
{
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::PermissionDenied as u32,
|
||||
message: "guild membership required".into(),
|
||||
message: "VOICE_SPEAK permission required".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
if prev_channel.as_deref() == Some(channel_id) {
|
||||
let previous = if is_voice {
|
||||
sess.voice_channel_id.clone()
|
||||
} else {
|
||||
sess.channel_id.clone()
|
||||
};
|
||||
if previous.as_deref() == Some(channel_id) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(prev) = prev_channel {
|
||||
channels::leave(&state.channels, &prev, session_id).await;
|
||||
broadcast_leave(state, &prev, session_id).await;
|
||||
if let Some(previous) = previous {
|
||||
channels::leave(&state.channels, &previous, session_id).await;
|
||||
broadcast_leave(state, &previous, session_id).await;
|
||||
if is_voice {
|
||||
state.media.revoke(state, session_id).await;
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
let _=tx.send(serde_json::json!({"type":"leave","session_id":session_id,"channel_id":previous,"user_id":sess.user_id}).to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
channels::join(&state.channels, channel_id, session_id).await;
|
||||
set_channel(state, session_id, Some(channel_id.into())).await;
|
||||
|
||||
if is_voice {
|
||||
set_voice_channel(state, session_id, Some(channel_id.into())).await;
|
||||
} else {
|
||||
set_channel(state, session_id, Some(channel_id.into())).await;
|
||||
}
|
||||
// Issue/revoke credentials while access mutations are serialized. Never hold this guard while writing to a client socket.
|
||||
let credentials = if is_voice {
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
use rand::Rng;
|
||||
let (route_id, c2s_key, s2c_key) = {
|
||||
let mut rng = rand::rng();
|
||||
let mut r = [0u8; 16];
|
||||
let mut c = [0u8; 32];
|
||||
let mut s = [0u8; 32];
|
||||
rng.fill_bytes(&mut r);
|
||||
rng.fill_bytes(&mut c);
|
||||
rng.fill_bytes(&mut s);
|
||||
(r, c, s)
|
||||
};
|
||||
let event = serde_json::json!({"type":"join","session_id":session_id,"channel_id":channel_id,"user_id":sess.user_id,"route_id":hex::encode(route_id),"c2s_key":hex::encode(c2s_key),"s2c_key":hex::encode(s2c_key)});
|
||||
if tx.send(event.to_string()).is_err() {
|
||||
channels::leave(&state.channels, channel_id, session_id).await;
|
||||
set_voice_channel(state, session_id, None).await;
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::NodeUnavailable as u32,
|
||||
message: "voice service unavailable".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Some(proto::VoiceSession {
|
||||
route_id: route_id.to_vec(),
|
||||
c2s_key: c2s_key.to_vec(),
|
||||
s2c_key: s2c_key.to_vec(),
|
||||
channel_id: channel_id.into(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut members = Vec::new();
|
||||
for sid in channels::members(&state.channels, channel_id).await {
|
||||
if let Some(s) = session::get(&state.sessions, &sid).await {
|
||||
members.push(MemberInfo {
|
||||
user_id: s.user_id.clone(),
|
||||
nickname: s.nickname.clone(),
|
||||
in_voice: ch.kind == channels::ChannelKind::Voice,
|
||||
user_id: s.user_id,
|
||||
nickname: s.nickname,
|
||||
in_voice: is_voice,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let sp = ChannelStatePayload {
|
||||
channel_id: ch.id.clone(),
|
||||
channel_name: ch.name.clone(),
|
||||
let message = UserJoinPayload {
|
||||
channel_id: channel_id.into(),
|
||||
user_id: sess.user_id,
|
||||
nickname: sess.nickname,
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.into()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::UserJoin, 0, &to_payload(&message)),
|
||||
});
|
||||
drop(guard);
|
||||
let payload = ChannelStatePayload {
|
||||
channel_id: ch.id,
|
||||
channel_name: ch.name,
|
||||
kind: ch.kind.as_str().into(),
|
||||
members,
|
||||
voice_endpoint: state.config.voice.bind.clone(),
|
||||
guild_id: ch.guild_id.clone(),
|
||||
guild_id: ch.guild_id,
|
||||
};
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::ChannelState,
|
||||
seq,
|
||||
&to_payload(&sp),
|
||||
&to_payload(&payload),
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let history = state.storage.get_history(channel_id, HISTORY_LIMIT).await?;
|
||||
if !history.is_empty() {
|
||||
let hp = ChatHistoryPayload {
|
||||
channel_id: channel_id.into(),
|
||||
messages: history,
|
||||
};
|
||||
io::send_encrypted(stream, PacketId::ChatHistory, seq, &to_payload(&hp), crypto).await?;
|
||||
if let Some(credentials) = credentials {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::VoiceSession,
|
||||
seq,
|
||||
&to_payload(&credentials),
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
if let Some(sess) = session::get(&state.sessions, session_id).await {
|
||||
let jp = UserJoinPayload {
|
||||
channel_id: channel_id.into(),
|
||||
user_id: sess.user_id.clone(),
|
||||
nickname: sess.nickname.clone(),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.into()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::UserJoin, 0, &to_payload(&jp)),
|
||||
});
|
||||
if !is_voice {
|
||||
let history = state.storage.get_history(channel_id, HISTORY_LIMIT).await?;
|
||||
if !history.is_empty() {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: Some(session_id.into()),
|
||||
data: encode_packet(
|
||||
PacketId::ChatHistory,
|
||||
0,
|
||||
&to_payload(&ChatHistoryPayload {
|
||||
channel_id: channel_id.into(),
|
||||
messages: history,
|
||||
}),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if ch.kind == channels::ChannelKind::Voice
|
||||
&& let Some(tx) = &state.voice_member_tx
|
||||
&& let Some(sess) = session::get(&state.sessions, session_id).await
|
||||
{
|
||||
let event = serde_json::json!({
|
||||
"type": "join",
|
||||
"channel_id": channel_id,
|
||||
"user_id": sess.user_id,
|
||||
"endpoint": format!("{}:{}", addr.ip(), addr.port()),
|
||||
});
|
||||
let _ = tx.send(event.to_string());
|
||||
}
|
||||
|
||||
info!("session {} joined {channel_id}", &session_id[..8]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
|
|
@ -143,3 +143,574 @@ async fn guild_member_can_switch_channels() {
|
|||
Some("private")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn text_navigation_preserves_voice_and_leaving_unrelated_channel_is_noop() {
|
||||
let (mut state, sid) = fixture().await;
|
||||
let (tx, mut rx) = tokio::sync::broadcast::channel(16);
|
||||
tokio::spawn(async move { while rx.recv().await.is_ok() {} });
|
||||
state.voice_member_tx = Some(tx);
|
||||
attempt_join(&state, &sid, "voice").await;
|
||||
let sess = session::get(&state.sessions, &sid).await.unwrap();
|
||||
assert_eq!(sess.channel_id.as_deref(), Some("general"));
|
||||
assert_eq!(sess.voice_channel_id.as_deref(), Some("voice"));
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"other-text",
|
||||
"Other",
|
||||
channels::ChannelKind::Text,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
attempt_join(&state, &sid, "other-text").await;
|
||||
assert!(
|
||||
channels::members(&state.channels, "voice")
|
||||
.await
|
||||
.contains(&sid)
|
||||
);
|
||||
let (mut stream, _) = tokio::io::duplex(65536);
|
||||
super::super::leave(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
"general",
|
||||
&SessionCrypto::derive(&[7; 32], &sid),
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let sess = session::get(&state.sessions, &sid).await.unwrap();
|
||||
assert_eq!(sess.channel_id.as_deref(), Some("other-text"));
|
||||
assert_eq!(sess.voice_channel_id.as_deref(), Some("voice"));
|
||||
super::super::leave(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
"voice",
|
||||
&SessionCrypto::derive(&[7; 32], &sid),
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let sess = session::get(&state.sessions, &sid).await.unwrap();
|
||||
assert_eq!(sess.channel_id.as_deref(), Some("other-text"));
|
||||
assert_eq!(sess.voice_channel_id, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_credentials() {
|
||||
use crate::proto::{ChannelDeletePayload, ChannelEditPayload};
|
||||
let (mut state, sid) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("owner", "Private")
|
||||
.await
|
||||
.unwrap();
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"managed",
|
||||
"Managed",
|
||||
channels::ChannelKind::Voice,
|
||||
Some(guild.clone()),
|
||||
)
|
||||
.await;
|
||||
state
|
||||
.storage
|
||||
.create_channel("managed", "Managed", "voice", Some(&guild))
|
||||
.await
|
||||
.unwrap();
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
let crypto = SessionCrypto::derive(&[7; 32], &sid);
|
||||
crate::handler::channel::handle_channel_edit(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: "managed".into(),
|
||||
channel_name: "stolen".into(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
channels::get_channel(&state.channels, "managed")
|
||||
.await
|
||||
.unwrap()
|
||||
.name,
|
||||
"Managed"
|
||||
);
|
||||
crate::handler::channel::handle_channel_delete(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: "managed".into(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
channels::get_channel(&state.channels, "managed")
|
||||
.await
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
!super::super::may_manage(&state, "owner", None)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let owner = session::create(&state.sessions, "owner".into(), "Owner".into()).await;
|
||||
channels::join(&state.channels, "managed", &owner.session_id).await;
|
||||
super::super::set_voice_channel(&state, &owner.session_id, Some("managed".into())).await;
|
||||
let (tx, mut rx) = tokio::sync::broadcast::channel(8);
|
||||
state.voice_member_tx = Some(tx);
|
||||
crate::handler::channel::handle_channel_delete(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner.session_id,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: "managed".into(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
channels::get_channel(&state.channels, "managed")
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
session::get(&state.sessions, &owner.session_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.voice_channel_id
|
||||
.is_none()
|
||||
);
|
||||
let event: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
|
||||
assert_eq!(event["type"], "leave");
|
||||
assert_eq!(event["session_id"], owner.session_id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation() {
|
||||
use crate::domain::permissions::Permissions;
|
||||
use crate::proto::{RoleAssignPayload, RoleDeletePayload};
|
||||
let (state, sid) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("visitor", "Owned")
|
||||
.await
|
||||
.unwrap();
|
||||
let other = state
|
||||
.storage
|
||||
.create_guild("elsewhere", "Other")
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign = state
|
||||
.storage
|
||||
.create_role(
|
||||
&other,
|
||||
"foreign",
|
||||
"#fff",
|
||||
Permissions::ADMINISTRATOR.bits(),
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
let crypto = SessionCrypto::derive(&[7; 32], &sid);
|
||||
crate::handler::guild::handle_role_assign(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&RoleAssignPayload {
|
||||
guild_id: guild.clone(),
|
||||
user_id: "visitor".into(),
|
||||
role_id: foreign.clone(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::guild::handle_role_delete(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&RoleDeletePayload {
|
||||
guild_id: guild.clone(),
|
||||
role_id: foreign.clone(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
state
|
||||
.storage
|
||||
.list_guild_roles(&other)
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| r.id == foreign)
|
||||
);
|
||||
let otherguild = state
|
||||
.storage
|
||||
.create_guild("owner", "Managed")
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&otherguild, "visitor")
|
||||
.await
|
||||
.unwrap();
|
||||
let manager = state
|
||||
.storage
|
||||
.create_role(
|
||||
&otherguild,
|
||||
"manager",
|
||||
"#fff",
|
||||
Permissions::MANAGE_ROLES.bits(),
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.assign_role(&otherguild, "visitor", &manager)
|
||||
.await
|
||||
.unwrap();
|
||||
let powerful = state
|
||||
.storage
|
||||
.create_role(
|
||||
&otherguild,
|
||||
"admin",
|
||||
"#fff",
|
||||
Permissions::ADMINISTRATOR.bits(),
|
||||
2,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::guild::handle_role_assign(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&RoleAssignPayload {
|
||||
guild_id: otherguild.clone(),
|
||||
user_id: "visitor".into(),
|
||||
role_id: powerful,
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let actual = Permissions::from_role_perms(
|
||||
&state
|
||||
.storage
|
||||
.get_user_role_perms(&otherguild, "visitor")
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(!actual.contains(Permissions::ADMINISTRATOR));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn removing_voice_role_revokes_existing_udp_membership() {
|
||||
use crate::domain::permissions::Permissions;
|
||||
use crate::proto::RoleAssignPayload;
|
||||
let (mut state, sid) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("owner", "Private")
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&guild, "visitor")
|
||||
.await
|
||||
.unwrap();
|
||||
let role = state
|
||||
.storage
|
||||
.create_role(
|
||||
&guild,
|
||||
"speaker",
|
||||
"#fff",
|
||||
Permissions::VOICE_SPEAK.bits(),
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.assign_role(&guild, "visitor", &role)
|
||||
.await
|
||||
.unwrap();
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"managed",
|
||||
"Managed",
|
||||
channels::ChannelKind::Voice,
|
||||
Some(guild.clone()),
|
||||
)
|
||||
.await;
|
||||
channels::join(&state.channels, "managed", &sid).await;
|
||||
super::super::set_voice_channel(&state, &sid, Some("managed".into())).await;
|
||||
let owner = session::create(&state.sessions, "owner".into(), "Owner".into()).await;
|
||||
let (tx, mut rx) = tokio::sync::broadcast::channel(8);
|
||||
state.voice_member_tx = Some(tx);
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
crate::handler::guild::handle_role_unassign(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner.session_id,
|
||||
&to_payload(&RoleAssignPayload {
|
||||
guild_id: guild,
|
||||
user_id: "visitor".into(),
|
||||
role_id: role,
|
||||
}),
|
||||
&SessionCrypto::derive(&[7; 32], &owner.session_id),
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
session::get(&state.sessions, &sid)
|
||||
.await
|
||||
.unwrap()
|
||||
.voice_channel_id
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
!channels::members(&state.channels, "managed")
|
||||
.await
|
||||
.contains(&sid)
|
||||
);
|
||||
let event: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
|
||||
assert_eq!(event["type"], "leave");
|
||||
assert_eq!(event["session_id"], sid);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn private_channel_notifications_target_members_and_acknowledge_editor() {
|
||||
use crate::proto::{ChannelCreatePayload, ChannelDeletePayload, ChannelEditPayload};
|
||||
let (state, owner_sid) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("visitor", "Private")
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&guild, "member")
|
||||
.await
|
||||
.unwrap();
|
||||
let member = session::create(&state.sessions, "member".into(), "Member".into()).await;
|
||||
let outsider = session::create(&state.sessions, "outsider".into(), "Outsider".into()).await;
|
||||
let mut events = state.broadcast.subscribe();
|
||||
let crypto = SessionCrypto::derive(&[7; 32], &owner_sid);
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
let creation = ChannelCreatePayload {
|
||||
channel_id: "private-notification".into(),
|
||||
channel_name: "Private name".into(),
|
||||
kind: "text".into(),
|
||||
guild_id: Some(guild.clone()),
|
||||
};
|
||||
crate::handler::channel::handle_channel_create(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner_sid,
|
||||
&to_payload(&creation),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::channel::handle_channel_edit(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner_sid,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: creation.channel_id.clone(),
|
||||
channel_name: "Renamed privately".into(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::channel::handle_channel_delete(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner_sid,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: creation.channel_id.clone(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut notifications = Vec::new();
|
||||
while let Ok(event) = events.try_recv() {
|
||||
notifications.push(event)
|
||||
}
|
||||
assert_eq!(notifications.len(), 5);
|
||||
assert!(notifications.iter().all(|event|matches!(event.target_session_id.as_deref(),Some(id) if id==owner_sid || id==member.session_id)));
|
||||
assert!(
|
||||
notifications
|
||||
.iter()
|
||||
.all(|event| event.target_session_id.as_deref() != Some(&outsider.session_id))
|
||||
);
|
||||
assert!(
|
||||
notifications.iter().any(
|
||||
|event| event.target_session_id.as_deref() == Some(&owner_sid)
|
||||
&& crate::proto::PacketHeader::from_bytes(event.data[..12].try_into().unwrap())
|
||||
.packet_id
|
||||
== PacketId::ChannelEdit as u16
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
super::super::may_deliver_metadata(
|
||||
&state,
|
||||
&member.session_id,
|
||||
PacketId::ChannelCreate,
|
||||
&to_payload(&creation)
|
||||
)
|
||||
.await
|
||||
);
|
||||
state
|
||||
.storage
|
||||
.remove_guild_member(&guild, "member")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!super::super::may_deliver_metadata(
|
||||
&state,
|
||||
&member.session_id,
|
||||
PacketId::ChannelCreate,
|
||||
&to_payload(&creation)
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncReadExt;
|
||||
let (state, sid) = fixture().await;
|
||||
let crypto = SessionCrypto::derive(&[7; 32], &sid);
|
||||
let history = |channel: &str| BroadcastMsg {
|
||||
channel_id: Some(channel.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: Some(sid.clone()),
|
||||
data: encode_packet(
|
||||
PacketId::ChatHistory,
|
||||
0,
|
||||
&to_payload(&ChatHistoryPayload {
|
||||
channel_id: channel.into(),
|
||||
messages: vec![],
|
||||
}),
|
||||
),
|
||||
};
|
||||
// The same queued target/channel envelope is deliverable while subscribed.
|
||||
let (mut stream, mut peer) = tokio::io::duplex(65536);
|
||||
let mut seq = 2;
|
||||
crate::handler::deliver::deliver_encrypted(
|
||||
&mut stream,
|
||||
&mut seq,
|
||||
&sid,
|
||||
&history("general"),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut first = [0u8; 12];
|
||||
peer.read_exact(&mut first).await.unwrap();
|
||||
assert_eq!(
|
||||
u16::from_be_bytes(first[..2].try_into().unwrap()),
|
||||
PacketId::ChatHistory as u16
|
||||
);
|
||||
assert_eq!(seq, 3);
|
||||
|
||||
super::super::leave(&mut stream, &mut seq, &sid, "general", &crypto, &state)
|
||||
.await
|
||||
.unwrap();
|
||||
let (mut stream, mut peer) = tokio::io::duplex(65536);
|
||||
crate::handler::deliver::deliver_encrypted(
|
||||
&mut stream,
|
||||
&mut seq,
|
||||
&sid,
|
||||
&history("general"),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
seq, 3,
|
||||
"discarded history cannot consume an encryption sequence"
|
||||
);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(15), peer.read_u8())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("owner", "Private history")
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&guild, "visitor")
|
||||
.await
|
||||
.unwrap();
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"private-history",
|
||||
"Private",
|
||||
channels::ChannelKind::Text,
|
||||
Some(guild.clone()),
|
||||
)
|
||||
.await;
|
||||
attempt_join(&state, &sid, "private-history").await;
|
||||
let queued = history("private-history");
|
||||
{
|
||||
let _access = state.access.write().await;
|
||||
state
|
||||
.storage
|
||||
.remove_guild_member(&guild, "visitor")
|
||||
.await
|
||||
.unwrap();
|
||||
super::super::revoke_guild_access(&state, &guild, Some("visitor")).await;
|
||||
}
|
||||
let (mut stream, mut peer) = tokio::io::duplex(65536);
|
||||
crate::handler::deliver::deliver_encrypted(
|
||||
&mut stream,
|
||||
&mut seq,
|
||||
&sid,
|
||||
&queued,
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(seq, 3);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(15), peer.read_u8())
|
||||
.await
|
||||
.is_err(),
|
||||
"history queued before a guild kick must not be delivered afterwards"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use crate::{
|
|||
proto::SessionCrypto,
|
||||
};
|
||||
|
||||
use super::{broadcast_leave, set_channel};
|
||||
use super::{broadcast_leave, set_channel, set_voice_channel};
|
||||
|
||||
pub async fn leave(
|
||||
_stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
|
|
@ -18,17 +18,25 @@ pub async fn leave(
|
|||
_crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let user_id = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
.map(|s| s.user_id);
|
||||
|
||||
let is_voice = channels::get_channel(&state.channels, channel_id)
|
||||
.await
|
||||
.is_some_and(|c| c.kind == channels::ChannelKind::Voice);
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
let is_voice = sess.voice_channel_id.as_deref() == Some(channel_id);
|
||||
if !is_voice && sess.channel_id.as_deref() != Some(channel_id) {
|
||||
return Ok(());
|
||||
}
|
||||
let user_id = Some(sess.user_id);
|
||||
|
||||
channels::leave(&state.channels, channel_id, session_id).await;
|
||||
set_channel(state, session_id, None).await;
|
||||
if is_voice {
|
||||
set_voice_channel(state, session_id, None).await;
|
||||
} else {
|
||||
set_channel(state, session_id, None).await;
|
||||
}
|
||||
broadcast_leave(state, channel_id, session_id).await;
|
||||
if is_voice {
|
||||
state.media.revoke(state, session_id).await;
|
||||
}
|
||||
|
||||
if is_voice
|
||||
&& let Some(tx) = &state.voice_member_tx
|
||||
|
|
@ -36,6 +44,7 @@ pub async fn leave(
|
|||
{
|
||||
let event = serde_json::json!({
|
||||
"type": "leave",
|
||||
"session_id": session_id,
|
||||
"channel_id": channel_id,
|
||||
"user_id": uid,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -33,3 +33,274 @@ async fn set_channel(state: &State, session_id: &str, ch: Option<String>) {
|
|||
s.channel_id = ch;
|
||||
}
|
||||
}
|
||||
|
||||
async fn set_voice_channel(state: &State, session_id: &str, ch: Option<String>) {
|
||||
if let Some(s) = state.sessions.write().await.get_mut(session_id) {
|
||||
s.voice_channel_id = ch;
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove active subscriptions and UDP credentials when guild access is revoked.
|
||||
pub async fn revoke_guild_access(state: &State, guild: &str, user: Option<&str>) {
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|s| user.is_none_or(|u| u == s.user_id))
|
||||
.cloned()
|
||||
.collect();
|
||||
for sess in sessions {
|
||||
for (voice, ch) in [(false, sess.channel_id), (true, sess.voice_channel_id)] {
|
||||
let Some(ch) = ch else { continue };
|
||||
if !crate::domain::channels::get_channel(&state.channels, &ch)
|
||||
.await
|
||||
.is_some_and(|c| c.guild_id.as_deref() == Some(guild))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
crate::domain::channels::leave(&state.channels, &ch, &sess.session_id).await;
|
||||
if voice {
|
||||
set_voice_channel(state, &sess.session_id, None).await;
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
let _=tx.send(serde_json::json!({"type":"leave","session_id":sess.session_id,"channel_id":ch,"user_id":sess.user_id}).to_string());
|
||||
}
|
||||
state.media.revoke(state, &sess.session_id).await;
|
||||
let event = crate::proto::VoiceState {
|
||||
user_id: sess.user_id.clone(),
|
||||
channel_id: ch.clone(),
|
||||
state: "disconnected".into(),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(sess.session_id.clone()),
|
||||
data: encode_packet(PacketId::VoiceState, 0, &to_payload(&event)),
|
||||
});
|
||||
} else {
|
||||
set_channel(state, &sess.session_id, None).await;
|
||||
}
|
||||
broadcast_leave(state, &ch, &sess.session_id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Global channels have no modeled server administrator: authenticated users cannot mutate them.
|
||||
pub(super) async fn may_manage(
|
||||
state: &State,
|
||||
user: &str,
|
||||
guild: Option<&str>,
|
||||
) -> anyhow::Result<bool> {
|
||||
let Some(guild) = guild else { return Ok(false) };
|
||||
let Some(info) = state.storage.get_guild(guild).await? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if info.owner_id == user {
|
||||
return Ok(true);
|
||||
}
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(user)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == guild)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let roles = state.storage.get_user_role_perms(guild, user).await?;
|
||||
Ok(
|
||||
crate::domain::permissions::Permissions::from_role_perms(&roles)
|
||||
.has(crate::domain::permissions::Permissions::MANAGE_CHANNELS),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn denied(
|
||||
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
crypto: &crate::proto::SessionCrypto,
|
||||
) -> anyhow::Result<()> {
|
||||
crate::net::io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::PermissionDenied as u32,
|
||||
message: "guild MANAGE_CHANNELS permission required".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Caller serializes access mutation against joins. Revoke before removing cached channel metadata.
|
||||
pub async fn revoke_channel(state: &State, channel: &str) {
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|s| {
|
||||
s.channel_id.as_deref() == Some(channel)
|
||||
|| s.voice_channel_id.as_deref() == Some(channel)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
for session in sessions {
|
||||
crate::domain::channels::leave(&state.channels, channel, &session.session_id).await;
|
||||
if session.channel_id.as_deref() == Some(channel) {
|
||||
set_channel(state, &session.session_id, None).await;
|
||||
}
|
||||
if session.voice_channel_id.as_deref() == Some(channel) {
|
||||
set_voice_channel(state, &session.session_id, None).await;
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
let _ = tx.send(
|
||||
serde_json::json!({"type":"leave","session_id":session.session_id}).to_string(),
|
||||
);
|
||||
}
|
||||
state.media.revoke(state, &session.session_id).await;
|
||||
let event = crate::proto::VoiceState {
|
||||
user_id: session.user_id,
|
||||
channel_id: channel.into(),
|
||||
state: "disconnected".into(),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(session.session_id.clone()),
|
||||
data: encode_packet(PacketId::VoiceState, 0, &to_payload(&event)),
|
||||
});
|
||||
}
|
||||
broadcast_leave(state, channel, &session.session_id).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Removing voice permission also invalidates existing relay credentials and screen shares.
|
||||
pub async fn recheck_voice_permissions(
|
||||
state: &State,
|
||||
guild: &str,
|
||||
user: Option<&str>,
|
||||
) -> anyhow::Result<()> {
|
||||
let owner = state.storage.get_guild(guild).await?.map(|g| g.owner_id);
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|s| user.is_none_or(|u| u == s.user_id))
|
||||
.cloned()
|
||||
.collect();
|
||||
for session in sessions {
|
||||
let Some(channel) = session.voice_channel_id else {
|
||||
continue;
|
||||
};
|
||||
if !crate::domain::channels::get_channel(&state.channels, &channel)
|
||||
.await
|
||||
.is_some_and(|c| c.guild_id.as_deref() == Some(guild))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if owner.as_deref() == Some(&session.user_id) {
|
||||
continue;
|
||||
}
|
||||
let roles = state
|
||||
.storage
|
||||
.get_user_role_perms(guild, &session.user_id)
|
||||
.await?;
|
||||
if crate::domain::permissions::Permissions::from_role_perms(&roles)
|
||||
.has(crate::domain::permissions::Permissions::VOICE_SPEAK)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
crate::domain::channels::leave(&state.channels, &channel, &session.session_id).await;
|
||||
set_voice_channel(state, &session.session_id, None).await;
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
let _ = tx.send(
|
||||
serde_json::json!({"type":"leave","session_id":session.session_id}).to_string(),
|
||||
);
|
||||
}
|
||||
state.media.revoke(state, &session.session_id).await;
|
||||
let event = crate::proto::VoiceState {
|
||||
user_id: session.user_id,
|
||||
channel_id: channel,
|
||||
state: "disconnected".into(),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(session.session_id.clone()),
|
||||
data: encode_packet(PacketId::VoiceState, 0, &to_payload(&event)),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Metadata is addressed only to currently persisted guild members, including non-subscribers.
|
||||
pub(super) async fn notify_guild(
|
||||
state: &State,
|
||||
guild: Option<&str>,
|
||||
exclude: Option<&str>,
|
||||
data: Vec<u8>,
|
||||
) -> anyhow::Result<()> {
|
||||
let Some(guild) = guild else { return Ok(()) };
|
||||
let _access = state.access.read().await;
|
||||
let members = state.storage.list_guild_members(guild).await?;
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|session| {
|
||||
Some(session.session_id.as_str()) != exclude
|
||||
&& members
|
||||
.iter()
|
||||
.any(|member| member.user_id == session.user_id)
|
||||
})
|
||||
.map(|session| session.session_id.clone())
|
||||
.collect();
|
||||
for target in sessions {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(target),
|
||||
data: data.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creation/rename payloads queued before removal must not disclose new metadata afterwards.
|
||||
pub async fn may_deliver_metadata(
|
||||
state: &State,
|
||||
recipient: &str,
|
||||
packet: PacketId,
|
||||
payload: &[u8],
|
||||
) -> bool {
|
||||
use prost::Message;
|
||||
let guild = match packet {
|
||||
PacketId::ChannelCreate => match crate::proto::ChannelCreatePayload::decode(payload) {
|
||||
Ok(message) => message.guild_id,
|
||||
Err(_) => return false,
|
||||
},
|
||||
PacketId::ChannelEdit => match crate::proto::ChannelEditPayload::decode(payload) {
|
||||
Ok(message) => {
|
||||
match crate::domain::channels::get_channel(&state.channels, &message.channel_id)
|
||||
.await
|
||||
{
|
||||
Some(channel) => channel.guild_id,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
Err(_) => return false,
|
||||
},
|
||||
_ => return true,
|
||||
};
|
||||
let Some(guild) = guild else { return true };
|
||||
let Some(session) = crate::domain::session::get(&state.sessions, recipient).await else {
|
||||
return false;
|
||||
};
|
||||
state
|
||||
.storage
|
||||
.list_user_guilds(&session.user_id)
|
||||
.await
|
||||
.is_ok_and(|guilds| guilds.iter().any(|g| g.id == guild))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,15 +48,12 @@ pub async fn handle(session_id: &str, mut msg: ChatMessagePayload, state: &State
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(msg.channel_id.clone()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::ChatMessage, 0, &to_payload(&msg)),
|
||||
});
|
||||
|
||||
debug!(
|
||||
"chat {} → {}: {}",
|
||||
sess.nickname, msg.channel_id, msg.content
|
||||
);
|
||||
debug!(channel=%msg.channel_id,message_id=%msg.message_id,"chat message accepted");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ pub async fn handle_message_edit(session_id: &str, payload: &[u8], state: &State
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(edit.channel_id.clone()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::MessageEdit, 0, &to_payload(&broadcast_msg)),
|
||||
});
|
||||
|
|
@ -81,7 +81,7 @@ pub async fn handle_message_delete(session_id: &str, payload: &[u8], state: &Sta
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(delete.channel_id.clone()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::MessageDelete, 0, &to_payload(&delete)),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ pub async fn handle_reaction_add(
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(payload.channel_id.clone()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::MessageReactionAdd, 0, &to_payload(&payload)),
|
||||
});
|
||||
|
|
@ -79,7 +79,7 @@ pub async fn handle_reaction_remove(
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(payload.channel_id.clone()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::MessageReactionRemove, 0, &to_payload(&payload)),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,25 +15,59 @@ pub async fn deliver_encrypted(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
if msg.exclude_session.as_deref() == Some(session_id) {
|
||||
if msg.exclude_session.as_deref() == Some(session_id)
|
||||
|| msg
|
||||
.target_session_id
|
||||
.as_deref()
|
||||
.is_some_and(|target| target != session_id)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(ref target) = msg.target_session_id {
|
||||
if target != session_id {
|
||||
if msg.data.len() >= crate::proto::PacketHeader::SIZE {
|
||||
let hdr = crate::proto::PacketHeader::from_bytes(
|
||||
msg.data[..crate::proto::PacketHeader::SIZE]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
if let Some(packet) = crate::proto::PacketId::from_u16(hdr.packet_id)
|
||||
&& matches!(
|
||||
packet,
|
||||
crate::proto::PacketId::ChannelCreate | crate::proto::PacketId::ChannelEdit
|
||||
)
|
||||
&& !crate::handler::channel::may_deliver_metadata(
|
||||
state,
|
||||
session_id,
|
||||
packet,
|
||||
&msg.data[crate::proto::PacketHeader::SIZE..],
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if crate::proto::PacketId::from_u16(hdr.packet_id)
|
||||
== Some(crate::proto::PacketId::MediaEvent)
|
||||
&& !crate::media::may_deliver(
|
||||
state,
|
||||
session_id,
|
||||
&msg.data[crate::proto::PacketHeader::SIZE..],
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
io::deliver_encrypted(stream, crypto, seq, &msg.data).await?;
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(ref ch) = msg.channel_id {
|
||||
let access = state.access.read().await;
|
||||
let in_ch = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
.and_then(|s| s.channel_id)
|
||||
.as_deref()
|
||||
== Some(ch.as_str());
|
||||
.is_some_and(|s| {
|
||||
s.channel_id.as_deref() == Some(ch.as_str())
|
||||
|| s.voice_channel_id.as_deref() == Some(ch.as_str())
|
||||
});
|
||||
if !in_ch {
|
||||
return Ok(());
|
||||
}
|
||||
drop(access);
|
||||
}
|
||||
io::deliver_encrypted(stream, crypto, seq, &msg.data).await
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
addr: std::net::SocketAddr,
|
||||
) -> Result<()> {
|
||||
match pid {
|
||||
PacketId::MediaControl => crate::media::handle(ctx, session_id, payload).await?,
|
||||
PacketId::WebhookCreate
|
||||
| PacketId::WebhookList
|
||||
| PacketId::WebhookRotate
|
||||
|
|
|
|||
|
|
@ -35,3 +35,26 @@ pub use decline::handle_friend_decline;
|
|||
pub use list::handle_friend_list;
|
||||
pub use manage::{handle_block_list, handle_block_user, handle_friend_remove, handle_unblock_user};
|
||||
pub use requests::{handle_friend_accept, handle_friend_request};
|
||||
|
||||
async fn notify_user(
|
||||
state: &crate::net::state::State,
|
||||
user: &str,
|
||||
event: &crate::proto::FriendEventPayload,
|
||||
) {
|
||||
let ids: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|s| s.user_id == user)
|
||||
.map(|s| s.session_id.clone())
|
||||
.collect();
|
||||
for id in ids {
|
||||
let _ = state.broadcast.send(crate::net::state::BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(id),
|
||||
data: crate::proto::encode_packet(PacketId::FriendEvent, 0, &to_payload(event)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,13 +4,10 @@ use tokio::io::{AsyncRead, AsyncWrite};
|
|||
|
||||
use crate::{
|
||||
domain::session,
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
net::{io, state::State},
|
||||
proto::{
|
||||
FriendAcceptPayload, FriendEventPayload, FriendRequestPayload, PacketId, SessionCrypto,
|
||||
encode_packet, to_payload,
|
||||
to_payload,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -82,12 +79,7 @@ pub async fn handle_friend_request(
|
|||
user_id: sess.user_id.clone(),
|
||||
nickname: Some(sess.nickname.clone()),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(req.to_user_id.clone()),
|
||||
data: encode_packet(PacketId::FriendRequest, *seq, &to_payload(&ev)),
|
||||
});
|
||||
super::notify_user(state, &req.to_user_id, &ev).await;
|
||||
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
@ -136,12 +128,7 @@ pub async fn handle_friend_accept(
|
|||
user_id: sess.user_id.clone(),
|
||||
nickname: Some(sess.nickname.clone()),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(req.from_user_id.clone()),
|
||||
data: encode_packet(PacketId::FriendAccept, *seq, &to_payload(&ev)),
|
||||
});
|
||||
super::notify_user(state, &req.from_user_id, &ev).await;
|
||||
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
|
|||
|
|
@ -75,6 +75,7 @@ pub async fn handle_guild_delete(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.write().await;
|
||||
let req = crate::proto::GuildDeletePayload::decode(payload)?;
|
||||
let sess = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
|
|
@ -86,6 +87,7 @@ pub async fn handle_guild_delete(
|
|||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("guild not found"))?;
|
||||
if guild.owner_id != sess.user_id {
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -97,6 +99,7 @@ pub async fn handle_guild_delete(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
crate::handler::channel::revoke_guild_access(state, &req.guild_id, None).await;
|
||||
state.storage.delete_guild(&req.guild_id).await?;
|
||||
state
|
||||
.storage
|
||||
|
|
@ -110,6 +113,7 @@ pub async fn handle_guild_delete(
|
|||
)
|
||||
.await?;
|
||||
|
||||
drop(guard);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildDelete,
|
||||
|
|
|
|||
|
|
@ -21,11 +21,30 @@ pub async fn handle_guild_member_join(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.write().await;
|
||||
let req = GuildMemberJoinPayload::decode(payload)?;
|
||||
let sess = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("session not found"))?;
|
||||
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&sess.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
{
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"a valid invitation is required",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&req.guild_id, &sess.user_id)
|
||||
|
|
@ -41,6 +60,7 @@ pub async fn handle_guild_member_join(
|
|||
.map(|r| r.color.clone())
|
||||
.unwrap_or_else(|| "#ffffff".into());
|
||||
|
||||
drop(guard);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildMemberJoin,
|
||||
|
|
@ -75,6 +95,7 @@ pub async fn handle_guild_member_leave(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.write().await;
|
||||
let req = GuildMemberLeavePayload::decode(payload)?;
|
||||
let sess = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
|
|
@ -85,10 +106,29 @@ pub async fn handle_guild_member_leave(
|
|||
} else {
|
||||
req.user_id.clone()
|
||||
};
|
||||
let owner = state
|
||||
.storage
|
||||
.get_guild(&req.guild_id)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == target);
|
||||
if target != sess.user_id || owner {
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"only a non-owner may leave their own membership",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.remove_guild_member(&req.guild_id, target.as_str())
|
||||
.await?;
|
||||
crate::handler::channel::revoke_guild_access(state, &req.guild_id, Some(&target)).await;
|
||||
drop(guard);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildMemberLeave,
|
||||
|
|
@ -111,6 +151,7 @@ pub async fn handle_guild_member_kick(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.write().await;
|
||||
let req = GuildMemberKickPayload::decode(payload)?;
|
||||
let sess = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
|
|
@ -124,6 +165,7 @@ pub async fn handle_guild_member_kick(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -135,10 +177,28 @@ pub async fn handle_guild_member_kick(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
if state
|
||||
.storage
|
||||
.get_guild(&req.guild_id)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == req.user_id)
|
||||
{
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"guild owner cannot be kicked",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.remove_guild_member(&req.guild_id, &req.user_id)
|
||||
.await?;
|
||||
crate::handler::channel::revoke_guild_access(state, &req.guild_id, Some(&req.user_id)).await;
|
||||
state
|
||||
.storage
|
||||
.append_audit_log(
|
||||
|
|
@ -150,6 +210,7 @@ pub async fn handle_guild_member_kick(
|
|||
None,
|
||||
)
|
||||
.await?;
|
||||
drop(guard);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildMemberKick,
|
||||
|
|
|
|||
|
|
@ -29,7 +29,24 @@ pub async fn handle_member_list_fetch(
|
|||
None => return Ok(()),
|
||||
};
|
||||
|
||||
// Optional: verify the requester is a member of the guild.
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&sess.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
{
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"guild membership required",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
// Membership is checked before listing identities.
|
||||
let owner_id = state
|
||||
.storage
|
||||
.get_guild(&req.guild_id)
|
||||
|
|
@ -79,6 +96,7 @@ pub async fn handle_role_assign(
|
|||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !require_perm(
|
||||
state,
|
||||
&req.guild_id,
|
||||
|
|
@ -87,6 +105,7 @@ pub async fn handle_role_assign(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -98,6 +117,31 @@ pub async fn handle_role_assign(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let role = super::roles::role_permissions(state, &req.guild_id, &req.role_id).await?;
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&req.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
|| match role {
|
||||
Some(permissions) => {
|
||||
!super::roles::may_grant(state, &req.guild_id, &sess.user_id, permissions).await?
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"role or target not permitted in this guild",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.assign_role(&req.guild_id, &req.user_id, &req.role_id)
|
||||
|
|
@ -114,6 +158,7 @@ pub async fn handle_role_assign(
|
|||
)
|
||||
.await?;
|
||||
|
||||
drop(access);
|
||||
// Confirm to caller.
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
@ -145,6 +190,7 @@ pub async fn handle_role_unassign(
|
|||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !require_perm(
|
||||
state,
|
||||
&req.guild_id,
|
||||
|
|
@ -153,6 +199,7 @@ pub async fn handle_role_unassign(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -164,10 +211,37 @@ pub async fn handle_role_unassign(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let role = super::roles::role_permissions(state, &req.guild_id, &req.role_id).await?;
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&req.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
|| match role {
|
||||
Some(permissions) => {
|
||||
!super::roles::may_grant(state, &req.guild_id, &sess.user_id, permissions).await?
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"role or target not permitted in this guild",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.remove_role_from_user(&req.guild_id, &req.user_id, &req.role_id)
|
||||
.await?;
|
||||
crate::handler::channel::recheck_voice_permissions(state, &req.guild_id, Some(&req.user_id))
|
||||
.await?;
|
||||
state
|
||||
.storage
|
||||
.append_audit_log(
|
||||
|
|
@ -180,6 +254,7 @@ pub async fn handle_role_unassign(
|
|||
)
|
||||
.await?;
|
||||
|
||||
drop(access);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildRoleUnassign,
|
||||
|
|
@ -205,7 +280,26 @@ pub async fn handle_role_list_fetch(
|
|||
state: &State,
|
||||
) -> Result<()> {
|
||||
let req = GuildRoleListFetchPayload::decode(payload)?;
|
||||
let _sess = session::get(&state.sessions, session_id).await;
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&sess.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
{
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"guild membership required",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let rows = state.storage.list_guild_roles(&req.guild_id).await?;
|
||||
let roles: Vec<GuildRoleInfoPayload> = rows
|
||||
|
|
|
|||
|
|
@ -46,6 +46,15 @@ async fn require_perm(
|
|||
{
|
||||
return Ok(true);
|
||||
}
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == guild_id)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let perms = state.storage.get_user_role_perms(guild_id, user_id).await?;
|
||||
Ok(Permissions::from_role_perms(&perms).has(required))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ pub async fn handle_role_create(
|
|||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("session not found"))?;
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !super::require_perm(
|
||||
state,
|
||||
&req.guild_id,
|
||||
|
|
@ -31,6 +32,7 @@ pub async fn handle_role_create(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -44,6 +46,22 @@ pub async fn handle_role_create(
|
|||
|
||||
let color = req.color.as_deref().unwrap_or("#ffffff");
|
||||
let permissions = req.permissions.unwrap_or(0);
|
||||
if req.name.trim().is_empty()
|
||||
|| req.name.chars().count() > 64
|
||||
|| req.name.chars().any(char::is_control)
|
||||
|| !may_grant(state, &req.guild_id, &sess.user_id, permissions).await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"cannot grant requested role",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
let role_id = state
|
||||
.storage
|
||||
.create_role(&req.guild_id, &req.name, color, permissions, 1)
|
||||
|
|
@ -60,6 +78,7 @@ pub async fn handle_role_create(
|
|||
None,
|
||||
)
|
||||
.await?;
|
||||
drop(access);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::RoleCreate,
|
||||
|
|
@ -90,6 +109,7 @@ pub async fn handle_role_delete(
|
|||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("session not found"))?;
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !super::require_perm(
|
||||
state,
|
||||
&req.guild_id,
|
||||
|
|
@ -98,6 +118,7 @@ pub async fn handle_role_delete(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -109,7 +130,32 @@ pub async fn handle_role_delete(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(permissions) = role_permissions(state, &req.guild_id, &req.role_id).await? else {
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"role is outside this guild",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
};
|
||||
if !may_grant(state, &req.guild_id, &sess.user_id, permissions).await? {
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"cannot manage requested role",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state.storage.delete_role(&req.role_id).await?;
|
||||
crate::handler::channel::recheck_voice_permissions(state, &req.guild_id, None).await?;
|
||||
state
|
||||
.storage
|
||||
.append_audit_log(
|
||||
|
|
@ -121,6 +167,7 @@ pub async fn handle_role_delete(
|
|||
None,
|
||||
)
|
||||
.await?;
|
||||
drop(access);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::RoleDelete,
|
||||
|
|
@ -134,3 +181,36 @@ pub async fn handle_role_delete(
|
|||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A role manager cannot create/assign permissions they do not themselves hold.
|
||||
pub(super) async fn may_grant(
|
||||
state: &State,
|
||||
guild: &str,
|
||||
actor: &str,
|
||||
permissions: u64,
|
||||
) -> Result<bool> {
|
||||
if state
|
||||
.storage
|
||||
.get_guild(guild)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == actor)
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
let held =
|
||||
Permissions::from_role_perms(&state.storage.get_user_role_perms(guild, actor).await?);
|
||||
Ok(held.has(Permissions::ADMINISTRATOR) || permissions & !held.bits() == 0)
|
||||
}
|
||||
pub(super) async fn role_permissions(
|
||||
state: &State,
|
||||
guild: &str,
|
||||
role: &str,
|
||||
) -> Result<Option<u64>> {
|
||||
Ok(state
|
||||
.storage
|
||||
.list_guild_roles(guild)
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|r| r.id == role)
|
||||
.map(|r| r.permissions as u64))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,9 +25,10 @@ pub async fn run_session<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
crypto,
|
||||
state,
|
||||
};
|
||||
let mut reader = io::EncryptedReader::default();
|
||||
loop {
|
||||
tokio::select! {
|
||||
result = io::read_encrypted(ctx.stream, ctx.crypto) => {
|
||||
result = reader.read(ctx.stream, ctx.crypto) => {
|
||||
let (hdr, payload) = result?;
|
||||
let pid = match PacketId::from_u16(hdr.packet_id) {
|
||||
Some(p) => p,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue