chore(server): checkpoint deployed services and unfinished forums
User requested a checkpoint and stopped all agents. Deployed artifacts remain the last verified releases; unfinished settings/categories/forums are preserved as WIP. See TODO/roadmap for verification and remaining release/updater work.
This commit is contained in:
parent
d6d406bbf5
commit
c18ccadf99
96 changed files with 8665 additions and 276 deletions
|
|
@ -17,6 +17,7 @@ name = "vnox-gateway"
|
|||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif"] }
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
|
|
|||
|
|
@ -63,7 +63,7 @@ async fn version(State(_s): State<AdminState>) -> impl IntoResponse {
|
|||
let body = serde_json::json!({
|
||||
"name": "vnox-gateway",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"lnex_version": "1",
|
||||
"lnex_version": crate::net::handshake::LNEX_VERSION,
|
||||
});
|
||||
(StatusCode::OK, axum::Json(body))
|
||||
}
|
||||
|
|
|
|||
213
gateway/src/domain/account.rs
Normal file
213
gateway/src/domain/account.rs
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
//! Central-issued, identity-bound account proofs required for LNEx admission.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::config::CentralAccountConfig;
|
||||
|
||||
const CONTEXT: &[u8] = b"VNOX-CENTRAL-ACCOUNT-v1\0";
|
||||
const MAX_PROOF_BYTES: usize = 8192;
|
||||
const MAX_LIFETIME: i64 = 600;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Envelope {
|
||||
claims: String,
|
||||
signature: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Claims {
|
||||
#[serde(default)]
|
||||
display_name: Option<String>,
|
||||
#[serde(default)]
|
||||
avatar_url: Option<String>,
|
||||
version: u32,
|
||||
issuer: String,
|
||||
subject: String,
|
||||
public_key: String,
|
||||
issued_at: i64,
|
||||
expires_at: i64,
|
||||
audience: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AccountClaims {
|
||||
pub issued_at: i64,
|
||||
pub account_id: String,
|
||||
pub display_name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
pub fn safe_avatar_path(path: &str) -> bool {
|
||||
path.len() <= 256
|
||||
&& path.starts_with("/v1/avatars/")
|
||||
&& path
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"/-".contains(&b))
|
||||
}
|
||||
|
||||
/// Verify an account proof against configured issuer trust and the authenticated device key.
|
||||
/// Returns the Central account UUID; no input key can establish its own trust.
|
||||
pub fn verify(
|
||||
proof: &[u8],
|
||||
device_public_key: &[u8; 32],
|
||||
trust: Option<&CentralAccountConfig>,
|
||||
now: i64,
|
||||
) -> Result<AccountClaims> {
|
||||
let trust = trust.context("Central account issuer is not configured")?;
|
||||
ensure!(
|
||||
!proof.is_empty() && proof.len() <= MAX_PROOF_BYTES,
|
||||
"missing or oversized account proof"
|
||||
);
|
||||
let envelope: Envelope = serde_json::from_slice(proof).context("invalid account proof")?;
|
||||
let claims_bytes = hex::decode(&envelope.claims).context("invalid account claims encoding")?;
|
||||
let signature = Signature::from_slice(&hex::decode(&envelope.signature)?)?;
|
||||
let public_key: [u8; 32] = hex::decode(&trust.public_key)?
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid Central issuer key"))?;
|
||||
let key = VerifyingKey::from_bytes(&public_key)?;
|
||||
let mut signed = CONTEXT.to_vec();
|
||||
signed.extend_from_slice(&claims_bytes);
|
||||
key.verify_strict(&signed, &signature)
|
||||
.context("invalid account proof signature")?;
|
||||
let claims: Claims = serde_json::from_slice(&claims_bytes).context("invalid account claims")?;
|
||||
ensure!(
|
||||
claims.version == 1 && claims.audience == "vnox-gateway",
|
||||
"unsupported account proof"
|
||||
);
|
||||
let issuer = uuid::Uuid::parse_str(&claims.issuer).context("invalid account issuer")?;
|
||||
ensure!(
|
||||
issuer == uuid::Uuid::parse_str(&trust.issuer)?,
|
||||
"untrusted account issuer"
|
||||
);
|
||||
let subject = uuid::Uuid::parse_str(&claims.subject).context("invalid account subject")?;
|
||||
ensure!(!subject.is_nil(), "invalid account subject");
|
||||
ensure!(
|
||||
claims.public_key == hex::encode(device_public_key),
|
||||
"account proof belongs to another device"
|
||||
);
|
||||
ensure!(
|
||||
claims.issued_at > 0 && claims.issued_at <= now,
|
||||
"account proof issued in the future"
|
||||
);
|
||||
ensure!(claims.expires_at > now, "account proof expired");
|
||||
ensure!(
|
||||
claims
|
||||
.expires_at
|
||||
.checked_sub(claims.issued_at)
|
||||
.is_some_and(|ttl| ttl > 0 && ttl <= MAX_LIFETIME),
|
||||
"invalid account proof lifetime"
|
||||
);
|
||||
let display_name = claims
|
||||
.display_name
|
||||
.filter(|name| !name.trim().is_empty() && name.chars().count() <= 64);
|
||||
let avatar_url = claims.avatar_url.filter(|path| safe_avatar_path(path));
|
||||
Ok(AccountClaims {
|
||||
issued_at: claims.issued_at,
|
||||
account_id: subject.to_string(),
|
||||
display_name,
|
||||
avatar_url,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(crate) fn issuer_key() -> SigningKey {
|
||||
SigningKey::from_bytes(&[73; 32])
|
||||
}
|
||||
pub(crate) fn trust() -> CentralAccountConfig {
|
||||
CentralAccountConfig {
|
||||
issuer: "8a1495ae-7174-4d22-94a5-080f61aa1691".into(),
|
||||
public_key: hex::encode(issuer_key().verifying_key().to_bytes()),
|
||||
}
|
||||
}
|
||||
pub(crate) fn claims(public_key: &[u8; 32], now: i64) -> Value {
|
||||
json!({"version":1,"issuer":trust().issuer,"subject":"c3ebd30f-6bb4-4c31-9016-bec57e986c93","public_key":hex::encode(public_key),"issued_at":now,"expires_at":now+600,"audience":"vnox-gateway"})
|
||||
}
|
||||
pub(crate) fn sign(claims: Value) -> Vec<u8> {
|
||||
let raw = serde_json::to_vec(&claims).unwrap();
|
||||
let mut signed = CONTEXT.to_vec();
|
||||
signed.extend_from_slice(&raw);
|
||||
serde_json::to_vec(&json!({"claims":hex::encode(raw),"signature":hex::encode(issuer_key().sign(&signed).to_bytes())})).unwrap()
|
||||
}
|
||||
pub(crate) fn proof(public_key: &[u8; 32], now: i64) -> Vec<u8> {
|
||||
sign(claims(public_key, now))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_profile_is_bound_to_account_and_unsafe_avatar_is_dropped() {
|
||||
let mut value = claims(&[9; 32], 1000);
|
||||
value["display_name"] = json!("Central Name");
|
||||
value["avatar_url"] = json!("/v1/avatars/default/c3ebd30f-6bb4-4c31-9016-bec57e986c93");
|
||||
let verified = verify(&sign(value.clone()), &[9; 32], Some(&trust()), 1001).unwrap();
|
||||
assert_eq!(verified.display_name.as_deref(), Some("Central Name"));
|
||||
assert!(verified.avatar_url.is_some());
|
||||
value["avatar_url"] = json!("https://github.com/avatar");
|
||||
assert!(
|
||||
verify(&sign(value), &[9; 32], Some(&trust()), 1001)
|
||||
.unwrap()
|
||||
.avatar_url
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn trusted_identity_bound_proof_is_accepted() {
|
||||
assert!(verify(&proof(&[9; 32], 1000), &[9; 32], Some(&trust()), 1001).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn missing_proof_and_missing_trust_fail_closed() {
|
||||
assert!(verify(&[], &[9; 32], Some(&trust()), 1001).is_err());
|
||||
assert!(verify(&proof(&[9; 32], 1000), &[9; 32], None, 1001).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn expiration_future_and_excessive_lifetime_are_rejected() {
|
||||
for (issued, expires) in [
|
||||
(400, 1000),
|
||||
(1001, 1600),
|
||||
(1000, 1601),
|
||||
(1000, 999),
|
||||
(i64::MIN, i64::MAX),
|
||||
] {
|
||||
let mut value = claims(&[9; 32], 1000);
|
||||
value["issued_at"] = json!(issued);
|
||||
value["expires_at"] = json!(expires);
|
||||
assert!(verify(&sign(value), &[9; 32], Some(&trust()), 1000).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn wrong_identity_issuer_audience_and_signature_are_rejected() {
|
||||
assert!(verify(&proof(&[9; 32], 1000), &[8; 32], Some(&trust()), 1001).is_err());
|
||||
for (field, value) in [
|
||||
("issuer", "45cb4c36-7846-41f3-adf6-39e2e208cd50"),
|
||||
("audience", "other"),
|
||||
("subject", "not-a-uuid"),
|
||||
] {
|
||||
let mut claims = claims(&[9; 32], 1000);
|
||||
claims[field] = json!(value);
|
||||
assert!(verify(&sign(claims), &[9; 32], Some(&trust()), 1001).is_err());
|
||||
}
|
||||
let mut envelope: Value = serde_json::from_slice(&proof(&[9; 32], 1000)).unwrap();
|
||||
envelope["signature"] = json!("00".repeat(64));
|
||||
assert!(
|
||||
verify(
|
||||
&serde_json::to_vec(&envelope).unwrap(),
|
||||
&[9; 32],
|
||||
Some(&trust()),
|
||||
1001
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn malformed_and_oversized_envelopes_are_rejected() {
|
||||
for proof in [b"{}".to_vec(), b"not-json".to_vec(), vec![b' '; 8193]] {
|
||||
assert!(verify(&proof, &[9; 32], Some(&trust()), 1001).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
pub mod ops;
|
||||
|
||||
pub use ops::{create, delete, get_channel, join, leave, list, members, rename};
|
||||
pub use ops::{create, delete, get_channel, join, leave, list, members, rename, set_layout};
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
|
@ -10,6 +10,8 @@ use tokio::sync::RwLock;
|
|||
pub enum ChannelKind {
|
||||
Text,
|
||||
Voice,
|
||||
Category,
|
||||
Forum,
|
||||
}
|
||||
|
||||
impl ChannelKind {
|
||||
|
|
@ -17,6 +19,8 @@ impl ChannelKind {
|
|||
match self {
|
||||
Self::Text => "text",
|
||||
Self::Voice => "voice",
|
||||
Self::Category => "category",
|
||||
Self::Forum => "forum",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -27,6 +31,8 @@ pub struct Channel {
|
|||
pub name: String,
|
||||
pub kind: ChannelKind,
|
||||
pub guild_id: Option<String>,
|
||||
pub parent_id: Option<String>,
|
||||
pub position: i32,
|
||||
pub members: HashSet<String>,
|
||||
}
|
||||
|
||||
|
|
@ -41,6 +47,8 @@ pub fn new_store() -> ChannelStore {
|
|||
name: "general".into(),
|
||||
kind: ChannelKind::Text,
|
||||
guild_id: None,
|
||||
parent_id: None,
|
||||
position: 0,
|
||||
members: HashSet::new(),
|
||||
},
|
||||
);
|
||||
|
|
@ -51,6 +59,8 @@ pub fn new_store() -> ChannelStore {
|
|||
name: "voice".into(),
|
||||
kind: ChannelKind::Voice,
|
||||
guild_id: None,
|
||||
parent_id: None,
|
||||
position: 0,
|
||||
members: HashSet::new(),
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -49,6 +49,8 @@ pub async fn create(
|
|||
name: channel_name.to_string(),
|
||||
kind,
|
||||
guild_id,
|
||||
parent_id: None,
|
||||
position: 0,
|
||||
members: std::collections::HashSet::new(),
|
||||
},
|
||||
);
|
||||
|
|
@ -75,3 +77,19 @@ pub async fn rename(store: &ChannelStore, channel_id: &str, new_name: &str) -> b
|
|||
pub async fn list(store: &ChannelStore) -> Vec<Channel> {
|
||||
store.read().await.values().cloned().collect()
|
||||
}
|
||||
|
||||
/// Set persisted one-level parent/order metadata without changing subscriptions.
|
||||
pub async fn set_layout(
|
||||
store: &ChannelStore,
|
||||
id: &str,
|
||||
parent: Option<String>,
|
||||
position: i32,
|
||||
) -> bool {
|
||||
if let Some(channel) = store.write().await.get_mut(id) {
|
||||
channel.parent_id = parent;
|
||||
channel.position = position;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,6 +75,12 @@ pub struct NodeConfig {
|
|||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GatewayConfig {
|
||||
/// Operator-selected Central account UUIDs allowed to manage global node channels.
|
||||
#[serde(default)]
|
||||
pub admin_account_ids: Vec<String>,
|
||||
/// Trusted Central issuer. Missing trust fails closed for every account admission.
|
||||
#[serde(default)]
|
||||
pub central_account: Option<CentralAccountConfig>,
|
||||
pub bind: String,
|
||||
pub max_connections: Option<usize>,
|
||||
pub session_timeout: Option<u64>,
|
||||
|
|
@ -90,7 +96,7 @@ pub struct GatewayConfig {
|
|||
/// Defaults to 10.
|
||||
#[serde(default)]
|
||||
pub message_rate_burst: Option<u32>,
|
||||
/// Deprecated. TLS 1.3 is always on since LNEx v3. `true` is accepted with a warning,
|
||||
/// Deprecated. TLS 1.3 is always on since LNEx v4. `true` is accepted with a warning,
|
||||
/// `false` is a startup error because plaintext is no longer supported.
|
||||
#[serde(default)]
|
||||
pub tls_enabled: Option<bool>,
|
||||
|
|
@ -103,12 +109,54 @@ pub struct GatewayConfig {
|
|||
pub tls_key_path: Option<String>,
|
||||
}
|
||||
|
||||
/// Explicit account proof trust anchor; never accepted from a client or discovered over HTTP.
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CentralAccountConfig {
|
||||
pub issuer: String,
|
||||
pub public_key: String,
|
||||
}
|
||||
|
||||
impl GatewayConfig {
|
||||
/// Validate the explicit account allowlist before opening the gateway listener.
|
||||
pub fn validate_admin_accounts(&self) -> Result<()> {
|
||||
anyhow::ensure!(
|
||||
self.admin_account_ids.len() <= 256,
|
||||
"gateway.admin_account_ids has more than 256 entries"
|
||||
);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for account in &self.admin_account_ids {
|
||||
let id = uuid::Uuid::parse_str(account).map_err(|_| {
|
||||
anyhow::anyhow!("gateway.admin_account_ids must contain Central account UUIDs")
|
||||
})?;
|
||||
anyhow::ensure!(
|
||||
!id.is_nil(),
|
||||
"gateway.admin_account_ids cannot contain the nil UUID"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
seen.insert(id),
|
||||
"gateway.admin_account_ids contains a duplicate account UUID"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// This capability is tied to the admitted Central subject, never a name or device key.
|
||||
pub fn is_node_admin(&self, account_id: &str) -> bool {
|
||||
let Ok(account_id) = uuid::Uuid::parse_str(account_id) else {
|
||||
return false;
|
||||
};
|
||||
!account_id.is_nil()
|
||||
&& self
|
||||
.admin_account_ids
|
||||
.iter()
|
||||
.any(|id| uuid::Uuid::parse_str(id).ok() == Some(account_id))
|
||||
}
|
||||
|
||||
/// Reject configurations that would weaken or break the mandatory TLS 1.3 listener.
|
||||
pub fn validate_tls(&self) -> Result<()> {
|
||||
if self.tls_enabled == Some(false) {
|
||||
anyhow::bail!(
|
||||
"gateway.tls_enabled = false is no longer supported: LNEx v3 requires TLS 1.3; remove the option"
|
||||
"gateway.tls_enabled = false is no longer supported: LNEx v4 requires TLS 1.3; remove the option"
|
||||
);
|
||||
}
|
||||
if self.tls_cert_path.is_some() != self.tls_key_path.is_some() {
|
||||
|
|
@ -140,7 +188,10 @@ pub fn load() -> Result<Config> {
|
|||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| anyhow::anyhow!("cannot read config {path}: {e}"))?;
|
||||
|
||||
toml::from_str(&text).map_err(|e| anyhow::anyhow!("invalid config: {e}"))
|
||||
let config: Config =
|
||||
toml::from_str(&text).map_err(|e| anyhow::anyhow!("invalid config: {e}"))?;
|
||||
config.gateway.validate_admin_accounts()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -151,6 +202,35 @@ mod tests {
|
|||
toml::from_str(&format!("bind = \"127.0.0.1:0\"\n{extra}")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_admin_allowlist_accepts_only_explicit_non_nil_account_uuids() {
|
||||
let none = gateway("");
|
||||
none.validate_admin_accounts().unwrap();
|
||||
assert!(!none.is_node_admin("nick"));
|
||||
for invalid in [
|
||||
"nickname".to_owned(),
|
||||
"a".repeat(64),
|
||||
uuid::Uuid::nil().to_string(),
|
||||
] {
|
||||
assert!(
|
||||
gateway(&format!("admin_account_ids = [\"{invalid}\"]"))
|
||||
.validate_admin_accounts()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let account = uuid::Uuid::new_v4();
|
||||
let valid = gateway(&format!("admin_account_ids = [\"{account}\"]"));
|
||||
valid.validate_admin_accounts().unwrap();
|
||||
assert!(valid.is_node_admin(&account.to_string()));
|
||||
assert!(!valid.is_node_admin(&uuid::Uuid::new_v4().to_string()));
|
||||
assert!(
|
||||
gateway(&format!(
|
||||
"admin_account_ids = [\"{account}\",\"{account}\"]"
|
||||
))
|
||||
.validate_admin_accounts()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn tls_defaults_to_generated_certificate() {
|
||||
gateway("").validate_tls().unwrap();
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
pub mod account;
|
||||
pub mod auth;
|
||||
pub mod channels;
|
||||
pub mod config;
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ pub struct RateLimiter {
|
|||
|
||||
struct Bucket {
|
||||
tokens: f32,
|
||||
fetch_tokens: f32,
|
||||
last_refill: Instant,
|
||||
}
|
||||
|
||||
|
|
@ -34,7 +35,17 @@ impl RateLimiter {
|
|||
/// Try to consume one token. Returns `true` if allowed, `false` if rate-limited.
|
||||
/// Lazily creates a bucket for new sessions.
|
||||
pub fn try_consume(&self, session_id: &str) -> bool {
|
||||
if self.rate_per_sec <= 0.0 {
|
||||
self.consume(session_id, false)
|
||||
}
|
||||
|
||||
/// Separate image-download budget within the same live session entry.
|
||||
/// Fifty initial tokens cover one history page without spending chat tokens.
|
||||
pub fn try_consume_attachment_fetch(&self, session_id: &str) -> bool {
|
||||
self.consume(session_id, true)
|
||||
}
|
||||
|
||||
fn consume(&self, session_id: &str, attachment_fetch: bool) -> bool {
|
||||
if !attachment_fetch && self.rate_per_sec <= 0.0 {
|
||||
return true;
|
||||
}
|
||||
let mut guard = self.inner.lock().unwrap();
|
||||
|
|
@ -43,14 +54,21 @@ impl RateLimiter {
|
|||
.entry(session_id.to_string())
|
||||
.or_insert_with(|| Bucket {
|
||||
tokens: self.burst as f32,
|
||||
fetch_tokens: 50.0,
|
||||
last_refill: now,
|
||||
});
|
||||
// Refill
|
||||
let elapsed = now.duration_since(bucket.last_refill).as_secs_f32();
|
||||
bucket.tokens = (bucket.tokens + elapsed * self.rate_per_sec).min(self.burst as f32);
|
||||
bucket.fetch_tokens = (bucket.fetch_tokens + elapsed * 4.0).min(50.0);
|
||||
bucket.last_refill = now;
|
||||
if bucket.tokens >= 1.0 {
|
||||
bucket.tokens -= 1.0;
|
||||
let tokens = if attachment_fetch {
|
||||
&mut bucket.fetch_tokens
|
||||
} else {
|
||||
&mut bucket.tokens
|
||||
};
|
||||
if *tokens >= 1.0 {
|
||||
*tokens -= 1.0;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
|
@ -105,6 +123,23 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_history_budget_is_separate_and_removed_with_session() {
|
||||
let r = RateLimiter::new(0.1, 1);
|
||||
for _ in 0..50 {
|
||||
assert!(r.try_consume_attachment_fetch("s1"));
|
||||
}
|
||||
assert!(!r.try_consume_attachment_fetch("s1"));
|
||||
assert!(
|
||||
r.try_consume("s1"),
|
||||
"downloads must not consume chat tokens"
|
||||
);
|
||||
assert!(!r.try_consume("s1"));
|
||||
assert!(r.try_consume_attachment_fetch("s2"));
|
||||
r.remove("s1");
|
||||
assert!(r.try_consume_attachment_fetch("s1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_clears_bucket() {
|
||||
let r = RateLimiter::new(0.1, 1);
|
||||
|
|
|
|||
|
|
@ -9,6 +9,10 @@ pub struct Session {
|
|||
pub token: String,
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub account_id: String,
|
||||
pub avatar_url: String,
|
||||
pub profile_issued_at: i64,
|
||||
pub client_features: crate::proto::ClientFeatures,
|
||||
/// Viewed text channel; independent of the active voice room.
|
||||
pub channel_id: Option<String>,
|
||||
pub voice_channel_id: Option<String>,
|
||||
|
|
@ -24,8 +28,12 @@ pub async fn create(store: &SessionStore, user_id: String, nickname: String) ->
|
|||
let s = Session {
|
||||
session_id: Uuid::new_v4().to_string(),
|
||||
token: Uuid::new_v4().to_string(),
|
||||
user_id,
|
||||
user_id: user_id.clone(),
|
||||
nickname,
|
||||
account_id: user_id.clone(),
|
||||
avatar_url: String::new(),
|
||||
profile_issued_at: 0,
|
||||
client_features: Default::default(),
|
||||
channel_id: None,
|
||||
voice_channel_id: None,
|
||||
};
|
||||
|
|
|
|||
116
gateway/src/domain/storage/attachments.rs
Normal file
116
gateway/src/domain/storage/attachments.rs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
use super::{Pool, Storage};
|
||||
use anyhow::Result;
|
||||
|
||||
impl Storage {
|
||||
pub async fn migrate_attachments(&self) -> Result<()> {
|
||||
let sql = "CREATE TABLE IF NOT EXISTS chat_attachments (id TEXT PRIMARY KEY, channel_id TEXT NOT NULL, sender_id TEXT NOT NULL, mime TEXT NOT NULL, data BYTEA NOT NULL)";
|
||||
match &self.pool {
|
||||
Pool::Sqlite(p) => {
|
||||
sqlx::query(sql).execute(p).await?;
|
||||
}
|
||||
Pool::Postgres(p) => {
|
||||
sqlx::query(sql).execute(p).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_attachment(
|
||||
&self,
|
||||
id: &str,
|
||||
channel: &str,
|
||||
) -> Result<Option<(String, Vec<u8>)>> {
|
||||
Ok(match &self.pool {
|
||||
Pool::Sqlite(p) => {
|
||||
sqlx::query_as("SELECT mime,data FROM chat_attachments WHERE id=? AND channel_id=?")
|
||||
.bind(id)
|
||||
.bind(channel)
|
||||
.fetch_optional(p)
|
||||
.await?
|
||||
}
|
||||
Pool::Postgres(p) => {
|
||||
sqlx::query_as(
|
||||
"SELECT mime,data FROM chat_attachments WHERE id=$1 AND channel_id=$2",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(channel)
|
||||
.fetch_optional(p)
|
||||
.await?
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_uploads_cannot_exceed_sender_quota() -> Result<()> {
|
||||
let path = std::env::temp_dir().join(format!("vnox-quota-{}.db", uuid::Uuid::new_v4()));
|
||||
let storage = Storage::connect_sqlite(&path.to_string_lossy()).await?;
|
||||
if let Pool::Sqlite(pool) = &storage.pool {
|
||||
sqlx::query("INSERT INTO chat_attachments(id,channel_id,sender_id,mime,data) VALUES ('existing','one','sender','image/png',zeroblob(66060288))").execute(pool).await?;
|
||||
}
|
||||
let one = crate::proto::ChatMessage {
|
||||
message_id: "one".into(),
|
||||
channel_id: "one".into(),
|
||||
sender_id: "sender".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let two = crate::proto::ChatMessage {
|
||||
message_id: "two".into(),
|
||||
..one.clone()
|
||||
};
|
||||
let data = vec![0; 1024 * 1024];
|
||||
let (a, b) = tokio::join!(
|
||||
storage.save_attachment_message(&one, "a", "image/png", &data),
|
||||
storage.save_attachment_message(&two, "b", "image/png", &data)
|
||||
);
|
||||
assert_eq!(usize::from(a.is_ok()) + usize::from(b.is_ok()), 1);
|
||||
let count = usize::from(storage.get_attachment("a", "one").await?.is_some())
|
||||
+ usize::from(storage.get_attachment("b", "one").await?.is_some());
|
||||
assert_eq!(count, 1);
|
||||
drop(storage);
|
||||
let _ = tokio::fs::remove_file(path).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_bytes_survive_reopen_and_are_channel_scoped() -> Result<()> {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("vnox-attachment-{}.db", uuid::Uuid::new_v4()));
|
||||
let path_text = path.to_string_lossy();
|
||||
let storage = Storage::connect_sqlite(&path_text).await?;
|
||||
let msg = crate::proto::ChatMessage {
|
||||
message_id: "message".into(),
|
||||
channel_id: "one".into(),
|
||||
sender_id: "sender".into(),
|
||||
content: "vnox-attachment:id".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(
|
||||
storage
|
||||
.save_attachment_message(&msg, "id", "image/png", b"test bytes")
|
||||
.await?
|
||||
);
|
||||
assert!(
|
||||
storage
|
||||
.save_attachment_message(&msg, "orphan", "image/png", b"test bytes")
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(storage.get_attachment("orphan", "one").await?.is_none());
|
||||
assert!(storage.get_attachment("id", "two").await?.is_none());
|
||||
assert!(storage.get_attachment("missing", "one").await?.is_none());
|
||||
drop(storage);
|
||||
let storage = Storage::connect_sqlite(&path_text).await?;
|
||||
assert_eq!(
|
||||
storage.get_attachment("id", "one").await?,
|
||||
Some(("image/png".into(), b"test bytes".to_vec()))
|
||||
);
|
||||
drop(storage);
|
||||
let _ = tokio::fs::remove_file(path).await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,10 @@
|
|||
pub mod attachments;
|
||||
pub mod dm_unread;
|
||||
pub mod dms;
|
||||
pub mod e2ee_dms;
|
||||
pub mod guilds;
|
||||
pub mod messages;
|
||||
pub mod node_features;
|
||||
pub mod presence;
|
||||
pub mod social;
|
||||
pub mod webhooks;
|
||||
|
|
@ -31,6 +33,8 @@ impl Storage {
|
|||
};
|
||||
s.migrate().await?;
|
||||
s.migrate_webhooks().await?;
|
||||
s.migrate_attachments().await?;
|
||||
s.migrate_node_features().await?;
|
||||
info!("storage (sqlite): {path}");
|
||||
Ok(s)
|
||||
}
|
||||
|
|
@ -42,6 +46,8 @@ impl Storage {
|
|||
};
|
||||
s.migrate().await?;
|
||||
s.migrate_webhooks().await?;
|
||||
s.migrate_attachments().await?;
|
||||
s.migrate_node_features().await?;
|
||||
info!("storage (postgres): connected");
|
||||
Ok(s)
|
||||
}
|
||||
|
|
@ -445,6 +451,8 @@ pub struct ChannelRecord {
|
|||
pub kind: String,
|
||||
pub guild_id: Option<String>,
|
||||
pub created_at: i64,
|
||||
pub parent_id: Option<String>,
|
||||
pub position: i32,
|
||||
}
|
||||
|
||||
impl Storage {
|
||||
|
|
@ -507,36 +515,47 @@ impl Storage {
|
|||
}
|
||||
|
||||
pub async fn delete_channel(&self, id: &str) -> Result<bool> {
|
||||
macro_rules! delete {
|
||||
($pool:expr) => {{
|
||||
let mut tx = $pool.begin().await?;
|
||||
// A category is organizational: removing it never removes child channels.
|
||||
sqlx::query("UPDATE channel_layout SET parent_id=NULL WHERE parent_id=$1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM channel_layout WHERE channel_id=$1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
// Forum FK RESTRICT refuses data loss if a caller omitted the topic guard.
|
||||
let changed = sqlx::query("DELETE FROM channels WHERE id=$1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected()
|
||||
> 0;
|
||||
tx.commit().await?;
|
||||
Ok(changed)
|
||||
}};
|
||||
}
|
||||
match &self.pool {
|
||||
Pool::Sqlite(p) => {
|
||||
let result = sqlx::query("DELETE FROM channels WHERE id=?")
|
||||
.bind(id)
|
||||
.execute(p)
|
||||
.await?;
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
Pool::Postgres(p) => {
|
||||
let result = sqlx::query("DELETE FROM channels WHERE id=$1")
|
||||
.bind(id)
|
||||
.execute(p)
|
||||
.await?;
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
Pool::Sqlite(pool) => delete!(pool),
|
||||
Pool::Postgres(pool) => delete!(pool),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_channels(&self) -> Result<Vec<ChannelRecord>> {
|
||||
let rows = match &self.pool {
|
||||
Pool::Sqlite(p) => {
|
||||
sqlx::query_as::<_, (String, String, String, Option<String>, i64)>(
|
||||
"SELECT id, name, kind, guild_id, created_at FROM channels",
|
||||
sqlx::query_as::<_, (String, String, String, Option<String>, i64, Option<String>, i32)>(
|
||||
"SELECT c.id,c.name,c.kind,c.guild_id,c.created_at,l.parent_id,COALESCE(l.position,0) FROM channels c LEFT JOIN channel_layout l ON l.channel_id=c.id",
|
||||
)
|
||||
.fetch_all(p)
|
||||
.await?
|
||||
}
|
||||
Pool::Postgres(p) => {
|
||||
sqlx::query_as::<_, (String, String, String, Option<String>, i64)>(
|
||||
"SELECT id, name, kind, guild_id, created_at FROM channels",
|
||||
sqlx::query_as::<_, (String, String, String, Option<String>, i64, Option<String>, i32)>(
|
||||
"SELECT c.id,c.name,c.kind,c.guild_id,c.created_at,l.parent_id,COALESCE(l.position,0) FROM channels c LEFT JOIN channel_layout l ON l.channel_id=c.id",
|
||||
)
|
||||
.fetch_all(p)
|
||||
.await?
|
||||
|
|
@ -544,13 +563,17 @@ impl Storage {
|
|||
};
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(id, name, kind, guild_id, created_at)| ChannelRecord {
|
||||
id,
|
||||
name,
|
||||
kind,
|
||||
guild_id,
|
||||
created_at,
|
||||
})
|
||||
.map(
|
||||
|(id, name, kind, guild_id, created_at, parent_id, position)| ChannelRecord {
|
||||
id,
|
||||
name,
|
||||
kind,
|
||||
guild_id,
|
||||
created_at,
|
||||
parent_id,
|
||||
position,
|
||||
},
|
||||
)
|
||||
.collect())
|
||||
}
|
||||
|
||||
|
|
@ -559,9 +582,18 @@ impl Storage {
|
|||
for ch in channels {
|
||||
let kind = match ch.kind.as_str() {
|
||||
"voice" => ChannelKind::Voice,
|
||||
_ => ChannelKind::Text,
|
||||
"text" => ChannelKind::Text,
|
||||
"category" => ChannelKind::Category,
|
||||
"forum" => ChannelKind::Forum,
|
||||
_ => anyhow::bail!("unsupported stored channel kind"),
|
||||
};
|
||||
crate::domain::channels::create(channel_store, &ch.id, &ch.name, kind, ch.guild_id)
|
||||
if !crate::domain::channels::create(channel_store, &ch.id, &ch.name, kind, ch.guild_id)
|
||||
.await
|
||||
{
|
||||
// Bootstrap IDs already exist in the fresh cache; retain their stored names.
|
||||
crate::domain::channels::rename(channel_store, &ch.id, &ch.name).await;
|
||||
}
|
||||
crate::domain::channels::set_layout(channel_store, &ch.id, ch.parent_id, ch.position)
|
||||
.await;
|
||||
}
|
||||
Ok(())
|
||||
|
|
|
|||
469
gateway/src/domain/storage/node_features.rs
Normal file
469
gateway/src/domain/storage/node_features.rs
Normal file
|
|
@ -0,0 +1,469 @@
|
|||
//! Durable node presentation, category layout and transactional forum posts.
|
||||
use super::{Pool, Storage, now_ms};
|
||||
use crate::proto::{ChatMessagePayload, ForumPost, ForumTopic, MemberInfo};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
|
||||
macro_rules! db {
|
||||
($storage:expr, $pool:ident, $body:block) => {
|
||||
match &$storage.pool {
|
||||
Pool::Sqlite($pool) => $body,
|
||||
Pool::Postgres($pool) => $body,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! validate_layout {
|
||||
($tx:ident,$id:expr,$parent:expr) => {{
|
||||
let (kind,scope):(String,Option<String>)=sqlx::query_as("SELECT kind,guild_id FROM channels WHERE id=$1").bind($id).fetch_one(&mut *$tx).await?;
|
||||
if let Some(parent)=$parent {
|
||||
ensure!(kind!="category", "categories cannot be nested");
|
||||
let target:Option<(String,Option<String>)>=sqlx::query_as("SELECT kind,guild_id FROM channels WHERE id=$1").bind(parent).fetch_optional(&mut *$tx).await?;
|
||||
ensure!(target.is_some_and(|(kind,parent_scope)|kind=="category" && parent_scope==scope), "category must exist in the same scope");
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct TopicRow {
|
||||
topic_id: String,
|
||||
channel_id: String,
|
||||
title: String,
|
||||
author_user_id: String,
|
||||
author_account_id: String,
|
||||
author_nickname: String,
|
||||
author_avatar_url: String,
|
||||
created_at: i64,
|
||||
updated_at: i64,
|
||||
reply_count: i64,
|
||||
}
|
||||
impl TopicRow {
|
||||
fn wire(self) -> ForumTopic {
|
||||
ForumTopic {
|
||||
topic_id: self.topic_id,
|
||||
channel_id: self.channel_id,
|
||||
title: self.title,
|
||||
author: Some(MemberInfo {
|
||||
user_id: self.author_user_id,
|
||||
account_id: self.author_account_id,
|
||||
nickname: self.author_nickname,
|
||||
avatar_url: self.author_avatar_url,
|
||||
in_voice: false,
|
||||
}),
|
||||
created_at: self.created_at,
|
||||
updated_at: self.updated_at,
|
||||
reply_count: u32::try_from(self.reply_count).unwrap_or(u32::MAX),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct PostRow {
|
||||
id: String,
|
||||
channel_id: String,
|
||||
sender_id: String,
|
||||
content: String,
|
||||
timestamp: i64,
|
||||
reply_to: Option<String>,
|
||||
topic_id: String,
|
||||
post_index: i64,
|
||||
author_account_id: String,
|
||||
author_nickname: String,
|
||||
author_avatar_url: String,
|
||||
}
|
||||
impl PostRow {
|
||||
fn same_request(&self, channel: &str, topic: &str, body: &str, author: &MemberInfo) -> bool {
|
||||
self.channel_id == channel
|
||||
&& self.topic_id == topic
|
||||
&& self.content == body
|
||||
&& self.sender_id == author.user_id
|
||||
&& self.author_account_id == author.account_id
|
||||
}
|
||||
fn wire(self) -> ForumPost {
|
||||
ForumPost {
|
||||
topic_id: self.topic_id,
|
||||
ordinal: u64::try_from(self.post_index).unwrap_or_default(),
|
||||
author: Some(MemberInfo {
|
||||
user_id: self.sender_id.clone(),
|
||||
account_id: self.author_account_id,
|
||||
nickname: self.author_nickname,
|
||||
avatar_url: self.author_avatar_url,
|
||||
in_voice: false,
|
||||
}),
|
||||
message: Some(ChatMessagePayload {
|
||||
message_id: self.id,
|
||||
channel_id: self.channel_id,
|
||||
sender_id: self.sender_id,
|
||||
content: self.content,
|
||||
timestamp: self.timestamp,
|
||||
reply_to: self.reply_to,
|
||||
edited: false,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
macro_rules! topic_sql { ($tail:literal) => { concat!("SELECT topic_id,channel_id,title,author_user_id,author_account_id,author_nickname,author_avatar_url,created_at,updated_at,reply_count FROM forum_topics", $tail) }; }
|
||||
macro_rules! post_sql { ($tail:literal) => { concat!("SELECT m.id,m.channel_id,m.sender_id,m.content,m.timestamp,m.reply_to,p.topic_id,p.post_index,p.author_account_id,p.author_nickname,p.author_avatar_url FROM forum_posts p JOIN messages m ON m.id=p.message_id JOIN forum_topics t ON t.topic_id=p.topic_id AND t.channel_id=m.channel_id", $tail) }; }
|
||||
fn validate_post(
|
||||
topic: &str,
|
||||
message: &str,
|
||||
channel: &str,
|
||||
body: &str,
|
||||
author: &MemberInfo,
|
||||
) -> Result<()> {
|
||||
for id in [topic, message] {
|
||||
ensure!(
|
||||
uuid::Uuid::parse_str(id).is_ok_and(|v| !v.is_nil() && v.to_string() == id),
|
||||
"forum identifiers must be canonical UUIDs"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
!channel.is_empty() && channel.len() <= 128,
|
||||
"invalid forum channel"
|
||||
);
|
||||
ensure!(
|
||||
!body.trim().is_empty() && body.len() <= 64 * 1024 && body.chars().count() <= 16_000,
|
||||
"forum post must contain 1–16000 characters within 64 KiB"
|
||||
);
|
||||
ensure!(
|
||||
!author.user_id.is_empty()
|
||||
&& author.user_id.len() <= 128
|
||||
&& !author.account_id.is_empty()
|
||||
&& author.account_id.len() <= 128,
|
||||
"authenticated forum author required"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
impl Storage {
|
||||
pub async fn migrate_node_features(&self) -> Result<()> {
|
||||
let schema = "CREATE TABLE IF NOT EXISTS node_settings (singleton INTEGER PRIMARY KEY CHECK(singleton=1),display_name TEXT NOT NULL,description TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS channel_layout (channel_id TEXT PRIMARY KEY REFERENCES channels(id) ON DELETE CASCADE,parent_id TEXT REFERENCES channels(id) ON DELETE SET NULL,position INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_layout_parent ON channel_layout(parent_id,position);
|
||||
CREATE TABLE IF NOT EXISTS forum_topics (topic_id TEXT PRIMARY KEY,channel_id TEXT NOT NULL REFERENCES channels(id) ON DELETE RESTRICT,title TEXT NOT NULL,author_user_id TEXT NOT NULL,author_account_id TEXT NOT NULL,author_nickname TEXT NOT NULL,author_avatar_url TEXT NOT NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,reply_count BIGINT NOT NULL DEFAULT 0 CHECK(reply_count>=0));
|
||||
CREATE INDEX IF NOT EXISTS idx_forum_topics_channel ON forum_topics(channel_id,updated_at,topic_id);
|
||||
CREATE TABLE IF NOT EXISTS forum_posts (message_id TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE RESTRICT,topic_id TEXT NOT NULL REFERENCES forum_topics(topic_id) ON DELETE RESTRICT,post_index BIGINT NOT NULL CHECK(post_index>=0),author_account_id TEXT NOT NULL,author_nickname TEXT NOT NULL,author_avatar_url TEXT NOT NULL,UNIQUE(topic_id,post_index));
|
||||
CREATE INDEX IF NOT EXISTS idx_forum_posts_topic ON forum_posts(topic_id,post_index);";
|
||||
db!(self, pool, {
|
||||
sqlx::raw_sql(schema).execute(pool).await?;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
pub async fn load_node_settings(&self) -> Result<Option<(String, String)>> {
|
||||
db!(self, pool, {
|
||||
Ok(sqlx::query_as(
|
||||
"SELECT display_name,description FROM node_settings WHERE singleton=1",
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await?)
|
||||
})
|
||||
}
|
||||
pub async fn save_node_settings(&self, name: &str, description: &str) -> Result<()> {
|
||||
ensure!(
|
||||
!name.trim().is_empty()
|
||||
&& name.chars().count() <= 100
|
||||
&& !name.chars().any(char::is_control),
|
||||
"invalid node name"
|
||||
);
|
||||
ensure!(
|
||||
description.chars().count() <= 2000,
|
||||
"node description is too long"
|
||||
);
|
||||
db!(self, pool, {
|
||||
sqlx::query("INSERT INTO node_settings(singleton,display_name,description) VALUES(1,$1,$2) ON CONFLICT(singleton) DO UPDATE SET display_name=excluded.display_name,description=excluded.description").bind(name).bind(description).execute(pool).await?;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
pub async fn set_channel_layout(
|
||||
&self,
|
||||
id: &str,
|
||||
parent: Option<&str>,
|
||||
position: i32,
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
position >= 0 && parent != Some(id),
|
||||
"invalid channel layout"
|
||||
);
|
||||
db!(self, pool, {
|
||||
let mut tx = pool.begin().await?;
|
||||
// Built-in channels predate persistent channel rows; materialize only these IDs.
|
||||
if ["general", "voice"].contains(&id) {
|
||||
sqlx::query("INSERT INTO channels(id,name,kind,guild_id,created_at) VALUES($1,$1,$2,NULL,$3) ON CONFLICT(id) DO NOTHING")
|
||||
.bind(id).bind(if id=="voice" {"voice"} else {"text"}).bind(now_ms()).execute(&mut *tx).await?;
|
||||
}
|
||||
let (kind, scope): (String, Option<String>) =
|
||||
sqlx::query_as("SELECT kind,guild_id FROM channels WHERE id=$1")
|
||||
.bind(id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if let Some(parent) = parent {
|
||||
ensure!(kind != "category", "categories cannot be nested");
|
||||
let target: Option<(String, Option<String>)> =
|
||||
sqlx::query_as("SELECT kind,guild_id FROM channels WHERE id=$1")
|
||||
.bind(parent)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
ensure!(
|
||||
target.is_some_and(
|
||||
|(kind, parent_scope)| kind == "category" && parent_scope == scope
|
||||
),
|
||||
"category must exist in the same scope"
|
||||
);
|
||||
}
|
||||
sqlx::query("INSERT INTO channel_layout(channel_id,parent_id,position) VALUES($1,$2,$3) ON CONFLICT(channel_id) DO UPDATE SET parent_id=excluded.parent_id,position=excluded.position")
|
||||
.bind(id).bind(parent).bind(position).execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
/// Commit a channel and its layout together; a rejected parent cannot leave an orphan.
|
||||
pub async fn create_channel_with_layout(
|
||||
&self,
|
||||
id: &str,
|
||||
name: &str,
|
||||
kind: &str,
|
||||
guild: Option<&str>,
|
||||
parent: Option<&str>,
|
||||
position: i32,
|
||||
) -> Result<bool> {
|
||||
ensure!(
|
||||
position >= 0 && parent != Some(id),
|
||||
"invalid channel layout"
|
||||
);
|
||||
db!(self, pool, {
|
||||
let mut tx = pool.begin().await?;
|
||||
let inserted=sqlx::query("INSERT INTO channels(id,name,kind,guild_id,created_at) VALUES($1,$2,$3,$4,$5) ON CONFLICT(id) DO NOTHING")
|
||||
.bind(id).bind(name).bind(kind).bind(guild).bind(now_ms()).execute(&mut *tx).await?.rows_affected()>0;
|
||||
if !inserted {
|
||||
tx.commit().await?;
|
||||
return Ok(false);
|
||||
}
|
||||
validate_layout!(tx, id, parent);
|
||||
sqlx::query(
|
||||
"INSERT INTO channel_layout(channel_id,parent_id,position) VALUES($1,$2,$3)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(parent)
|
||||
.bind(position)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
/// Rename/move is one transaction, including legacy bootstrap-row materialization.
|
||||
pub async fn update_channel_with_layout(
|
||||
&self,
|
||||
id: &str,
|
||||
name: &str,
|
||||
parent: Option<&str>,
|
||||
position: i32,
|
||||
) -> Result<bool> {
|
||||
ensure!(
|
||||
position >= 0 && parent != Some(id),
|
||||
"invalid channel layout"
|
||||
);
|
||||
db!(self, pool, {
|
||||
let mut tx = pool.begin().await?;
|
||||
if ["general", "voice"].contains(&id) {
|
||||
sqlx::query("INSERT INTO channels(id,name,kind,guild_id,created_at) VALUES($1,$2,$3,NULL,$4) ON CONFLICT(id) DO NOTHING")
|
||||
.bind(id).bind(name).bind(if id=="voice" {"voice"} else {"text"}).bind(now_ms()).execute(&mut *tx).await?;
|
||||
}
|
||||
let changed = sqlx::query("UPDATE channels SET name=$1 WHERE id=$2")
|
||||
.bind(name)
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected()
|
||||
> 0;
|
||||
if !changed {
|
||||
tx.commit().await?;
|
||||
return Ok(false);
|
||||
}
|
||||
validate_layout!(tx, id, parent);
|
||||
sqlx::query("INSERT INTO channel_layout(channel_id,parent_id,position) VALUES($1,$2,$3) ON CONFLICT(channel_id) DO UPDATE SET parent_id=excluded.parent_id,position=excluded.position")
|
||||
.bind(id).bind(parent).bind(position).execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
pub async fn forum_has_topics(&self, channel: &str) -> Result<bool> {
|
||||
db!(self, pool, {
|
||||
Ok(sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM forum_topics WHERE channel_id=$1)",
|
||||
)
|
||||
.bind(channel)
|
||||
.fetch_one(pool)
|
||||
.await?)
|
||||
})
|
||||
}
|
||||
pub async fn guild_has_forum_topics(&self, guild: &str) -> Result<bool> {
|
||||
db!(self, pool, {
|
||||
Ok(sqlx::query_scalar::<_,bool>("SELECT EXISTS(SELECT 1 FROM forum_topics t JOIN channels c ON c.id=t.channel_id WHERE c.guild_id=$1)").bind(guild).fetch_one(pool).await?)
|
||||
})
|
||||
}
|
||||
pub async fn forum_list(
|
||||
&self,
|
||||
channel: &str,
|
||||
offset: u32,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ForumTopic>> {
|
||||
db!(self, pool, {
|
||||
let query = topic_sql!(
|
||||
" WHERE channel_id=$1 ORDER BY updated_at DESC,topic_id LIMIT $2 OFFSET $3"
|
||||
);
|
||||
Ok(sqlx::query_as::<_, TopicRow>(query)
|
||||
.bind(channel)
|
||||
.bind(i64::from(limit.min(101)))
|
||||
.bind(i64::from(offset))
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(TopicRow::wire)
|
||||
.collect())
|
||||
})
|
||||
}
|
||||
pub async fn forum_topic(&self, channel: &str, topic: &str) -> Result<Option<ForumTopic>> {
|
||||
db!(self, pool, {
|
||||
let query = topic_sql!(" WHERE channel_id=$1 AND topic_id=$2");
|
||||
Ok(sqlx::query_as::<_, TopicRow>(query)
|
||||
.bind(channel)
|
||||
.bind(topic)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.map(TopicRow::wire))
|
||||
})
|
||||
}
|
||||
pub async fn forum_posts(
|
||||
&self,
|
||||
channel: &str,
|
||||
topic: &str,
|
||||
offset: u32,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ForumPost>> {
|
||||
db!(self, pool, {
|
||||
let query = post_sql!(
|
||||
" WHERE m.channel_id=$1 AND p.topic_id=$2 ORDER BY p.post_index LIMIT $3 OFFSET $4"
|
||||
);
|
||||
Ok(sqlx::query_as::<_, PostRow>(query)
|
||||
.bind(channel)
|
||||
.bind(topic)
|
||||
.bind(i64::from(limit.min(101)))
|
||||
.bind(i64::from(offset))
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(PostRow::wire)
|
||||
.collect())
|
||||
})
|
||||
}
|
||||
pub async fn forum_create(
|
||||
&self,
|
||||
topic_id: &str,
|
||||
message_id: &str,
|
||||
channel: &str,
|
||||
title: &str,
|
||||
content: &str,
|
||||
author: &MemberInfo,
|
||||
) -> Result<(ForumTopic, ForumPost)> {
|
||||
validate_post(topic_id, message_id, channel, content, author)?;
|
||||
ensure!(
|
||||
!title.trim().is_empty()
|
||||
&& title.chars().count() <= 160
|
||||
&& !title.chars().any(char::is_control),
|
||||
"invalid forum topic title"
|
||||
);
|
||||
db!(self, pool, {
|
||||
let mut tx = pool.begin().await?;
|
||||
let time = now_ms();
|
||||
let inserted=sqlx::query("INSERT INTO forum_topics(topic_id,channel_id,title,author_user_id,author_account_id,author_nickname,author_avatar_url,created_at,updated_at,reply_count) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$8,0) ON CONFLICT(topic_id) DO NOTHING")
|
||||
.bind(topic_id).bind(channel).bind(title).bind(&author.user_id).bind(&author.account_id).bind(&author.nickname).bind(&author.avatar_url).bind(time).execute(&mut *tx).await?.rows_affected()>0;
|
||||
if !inserted {
|
||||
let tq = topic_sql!(" WHERE topic_id=$1");
|
||||
let topic = sqlx::query_as::<_, TopicRow>(tq)
|
||||
.bind(topic_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let pq = post_sql!(" WHERE p.topic_id=$1 AND p.post_index=0");
|
||||
let post = sqlx::query_as::<_, PostRow>(pq)
|
||||
.bind(topic_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
ensure!(
|
||||
topic.channel_id == channel
|
||||
&& topic.title == title
|
||||
&& post.id == message_id
|
||||
&& post.same_request(channel, topic_id, content, author),
|
||||
"forum topic identifier conflict"
|
||||
);
|
||||
tx.commit().await?;
|
||||
return Ok((topic.wire(), post.wire()));
|
||||
}
|
||||
// Never adopt an existing chat message ID into a forum: conflict rolls back topic too.
|
||||
sqlx::query("INSERT INTO messages(id,channel_id,sender_id,content,timestamp,reply_to) VALUES($1,$2,$3,$4,$5,NULL)").bind(message_id).bind(channel).bind(&author.user_id).bind(content).bind(time).execute(&mut *tx).await?;
|
||||
sqlx::query("INSERT INTO forum_posts(message_id,topic_id,post_index,author_account_id,author_nickname,author_avatar_url) VALUES($1,$2,0,$3,$4,$5)").bind(message_id).bind(topic_id).bind(&author.account_id).bind(&author.nickname).bind(&author.avatar_url).execute(&mut *tx).await?;
|
||||
let tq = topic_sql!(" WHERE topic_id=$1");
|
||||
let pq = post_sql!(" WHERE p.message_id=$1");
|
||||
let topic = sqlx::query_as::<_, TopicRow>(tq)
|
||||
.bind(topic_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let post = sqlx::query_as::<_, PostRow>(pq)
|
||||
.bind(message_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok((topic.wire(), post.wire()))
|
||||
})
|
||||
}
|
||||
pub async fn forum_reply(
|
||||
&self,
|
||||
message_id: &str,
|
||||
channel: &str,
|
||||
topic_id: &str,
|
||||
content: &str,
|
||||
author: &MemberInfo,
|
||||
) -> Result<(ForumTopic, ForumPost)> {
|
||||
validate_post(topic_id, message_id, channel, content, author)?;
|
||||
db!(self, pool, {
|
||||
let mut tx = pool.begin().await?;
|
||||
// Acquire the writer/row lock before reading idempotency state; increments cannot race.
|
||||
let query = "UPDATE forum_topics SET updated_at=updated_at WHERE channel_id=$1 AND topic_id=$2 RETURNING topic_id,channel_id,title,author_user_id,author_account_id,author_nickname,author_avatar_url,created_at,updated_at,reply_count";
|
||||
let topic = sqlx::query_as::<_, TopicRow>(query)
|
||||
.bind(channel)
|
||||
.bind(topic_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.context("forum topic not found")?;
|
||||
let pq = post_sql!(" WHERE p.message_id=$1");
|
||||
if let Some(post) = sqlx::query_as::<_, PostRow>(pq)
|
||||
.bind(message_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
{
|
||||
ensure!(
|
||||
post.same_request(channel, topic_id, content, author),
|
||||
"forum post identifier conflict"
|
||||
);
|
||||
tx.commit().await?;
|
||||
return Ok((topic.wire(), post.wire()));
|
||||
}
|
||||
let time = now_ms();
|
||||
sqlx::query("INSERT INTO messages(id,channel_id,sender_id,content,timestamp,reply_to) VALUES($1,$2,$3,$4,$5,NULL)").bind(message_id).bind(channel).bind(&author.user_id).bind(content).bind(time).execute(&mut *tx).await?;
|
||||
let query = "UPDATE forum_topics SET reply_count=reply_count+1,updated_at=CASE WHEN updated_at>$1 THEN updated_at ELSE $1 END WHERE channel_id=$2 AND topic_id=$3 RETURNING topic_id,channel_id,title,author_user_id,author_account_id,author_nickname,author_avatar_url,created_at,updated_at,reply_count";
|
||||
let topic = sqlx::query_as::<_, TopicRow>(query)
|
||||
.bind(time)
|
||||
.bind(channel)
|
||||
.bind(topic_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO forum_posts(message_id,topic_id,post_index,author_account_id,author_nickname,author_avatar_url) VALUES($1,$2,$3,$4,$5,$6)").bind(message_id).bind(topic_id).bind(topic.reply_count).bind(&author.account_id).bind(&author.nickname).bind(&author.avatar_url).execute(&mut *tx).await?;
|
||||
let post = sqlx::query_as::<_, PostRow>(pq)
|
||||
.bind(message_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok((topic.wire(), post.wire()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
354
gateway/src/domain/storage/node_features/tests.rs
Normal file
354
gateway/src/domain/storage/node_features/tests.rs
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
use super::*;
|
||||
use std::sync::Arc;
|
||||
fn id() -> String {
|
||||
uuid::Uuid::new_v4().to_string()
|
||||
}
|
||||
fn author() -> MemberInfo {
|
||||
MemberInfo {
|
||||
user_id: "device-a".into(),
|
||||
account_id: "account-a".into(),
|
||||
nickname: "Alice".into(),
|
||||
avatar_url: "/v1/avatars/default-v2/11111111-1111-4111-8111-111111111111".into(),
|
||||
in_voice: false,
|
||||
}
|
||||
}
|
||||
async fn fixture() -> Result<Storage> {
|
||||
let store = Storage::connect_sqlite(":memory:").await?;
|
||||
store
|
||||
.create_channel("forum", "Forum", "forum", None)
|
||||
.await?;
|
||||
Ok(store)
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn forum_creation_reply_and_retries_are_atomic_and_ordered() -> Result<()> {
|
||||
let store = fixture().await?;
|
||||
let topic = id();
|
||||
let first = id();
|
||||
let reply = id();
|
||||
let (t, p) = store
|
||||
.forum_create(&topic, &first, "forum", "Topic", "first", &author())
|
||||
.await?;
|
||||
assert_eq!(t.reply_count, 0);
|
||||
assert_eq!(p.ordinal, 0);
|
||||
let retry = store
|
||||
.forum_create(&topic, &first, "forum", "Topic", "first", &author())
|
||||
.await?;
|
||||
assert_eq!(retry.1.message.as_ref().unwrap().message_id, first);
|
||||
let (t, p) = store
|
||||
.forum_reply(&reply, "forum", &topic, "reply", &author())
|
||||
.await?;
|
||||
assert_eq!(t.reply_count, 1);
|
||||
assert_eq!(p.ordinal, 1);
|
||||
let retry = store
|
||||
.forum_reply(&reply, "forum", &topic, "reply", &author())
|
||||
.await?;
|
||||
assert_eq!(retry.0.reply_count, 1);
|
||||
let posts = store.forum_posts("forum", &topic, 0, 101).await?;
|
||||
assert_eq!(posts.len(), 2);
|
||||
assert_eq!(posts.iter().map(|p| p.ordinal).collect::<Vec<_>>(), [0, 1]);
|
||||
assert_eq!(
|
||||
store.forum_posts("forum", &topic, 1, 1).await?[0]
|
||||
.message
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.content,
|
||||
"reply"
|
||||
);
|
||||
assert_eq!(store.forum_list("forum", 0, 51).await?.len(), 1);
|
||||
assert!(
|
||||
store
|
||||
.forum_posts("another-forum", &topic, 0, 100)
|
||||
.await?
|
||||
.is_empty()
|
||||
);
|
||||
assert!(store.forum_topic("another-forum", &topic).await?.is_none());
|
||||
let mut other = author();
|
||||
other.account_id = "another-account".into();
|
||||
assert!(
|
||||
store
|
||||
.forum_create(&topic, &first, "forum", "Topic", "first", &other)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
.forum_reply(&reply, "forum", &topic, "changed", &author())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.forum_topic("forum", &topic)
|
||||
.await?
|
||||
.unwrap()
|
||||
.reply_count,
|
||||
1
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn an_existing_private_chat_message_cannot_be_adopted_or_leave_a_partial_topic() -> Result<()>
|
||||
{
|
||||
let store = fixture().await?;
|
||||
let message = id();
|
||||
let bad_topic = id();
|
||||
store
|
||||
.save_message(&ChatMessagePayload {
|
||||
message_id: message.clone(),
|
||||
channel_id: "private-room".into(),
|
||||
sender_id: author().user_id,
|
||||
content: "private existing body".into(),
|
||||
timestamp: 1,
|
||||
edited: false,
|
||||
reply_to: None,
|
||||
})
|
||||
.await?;
|
||||
assert!(
|
||||
store
|
||||
.forum_create(&bad_topic, &message, "forum", "Topic", "first", &author())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(store.forum_topic("forum", &bad_topic).await?.is_none());
|
||||
assert!(store.forum_list("forum", 0, 50).await?.is_empty());
|
||||
let topic = id();
|
||||
store
|
||||
.forum_create(&topic, &id(), "forum", "Valid", "first", &author())
|
||||
.await?;
|
||||
assert!(
|
||||
store
|
||||
.forum_reply(
|
||||
&message,
|
||||
"forum",
|
||||
&topic,
|
||||
"private existing body",
|
||||
&author()
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.forum_topic("forum", &topic)
|
||||
.await?
|
||||
.unwrap()
|
||||
.reply_count,
|
||||
0
|
||||
);
|
||||
assert_eq!(store.forum_posts("forum", &topic, 0, 100).await?.len(), 1);
|
||||
assert_eq!(
|
||||
store.get_history("private-room", 10).await?[0].content,
|
||||
"private existing body"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn category_removal_keeps_child_channels_and_forum_posts_and_invalid_scope_rolls_back()
|
||||
-> Result<()> {
|
||||
let store = fixture().await?;
|
||||
store
|
||||
.create_channel("category", "Group", "category", None)
|
||||
.await?;
|
||||
store
|
||||
.create_channel("foreign", "Private", "category", Some("guild"))
|
||||
.await?;
|
||||
store
|
||||
.set_channel_layout("forum", Some("category"), 4)
|
||||
.await?;
|
||||
store
|
||||
.set_channel_layout("general", Some("category"), 5)
|
||||
.await?;
|
||||
assert!(
|
||||
store
|
||||
.set_channel_layout("forum", Some("foreign"), 2)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
.set_channel_layout("category", Some("foreign"), 2)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
.set_channel_layout("forum", Some("general"), 2)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.list_channels()
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|c| c.id == "forum")
|
||||
.unwrap()
|
||||
.parent_id
|
||||
.as_deref(),
|
||||
Some("category")
|
||||
);
|
||||
let topic = id();
|
||||
store
|
||||
.forum_create(&topic, &id(), "forum", "Topic", "first", &author())
|
||||
.await?;
|
||||
assert!(store.delete_channel("forum").await.is_err());
|
||||
assert_eq!(
|
||||
store
|
||||
.list_channels()
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|c| c.id == "forum")
|
||||
.unwrap()
|
||||
.parent_id
|
||||
.as_deref(),
|
||||
Some("category")
|
||||
);
|
||||
assert!(store.delete_channel("category").await?);
|
||||
let rows = store.list_channels().await?;
|
||||
assert!(
|
||||
rows.iter()
|
||||
.any(|c| c.id == "forum" && c.parent_id.is_none())
|
||||
);
|
||||
assert!(
|
||||
rows.iter()
|
||||
.any(|c| c.id == "general" && c.parent_id.is_none())
|
||||
);
|
||||
assert_eq!(store.forum_posts("forum", &topic, 0, 100).await?.len(), 1);
|
||||
Ok(())
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn concurrent_replies_and_duplicate_creates_have_one_total_order() -> Result<()> {
|
||||
let store = Arc::new(fixture().await?);
|
||||
let topic = id();
|
||||
let first = id();
|
||||
let a = author();
|
||||
let (left, right) = tokio::join!(
|
||||
store.forum_create(&topic, &first, "forum", "Topic", "first", &a),
|
||||
store.forum_create(&topic, &first, "forum", "Topic", "first", &a)
|
||||
);
|
||||
left?;
|
||||
right?;
|
||||
let mut workers = Vec::new();
|
||||
for index in 0..12 {
|
||||
let store = store.clone();
|
||||
let topic = topic.clone();
|
||||
workers.push(tokio::spawn(async move {
|
||||
store
|
||||
.forum_reply(&id(), "forum", &topic, &format!("reply {index}"), &author())
|
||||
.await
|
||||
}));
|
||||
}
|
||||
for worker in workers {
|
||||
worker.await??;
|
||||
}
|
||||
let posts = store.forum_posts("forum", &topic, 0, 100).await?;
|
||||
assert_eq!(posts.len(), 13);
|
||||
assert_eq!(
|
||||
posts.iter().map(|post| post.ordinal).collect::<Vec<_>>(),
|
||||
(0..=12).collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.forum_topic("forum", &topic)
|
||||
.await?
|
||||
.unwrap()
|
||||
.reply_count,
|
||||
12
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn node_settings_layout_and_topics_survive_reopen_and_cache_load() -> Result<()> {
|
||||
let folder = std::env::temp_dir().join(format!("vnox-node-features-{}", id()));
|
||||
std::fs::create_dir_all(&folder)?;
|
||||
let path = folder.join("data.sqlite");
|
||||
let path = path.to_str().unwrap();
|
||||
let store = Storage::connect_sqlite(path).await?;
|
||||
store
|
||||
.save_node_settings("Наш сервер", "Описание\nсервера")
|
||||
.await?;
|
||||
assert!(store.save_node_settings("\ninvalid", "x").await.is_err());
|
||||
store
|
||||
.create_channel("category", "Group", "category", None)
|
||||
.await?;
|
||||
store
|
||||
.create_channel("forum", "Forum", "forum", None)
|
||||
.await?;
|
||||
store
|
||||
.set_channel_layout("forum", Some("category"), 3)
|
||||
.await?;
|
||||
let topic = id();
|
||||
store
|
||||
.forum_create(&topic, &id(), "forum", "Topic", "first", &author())
|
||||
.await?;
|
||||
if let Pool::Sqlite(pool) = &store.pool {
|
||||
pool.close().await;
|
||||
}
|
||||
let reopened = Storage::connect_sqlite(path).await?;
|
||||
assert_eq!(
|
||||
reopened.load_node_settings().await?,
|
||||
Some(("Наш сервер".into(), "Описание\nсервера".into()))
|
||||
);
|
||||
let cache = crate::domain::channels::new_store();
|
||||
reopened.load_channels_to_cache(&cache).await?;
|
||||
let forum = crate::domain::channels::get_channel(&cache, "forum")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(forum.kind, crate::domain::channels::ChannelKind::Forum);
|
||||
assert_eq!(forum.parent_id.as_deref(), Some("category"));
|
||||
assert_eq!(forum.position, 3);
|
||||
assert_eq!(
|
||||
reopened.forum_posts("forum", &topic, 0, 100).await?.len(),
|
||||
1
|
||||
);
|
||||
assert!(reopened.forum_has_topics("forum").await?);
|
||||
assert!(!reopened.guild_has_forum_topics("absent").await?);
|
||||
if let Pool::Sqlite(pool) = &reopened.pool {
|
||||
pool.close().await;
|
||||
}
|
||||
std::fs::remove_dir_all(folder)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_layout_cannot_partially_create_rename_or_materialize_a_bootstrap_channel()
|
||||
-> Result<()> {
|
||||
let store = fixture().await?;
|
||||
assert!(
|
||||
store
|
||||
.create_channel_with_layout("new", "New", "text", None, Some("missing"), 0)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(!store.list_channels().await?.iter().any(|c| c.id == "new"));
|
||||
assert!(
|
||||
store
|
||||
.update_channel_with_layout("forum", "Changed", Some("missing"), 1)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.list_channels()
|
||||
.await?
|
||||
.iter()
|
||||
.find(|c| c.id == "forum")
|
||||
.unwrap()
|
||||
.name,
|
||||
"Forum"
|
||||
);
|
||||
assert!(
|
||||
store
|
||||
.update_channel_with_layout("general", "Changed", Some("missing"), 1)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
!store
|
||||
.list_channels()
|
||||
.await?
|
||||
.iter()
|
||||
.any(|c| c.id == "general")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -126,6 +126,27 @@ impl Storage {
|
|||
&self,
|
||||
msg: &ChatMessagePayload,
|
||||
receipt: Option<(&str, &str, &str, &str)>,
|
||||
) -> Result<bool> {
|
||||
self.save_message_with_attachment(msg, receipt, None).await
|
||||
}
|
||||
|
||||
/// Commit validated image bytes, quotas, history and outgoing events atomically.
|
||||
pub async fn save_attachment_message(
|
||||
&self,
|
||||
msg: &ChatMessagePayload,
|
||||
id: &str,
|
||||
mime: &str,
|
||||
data: &[u8],
|
||||
) -> Result<bool> {
|
||||
self.save_message_with_attachment(msg, None, Some((id, mime, data)))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn save_message_with_attachment(
|
||||
&self,
|
||||
msg: &ChatMessagePayload,
|
||||
receipt: Option<(&str, &str, &str, &str)>,
|
||||
attachment: Option<(&str, &str, &[u8])>,
|
||||
) -> Result<bool> {
|
||||
let event_id = uuid::Uuid::new_v4().to_string();
|
||||
let event=serde_json::json!({"type":"message.created","id":event_id,"occurred_at":crate::webhooks::now_ms(),"message":{"id":msg.message_id.chars().take(128).collect::<String>(),"id_truncated":msg.message_id.chars().count()>128,"channel_id":msg.channel_id,"sender_id":msg.sender_id,"content":msg.content.chars().take(8000).collect::<String>(),"content_truncated":msg.content.chars().count()>8000,"timestamp":msg.timestamp}}).to_string();
|
||||
|
|
@ -133,6 +154,14 @@ impl Storage {
|
|||
let mut tx = $p.begin().await?;
|
||||
// Serialize capacity checks and receipt inserts across concurrent publishers.
|
||||
sqlx::query($lock).execute(&mut *tx).await?;
|
||||
if let Some((id, mime, data)) = attachment {
|
||||
anyhow::ensure!(!data.is_empty() && data.len() <= 3 * 1024 * 1024, "image exceeds byte limits");
|
||||
let (global_count, personal_count): (i64,i64) = sqlx::query_as("SELECT COUNT(*), COALESCE(SUM(CASE WHEN sender_id=$1 THEN 1 ELSE 0 END),0) FROM chat_attachments").bind(&msg.sender_id).fetch_one(&mut *tx).await?;
|
||||
anyhow::ensure!(global_count < 100_000 && personal_count < 10_000, "image attachment count quota reached");
|
||||
let (global, personal): (i64, i64) = sqlx::query_as("SELECT COALESCE(SUM(length(data)),0), COALESCE(SUM(CASE WHEN sender_id=$1 THEN length(data) ELSE 0 END),0) FROM chat_attachments").bind(&msg.sender_id).fetch_one(&mut *tx).await?;
|
||||
anyhow::ensure!(global + data.len() as i64 <= 512 * 1024 * 1024 && personal + data.len() as i64 <= 64 * 1024 * 1024, "image storage quota reached");
|
||||
sqlx::query("INSERT INTO chat_attachments (id,channel_id,sender_id,mime,data) VALUES ($1,$2,$3,$4,$5)").bind(id).bind(&msg.channel_id).bind(&msg.sender_id).bind(mime).bind(data).execute(&mut *tx).await?;
|
||||
}
|
||||
if let Some((hook, delivery, hash, token_hash)) = receipt {
|
||||
// Lock and revalidate the credential immediately before persistence, so rotation/revocation cannot race a waiting delivery.
|
||||
let active=sqlx::query("UPDATE webhooks SET created_at=created_at WHERE id=$1 AND token_hash=$2 AND channel_id=$3 AND revoked_at IS NULL AND direction='incoming'").bind(hook).bind(token_hash).bind(&msg.channel_id).execute(&mut *tx).await?.rows_affected();
|
||||
|
|
@ -163,6 +192,7 @@ impl Storage {
|
|||
sqlx::query("INSERT INTO webhook_receipts(hook_id,delivery_id,body_hash,message_id,created_at) VALUES($1,$2,$3,$4,$5)").bind(hook).bind(delivery).bind(hash).bind(&msg.message_id).bind(crate::webhooks::now_ms()).execute(&mut *tx).await?;
|
||||
}
|
||||
let inserted=sqlx::query("INSERT INTO messages(id,channel_id,sender_id,content,timestamp,reply_to) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(id) DO NOTHING").bind(&msg.message_id).bind(&msg.channel_id).bind(&msg.sender_id).bind(&msg.content).bind(msg.timestamp).bind(&msg.reply_to).execute(&mut *tx).await?.rows_affected()>0;
|
||||
anyhow::ensure!(attachment.is_none() || inserted, "image message ID already exists");
|
||||
if inserted {
|
||||
let hooks=sqlx::query_as::<_,(String,)>("SELECT id FROM webhooks WHERE channel_id=$1 AND direction='outgoing' AND revoked_at IS NULL AND suspended_reason IS NULL LIMIT 32").bind(&msg.channel_id).fetch_all(&mut *tx).await?;
|
||||
for (hook,) in hooks {
|
||||
|
|
|
|||
489
gateway/src/handler/channel/admin_tests.rs
Normal file
489
gateway/src/handler/channel/admin_tests.rs
Normal file
|
|
@ -0,0 +1,489 @@
|
|||
use super::*;
|
||||
use crate::{
|
||||
domain::{channels, config, session, storage::Storage},
|
||||
handler::{Ctx, dispatch},
|
||||
proto::{self, PacketId, to_payload},
|
||||
};
|
||||
use prost::Message;
|
||||
use std::sync::{Arc, atomic::AtomicUsize};
|
||||
|
||||
pub(super) async fn fixture() -> (State, String, String, String, std::path::PathBuf) {
|
||||
let directory = std::env::temp_dir().join(format!("vnox-node-admin-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
let storage = Storage::connect_sqlite(directory.join("node.sqlite").to_str().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut config: config::Config =
|
||||
toml::from_str(include_str!("../../../../dev/config.toml")).unwrap();
|
||||
let account = uuid::Uuid::new_v4().to_string();
|
||||
config.gateway.admin_account_ids = vec![account.clone()];
|
||||
config.gateway.validate_admin_accounts().unwrap();
|
||||
let identity = crate::bootstrap::server_identity::ServerIdentity::load_or_generate(
|
||||
&directory.join("identity"),
|
||||
)
|
||||
.unwrap();
|
||||
let (broadcast, _) = tokio::sync::broadcast::channel(64);
|
||||
let state = State::new(
|
||||
session::new_store(),
|
||||
channels::new_store(),
|
||||
Arc::new(storage),
|
||||
Arc::new(config),
|
||||
Arc::new(identity),
|
||||
broadcast,
|
||||
crate::admin::metrics::Metrics::new(),
|
||||
Arc::new(AtomicUsize::new(0)),
|
||||
Arc::new(AtomicUsize::new(0)),
|
||||
None,
|
||||
);
|
||||
let admin = session::create(&state.sessions, hex::encode([9; 32]), "Admin".into()).await;
|
||||
let second = session::create(
|
||||
&state.sessions,
|
||||
hex::encode([10; 32]),
|
||||
"Other device".into(),
|
||||
)
|
||||
.await;
|
||||
// Exactly the same device key admitted under a DIFFERENT account must not inherit role.
|
||||
let other = session::create(&state.sessions, admin.user_id.clone(), "Admin".into()).await;
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(&admin.session_id)
|
||||
.unwrap()
|
||||
.account_id = account.clone();
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(&second.session_id)
|
||||
.unwrap()
|
||||
.account_id = account;
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(&other.session_id)
|
||||
.unwrap()
|
||||
.account_id = uuid::Uuid::new_v4().to_string();
|
||||
(
|
||||
state,
|
||||
admin.session_id,
|
||||
second.session_id,
|
||||
other.session_id,
|
||||
directory,
|
||||
)
|
||||
}
|
||||
pub(super) async fn request(
|
||||
state: &State,
|
||||
sid: &str,
|
||||
packet: PacketId,
|
||||
payload: Vec<u8>,
|
||||
) -> Option<(proto::PacketHeader, Vec<u8>)> {
|
||||
let (mut stream, mut client) = tokio::io::duplex(65536);
|
||||
let mut seq = 0;
|
||||
dispatch(
|
||||
&mut Ctx {
|
||||
stream: &mut stream,
|
||||
seq: &mut seq,
|
||||
state,
|
||||
},
|
||||
sid,
|
||||
packet,
|
||||
&payload,
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
drop(stream);
|
||||
crate::net::io::read_packet(&mut client).await.ok()
|
||||
}
|
||||
fn create(id: &str, guild: Option<String>) -> Vec<u8> {
|
||||
to_payload(&proto::ChannelCreate {
|
||||
channel_id: id.into(),
|
||||
channel_name: "New channel".into(),
|
||||
kind: "text".into(),
|
||||
guild_id: guild,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
fn deny(response: Option<(proto::PacketHeader, Vec<u8>)>) {
|
||||
let (header, payload) = response.expect("permission error response");
|
||||
assert_eq!(header.packet_id, PacketId::Error as u16);
|
||||
assert_eq!(
|
||||
proto::ErrorPayload::decode(payload.as_slice())
|
||||
.unwrap()
|
||||
.code,
|
||||
proto::ErrorCode::PermissionDenied as u32
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn listed_account_and_second_device_can_manage_global_channels_but_same_key_other_account_cannot()
|
||||
{
|
||||
let (state, admin, second, other, dir) = fixture().await;
|
||||
let mut events = state.broadcast.subscribe();
|
||||
deny(
|
||||
request(
|
||||
&state,
|
||||
&other,
|
||||
PacketId::ChannelCreate,
|
||||
create("blocked", None),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
assert!(
|
||||
channels::get_channel(&state.channels, "blocked")
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
let created = request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelCreate,
|
||||
create("global", None),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(created.0.packet_id, PacketId::ChannelState as u16);
|
||||
let notification = events.try_recv().unwrap();
|
||||
assert_eq!(notification.channel_id, None);
|
||||
assert_eq!(notification.target_session_id, None);
|
||||
assert_eq!(
|
||||
notification.exclude_session.as_deref(),
|
||||
Some(admin.as_str())
|
||||
);
|
||||
assert!(
|
||||
channels::get_channel(&state.channels, "global")
|
||||
.await
|
||||
.is_some()
|
||||
);
|
||||
deny(
|
||||
request(
|
||||
&state,
|
||||
&other,
|
||||
PacketId::ChannelEdit,
|
||||
to_payload(&proto::ChannelEdit {
|
||||
channel_id: "global".into(),
|
||||
channel_name: "Stolen".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
request(
|
||||
&state,
|
||||
&second,
|
||||
PacketId::ChannelEdit,
|
||||
to_payload(&proto::ChannelEdit {
|
||||
channel_id: "global".into(),
|
||||
channel_name: "Renamed by same account".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
channels::get_channel(&state.channels, "global")
|
||||
.await
|
||||
.unwrap()
|
||||
.name,
|
||||
"Renamed by same account"
|
||||
);
|
||||
deny(
|
||||
request(
|
||||
&state,
|
||||
&other,
|
||||
PacketId::ChannelDelete,
|
||||
to_payload(&proto::ChannelDelete {
|
||||
channel_id: "global".into(),
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
request(
|
||||
&state,
|
||||
&second,
|
||||
PacketId::ChannelDelete,
|
||||
to_payload(&proto::ChannelDelete {
|
||||
channel_id: "global".into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
channels::get_channel(&state.channels, "global")
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
for id in ["general", "voice"] {
|
||||
deny(
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelDelete,
|
||||
to_payload(&proto::ChannelDelete {
|
||||
channel_id: id.into(),
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
assert!(channels::get_channel(&state.channels, id).await.is_some());
|
||||
}
|
||||
drop(state);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn node_administration_never_bypasses_another_guilds_channel_permissions() {
|
||||
let (state, admin, _second, _other, dir) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("guild-owner-device", "Private guild")
|
||||
.await
|
||||
.unwrap();
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"private",
|
||||
"Private",
|
||||
channels::ChannelKind::Text,
|
||||
Some(guild.clone()),
|
||||
)
|
||||
.await;
|
||||
state
|
||||
.storage
|
||||
.create_channel("private", "Private", "text", Some(&guild))
|
||||
.await
|
||||
.unwrap();
|
||||
deny(
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelCreate,
|
||||
create("private-new", Some(guild.clone())),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let collision = request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelCreate,
|
||||
create("private", None),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collision.0.packet_id, PacketId::Error as u16);
|
||||
assert_eq!(
|
||||
channels::get_channel(&state.channels, "private")
|
||||
.await
|
||||
.unwrap()
|
||||
.guild_id,
|
||||
Some(guild.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.storage
|
||||
.list_channels()
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|channel| channel.id == "private")
|
||||
.unwrap()
|
||||
.guild_id,
|
||||
Some(guild.clone())
|
||||
);
|
||||
|
||||
deny(
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelEdit,
|
||||
to_payload(&proto::ChannelEdit {
|
||||
channel_id: "private".into(),
|
||||
channel_name: "Stolen".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
deny(
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelDelete,
|
||||
to_payload(&proto::ChannelDelete {
|
||||
channel_id: "private".into(),
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
assert_eq!(
|
||||
channels::get_channel(&state.channels, "private")
|
||||
.await
|
||||
.unwrap()
|
||||
.name,
|
||||
"Private"
|
||||
);
|
||||
let owner = session::create(&state.sessions, "guild-owner-device".into(), "Owner".into()).await;
|
||||
request(
|
||||
&state,
|
||||
&owner.session_id,
|
||||
PacketId::ChannelEdit,
|
||||
to_payload(&proto::ChannelEdit {
|
||||
channel_id: "private".into(),
|
||||
channel_name: "Owner edit".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
channels::get_channel(&state.channels, "private")
|
||||
.await
|
||||
.unwrap()
|
||||
.name,
|
||||
"Owner edit"
|
||||
);
|
||||
drop(state);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn global_created_renamed_and_deleted_channels_survive_fresh_storage_bootstrap() {
|
||||
let (state, admin, _second, other, dir) = fixture().await;
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelCreate,
|
||||
create("persistent-global", None),
|
||||
)
|
||||
.await;
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelCreate,
|
||||
create("deleted-global", None),
|
||||
)
|
||||
.await;
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelDelete,
|
||||
to_payload(&proto::ChannelDelete {
|
||||
channel_id: "deleted-global".into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelEdit,
|
||||
to_payload(&proto::ChannelEdit {
|
||||
channel_id: "persistent-global".into(),
|
||||
channel_name: "Saved name".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelEdit,
|
||||
to_payload(&proto::ChannelEdit {
|
||||
channel_id: "general".into(),
|
||||
channel_name: "Saved bootstrap name".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
super::join(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&other,
|
||||
"persistent-global",
|
||||
&state,
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
state.sessions.read().await[&other].channel_id.as_deref(),
|
||||
Some("persistent-global")
|
||||
);
|
||||
drop(state);
|
||||
let restarted = Storage::connect_sqlite(dir.join("node.sqlite").to_str().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let cache = channels::new_store();
|
||||
restarted.load_channels_to_cache(&cache).await.unwrap();
|
||||
let global = channels::get_channel(&cache, "persistent-global")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(global.name, "Saved name");
|
||||
assert_eq!(global.kind, channels::ChannelKind::Text);
|
||||
assert_eq!(global.guild_id, None);
|
||||
assert!(global.members.is_empty());
|
||||
assert!(
|
||||
channels::get_channel(&cache, "deleted-global")
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
channels::get_channel(&cache, "general").await.unwrap().name,
|
||||
"Saved bootstrap name"
|
||||
);
|
||||
assert!(channels::get_channel(&cache, "voice").await.is_some());
|
||||
drop(restarted);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn global_create_notification_precedes_delete_even_when_creator_socket_is_blocked() {
|
||||
let (state, admin, _second, _other, dir) = fixture().await;
|
||||
let mut events = state.broadcast.subscribe();
|
||||
let (mut socket, mut client) = tokio::io::duplex(1);
|
||||
let shared = state.clone();
|
||||
let actor = admin.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
super::handle_channel_create(
|
||||
&mut socket,
|
||||
&mut 0,
|
||||
&actor,
|
||||
&create("ordered-global", None),
|
||||
&shared,
|
||||
)
|
||||
.await
|
||||
});
|
||||
let created = tokio::time::timeout(std::time::Duration::from_secs(1), events.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let header = proto::PacketHeader::from_bytes(created.data[..12].try_into().unwrap());
|
||||
assert_eq!(header.packet_id, PacketId::ChannelCreate as u16);
|
||||
assert!(
|
||||
!task.is_finished(),
|
||||
"creator socket intentionally blocked before its response"
|
||||
);
|
||||
request(
|
||||
&state,
|
||||
&admin,
|
||||
PacketId::ChannelDelete,
|
||||
to_payload(&proto::ChannelDelete {
|
||||
channel_id: "ordered-global".into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let deleted = events.try_recv().unwrap();
|
||||
let header = proto::PacketHeader::from_bytes(deleted.data[..12].try_into().unwrap());
|
||||
assert_eq!(header.packet_id, PacketId::ChannelDelete as u16);
|
||||
crate::net::io::read_packet(&mut client).await.unwrap();
|
||||
task.await.unwrap().unwrap();
|
||||
assert!(
|
||||
events.try_recv().is_err(),
|
||||
"no late create event can recreate a deleted sidebar row"
|
||||
);
|
||||
assert!(
|
||||
channels::get_channel(&state.channels, "ordered-global")
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
drop(state);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
|
@ -31,6 +31,8 @@ pub async fn handle_channel_create(
|
|||
let kind = match req.kind.as_str() {
|
||||
"text" => channels::ChannelKind::Text,
|
||||
"voice" => channels::ChannelKind::Voice,
|
||||
"category" => channels::ChannelKind::Category,
|
||||
"forum" => channels::ChannelKind::Forum,
|
||||
other => {
|
||||
warn!(
|
||||
"channel_create from {}: invalid kind '{other}'",
|
||||
|
|
@ -50,6 +52,24 @@ pub async fn handle_channel_create(
|
|||
}
|
||||
};
|
||||
|
||||
if !super::visible_kind(&kind, &sess) {
|
||||
return io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::InvalidPacket as u32,
|
||||
message: "channel kind capability was not negotiated".into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let parent_id = req
|
||||
.parent_id
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(str::to_owned);
|
||||
let channel_id = req.channel_id.trim().to_string();
|
||||
let channel_name = if req.channel_name.trim().is_empty() {
|
||||
channel_id.clone()
|
||||
|
|
@ -95,38 +115,89 @@ pub async fn handle_channel_create(
|
|||
}
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !super::may_manage(state, &sess.user_id, req.guild_id.as_deref()).await? {
|
||||
if !super::may_manage_session(state, &sess, req.guild_id.as_deref()).await? {
|
||||
drop(access);
|
||||
super::denied(stream, seq).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let guild_id = req.guild_id.clone();
|
||||
|
||||
let created = channels::create(
|
||||
&state.channels,
|
||||
if let Err(message) = super::layout::validate(
|
||||
state,
|
||||
&channel_id,
|
||||
&channel_name,
|
||||
kind.clone(),
|
||||
guild_id.clone(),
|
||||
&kind,
|
||||
guild_id.as_deref(),
|
||||
parent_id.as_deref(),
|
||||
req.position,
|
||||
)
|
||||
.await;
|
||||
.await
|
||||
{
|
||||
drop(access);
|
||||
return io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::InvalidPacket as u32,
|
||||
message: message.into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
if created
|
||||
&& let Err(error) = state
|
||||
let created = if channels::get_channel(&state.channels, &channel_id)
|
||||
.await
|
||||
.is_some()
|
||||
{
|
||||
false
|
||||
} else {
|
||||
state
|
||||
.storage
|
||||
.create_channel(
|
||||
.create_channel_with_layout(
|
||||
&channel_id,
|
||||
&channel_name,
|
||||
kind.as_str(),
|
||||
guild_id.as_deref(),
|
||||
parent_id.as_deref(),
|
||||
req.position,
|
||||
)
|
||||
.await
|
||||
{
|
||||
channels::delete(&state.channels, &channel_id).await;
|
||||
return Err(error);
|
||||
.await?
|
||||
};
|
||||
if created {
|
||||
channels::create(
|
||||
&state.channels,
|
||||
&channel_id,
|
||||
&channel_name,
|
||||
kind.clone(),
|
||||
guild_id.clone(),
|
||||
)
|
||||
.await;
|
||||
channels::set_layout(
|
||||
&state.channels,
|
||||
&channel_id,
|
||||
parent_id.clone(),
|
||||
req.position,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if created && guild_id.is_none() {
|
||||
super::notify_global(
|
||||
state,
|
||||
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: None,
|
||||
parent_id: parent_id.clone(),
|
||||
position: req.position,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
drop(access);
|
||||
if !created {
|
||||
io::send_frame(
|
||||
|
|
@ -158,25 +229,31 @@ pub async fn handle_channel_create(
|
|||
members: Vec::new(),
|
||||
voice_endpoint: state.config.voice.bind.clone(),
|
||||
guild_id: req.guild_id.clone(),
|
||||
parent_id: parent_id.clone(),
|
||||
position: req.position,
|
||||
};
|
||||
io::send_frame(stream, PacketId::ChannelState, seq, &to_payload(&sp)).await?;
|
||||
|
||||
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: guild_id.clone(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
if guild_id.is_some() {
|
||||
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: guild_id.clone(),
|
||||
parent_id: parent_id.clone(),
|
||||
position: req.position,
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -213,9 +290,9 @@ pub async fn handle_channel_delete(
|
|||
|
||||
let access = state.access.write().await;
|
||||
let channel = channels::get_channel(&state.channels, &req.channel_id).await;
|
||||
if !super::may_manage(
|
||||
if !super::may_manage_session(
|
||||
state,
|
||||
&sess.user_id,
|
||||
&sess,
|
||||
channel.as_ref().and_then(|c| c.guild_id.as_deref()),
|
||||
)
|
||||
.await?
|
||||
|
|
@ -224,9 +301,75 @@ pub async fn handle_channel_delete(
|
|||
super::denied(stream, seq).await?;
|
||||
return Ok(());
|
||||
}
|
||||
if channel
|
||||
.as_ref()
|
||||
.is_some_and(|channel| channel.kind == channels::ChannelKind::Forum)
|
||||
&& state.storage.forum_has_topics(&req.channel_id).await?
|
||||
{
|
||||
drop(access);
|
||||
return io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::PermissionDenied as u32,
|
||||
message: "forum contains topics; deletion is disabled to preserve its posts".into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let children = if channel
|
||||
.as_ref()
|
||||
.is_some_and(|channel| channel.kind == channels::ChannelKind::Category)
|
||||
{
|
||||
channels::list(&state.channels)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|child| child.parent_id.as_deref() == Some(req.channel_id.as_str()))
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
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;
|
||||
for child in children {
|
||||
channels::set_layout(&state.channels, &child.id, None, child.position).await;
|
||||
super::notify_scope_locked(
|
||||
state,
|
||||
child.guild_id.as_deref(),
|
||||
None,
|
||||
encode_packet(
|
||||
PacketId::ChannelEdit,
|
||||
0,
|
||||
&to_payload(&crate::proto::ChannelEdit {
|
||||
channel_id: child.id,
|
||||
channel_name: child.name,
|
||||
parent_id: Some(String::new()),
|
||||
position: Some(child.position),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
if existed
|
||||
&& channel
|
||||
.as_ref()
|
||||
.is_some_and(|channel| channel.guild_id.is_none())
|
||||
{
|
||||
super::notify_global(
|
||||
state,
|
||||
None,
|
||||
encode_packet(
|
||||
PacketId::ChannelDelete,
|
||||
0,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: req.channel_id.clone(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
drop(access);
|
||||
|
||||
if !existed {
|
||||
|
|
@ -248,21 +391,26 @@ pub async fn handle_channel_delete(
|
|||
req.channel_id, sess.nickname
|
||||
);
|
||||
|
||||
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?;
|
||||
if channel
|
||||
.as_ref()
|
||||
.is_some_and(|channel| channel.guild_id.is_some())
|
||||
{
|
||||
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(())
|
||||
}
|
||||
|
|
@ -288,7 +436,8 @@ pub async fn handle_channel_list(
|
|||
None
|
||||
};
|
||||
|
||||
let channels = channels::list(&state.channels).await;
|
||||
let mut channels = channels::list(&state.channels).await;
|
||||
channels.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.id.cmp(&b.id)));
|
||||
let items: Vec<ChannelListItem> = channels
|
||||
.iter()
|
||||
.filter(|c| {
|
||||
|
|
@ -302,11 +451,14 @@ pub async fn handle_channel_list(
|
|||
.map(|gid| c.guild_id.as_deref() == Some(gid.as_str()))
|
||||
.unwrap_or(true)
|
||||
})
|
||||
.filter(|c| super::visible_kind(&c.kind, &sess))
|
||||
.map(|c| ChannelListItem {
|
||||
channel_id: c.id.clone(),
|
||||
channel_name: c.name.clone(),
|
||||
kind: c.kind.as_str().into(),
|
||||
guild_id: c.guild_id.clone(),
|
||||
parent_id: c.parent_id.clone(),
|
||||
position: c.position,
|
||||
})
|
||||
.collect();
|
||||
let p = ChannelListPayload {
|
||||
|
|
|
|||
|
|
@ -46,9 +46,9 @@ pub async fn handle_channel_edit(
|
|||
|
||||
let access = state.access.write().await;
|
||||
let channel = channels::get_channel(&state.channels, &channel_id).await;
|
||||
if !super::may_manage(
|
||||
if !super::may_manage_session(
|
||||
state,
|
||||
&sess.user_id,
|
||||
&sess,
|
||||
channel.as_ref().and_then(|c| c.guild_id.as_deref()),
|
||||
)
|
||||
.await?
|
||||
|
|
@ -57,12 +57,97 @@ pub async fn handle_channel_edit(
|
|||
super::denied(stream, seq).await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
let Some(existing) = channel.as_ref() else {
|
||||
drop(access);
|
||||
return io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::ChannelNotFound as u32,
|
||||
message: "channel not found".into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
};
|
||||
let parent_id = match req.parent_id.as_deref() {
|
||||
Some(parent) => {
|
||||
let parent = parent.trim();
|
||||
if parent.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(parent.to_owned())
|
||||
}
|
||||
}
|
||||
None => existing.parent_id.clone(),
|
||||
};
|
||||
let position = req.position.unwrap_or(existing.position);
|
||||
if !super::visible_kind(&existing.kind, &sess) {
|
||||
drop(access);
|
||||
return super::denied(stream, seq).await;
|
||||
}
|
||||
if let Err(message) = super::layout::validate(
|
||||
state,
|
||||
&channel_id,
|
||||
&existing.kind,
|
||||
existing.guild_id.as_deref(),
|
||||
parent_id.as_deref(),
|
||||
position,
|
||||
)
|
||||
.await
|
||||
{
|
||||
drop(access);
|
||||
return io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::InvalidPacket as u32,
|
||||
message: message.into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if !state
|
||||
.storage
|
||||
.update_channel(&channel_id, &channel_name)
|
||||
.await?;
|
||||
.update_channel_with_layout(&channel_id, &channel_name, parent_id.as_deref(), position)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
return io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::ChannelNotFound as u32,
|
||||
message: "channel not found".into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
channels::set_layout(&state.channels, &channel_id, parent_id.clone(), position).await;
|
||||
let renamed = channels::rename(&state.channels, &channel_id, &channel_name).await;
|
||||
|
||||
if renamed
|
||||
&& channel
|
||||
.as_ref()
|
||||
.is_some_and(|channel| channel.guild_id.is_none())
|
||||
{
|
||||
super::notify_global(
|
||||
state,
|
||||
None,
|
||||
encode_packet(
|
||||
PacketId::ChannelEdit,
|
||||
0,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: channel_id.clone(),
|
||||
channel_name: channel_name.clone(),
|
||||
parent_id: Some(parent_id.clone().unwrap_or_default()),
|
||||
position: Some(position),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
drop(access);
|
||||
if !renamed {
|
||||
io::send_frame(
|
||||
|
|
@ -83,22 +168,29 @@ pub async fn handle_channel_edit(
|
|||
channel_id, channel_name, sess.nickname
|
||||
);
|
||||
|
||||
super::notify_guild(
|
||||
state,
|
||||
channel
|
||||
.as_ref()
|
||||
.and_then(|channel| channel.guild_id.as_deref()),
|
||||
None,
|
||||
encode_packet(
|
||||
PacketId::ChannelEdit,
|
||||
0,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: channel_id.clone(),
|
||||
channel_name: channel_name.clone(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
if channel
|
||||
.as_ref()
|
||||
.is_some_and(|channel| channel.guild_id.is_some())
|
||||
{
|
||||
super::notify_guild(
|
||||
state,
|
||||
channel
|
||||
.as_ref()
|
||||
.and_then(|channel| channel.guild_id.as_deref()),
|
||||
None,
|
||||
encode_packet(
|
||||
PacketId::ChannelEdit,
|
||||
0,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: channel_id.clone(),
|
||||
channel_name: channel_name.clone(),
|
||||
parent_id: Some(parent_id.clone().unwrap_or_default()),
|
||||
position: Some(position),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -60,6 +60,21 @@ pub async fn join(
|
|||
)
|
||||
.await;
|
||||
}
|
||||
if ch.kind == channels::ChannelKind::Category || !super::visible_kind(&ch.kind, &sess) {
|
||||
drop(guard);
|
||||
return io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::InvalidPacket as u32,
|
||||
message:
|
||||
"categories cannot be joined and optional channel kinds require negotiation"
|
||||
.into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let is_voice = ch.kind == channels::ChannelKind::Voice;
|
||||
if is_voice && state.voice_member_tx.is_none() {
|
||||
drop(guard);
|
||||
|
|
@ -168,9 +183,15 @@ pub async fn join(
|
|||
None
|
||||
};
|
||||
let mut members = Vec::new();
|
||||
let mut devices = std::collections::HashSet::new();
|
||||
for sid in channels::members(&state.channels, channel_id).await {
|
||||
if let Some(s) = session::get(&state.sessions, &sid).await {
|
||||
if !devices.insert(s.user_id.clone()) {
|
||||
continue;
|
||||
}
|
||||
members.push(MemberInfo {
|
||||
account_id: s.account_id,
|
||||
avatar_url: s.avatar_url,
|
||||
user_id: s.user_id,
|
||||
nickname: s.nickname,
|
||||
in_voice: is_voice,
|
||||
|
|
@ -181,6 +202,8 @@ pub async fn join(
|
|||
channel_id: channel_id.into(),
|
||||
user_id: sess.user_id,
|
||||
nickname: sess.nickname,
|
||||
account_id: sess.account_id,
|
||||
avatar_url: sess.avatar_url,
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.into()),
|
||||
|
|
@ -196,6 +219,8 @@ pub async fn join(
|
|||
members,
|
||||
voice_endpoint: state.config.voice.bind.clone(),
|
||||
guild_id: ch.guild_id,
|
||||
parent_id: ch.parent_id,
|
||||
position: ch.position,
|
||||
};
|
||||
io::send_frame(stream, PacketId::ChannelState, seq, &to_payload(&payload)).await?;
|
||||
if let Some(credentials) = credentials {
|
||||
|
|
@ -207,7 +232,7 @@ pub async fn join(
|
|||
)
|
||||
.await?;
|
||||
}
|
||||
if !is_voice {
|
||||
if ch.kind == channels::ChannelKind::Text {
|
||||
let history = state.storage.get_history(channel_id, HISTORY_LIMIT).await?;
|
||||
if !history.is_empty() {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
|
|
|
|||
|
|
@ -212,6 +212,7 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
|
|||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: "managed".into(),
|
||||
channel_name: "stolen".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
&state,
|
||||
)
|
||||
|
|
@ -497,6 +498,7 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
|
|||
channel_name: "Private name".into(),
|
||||
kind: "text".into(),
|
||||
guild_id: Some(guild.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
crate::handler::channel::handle_channel_create(
|
||||
&mut stream,
|
||||
|
|
@ -514,6 +516,7 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
|
|||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: creation.channel_id.clone(),
|
||||
channel_name: "Renamed privately".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
&state,
|
||||
)
|
||||
|
|
@ -676,3 +679,68 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
|
|||
"history queued before a guild kick must not be delivered afterwards"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeated_device_sessions_leave_only_after_last_subscription_in_either_order() {
|
||||
for reverse in [false, true] {
|
||||
let (state, first) = fixture().await;
|
||||
let second = session::create(&state.sessions, "visitor".into(), "Visitor".into()).await;
|
||||
channels::join(&state.channels, "general", &second.session_id).await;
|
||||
let mut events = state.broadcast.subscribe();
|
||||
let order = if reverse {
|
||||
[second.session_id, first]
|
||||
} else {
|
||||
[first, second.session_id]
|
||||
};
|
||||
channels::leave(&state.channels, "general", &order[0]).await;
|
||||
broadcast_leave(&state, "general", &order[0]).await;
|
||||
assert!(
|
||||
events.try_recv().is_err(),
|
||||
"remaining session must retain member"
|
||||
);
|
||||
assert_eq!(channels::members(&state.channels, "general").await.len(), 1);
|
||||
channels::leave(&state.channels, "general", &order[1]).await;
|
||||
broadcast_leave(&state, "general", &order[1]).await;
|
||||
assert!(events.try_recv().is_ok(), "last session must emit leave");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_has_one_member_per_device_and_carries_central_profile() {
|
||||
use prost::Message;
|
||||
let (state, first) = fixture().await;
|
||||
let account = "c3ebd30f-6bb4-4c31-9016-bec57e986c93";
|
||||
{
|
||||
let mut sessions = state.sessions.write().await;
|
||||
let first = sessions.get_mut(&first).unwrap();
|
||||
first.account_id = account.into();
|
||||
first.avatar_url = format!("/v1/avatars/default/{account}");
|
||||
}
|
||||
let second = session::create(&state.sessions, "visitor".into(), "Visitor".into()).await;
|
||||
{
|
||||
let mut sessions = state.sessions.write().await;
|
||||
let member = sessions.get_mut(&second.session_id).unwrap();
|
||||
member.account_id = account.into();
|
||||
member.avatar_url = format!("/v1/avatars/default/{account}");
|
||||
}
|
||||
let (mut stream, mut peer) = tokio::io::duplex(65536);
|
||||
join(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&second.session_id,
|
||||
"general",
|
||||
&state,
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (_, payload) = io::read_packet(&mut peer).await.unwrap();
|
||||
let snapshot = ChannelStatePayload::decode(payload.as_slice()).unwrap();
|
||||
assert_eq!(snapshot.members.len(), 1);
|
||||
assert_eq!(snapshot.members[0].account_id, account);
|
||||
assert_eq!(
|
||||
snapshot.members[0].avatar_url,
|
||||
format!("/v1/avatars/default/{account}")
|
||||
);
|
||||
assert_eq!(snapshot.members[0].user_id, "visitor");
|
||||
}
|
||||
|
|
|
|||
33
gateway/src/handler/channel/layout.rs
Normal file
33
gateway/src/handler/channel/layout.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
//! One-level category layout. Call validation while holding the access mutation guard.
|
||||
use crate::{
|
||||
domain::channels::{self, ChannelKind},
|
||||
net::state::State,
|
||||
};
|
||||
|
||||
pub(super) async fn validate(
|
||||
state: &State,
|
||||
id: &str,
|
||||
kind: &ChannelKind,
|
||||
guild: Option<&str>,
|
||||
parent: Option<&str>,
|
||||
position: i32,
|
||||
) -> Result<(), &'static str> {
|
||||
if !(0..=1_000_000).contains(&position) {
|
||||
return Err("position must be between 0 and 1000000");
|
||||
}
|
||||
if kind == &ChannelKind::Category && parent.is_some() {
|
||||
return Err("categories must be at root");
|
||||
}
|
||||
if let Some(parent) = parent {
|
||||
if parent == id {
|
||||
return Err("channel cannot be its own parent");
|
||||
}
|
||||
let Some(category) = channels::get_channel(&state.channels, parent).await else {
|
||||
return Err("parent category not found");
|
||||
};
|
||||
if category.kind != ChannelKind::Category || category.guild_id.as_deref() != guild {
|
||||
return Err("parent must be a category in the same server or guild scope");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ pub async fn leave(
|
|||
channel_id: &str,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let _guard = state.access.write().await;
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
pub mod create;
|
||||
pub mod edit;
|
||||
pub mod join;
|
||||
mod layout;
|
||||
pub mod leave;
|
||||
|
||||
pub use create::{handle_channel_create, handle_channel_delete, handle_channel_list};
|
||||
|
|
@ -15,6 +16,14 @@ use crate::{
|
|||
|
||||
pub async fn broadcast_leave(state: &State, channel_id: &str, session_id: &str) {
|
||||
if let Some(sess) = crate::domain::session::get(&state.sessions, session_id).await {
|
||||
// Membership is session-scoped; a device remains until its last subscription leaves.
|
||||
for sid in crate::domain::channels::members(&state.channels, channel_id).await {
|
||||
if let Some(other) = crate::domain::session::get(&state.sessions, &sid).await
|
||||
&& other.user_id == sess.user_id
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
let p = UserLeavePayload {
|
||||
channel_id: channel_id.into(),
|
||||
user_id: sess.user_id.clone(),
|
||||
|
|
@ -85,7 +94,33 @@ pub async fn revoke_guild_access(state: &State, guild: &str, user: Option<&str>)
|
|||
}
|
||||
}
|
||||
|
||||
/// Global channels have no modeled server administrator: authenticated users cannot mutate them.
|
||||
/// Unknown structural kinds stay hidden from legacy clients that never opted in.
|
||||
pub(super) fn visible_kind(
|
||||
kind: &crate::domain::channels::ChannelKind,
|
||||
session: &crate::domain::session::Session,
|
||||
) -> bool {
|
||||
use crate::domain::channels::ChannelKind;
|
||||
match kind {
|
||||
ChannelKind::Category => session.client_features.channel_structure,
|
||||
ChannelKind::Forum => session.client_features.forums,
|
||||
ChannelKind::Text | ChannelKind::Voice => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Node capability is scoped to this exact authenticated account session. Device-key
|
||||
/// lookup could accidentally inherit a different account's concurrently admitted role.
|
||||
pub(super) async fn may_manage_session(
|
||||
state: &State,
|
||||
session: &crate::domain::session::Session,
|
||||
guild: Option<&str>,
|
||||
) -> anyhow::Result<bool> {
|
||||
if guild.is_none() {
|
||||
return Ok(state.config.gateway.is_node_admin(&session.account_id));
|
||||
}
|
||||
may_manage(state, &session.user_id, guild).await
|
||||
}
|
||||
|
||||
/// Guild authorization retains its existing device ownership/role model.
|
||||
pub(super) async fn may_manage(
|
||||
state: &State,
|
||||
user: &str,
|
||||
|
|
@ -124,7 +159,7 @@ pub(super) async fn denied(
|
|||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::PermissionDenied as u32,
|
||||
message: "guild MANAGE_CHANNELS permission required".into(),
|
||||
message: "node administrator or guild MANAGE_CHANNELS permission required".into(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
|
|
@ -232,15 +267,39 @@ pub async fn recheck_voice_permissions(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Metadata is addressed only to currently persisted guild members, including non-subscribers.
|
||||
/// Queue global metadata while the caller still serializes its channel mutation.
|
||||
/// This helper performs no socket I/O and never reacquires the access lock.
|
||||
pub(super) fn notify_global(state: &State, exclude: Option<&str>, data: Vec<u8>) {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: exclude.map(str::to_owned),
|
||||
target_session_id: None,
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
/// Global metadata is public to authenticated sessions; guild metadata is restricted to persisted members.
|
||||
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;
|
||||
notify_scope_locked(state, guild, exclude, data).await
|
||||
}
|
||||
|
||||
/// Caller holds the access guard so a mutation and its metadata queue remain ordered.
|
||||
pub(super) async fn notify_scope_locked(
|
||||
state: &State,
|
||||
guild: Option<&str>,
|
||||
exclude: Option<&str>,
|
||||
data: Vec<u8>,
|
||||
) -> anyhow::Result<()> {
|
||||
let Some(guild) = guild else {
|
||||
notify_global(state, exclude, data);
|
||||
return Ok(());
|
||||
};
|
||||
let members = state.storage.list_guild_members(guild).await?;
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
|
|
@ -274,9 +333,21 @@ pub async fn may_deliver_metadata(
|
|||
payload: &[u8],
|
||||
) -> bool {
|
||||
use prost::Message;
|
||||
let Some(recipient_session) = crate::domain::session::get(&state.sessions, recipient).await
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let guild = match packet {
|
||||
PacketId::ChannelCreate => match crate::proto::ChannelCreatePayload::decode(payload) {
|
||||
Ok(message) => message.guild_id,
|
||||
Ok(message) => {
|
||||
if (message.kind == "category"
|
||||
&& !recipient_session.client_features.channel_structure)
|
||||
|| (message.kind == "forum" && !recipient_session.client_features.forums)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
message.guild_id
|
||||
}
|
||||
Err(_) => return false,
|
||||
},
|
||||
PacketId::ChannelEdit => match crate::proto::ChannelEditPayload::decode(payload) {
|
||||
|
|
@ -284,7 +355,12 @@ pub async fn may_deliver_metadata(
|
|||
match crate::domain::channels::get_channel(&state.channels, &message.channel_id)
|
||||
.await
|
||||
{
|
||||
Some(channel) => channel.guild_id,
|
||||
Some(channel) => {
|
||||
if !visible_kind(&channel.kind, &recipient_session) {
|
||||
return false;
|
||||
}
|
||||
channel.guild_id
|
||||
}
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
|
|
@ -302,3 +378,6 @@ pub async fn may_deliver_metadata(
|
|||
.await
|
||||
.is_ok_and(|guilds| guilds.iter().any(|g| g.id == guild))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod admin_tests;
|
||||
|
|
|
|||
413
gateway/src/handler/content/attachments.rs
Normal file
413
gateway/src/handler/content/attachments.rs
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
use crate::{
|
||||
handler::Ctx,
|
||||
net::{io, state::BroadcastMsg},
|
||||
proto::{self, PacketId},
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use image::{AnimationDecoder, ImageDecoder};
|
||||
use prost::Message;
|
||||
use std::io::Cursor;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
const MAX_BYTES: usize = 3 * 1024 * 1024;
|
||||
|
||||
fn validate(data: &[u8]) -> Result<&'static str> {
|
||||
if data.is_empty() || data.len() > MAX_BYTES {
|
||||
bail!("image must be between 1 byte and 3 MiB");
|
||||
}
|
||||
let format = image::guess_format(data)?;
|
||||
let mime = match format {
|
||||
image::ImageFormat::Png => "image/png",
|
||||
image::ImageFormat::Jpeg => "image/jpeg",
|
||||
image::ImageFormat::Gif => "image/gif",
|
||||
_ => bail!("only PNG, JPEG and GIF are supported"),
|
||||
};
|
||||
let mut reader = image::ImageReader::with_format(Cursor::new(data), format);
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(4096);
|
||||
limits.max_image_height = Some(4096);
|
||||
limits.max_alloc = Some(32 * 1024 * 1024);
|
||||
reader.limits(limits.clone());
|
||||
let (w, h) = image::ImageReader::with_format(Cursor::new(data), format).into_dimensions()?;
|
||||
if w == 0 || h == 0 || w > 4096 || h > 4096 || u64::from(w) * u64::from(h) > 4_000_000 {
|
||||
bail!("image dimensions exceed limits");
|
||||
}
|
||||
if format == image::ImageFormat::Gif {
|
||||
let mut decoder = image::codecs::gif::GifDecoder::new(Cursor::new(data))?;
|
||||
decoder.set_limits(limits)?;
|
||||
let mut frames = 0;
|
||||
let mut pixels = 0u64;
|
||||
for frame in decoder.into_frames() {
|
||||
let frame = frame?;
|
||||
frames += 1;
|
||||
pixels += u64::from(frame.buffer().width()) * u64::from(frame.buffer().height());
|
||||
if frames > 120 || pixels > 8_388_608 {
|
||||
bail!("GIF animation exceeds limits");
|
||||
}
|
||||
}
|
||||
if frames == 0 {
|
||||
bail!("GIF has no frames");
|
||||
}
|
||||
} else {
|
||||
reader.decode()?;
|
||||
}
|
||||
Ok(mime)
|
||||
}
|
||||
|
||||
pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
ctx: &mut Ctx<'_, S>,
|
||||
session_id: &str,
|
||||
pid: PacketId,
|
||||
payload: &[u8],
|
||||
) -> Result<()> {
|
||||
let (request_id, channel_id, data, attachment_id) = if pid == PacketId::AttachmentUpload {
|
||||
let p = proto::AttachmentUpload::decode(payload)?;
|
||||
(p.request_id, p.channel_id, Some(p.data), String::new())
|
||||
} else {
|
||||
let p = proto::AttachmentFetch::decode(payload)?;
|
||||
(p.request_id, p.channel_id, None, p.attachment_id)
|
||||
};
|
||||
let mut response = proto::AttachmentResult {
|
||||
request_id,
|
||||
channel_id: channel_id.clone(),
|
||||
attachment_id,
|
||||
..Default::default()
|
||||
};
|
||||
let result: Result<()> = async {
|
||||
if response.request_id.len() > 128
|
||||
|| channel_id.len() > 128
|
||||
|| response.attachment_id.len() > 128
|
||||
{
|
||||
bail!("invalid attachment request");
|
||||
}
|
||||
let _access = ctx.state.access.read().await;
|
||||
let session = crate::domain::session::get(&ctx.state.sessions, session_id)
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("session expired"))?;
|
||||
if session.channel_id.as_deref() != Some(channel_id.as_str()) {
|
||||
bail!("join this channel before accessing attachments");
|
||||
}
|
||||
let channel = crate::domain::channels::get_channel(&ctx.state.channels, &channel_id)
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("channel not found"))?;
|
||||
if channel.kind != crate::domain::channels::ChannelKind::Text {
|
||||
bail!("image attachments require a text channel");
|
||||
}
|
||||
if let Some(guild_id) = &channel.guild_id {
|
||||
if !ctx
|
||||
.state
|
||||
.storage
|
||||
.list_user_guilds(&session.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|guild| &guild.id == guild_id)
|
||||
{
|
||||
bail!("guild membership required");
|
||||
}
|
||||
if data.is_some() {
|
||||
let owner = ctx
|
||||
.state
|
||||
.storage
|
||||
.get_guild(guild_id)
|
||||
.await?
|
||||
.is_some_and(|guild| guild.owner_id == session.user_id);
|
||||
let roles = ctx
|
||||
.state
|
||||
.storage
|
||||
.get_user_role_perms(guild_id, &session.user_id)
|
||||
.await?;
|
||||
let permissions = crate::domain::permissions::Permissions::from_role_perms(&roles);
|
||||
if !owner && !permissions.has(crate::domain::permissions::Permissions::MESSAGE_SEND)
|
||||
{
|
||||
bail!("MESSAGE_SEND permission required");
|
||||
}
|
||||
}
|
||||
}
|
||||
let allowed = if data.is_some() {
|
||||
ctx.state.rate_limiter.try_consume(session_id)
|
||||
} else {
|
||||
ctx.state
|
||||
.rate_limiter
|
||||
.try_consume_attachment_fetch(session_id)
|
||||
};
|
||||
if !allowed {
|
||||
bail!("image request rate limit reached");
|
||||
}
|
||||
if let Some(data) = data {
|
||||
if data.len() > MAX_BYTES {
|
||||
bail!("image exceeds 3 MiB");
|
||||
}
|
||||
static VALIDATIONS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2);
|
||||
let _permit = VALIDATIONS
|
||||
.try_acquire()
|
||||
.map_err(|_| anyhow::anyhow!("image validation is busy; try again"))?;
|
||||
let (data, mime) = tokio::task::spawn_blocking(move || -> Result<_> {
|
||||
let mime = validate(&data)?;
|
||||
Ok((data, mime))
|
||||
})
|
||||
.await??;
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
let msg = proto::ChatMessage {
|
||||
message_id: uuid::Uuid::new_v4().to_string(),
|
||||
channel_id: channel_id.clone(),
|
||||
sender_id: session.user_id,
|
||||
content: format!("vnox-attachment:{id}"),
|
||||
timestamp: crate::domain::storage::now_ms(),
|
||||
edited: false,
|
||||
reply_to: None,
|
||||
};
|
||||
if !ctx
|
||||
.state
|
||||
.storage
|
||||
.save_attachment_message(&msg, &id, mime, &data)
|
||||
.await?
|
||||
{
|
||||
bail!("could not save image message");
|
||||
}
|
||||
let _ = ctx.state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.clone()),
|
||||
exclude_session: None,
|
||||
target_session_id: None,
|
||||
data: proto::encode_packet(PacketId::ChatMessage, 0, &proto::to_payload(&msg)),
|
||||
});
|
||||
response.attachment_id = id;
|
||||
response.mime = mime.into();
|
||||
} else {
|
||||
let (mime, data) = ctx
|
||||
.state
|
||||
.storage
|
||||
.get_attachment(&response.attachment_id, &channel_id)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("image not found"))?;
|
||||
response.mime = mime;
|
||||
response.data = data;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
tracing::debug!(%error, "attachment request rejected");
|
||||
response.error = error.to_string().chars().take(256).collect();
|
||||
}
|
||||
response.request_id = response.request_id.chars().take(128).collect();
|
||||
response.channel_id = response.channel_id.chars().take(128).collect();
|
||||
response.attachment_id = response.attachment_id.chars().take(128).collect();
|
||||
io::send_frame(
|
||||
ctx.stream,
|
||||
PacketId::AttachmentResult,
|
||||
ctx.seq,
|
||||
&proto::to_payload(&response),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn authenticated_upload_broadcast_fetch_and_revoked_membership() -> Result<()> {
|
||||
use crate::{
|
||||
domain::{channels, session},
|
||||
net::state::State,
|
||||
};
|
||||
use std::sync::{Arc, atomic::AtomicUsize};
|
||||
let storage = crate::domain::storage::Storage::connect_sqlite(":memory:").await?;
|
||||
let config = toml::from_str(include_str!("../../../../dev/config.toml"))?;
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("vnox-attachment-auth-{}", uuid::Uuid::new_v4()));
|
||||
let identity = crate::bootstrap::server_identity::ServerIdentity::load_or_generate(&dir)?;
|
||||
std::fs::remove_file(dir.join("server_identity.json"))?;
|
||||
std::fs::remove_dir(dir)?;
|
||||
let (broadcast, _) = tokio::sync::broadcast::channel(16);
|
||||
let state = State::new(
|
||||
session::new_store(),
|
||||
channels::new_store(),
|
||||
Arc::new(storage),
|
||||
Arc::new(config),
|
||||
Arc::new(identity),
|
||||
broadcast,
|
||||
crate::admin::metrics::Metrics::new(),
|
||||
Arc::new(AtomicUsize::new(0)),
|
||||
Arc::new(AtomicUsize::new(0)),
|
||||
None,
|
||||
);
|
||||
let guild = state.storage.create_guild("owner", "private").await?;
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"private",
|
||||
"Private",
|
||||
channels::ChannelKind::Text,
|
||||
Some(guild),
|
||||
)
|
||||
.await;
|
||||
let session = session::create(&state.sessions, "outsider".into(), "Outsider".into()).await;
|
||||
// Model a stale channel field after permission revocation: current guild membership must still be checked.
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(&session.session_id)
|
||||
.expect("test session exists")
|
||||
.channel_id = Some("private".into());
|
||||
for (pid, payload) in [
|
||||
(
|
||||
PacketId::AttachmentUpload,
|
||||
proto::AttachmentUpload {
|
||||
request_id: "up".into(),
|
||||
channel_id: "private".into(),
|
||||
data: vec![1],
|
||||
}
|
||||
.encode_to_vec(),
|
||||
),
|
||||
(
|
||||
PacketId::AttachmentFetch,
|
||||
proto::AttachmentFetch {
|
||||
request_id: "get".into(),
|
||||
channel_id: "private".into(),
|
||||
attachment_id: "hidden".into(),
|
||||
}
|
||||
.encode_to_vec(),
|
||||
),
|
||||
] {
|
||||
let (mut stream, mut peer) = tokio::io::duplex(4096);
|
||||
handle(
|
||||
&mut Ctx {
|
||||
stream: &mut stream,
|
||||
seq: &mut 0,
|
||||
state: &state,
|
||||
},
|
||||
&session.session_id,
|
||||
pid,
|
||||
&payload,
|
||||
)
|
||||
.await?;
|
||||
let (_, bytes) = io::read_packet(&mut peer).await?;
|
||||
let response = proto::AttachmentResult::decode(bytes.as_slice())?;
|
||||
assert_eq!(response.error, "guild membership required");
|
||||
assert!(response.data.is_empty());
|
||||
}
|
||||
// A valid public-channel upload is persisted, announced, and fetchable by another joined participant.
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"public",
|
||||
"Public",
|
||||
channels::ChannelKind::Text,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(&session.session_id)
|
||||
.expect("test session exists")
|
||||
.channel_id = Some("public".into());
|
||||
let mut broadcasts = state.broadcast.subscribe();
|
||||
let mut png = Cursor::new(Vec::new());
|
||||
image::RgbaImage::new(2, 2).write_to(&mut png, image::ImageFormat::Png)?;
|
||||
let png = png.into_inner();
|
||||
let (mut stream, mut peer) = tokio::io::duplex(8192);
|
||||
let upload = proto::AttachmentUpload {
|
||||
request_id: "valid".into(),
|
||||
channel_id: "public".into(),
|
||||
data: png.clone(),
|
||||
};
|
||||
handle(
|
||||
&mut Ctx {
|
||||
stream: &mut stream,
|
||||
seq: &mut 0,
|
||||
state: &state,
|
||||
},
|
||||
&session.session_id,
|
||||
PacketId::AttachmentUpload,
|
||||
&upload.encode_to_vec(),
|
||||
)
|
||||
.await?;
|
||||
let (_, bytes) = io::read_packet(&mut peer).await?;
|
||||
let accepted = proto::AttachmentResult::decode(bytes.as_slice())?;
|
||||
assert!(accepted.error.is_empty(), "{}", accepted.error);
|
||||
assert!(!accepted.attachment_id.is_empty());
|
||||
let announced = broadcasts.recv().await?;
|
||||
assert_eq!(announced.channel_id.as_deref(), Some("public"));
|
||||
let message = proto::ChatMessage::decode(&announced.data[12..])?;
|
||||
assert_eq!(
|
||||
message.content,
|
||||
format!("vnox-attachment:{}", accepted.attachment_id)
|
||||
);
|
||||
assert_eq!(message.sender_id, "outsider");
|
||||
let recipient =
|
||||
session::create(&state.sessions, "recipient".into(), "Recipient".into()).await;
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(&recipient.session_id)
|
||||
.expect("recipient exists")
|
||||
.channel_id = Some("public".into());
|
||||
let fetch = proto::AttachmentFetch {
|
||||
request_id: "fetch".into(),
|
||||
channel_id: "public".into(),
|
||||
attachment_id: accepted.attachment_id,
|
||||
};
|
||||
handle(
|
||||
&mut Ctx {
|
||||
stream: &mut stream,
|
||||
seq: &mut 0,
|
||||
state: &state,
|
||||
},
|
||||
&recipient.session_id,
|
||||
PacketId::AttachmentFetch,
|
||||
&fetch.encode_to_vec(),
|
||||
)
|
||||
.await?;
|
||||
let (_, bytes) = io::read_packet(&mut peer).await?;
|
||||
let fetched = proto::AttachmentResult::decode(bytes.as_slice())?;
|
||||
assert!(fetched.error.is_empty(), "{}", fetched.error);
|
||||
assert_eq!(fetched.mime, "image/png");
|
||||
assert_eq!(fetched.data, png);
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn rejects_empty_oversized_and_unknown_images() {
|
||||
assert!(validate(&[]).is_err());
|
||||
assert!(validate(&vec![0; MAX_BYTES + 1]).is_err());
|
||||
assert!(validate(b"not an image").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn bounds_dimensions_and_gif_frame_count() {
|
||||
let image = image::RgbaImage::new(4097, 1);
|
||||
let mut bytes = Cursor::new(Vec::new());
|
||||
image
|
||||
.write_to(&mut bytes, image::ImageFormat::Png)
|
||||
.expect("encode wide test image");
|
||||
assert!(validate(bytes.get_ref()).is_err());
|
||||
let make_gif = |count| {
|
||||
let mut data = Vec::new();
|
||||
{
|
||||
let mut encoder = image::codecs::gif::GifEncoder::new(&mut data);
|
||||
for _ in 0..count {
|
||||
encoder
|
||||
.encode_frame(image::Frame::new(image::RgbaImage::new(1, 1)))
|
||||
.expect("encode gif frame");
|
||||
}
|
||||
}
|
||||
data
|
||||
};
|
||||
assert_eq!(
|
||||
validate(&make_gif(2)).expect("valid animated gif"),
|
||||
"image/gif"
|
||||
);
|
||||
assert!(validate(&make_gif(121)).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn validates_real_png_and_rejects_truncation() {
|
||||
let image = image::RgbaImage::new(2, 2);
|
||||
let mut bytes = Cursor::new(Vec::new());
|
||||
image
|
||||
.write_to(&mut bytes, image::ImageFormat::Png)
|
||||
.expect("encode test png");
|
||||
assert_eq!(validate(bytes.get_ref()).expect("valid png"), "image/png");
|
||||
assert!(validate(&bytes.get_ref()[..24]).is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ use crate::{
|
|||
};
|
||||
|
||||
pub async fn handle(session_id: &str, mut msg: ChatMessagePayload, state: &State) -> Result<()> {
|
||||
let _access = state.access.read().await;
|
||||
let sess = match crate::domain::session::get(&state.sessions, session_id).await {
|
||||
Some(s) => s,
|
||||
None => return Ok(()),
|
||||
|
|
@ -16,6 +17,13 @@ pub async fn handle(session_id: &str, mut msg: ChatMessagePayload, state: &State
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
if !crate::domain::channels::get_channel(&state.channels, &msg.channel_id)
|
||||
.await
|
||||
.is_some_and(|channel| channel.kind == crate::domain::channels::ChannelKind::Text)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Rate limit check (token bucket per session).
|
||||
if !state.rate_limiter.try_consume(session_id) {
|
||||
state.metrics.inc(&state.metrics.rate_limited_events);
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ use crate::{
|
|||
};
|
||||
|
||||
pub async fn handle_message_edit(session_id: &str, payload: &[u8], state: &State) -> Result<()> {
|
||||
let _access = state.access.read().await;
|
||||
let edit = crate::proto::MessageEditPayload::decode(payload)?;
|
||||
let sess = match session::get(&state.sessions, session_id).await {
|
||||
Some(s) => s,
|
||||
|
|
@ -31,6 +32,14 @@ pub async fn handle_message_edit(session_id: &str, payload: &[u8], state: &State
|
|||
None => return Ok(()),
|
||||
};
|
||||
|
||||
if msg.channel_id != edit.channel_id
|
||||
|| !crate::domain::channels::get_channel(&state.channels, &msg.channel_id)
|
||||
.await
|
||||
.is_some_and(|channel| channel.kind == crate::domain::channels::ChannelKind::Text)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
state
|
||||
.storage
|
||||
.edit_message(&edit.message_id, &edit.content)
|
||||
|
|
@ -61,6 +70,7 @@ pub async fn handle_message_edit(session_id: &str, payload: &[u8], state: &State
|
|||
}
|
||||
|
||||
pub async fn handle_message_delete(session_id: &str, payload: &[u8], state: &State) -> Result<()> {
|
||||
let _access = state.access.read().await;
|
||||
let delete = MessageDeletePayload::decode(payload)?;
|
||||
let sess = match session::get(&state.sessions, session_id).await {
|
||||
Some(s) => s,
|
||||
|
|
@ -77,6 +87,16 @@ pub async fn handle_message_delete(session_id: &str, payload: &[u8], state: &Sta
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(message) = state.storage.get_message(&delete.message_id).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if message.channel_id != delete.channel_id
|
||||
|| !crate::domain::channels::get_channel(&state.channels, &message.channel_id)
|
||||
.await
|
||||
.is_some_and(|channel| channel.kind == crate::domain::channels::ChannelKind::Text)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
state.storage.delete_message(&delete.message_id).await?;
|
||||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
pub mod attachments;
|
||||
pub mod chat;
|
||||
pub mod message_edit;
|
||||
pub mod presence;
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ pub async fn handle_reaction_add(
|
|||
mut payload: ReactionPayload,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let _access = state.access.read().await;
|
||||
let sess = match session::get(&state.sessions, session_id).await {
|
||||
Some(s) => s,
|
||||
None => return Ok(()),
|
||||
|
|
@ -27,6 +28,16 @@ pub async fn handle_reaction_add(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(message) = state.storage.get_message(&payload.message_id).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if message.channel_id != payload.channel_id
|
||||
|| !crate::domain::channels::get_channel(&state.channels, &message.channel_id)
|
||||
.await
|
||||
.is_some_and(|channel| channel.kind == crate::domain::channels::ChannelKind::Text)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
payload.user_id = sess.user_id.clone();
|
||||
state
|
||||
.storage
|
||||
|
|
@ -52,6 +63,7 @@ pub async fn handle_reaction_remove(
|
|||
mut payload: ReactionPayload,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let _access = state.access.read().await;
|
||||
let sess = match session::get(&state.sessions, session_id).await {
|
||||
Some(s) => s,
|
||||
None => return Ok(()),
|
||||
|
|
@ -61,6 +73,16 @@ pub async fn handle_reaction_remove(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(message) = state.storage.get_message(&payload.message_id).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if message.channel_id != payload.channel_id
|
||||
|| !crate::domain::channels::get_channel(&state.channels, &message.channel_id)
|
||||
.await
|
||||
.is_some_and(|channel| channel.kind == crate::domain::channels::ChannelKind::Text)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
payload.user_id = sess.user_id.clone();
|
||||
|
||||
// Check user owns the reaction
|
||||
|
|
|
|||
|
|
@ -42,6 +42,28 @@ pub async fn deliver_frame(
|
|||
{
|
||||
return Ok(());
|
||||
}
|
||||
if crate::proto::PacketId::from_u16(hdr.packet_id)
|
||||
== Some(crate::proto::PacketId::ForumChanged)
|
||||
&& !crate::handler::forum::may_deliver(
|
||||
state,
|
||||
session_id,
|
||||
&msg.data[crate::proto::PacketHeader::SIZE..],
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if crate::proto::PacketId::from_u16(hdr.packet_id)
|
||||
== Some(crate::proto::PacketId::ProfileUpdated)
|
||||
&& !crate::handler::profile::may_deliver(
|
||||
state,
|
||||
session_id,
|
||||
&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(
|
||||
|
|
|
|||
|
|
@ -21,6 +21,22 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
addr: std::net::SocketAddr,
|
||||
) -> Result<()> {
|
||||
match pid {
|
||||
PacketId::ClientFeatures => {
|
||||
super::node_settings::features(session_id, payload, ctx.state).await?
|
||||
}
|
||||
PacketId::NodeSettingsRequest => {
|
||||
super::node_settings::handle(ctx.stream, ctx.seq, session_id, payload, ctx.state)
|
||||
.await?
|
||||
}
|
||||
PacketId::ForumRequest => {
|
||||
super::forum::handle(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?
|
||||
}
|
||||
PacketId::ProfileUpdate => {
|
||||
super::profile::handle(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?
|
||||
}
|
||||
PacketId::AttachmentUpload | PacketId::AttachmentFetch => {
|
||||
content::attachments::handle(ctx, session_id, pid, payload).await?;
|
||||
}
|
||||
PacketId::MediaControl => crate::media::handle(ctx, session_id, payload).await?,
|
||||
PacketId::WebhookCreate
|
||||
| PacketId::WebhookList
|
||||
|
|
|
|||
251
gateway/src/handler/forum.rs
Normal file
251
gateway/src/handler/forum.rs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
//! Real topic/reply operations. Forum posts never pass through generic chat mutation APIs.
|
||||
use crate::{
|
||||
domain::{
|
||||
channels::{self, Channel, ChannelKind},
|
||||
permissions::Permissions,
|
||||
session::{self, Session},
|
||||
},
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
proto::{
|
||||
self, ForumChanged, ForumOperation, ForumRequest, ForumResult, MemberInfo, PacketId,
|
||||
encode_packet, to_payload,
|
||||
},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use prost::Message;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
type Rejection = (proto::ErrorCode, &'static str);
|
||||
fn invalid(message: &'static str) -> Rejection {
|
||||
(proto::ErrorCode::InvalidPacket, message)
|
||||
}
|
||||
fn text(value: &str, max: usize, multiline: bool) -> bool {
|
||||
value.chars().count()<=max && !value.chars().any(|c|(c.is_control() && !(multiline && matches!(c,'\n'|'\t'))) || matches!(c,'\u{061c}'|'\u{200e}'|'\u{200f}'|'\u{202a}'..='\u{202e}'|'\u{2066}'..='\u{2069}'))
|
||||
}
|
||||
fn uuid(value: &str) -> bool {
|
||||
uuid::Uuid::parse_str(value).is_ok_and(|id| !id.is_nil() && id.to_string() == value)
|
||||
}
|
||||
fn author(session: &Session) -> MemberInfo {
|
||||
MemberInfo {
|
||||
user_id: session.user_id.clone(),
|
||||
account_id: session.account_id.clone(),
|
||||
nickname: session.nickname.clone(),
|
||||
avatar_url: session.avatar_url.clone(),
|
||||
in_voice: false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn authorize(
|
||||
state: &State,
|
||||
session: &Session,
|
||||
channel: &Channel,
|
||||
posting: bool,
|
||||
) -> Result<std::result::Result<(), Rejection>> {
|
||||
if !session.client_features.forums {
|
||||
return Ok(Err(invalid("forum support was not negotiated")));
|
||||
}
|
||||
if channel.kind != ChannelKind::Forum
|
||||
|| session.channel_id.as_deref() != Some(channel.id.as_str())
|
||||
|| !channel.members.contains(&session.session_id)
|
||||
{
|
||||
return Ok(Err((
|
||||
proto::ErrorCode::PermissionDenied,
|
||||
"open this forum before reading or posting",
|
||||
)));
|
||||
}
|
||||
if let Some(guild) = &channel.guild_id {
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&session.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|membership| membership.id == *guild)
|
||||
{
|
||||
return Ok(Err((
|
||||
proto::ErrorCode::PermissionDenied,
|
||||
"guild membership required",
|
||||
)));
|
||||
}
|
||||
if posting {
|
||||
let owner = state
|
||||
.storage
|
||||
.get_guild(guild)
|
||||
.await?
|
||||
.is_some_and(|guild| guild.owner_id == session.user_id);
|
||||
let permissions = state
|
||||
.storage
|
||||
.get_user_role_perms(guild, &session.user_id)
|
||||
.await?;
|
||||
if !owner && !Permissions::from_role_perms(&permissions).has(Permissions::MESSAGE_SEND)
|
||||
{
|
||||
return Ok(Err((
|
||||
proto::ErrorCode::PermissionDenied,
|
||||
"MESSAGE_SEND permission required",
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Ok(()))
|
||||
}
|
||||
|
||||
pub async fn handle(
|
||||
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
sid: &str,
|
||||
payload: &[u8],
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let request = if payload.len() <= 70 * 1024 {
|
||||
ForumRequest::decode(payload).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(request) = request else {
|
||||
return send(
|
||||
stream,
|
||||
seq,
|
||||
ForumResult {
|
||||
error_code: proto::ErrorCode::InvalidPacket as u32,
|
||||
error: "invalid forum request".into(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
};
|
||||
let mut result = ForumResult {
|
||||
request_id: request.request_id.clone(),
|
||||
operation: request.operation,
|
||||
channel_id: request.channel_id.clone(),
|
||||
topic_id: request.topic_id.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let guard = state.access.read().await;
|
||||
let operation = ForumOperation::try_from(request.operation).ok();
|
||||
let posting = matches!(
|
||||
operation,
|
||||
Some(ForumOperation::Create | ForumOperation::Reply)
|
||||
);
|
||||
let session = session::get(&state.sessions, sid).await;
|
||||
let channel = channels::get_channel(&state.channels, &request.channel_id).await;
|
||||
let rejection = if request.request_id.is_empty()
|
||||
|| request.request_id.len() > 128
|
||||
|| request.channel_id.is_empty()
|
||||
|| request.channel_id.len() > 128
|
||||
{
|
||||
Some(invalid("request_id and channel_id are required"))
|
||||
} else if request.offset > 100_000 {
|
||||
Some(invalid("forum offset is too large"))
|
||||
} else if operation.is_none() || operation == Some(ForumOperation::Unspecified) {
|
||||
Some(invalid("unsupported forum operation"))
|
||||
} else if channel.is_none() {
|
||||
Some((proto::ErrorCode::ChannelNotFound, "forum not found"))
|
||||
} else if session.is_none() {
|
||||
Some((proto::ErrorCode::AuthFailed, "session not found"))
|
||||
} else {
|
||||
authorize(
|
||||
state,
|
||||
session.as_ref().expect("checked session"),
|
||||
channel.as_ref().expect("checked forum"),
|
||||
posting,
|
||||
)
|
||||
.await?
|
||||
.err()
|
||||
};
|
||||
if let Some((code, error)) = rejection {
|
||||
result.error_code = code as u32;
|
||||
result.error = error.into();
|
||||
drop(guard);
|
||||
return send(stream, seq, result).await;
|
||||
}
|
||||
let session = session.expect("checked session");
|
||||
if !state.rate_limiter.try_consume(sid) {
|
||||
result.error_code = proto::ErrorCode::RateLimited as u32;
|
||||
result.error = "forum requests are too frequent".into();
|
||||
drop(guard);
|
||||
return send(stream, seq, result).await;
|
||||
}
|
||||
let outcome:Result<std::result::Result<Option<ForumChanged>,Rejection>>=async {
|
||||
match operation.expect("checked operation") {
|
||||
ForumOperation::List=>{
|
||||
let limit=if request.limit==0 {20} else {request.limit.min(50)};
|
||||
result.topics=state.storage.forum_list(&request.channel_id,request.offset,limit+1).await?;
|
||||
result.has_more=result.topics.len()>limit as usize;result.topics.truncate(limit as usize);Ok(Ok(None))
|
||||
}
|
||||
ForumOperation::Open=>{
|
||||
if !uuid(&request.topic_id) {return Ok(Err(invalid("valid topic_id is required")));}
|
||||
let Some(topic)=state.storage.forum_topic(&request.channel_id,&request.topic_id).await? else {return Ok(Err((proto::ErrorCode::ChannelNotFound,"topic not found in this forum")))};
|
||||
let limit=if request.limit==0 {50} else {request.limit.min(100)};
|
||||
let posts=state.storage.forum_posts(&request.channel_id,&request.topic_id,request.offset,limit+1).await?;
|
||||
let mut bytes=0;let mut count=0;
|
||||
for post in &posts {if count>=limit as usize || bytes+post.encoded_len()>2*1024*1024 {break;}bytes+=post.encoded_len();count+=1;}
|
||||
result.has_more=posts.len()>count;result.posts=posts.into_iter().take(count).collect();result.topics.push(topic);Ok(Ok(None))
|
||||
}
|
||||
ForumOperation::Create=>{
|
||||
let title=request.title.trim();let content=request.content.trim();
|
||||
if !uuid(&request.topic_id) || !uuid(&request.message_id) || title.is_empty() || !text(title,160,false) || content.is_empty() || content.len()>64*1024 || !text(content,16000,true) {return Ok(Err(invalid("topic/message UUIDs, title (1–160) and body (1–16000 characters, 64 KiB maximum) are required")));}
|
||||
let (topic,post)=state.storage.forum_create(&request.topic_id,&request.message_id,&request.channel_id,title,content,&author(&session)).await?;
|
||||
result.topics.push(topic.clone());result.posts.push(post.clone());Ok(Ok(Some(ForumChanged {channel_id:request.channel_id.clone(),topic:Some(topic),post:Some(post)})))
|
||||
}
|
||||
ForumOperation::Reply=>{
|
||||
let content=request.content.trim();
|
||||
if !uuid(&request.topic_id) || !uuid(&request.message_id) || content.is_empty() || content.len()>64*1024 || !text(content,16000,true) {return Ok(Err(invalid("topic/message UUIDs and body (1–16000 characters, 64 KiB maximum) are required")));}
|
||||
if state.storage.forum_topic(&request.channel_id,&request.topic_id).await?.is_none() {return Ok(Err((proto::ErrorCode::ChannelNotFound,"topic not found in this forum")));}
|
||||
let (topic,post)=state.storage.forum_reply(&request.message_id,&request.channel_id,&request.topic_id,content,&author(&session)).await?;
|
||||
result.topics.push(topic.clone());result.posts.push(post.clone());Ok(Ok(Some(ForumChanged {channel_id:request.channel_id.clone(),topic:Some(topic),post:Some(post)})))
|
||||
}
|
||||
ForumOperation::Unspecified=>Ok(Err(invalid("unsupported forum operation"))),
|
||||
}
|
||||
}.await;
|
||||
match outcome {
|
||||
Ok(Ok(Some(event))) => {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(request.channel_id),
|
||||
exclude_session: Some(sid.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::ForumChanged, 0, &to_payload(&event)),
|
||||
});
|
||||
}
|
||||
Ok(Ok(None)) => {}
|
||||
Ok(Err((code, error))) => {
|
||||
result.error_code = code as u32;
|
||||
result.error = error.into();
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error,"forum operation failed");
|
||||
result.error_code = proto::ErrorCode::InvalidPacket as u32;
|
||||
result.error =
|
||||
"forum operation failed or mutation IDs conflict; no unrelated message was changed"
|
||||
.into();
|
||||
}
|
||||
}
|
||||
drop(guard);
|
||||
send(stream, seq, result).await
|
||||
}
|
||||
async fn send(
|
||||
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
result: ForumResult,
|
||||
) -> Result<()> {
|
||||
io::send_frame(stream, PacketId::ForumResult, seq, &to_payload(&result)).await
|
||||
}
|
||||
|
||||
/// Topic/reply content must remain hidden if access/subscription is revoked while queued.
|
||||
pub async fn may_deliver(state: &State, sid: &str, payload: &[u8]) -> bool {
|
||||
let Ok(event) = ForumChanged::decode(payload) else {
|
||||
return false;
|
||||
};
|
||||
let _guard = state.access.read().await;
|
||||
let Some(session) = session::get(&state.sessions, sid).await else {
|
||||
return false;
|
||||
};
|
||||
let Some(channel) = channels::get_channel(&state.channels, &event.channel_id).await else {
|
||||
return false;
|
||||
};
|
||||
matches!(
|
||||
authorize(state, &session, &channel, false).await,
|
||||
Ok(Ok(()))
|
||||
)
|
||||
}
|
||||
|
|
@ -88,6 +88,18 @@ pub async fn handle_guild_delete(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
if state.storage.guild_has_forum_topics(&req.guild_id).await? {
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"guild contains forum topics; deletion is disabled to preserve them",
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
crate::handler::channel::revoke_guild_access(state, &req.guild_id, None).await;
|
||||
state.storage.delete_guild(&req.guild_id).await?;
|
||||
state
|
||||
|
|
|
|||
|
|
@ -4,8 +4,11 @@ pub mod deliver;
|
|||
pub mod direct_message;
|
||||
pub mod dispatch;
|
||||
pub mod e2ee;
|
||||
pub mod forum;
|
||||
pub mod friends;
|
||||
pub mod guild;
|
||||
pub mod node_settings;
|
||||
pub mod profile;
|
||||
pub mod run;
|
||||
|
||||
pub use dispatch::dispatch;
|
||||
|
|
|
|||
133
gateway/src/handler/node_settings.rs
Normal file
133
gateway/src/handler/node_settings.rs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
//! Public node settings and post-SESSION feature negotiation.
|
||||
use crate::{
|
||||
domain::session,
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
proto::{
|
||||
self, ClientFeatures, NodeSettingsRequest, NodeSettingsResult, PacketId, encode_packet,
|
||||
to_payload,
|
||||
},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use prost::Message;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
pub async fn features(sid: &str, payload: &[u8], state: &State) -> Result<()> {
|
||||
anyhow::ensure!(payload.len() <= 128, "client feature report is too large");
|
||||
let features = ClientFeatures::decode(payload)?;
|
||||
if let Some(session) = state.sessions.write().await.get_mut(sid) {
|
||||
session.client_features = features;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn handle(
|
||||
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
sid: &str,
|
||||
payload: &[u8],
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let request = if payload.len() <= 12 * 1024 {
|
||||
NodeSettingsRequest::decode(payload).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(request) = request else {
|
||||
return send(
|
||||
stream,
|
||||
seq,
|
||||
NodeSettingsResult {
|
||||
error_code: proto::ErrorCode::InvalidPacket as u32,
|
||||
error: "invalid node settings request".into(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
};
|
||||
let Some(session) = session::get(&state.sessions, sid).await else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut result = NodeSettingsResult {
|
||||
request_id: request.request_id.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let reject = if request.request_id.is_empty() || request.request_id.len() > 128 {
|
||||
Some((proto::ErrorCode::InvalidPacket, "request_id is required"))
|
||||
} else if !session.client_features.node_settings {
|
||||
Some((
|
||||
proto::ErrorCode::InvalidPacket,
|
||||
"node settings capability was not negotiated",
|
||||
))
|
||||
} else if request.update && !state.config.gateway.is_node_admin(&session.account_id) {
|
||||
Some((
|
||||
proto::ErrorCode::PermissionDenied,
|
||||
"node administrator account required",
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((code, message)) = reject {
|
||||
result.error_code = code as u32;
|
||||
result.error = message.into();
|
||||
return send(stream, seq, result).await;
|
||||
}
|
||||
if request.update {
|
||||
let name = request.display_name.trim();
|
||||
let description = request.description.trim();
|
||||
if !valid_text(name, 100, false) || name.is_empty() || !valid_text(description, 2000, true)
|
||||
{
|
||||
result.error_code = proto::ErrorCode::InvalidPacket as u32;
|
||||
result.error="name must contain 1–100 characters; description maximum 2000 characters, without control characters".into();
|
||||
return send(stream, seq, result).await;
|
||||
}
|
||||
let guard = state.access.write().await;
|
||||
state.storage.save_node_settings(name, description).await?;
|
||||
*state.node_settings.write().await = (name.to_owned(), description.to_owned());
|
||||
let event = NodeSettingsResult {
|
||||
display_name: name.into(),
|
||||
description: description.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let recipients: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|session| session.session_id != sid && session.client_features.node_settings)
|
||||
.map(|session| session.session_id.clone())
|
||||
.collect();
|
||||
for recipient in recipients {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(recipient),
|
||||
data: encode_packet(PacketId::NodeSettingsResult, 0, &to_payload(&event)),
|
||||
});
|
||||
}
|
||||
drop(guard);
|
||||
}
|
||||
let current = state.node_settings.read().await;
|
||||
result.display_name = current.0.clone();
|
||||
result.description = current.1.clone();
|
||||
drop(current);
|
||||
send(stream, seq, result).await
|
||||
}
|
||||
fn valid_text(value: &str, max: usize, multiline: bool) -> bool {
|
||||
value.chars().count()<=max && !value.chars().any(|c|(c.is_control() && !(multiline && matches!(c,'\n'|'\t'))) || matches!(c,'\u{061c}'|'\u{200e}'|'\u{200f}'|'\u{202a}'..='\u{202e}'|'\u{2066}'..='\u{2069}'))
|
||||
}
|
||||
async fn send(
|
||||
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
result: NodeSettingsResult,
|
||||
) -> Result<()> {
|
||||
io::send_frame(
|
||||
stream,
|
||||
PacketId::NodeSettingsResult,
|
||||
seq,
|
||||
&to_payload(&result),
|
||||
)
|
||||
.await
|
||||
}
|
||||
164
gateway/src/handler/profile.rs
Normal file
164
gateway/src/handler/profile.rs
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
//! Account display metadata changes are authorized only by a fresh Central proof.
|
||||
use crate::{
|
||||
domain::{account, session},
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
proto::{self, PacketId, ProfileUpdate, ProfileUpdated, encode_packet, to_payload},
|
||||
};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use prost::Message;
|
||||
use std::collections::HashMap;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
pub async fn handle(
|
||||
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
sid: &str,
|
||||
payload: &[u8],
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
if !state.profile_rate_limiter.try_consume(sid) {
|
||||
return io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::RateLimited as u32,
|
||||
message: "profile updates are too frequent".into(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let result: Result<()> = async {
|
||||
ensure!(payload.len() <= 8300, "profile proof is too large");
|
||||
let update = ProfileUpdate::decode(payload)?;
|
||||
apply(state, sid, &update.account_proof).await
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
tracing::debug!(%error, "rejected signed profile update");
|
||||
io::send_frame(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::AuthFailed as u32,
|
||||
message: "Central profile proof is invalid or belongs to another account".into(),
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn apply(state: &State, sid: &str, proof: &[u8]) -> Result<()> {
|
||||
let _access = state.access.write().await;
|
||||
let current = session::get(&state.sessions, sid)
|
||||
.await
|
||||
.context("missing session")?;
|
||||
let device: [u8; 32] = hex::decode(¤t.user_id)?
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid device key"))?;
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)?
|
||||
.as_secs() as i64;
|
||||
let claims = account::verify(
|
||||
proof,
|
||||
&device,
|
||||
state.config.gateway.central_account.as_ref(),
|
||||
now,
|
||||
)?;
|
||||
ensure!(
|
||||
claims.account_id == current.account_id,
|
||||
"profile proof account does not match session"
|
||||
);
|
||||
let nickname = claims
|
||||
.display_name
|
||||
.context("signed display name required")?;
|
||||
let avatar_url = claims.avatar_url.context("signed avatar path required")?;
|
||||
let mut sessions = state.sessions.write().await;
|
||||
let newest = sessions
|
||||
.values()
|
||||
.filter(|s| s.account_id == current.account_id)
|
||||
.map(|s| s.profile_issued_at)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
if claims.issued_at < newest {
|
||||
return Ok(());
|
||||
}
|
||||
let mut devices: HashMap<String, (bool, Vec<String>)> = HashMap::new();
|
||||
for session in sessions
|
||||
.values_mut()
|
||||
.filter(|s| s.account_id == current.account_id)
|
||||
{
|
||||
let changed = session.nickname != nickname || session.avatar_url != avatar_url;
|
||||
session.nickname = nickname.clone();
|
||||
session.avatar_url = avatar_url.clone();
|
||||
session.profile_issued_at = claims.issued_at;
|
||||
let entry = devices.entry(session.user_id.clone()).or_default();
|
||||
entry.0 |= changed;
|
||||
entry.1.extend(
|
||||
[session.channel_id.clone(), session.voice_channel_id.clone()]
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
);
|
||||
}
|
||||
drop(sessions);
|
||||
for (device, (changed, mut channels)) in devices {
|
||||
if !changed {
|
||||
continue;
|
||||
}
|
||||
channels.sort();
|
||||
channels.dedup();
|
||||
let event = ProfileUpdated {
|
||||
user_id: device,
|
||||
account_id: current.account_id.clone(),
|
||||
nickname: nickname.clone(),
|
||||
avatar_url: avatar_url.clone(),
|
||||
issued_at: claims.issued_at,
|
||||
};
|
||||
for channel in channels {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel),
|
||||
exclude_session: None,
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::ProfileUpdated, 0, &to_payload(&event)),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recheck current visibility when a queued update is delivered after access changes.
|
||||
pub async fn may_deliver(state: &State, recipient: &str, payload: &[u8]) -> bool {
|
||||
let Ok(event) = ProfileUpdated::decode(payload) else {
|
||||
return false;
|
||||
};
|
||||
let _access = state.access.read().await;
|
||||
let sessions = state.sessions.read().await;
|
||||
let Some(recipient) = sessions.get(recipient) else {
|
||||
return false;
|
||||
};
|
||||
if recipient.user_id == event.user_id && recipient.account_id == event.account_id {
|
||||
return true;
|
||||
}
|
||||
sessions.values().any(|subject| {
|
||||
subject.user_id == event.user_id
|
||||
&& subject.account_id == event.account_id
|
||||
&& [
|
||||
subject.channel_id.as_deref(),
|
||||
subject.voice_channel_id.as_deref(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|channel| {
|
||||
recipient.channel_id.as_deref() == Some(channel)
|
||||
|| recipient.voice_channel_id.as_deref() == Some(channel)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
321
gateway/src/handler/profile/tests.rs
Normal file
321
gateway/src/handler/profile/tests.rs
Normal file
|
|
@ -0,0 +1,321 @@
|
|||
use super::*;
|
||||
use crate::domain::channels;
|
||||
use crate::handler::{Ctx, deliver::deliver_frame, dispatch};
|
||||
use std::sync::{Arc, atomic::AtomicUsize};
|
||||
|
||||
async fn fixture() -> (
|
||||
State,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
tokio::sync::broadcast::Receiver<String>,
|
||||
) {
|
||||
let storage = crate::domain::storage::Storage::connect_sqlite(":memory:")
|
||||
.await
|
||||
.unwrap();
|
||||
let mut config: crate::domain::config::Config =
|
||||
toml::from_str(include_str!("../../../../dev/config.toml")).unwrap();
|
||||
config.gateway.central_account = Some(account::tests::trust());
|
||||
let dir = std::env::temp_dir().join(format!("vnox-profile-{}", uuid::Uuid::new_v4()));
|
||||
let identity =
|
||||
crate::bootstrap::server_identity::ServerIdentity::load_or_generate(&dir).unwrap();
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
let (broadcast, _) = tokio::sync::broadcast::channel(128);
|
||||
let (voice, voice_rx) = tokio::sync::broadcast::channel(32);
|
||||
let state = State::new(
|
||||
session::new_store(),
|
||||
channels::new_store(),
|
||||
Arc::new(storage),
|
||||
Arc::new(config),
|
||||
Arc::new(identity),
|
||||
broadcast,
|
||||
crate::admin::metrics::Metrics::new(),
|
||||
Arc::new(AtomicUsize::new(0)),
|
||||
Arc::new(AtomicUsize::new(0)),
|
||||
Some(voice),
|
||||
);
|
||||
let a = session::create(&state.sessions, hex::encode([9; 32]), "Old Name".into()).await;
|
||||
let b = session::create(&state.sessions, hex::encode([8; 32]), "Peer".into()).await;
|
||||
let hidden = session::create(&state.sessions, hex::encode([7; 32]), "Hidden".into()).await;
|
||||
for sid in [&a.session_id, &b.session_id] {
|
||||
channels::join(&state.channels, "general", sid).await;
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(sid)
|
||||
.unwrap()
|
||||
.channel_id = Some("general".into());
|
||||
}
|
||||
let now = now();
|
||||
let mut sessions = state.sessions.write().await;
|
||||
let a = sessions.get_mut(&a.session_id).unwrap();
|
||||
a.account_id = "c3ebd30f-6bb4-4c31-9016-bec57e986c93".into();
|
||||
a.avatar_url = "/v1/avatars/old".into();
|
||||
a.profile_issued_at = now - 30;
|
||||
let a = a.session_id.clone();
|
||||
drop(sessions);
|
||||
(state, a, b.session_id, hidden.session_id, voice_rx)
|
||||
}
|
||||
fn now() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64
|
||||
}
|
||||
fn proof(key: &[u8; 32], issued: i64, name: &str, avatar: &str) -> Vec<u8> {
|
||||
let mut claims = account::tests::claims(key, issued);
|
||||
claims["display_name"] = serde_json::json!(name);
|
||||
claims["avatar_url"] = serde_json::json!(avatar);
|
||||
account::tests::sign(claims)
|
||||
}
|
||||
fn packet(msg: &BroadcastMsg) -> PacketId {
|
||||
PacketId::from_u16(
|
||||
crate::proto::PacketHeader::from_bytes(msg.data[..12].try_into().unwrap()).packet_id,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn two_clients_receive_signed_profile_before_chat_and_voice_rejoin_without_membership_changes()
|
||||
{
|
||||
let (state, a, b, hidden, mut voice_rx) = fixture().await;
|
||||
let (mut a_socket, mut a_client) = tokio::io::duplex(65536);
|
||||
let (mut b_socket, mut b_client) = tokio::io::duplex(65536);
|
||||
let mut a_seq = 0;
|
||||
let mut b_seq = 0;
|
||||
crate::handler::channel::join(
|
||||
&mut a_socket,
|
||||
&mut a_seq,
|
||||
&a,
|
||||
"voice",
|
||||
&state,
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for _ in 0..2 {
|
||||
io::read_packet(&mut a_client).await.unwrap();
|
||||
}
|
||||
assert!(voice_rx.try_recv().unwrap().contains("join"));
|
||||
channels::join(&state.channels, "voice", &b).await;
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(&b)
|
||||
.unwrap()
|
||||
.voice_channel_id = Some("voice".into());
|
||||
let before = channels::members(&state.channels, "general").await;
|
||||
let mut events = state.broadcast.subscribe();
|
||||
let fresh = proof(&[9; 32], now() - 1, "New Name", "/v1/avatars/new");
|
||||
let mut ctx = Ctx {
|
||||
stream: &mut a_socket,
|
||||
seq: &mut a_seq,
|
||||
state: &state,
|
||||
};
|
||||
dispatch(
|
||||
&mut ctx,
|
||||
&a,
|
||||
PacketId::ProfileUpdate,
|
||||
&to_payload(&ProfileUpdate {
|
||||
account_proof: fresh,
|
||||
}),
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
dispatch(
|
||||
&mut ctx,
|
||||
&a,
|
||||
PacketId::ChatMessage,
|
||||
&to_payload(&proto::ChatMessage {
|
||||
message_id: uuid::Uuid::new_v4().to_string(),
|
||||
channel_id: "general".into(),
|
||||
content: "fresh profile message".into(),
|
||||
..Default::default()
|
||||
}),
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(channels::members(&state.channels, "general").await, before);
|
||||
assert_eq!(
|
||||
state.sessions.read().await[&a].voice_channel_id.as_deref(),
|
||||
Some("voice")
|
||||
);
|
||||
assert!(
|
||||
voice_rx.try_recv().is_err(),
|
||||
"profile update must not issue/revoke voice credentials"
|
||||
);
|
||||
let mut received = Vec::new();
|
||||
while let Ok(event) = events.try_recv() {
|
||||
assert!(!matches!(
|
||||
packet(&event),
|
||||
PacketId::UserJoin | PacketId::UserLeave | PacketId::Disconnect
|
||||
));
|
||||
assert!(
|
||||
!may_deliver(&state, &hidden, &event.data[12..]).await
|
||||
|| packet(&event) != PacketId::ProfileUpdated
|
||||
);
|
||||
deliver_frame(&mut b_socket, &mut b_seq, &b, &event, &state)
|
||||
.await
|
||||
.unwrap();
|
||||
received.push(packet(&event));
|
||||
}
|
||||
assert_eq!(received.last(), Some(&PacketId::ChatMessage));
|
||||
assert_eq!(
|
||||
received
|
||||
.iter()
|
||||
.filter(|packet| **packet == PacketId::ProfileUpdated)
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
for _ in 0..2 {
|
||||
let (header, payload) = io::read_packet(&mut b_client).await.unwrap();
|
||||
assert_eq!(header.packet_id, PacketId::ProfileUpdated as u16);
|
||||
let profile = ProfileUpdated::decode(payload.as_slice()).unwrap();
|
||||
assert_eq!(profile.nickname, "New Name");
|
||||
assert_eq!(profile.avatar_url, "/v1/avatars/new");
|
||||
assert_eq!(profile.user_id, hex::encode([9; 32]));
|
||||
}
|
||||
assert_eq!(
|
||||
io::read_packet(&mut b_client).await.unwrap().0.packet_id,
|
||||
PacketId::ChatMessage as u16
|
||||
);
|
||||
crate::handler::channel::leave(&mut a_socket, &mut a_seq, &a, "voice", &state)
|
||||
.await
|
||||
.unwrap();
|
||||
while events.try_recv().is_ok() {}
|
||||
apply(
|
||||
&state,
|
||||
&a,
|
||||
&proof(&[9; 32], now(), "Newest Name", "/v1/avatars/newest"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::channel::join(
|
||||
&mut a_socket,
|
||||
&mut a_seq,
|
||||
&a,
|
||||
"voice",
|
||||
&state,
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (_, snapshot) = io::read_packet(&mut a_client).await.unwrap();
|
||||
let snapshot = proto::ChannelState::decode(snapshot.as_slice()).unwrap();
|
||||
assert_eq!(snapshot.members.len(), 2);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.members
|
||||
.iter()
|
||||
.find(|m| m.user_id == hex::encode([9; 32]))
|
||||
.unwrap()
|
||||
.nickname,
|
||||
"Newest Name"
|
||||
);
|
||||
assert_eq!(
|
||||
io::read_packet(&mut a_client).await.unwrap().0.packet_id,
|
||||
PacketId::VoiceSession as u16
|
||||
);
|
||||
let join = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.find(|e| packet(e) == PacketId::UserJoin)
|
||||
.unwrap();
|
||||
let join = proto::UserJoin::decode(&join.data[12..]).unwrap();
|
||||
assert_eq!(join.nickname, "Newest Name");
|
||||
assert_eq!(join.avatar_url, "/v1/avatars/newest");
|
||||
assert_eq!(state.sessions.read().await.len(), 3);
|
||||
assert_eq!(
|
||||
state.sessions.read().await[&a].user_id,
|
||||
hex::encode([9; 32])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forged_wrong_account_device_expired_and_older_profiles_cannot_downgrade_or_escape_visibility()
|
||||
{
|
||||
let (state, a, b, hidden, _voice) = fixture().await;
|
||||
let mut events = state.broadcast.subscribe();
|
||||
let accepted = proof(&[9; 32], now() - 1, "New Name", "/v1/avatars/new");
|
||||
apply(&state, &a, &accepted).await.unwrap();
|
||||
let event = events.try_recv().unwrap();
|
||||
assert!(may_deliver(&state, &b, &event.data[12..]).await);
|
||||
assert!(!may_deliver(&state, &hidden, &event.data[12..]).await);
|
||||
state.sessions.write().await.get_mut(&b).unwrap().channel_id = None;
|
||||
assert!(
|
||||
!may_deliver(&state, &b, &event.data[12..]).await,
|
||||
"queued event after access revocation is hidden"
|
||||
);
|
||||
let mut claims = account::tests::claims(&[9; 32], now());
|
||||
claims["subject"] = serde_json::json!(uuid::Uuid::new_v4().to_string());
|
||||
claims["display_name"] = serde_json::json!("Other");
|
||||
claims["avatar_url"] = serde_json::json!("/v1/avatars/other");
|
||||
let mut forged = accepted.clone();
|
||||
*forged.last_mut().unwrap() = b'!';
|
||||
for invalid in [
|
||||
account::tests::sign(claims),
|
||||
proof(&[8; 32], now(), "Other", "/v1/avatars/other"),
|
||||
proof(&[9; 32], now() - 1000, "Expired", "/v1/avatars/old"),
|
||||
forged,
|
||||
] {
|
||||
assert!(apply(&state, &a, &invalid).await.is_err());
|
||||
}
|
||||
apply(
|
||||
&state,
|
||||
&a,
|
||||
&proof(&[9; 32], now() - 10, "Old Name", "/v1/avatars/old"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(state.sessions.read().await[&a].nickname, "New Name");
|
||||
assert!(events.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_devices_share_only_metadata_and_older_other_device_proof_does_not_revert_it() {
|
||||
let (state, a, _b, _hidden, _voice) = fixture().await;
|
||||
let second = session::create(&state.sessions, hex::encode([10; 32]), "Old Name".into()).await;
|
||||
let account_id = state.sessions.read().await[&a].account_id.clone();
|
||||
state
|
||||
.sessions
|
||||
.write()
|
||||
.await
|
||||
.get_mut(&second.session_id)
|
||||
.unwrap()
|
||||
.account_id = account_id;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild(&second.user_id, "Device-owned guild")
|
||||
.await
|
||||
.unwrap();
|
||||
apply(
|
||||
&state,
|
||||
&a,
|
||||
&proof(&[9; 32], now() - 1, "New Name", "/v1/avatars/new"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
apply(
|
||||
&state,
|
||||
&second.session_id,
|
||||
&proof(&[10; 32], now() - 10, "Old Name", "/v1/avatars/old"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let second = state.sessions.read().await[&second.session_id].clone();
|
||||
assert_eq!(second.nickname, "New Name");
|
||||
assert_eq!(second.avatar_url, "/v1/avatars/new");
|
||||
assert_eq!(second.user_id, hex::encode([10; 32]));
|
||||
assert_eq!(
|
||||
state
|
||||
.storage
|
||||
.get_guild(&guild)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.owner_id,
|
||||
hex::encode([10; 32])
|
||||
);
|
||||
}
|
||||
|
|
@ -30,6 +30,7 @@ impl Drop for ConnGuard {
|
|||
|
||||
pub async fn run(cfg: Arc<config::Config>, voice_member_tx: Option<VoiceMemberTx>) -> Result<()> {
|
||||
cfg.gateway.validate_tls()?;
|
||||
cfg.gateway.validate_admin_accounts()?;
|
||||
if cfg.gateway.tls_enabled == Some(true) {
|
||||
warn!("gateway.tls_enabled is deprecated: TLS 1.3 is always on, remove the option");
|
||||
}
|
||||
|
|
@ -118,6 +119,9 @@ pub async fn run(cfg: Arc<config::Config>, voice_member_tx: Option<VoiceMemberTx
|
|||
.storage
|
||||
.load_channels_to_cache(&state.channels)
|
||||
.await?;
|
||||
if let Some(settings) = state.storage.load_node_settings().await? {
|
||||
*state.node_settings.write().await = settings;
|
||||
}
|
||||
state.webhooks.configure_from_env()?;
|
||||
tokio::spawn(webhooks::outgoing::run(state.clone()));
|
||||
|
||||
|
|
@ -256,11 +260,20 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
|
|||
.await;
|
||||
}
|
||||
|
||||
let _cleanup_guard = state.access.write().await;
|
||||
let user_id = session::get(&state.sessions, &sid)
|
||||
.await
|
||||
.map(|s| s.user_id.clone());
|
||||
|
||||
if let Some(ref uid) = user_id {
|
||||
let another_device_session = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.any(|other| other.session_id != sid && Some(&other.user_id) == user_id.as_ref());
|
||||
if let Some(ref uid) = user_id
|
||||
&& !another_device_session
|
||||
{
|
||||
state.presences.write().await.insert(
|
||||
uid.clone(),
|
||||
PresenceInfo {
|
||||
|
|
@ -316,6 +329,7 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
|
|||
.sessions_count
|
||||
.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
|
||||
state.rate_limiter.remove(&sid);
|
||||
state.profile_rate_limiter.remove(&sid);
|
||||
debug!("{addr} cleaned up");
|
||||
result
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,11 +10,11 @@ use crate::{
|
|||
proto::{self, AuthPayload, HelloPayload, PacketId, SessionPayload, to_payload},
|
||||
};
|
||||
|
||||
/// LNEx protocol version. v3 runs inside TLS 1.3 (see `docs/02-protocol/tls.md`).
|
||||
pub const LNEX_VERSION: &str = "v3";
|
||||
/// LNEx protocol version. v4 requires a Central account inside TLS 1.3 (see `docs/02-protocol/tls.md`).
|
||||
pub const LNEX_VERSION: &str = "v4";
|
||||
|
||||
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v3-server-hello\0";
|
||||
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v3-client-auth\0";
|
||||
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v4-server-hello\0";
|
||||
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v4-client-auth\0";
|
||||
|
||||
/// Bytes the server identity signs: context, TLS exporter, HELLO without its signature.
|
||||
pub fn server_hello_transcript(binding: &[u8], unsigned_hello: &[u8]) -> Vec<u8> {
|
||||
|
|
@ -56,7 +56,7 @@ pub async fn run(
|
|||
lnex_version: LNEX_VERSION.into(),
|
||||
server_pubkey: hex::decode(state.server_identity.pubkey_hex())?,
|
||||
challenge_nonce: challenge.to_vec(),
|
||||
node_name: state.config.node.name.clone(),
|
||||
node_name: state.node_settings.read().await.0.clone(),
|
||||
private_mode,
|
||||
server_signature: Vec::new(),
|
||||
};
|
||||
|
|
@ -84,7 +84,7 @@ pub async fn run(
|
|||
stream,
|
||||
seq,
|
||||
proto::ErrorCode::VersionMismatch,
|
||||
"unsupported version: LNEx v3 required",
|
||||
"unsupported version: LNEx v4 required",
|
||||
)
|
||||
.await?;
|
||||
return Err(anyhow::anyhow!("version mismatch"));
|
||||
|
|
@ -118,6 +118,30 @@ pub async fn run(
|
|||
return Err(anyhow::anyhow!("auth failed"));
|
||||
}
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)?
|
||||
.as_secs() as i64;
|
||||
let account = match crate::domain::account::verify(
|
||||
&msg.account_proof,
|
||||
&pubkey,
|
||||
state.config.gateway.central_account.as_ref(),
|
||||
now,
|
||||
) {
|
||||
Ok(account) => account,
|
||||
Err(error) => {
|
||||
warn!("{addr} Central account admission failed: {error}");
|
||||
state.metrics.inc(&state.metrics.auth_failures);
|
||||
io::send_error(
|
||||
stream,
|
||||
seq,
|
||||
proto::ErrorCode::AuthFailed,
|
||||
"Central account sign-in required; sign in again in the desktop client",
|
||||
)
|
||||
.await?;
|
||||
return Err(anyhow::anyhow!("Central account admission failed"));
|
||||
}
|
||||
};
|
||||
|
||||
if state
|
||||
.storage
|
||||
.is_banned(&hex::encode(&msg.client_pubkey))
|
||||
|
|
@ -134,13 +158,35 @@ pub async fn run(
|
|||
.await?;
|
||||
|
||||
// SESSION
|
||||
let sess = session::create(
|
||||
let mut sess = session::create(
|
||||
&state.sessions,
|
||||
hex::encode(&msg.client_pubkey),
|
||||
msg.nickname.clone(),
|
||||
)
|
||||
.await;
|
||||
|
||||
sess.profile_issued_at = account.issued_at;
|
||||
sess.account_id = account.account_id;
|
||||
sess.nickname = account.display_name.unwrap_or(sess.nickname);
|
||||
sess.avatar_url = account
|
||||
.avatar_url
|
||||
.unwrap_or_else(|| format!("/v1/avatars/default-v2/{}", sess.account_id));
|
||||
{
|
||||
let mut sessions = state.sessions.write().await;
|
||||
if let Some(latest) = sessions
|
||||
.values()
|
||||
.filter(|s| {
|
||||
s.account_id == sess.account_id && s.profile_issued_at > sess.profile_issued_at
|
||||
})
|
||||
.max_by_key(|s| s.profile_issued_at)
|
||||
{
|
||||
sess.nickname = latest.nickname.clone();
|
||||
sess.avatar_url = latest.avatar_url.clone();
|
||||
sess.profile_issued_at = latest.profile_issued_at;
|
||||
}
|
||||
sessions.insert(sess.session_id.clone(), sess.clone());
|
||||
}
|
||||
|
||||
let timeout_secs = state.config.gateway.session_timeout.unwrap_or(600);
|
||||
let expires_at = std::time::SystemTime::now()
|
||||
.checked_add(std::time::Duration::from_secs(timeout_secs))
|
||||
|
|
@ -148,6 +194,11 @@ pub async fn run(
|
|||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0);
|
||||
let sp = SessionPayload {
|
||||
live_profiles: true,
|
||||
node_settings: true,
|
||||
channel_structure: true,
|
||||
forums: true,
|
||||
node_admin: state.config.gateway.is_node_admin(&sess.account_id),
|
||||
session_id: sess.session_id.clone(),
|
||||
token: sess.token.clone(),
|
||||
expires_at,
|
||||
|
|
@ -173,7 +224,9 @@ mod tests {
|
|||
let storage = crate::domain::storage::Storage::connect_sqlite(":memory:")
|
||||
.await
|
||||
.unwrap();
|
||||
let config = toml::from_str(include_str!("../../../dev/config.toml")).unwrap();
|
||||
let mut config: crate::domain::config::Config =
|
||||
toml::from_str(include_str!("../../../dev/config.toml")).unwrap();
|
||||
config.gateway.central_account = Some(crate::domain::account::tests::trust());
|
||||
let dir = std::env::temp_dir().join(format!("vnox-hs-test-{}", uuid::Uuid::new_v4()));
|
||||
let identity =
|
||||
crate::bootstrap::server_identity::ServerIdentity::load_or_generate(&dir).unwrap();
|
||||
|
|
@ -208,6 +261,13 @@ mod tests {
|
|||
nickname: "tester".into(),
|
||||
lnex_version: version.into(),
|
||||
signature: Vec::new(),
|
||||
account_proof: crate::domain::account::tests::proof(
|
||||
&key.verifying_key().to_bytes(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64,
|
||||
),
|
||||
};
|
||||
let transcript = client_auth_transcript(client_binding, &payload, &auth.encode_to_vec());
|
||||
auth.signature = key.sign(&transcript).to_bytes().to_vec();
|
||||
|
|
@ -250,6 +310,57 @@ mod tests {
|
|||
(task.await.unwrap(), error)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn node_admin_session_capability_uses_verified_central_account_on_each_device() {
|
||||
for listed in [false, true] {
|
||||
let mut state = state().await;
|
||||
Arc::get_mut(&mut state.config)
|
||||
.unwrap()
|
||||
.gateway
|
||||
.admin_account_ids = vec![if listed {
|
||||
"c3ebd30f-6bb4-4c31-9016-bec57e986c93".into()
|
||||
} else {
|
||||
uuid::Uuid::new_v4().to_string()
|
||||
}];
|
||||
let mut devices = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let (mut server, mut peer) = tokio::io::duplex(65536);
|
||||
let shared = state.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
run(
|
||||
&mut server,
|
||||
"127.0.0.1:1".parse().unwrap(),
|
||||
&shared,
|
||||
&mut 0,
|
||||
&[9; 32],
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
client_auth(&mut peer, &[9; 32], LNEX_VERSION).await;
|
||||
let (header, payload) = io::read_packet(&mut peer).await.unwrap();
|
||||
assert_eq!(header.packet_id, PacketId::Session as u16);
|
||||
assert_eq!(
|
||||
SessionPayload::decode(payload.as_slice())
|
||||
.unwrap()
|
||||
.node_admin,
|
||||
listed
|
||||
);
|
||||
assert!(
|
||||
SessionPayload::decode(payload.as_slice())
|
||||
.unwrap()
|
||||
.live_profiles
|
||||
);
|
||||
let admitted = task.await.unwrap();
|
||||
assert_eq!(admitted.account_id, "c3ebd30f-6bb4-4c31-9016-bec57e986c93");
|
||||
devices.push(admitted.user_id);
|
||||
}
|
||||
assert_ne!(
|
||||
devices[0], devices[1],
|
||||
"two different devices of the same admitted account"
|
||||
);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn signature_for_the_same_channel_binding_is_accepted() {
|
||||
let (result, _) = handshake(&[9; 32], &[9; 32], LNEX_VERSION).await;
|
||||
|
|
@ -269,7 +380,7 @@ mod tests {
|
|||
let (result, error) = handshake(&[3; 32], &[3; 32], "v2").await;
|
||||
assert!(result.is_err());
|
||||
assert_eq!(error.code, proto::ErrorCode::VersionMismatch as u32);
|
||||
assert!(error.message.contains("v3"));
|
||||
assert!(error.message.contains("v4"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! LNEx v3 TCP framing. Frames are written directly into the TLS 1.3 stream, so there is
|
||||
//! LNEx v4 TCP framing. Frames are written directly into the TLS 1.3 stream, so there is
|
||||
//! no per frame encryption: the 12 byte header is followed by the protobuf payload and
|
||||
//! `flags` must be zero on the control plane.
|
||||
use anyhow::Result;
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ pub type VoiceMemberTx = tokio::sync::broadcast::Sender<String>;
|
|||
#[derive(Clone)]
|
||||
pub struct State {
|
||||
pub access: Arc<tokio::sync::RwLock<()>>,
|
||||
pub node_settings: Arc<RwLock<(String, String)>>,
|
||||
pub media: Arc<crate::media::Runtime>,
|
||||
pub webhooks: Arc<crate::webhooks::Runtime>,
|
||||
pub sessions: SessionStore,
|
||||
|
|
@ -35,6 +36,7 @@ pub struct State {
|
|||
pub channels_count: Arc<AtomicUsize>,
|
||||
/// Per-session rate limiter (token bucket).
|
||||
pub rate_limiter: Arc<RateLimiter>,
|
||||
pub profile_rate_limiter: Arc<RateLimiter>,
|
||||
/// Gateway → voice-node membership bridge.
|
||||
pub voice_member_tx: Option<VoiceMemberTx>,
|
||||
/// E2EE key store: user_id -> X25519 public key bytes
|
||||
|
|
@ -58,7 +60,9 @@ impl State {
|
|||
let rate_per_sec = config.gateway.message_rate_per_sec.unwrap_or(5.0);
|
||||
let burst = config.gateway.message_rate_burst.unwrap_or(10);
|
||||
let rate_limiter = Arc::new(RateLimiter::new(rate_per_sec, burst));
|
||||
let node_settings = Arc::new(RwLock::new((config.node.name.clone(), String::new())));
|
||||
Self {
|
||||
node_settings,
|
||||
access: Arc::default(),
|
||||
media: Arc::default(),
|
||||
webhooks: Arc::default(),
|
||||
|
|
@ -73,6 +77,7 @@ impl State {
|
|||
sessions_count,
|
||||
channels_count,
|
||||
rate_limiter,
|
||||
profile_rate_limiter: Arc::new(RateLimiter::new(1.0, 4)),
|
||||
voice_member_tx,
|
||||
e2ee_keys: Arc::new(RwLock::new(HashMap::new())),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,16 @@
|
|||
#[repr(u16)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PacketId {
|
||||
NodeSettingsRequest = 0x0230,
|
||||
NodeSettingsResult = 0x0231,
|
||||
ClientFeatures = 0x0232,
|
||||
ForumRequest = 0x0240,
|
||||
ForumResult = 0x0241,
|
||||
ForumChanged = 0x0242,
|
||||
WebhookErrorResult = 0x0206,
|
||||
AttachmentUpload = 0x0220,
|
||||
AttachmentFetch = 0x0221,
|
||||
AttachmentResult = 0x0222,
|
||||
MediaControl = 0x0180,
|
||||
MediaEvent = 0x0181,
|
||||
WebhookCreate = 0x0200,
|
||||
|
|
@ -29,6 +38,8 @@ pub enum PacketId {
|
|||
ChannelEdit = 0x0036,
|
||||
UserJoin = 0x0040,
|
||||
UserLeave = 0x0041,
|
||||
ProfileUpdate = 0x0042,
|
||||
ProfileUpdated = 0x0043,
|
||||
PermissionCheck = 0x0050,
|
||||
PermissionDeny = 0x0051,
|
||||
DmStart = 0x0060,
|
||||
|
|
@ -85,6 +96,15 @@ pub enum PacketId {
|
|||
impl PacketId {
|
||||
pub fn from_u16(v: u16) -> Option<Self> {
|
||||
match v {
|
||||
0x0230 => Some(Self::NodeSettingsRequest),
|
||||
0x0231 => Some(Self::NodeSettingsResult),
|
||||
0x0232 => Some(Self::ClientFeatures),
|
||||
0x0240 => Some(Self::ForumRequest),
|
||||
0x0241 => Some(Self::ForumResult),
|
||||
0x0242 => Some(Self::ForumChanged),
|
||||
0x0220 => Some(Self::AttachmentUpload),
|
||||
0x0221 => Some(Self::AttachmentFetch),
|
||||
0x0222 => Some(Self::AttachmentResult),
|
||||
0x0206 => Some(Self::WebhookErrorResult),
|
||||
0x0180 => Some(Self::MediaControl),
|
||||
0x0181 => Some(Self::MediaEvent),
|
||||
|
|
@ -113,6 +133,8 @@ impl PacketId {
|
|||
0x0036 => Some(Self::ChannelEdit),
|
||||
0x0040 => Some(Self::UserJoin),
|
||||
0x0041 => Some(Self::UserLeave),
|
||||
0x0042 => Some(Self::ProfileUpdate),
|
||||
0x0043 => Some(Self::ProfileUpdated),
|
||||
0x0050 => Some(Self::PermissionCheck),
|
||||
0x0051 => Some(Self::PermissionDeny),
|
||||
0x0060 => Some(Self::DmStart),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! TLS 1.3 for the TCP control plane (LNEx v3). See `docs/02-protocol/tls.md`.
|
||||
//! TLS 1.3 for the TCP control plane (LNEx v4). See `docs/02-protocol/tls.md`.
|
||||
//!
|
||||
//! * TLS 1.3 only, ALPN `vnox-lnex/3`, no client certificates, no plaintext fallback.
|
||||
//! * TLS 1.3 only, ALPN `vnox-lnex/4`, no client certificates, no plaintext fallback.
|
||||
//! * Certificate: user supplied (PEM chain + key) or auto generated and stored in the data
|
||||
//! directory. The auto generated certificate is signed with the server identity Ed25519
|
||||
//! key, so its SPKI fingerprint is a pure function of the identity.
|
||||
|
|
@ -18,13 +18,13 @@ use crate::bootstrap::server_identity::ServerIdentity;
|
|||
use crate::domain::config::GatewayConfig;
|
||||
|
||||
/// Application protocol negotiated through ALPN. A connection without it is dropped.
|
||||
pub const ALPN: &[u8] = b"vnox-lnex/3";
|
||||
pub const ALPN: &[u8] = b"vnox-lnex/4";
|
||||
/// TLS exporter label (RFC 5705 / RFC 8446 section 7.5) used for the channel binding.
|
||||
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding";
|
||||
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v4-channel-binding";
|
||||
/// Size of the exported channel binding value.
|
||||
pub const BINDING_LEN: usize = 32;
|
||||
/// Message shown to peers that do not speak TLS 1.3 (old LNEx v2 clients, plaintext probes).
|
||||
pub const LEGACY_MESSAGE: &str = "TLS 1.3 required (LNEx v3): update your client";
|
||||
pub const LEGACY_MESSAGE: &str = "TLS 1.3 required (LNEx v4): update your client";
|
||||
|
||||
/// Certificate chain, private key and the fingerprint of the leaf public key.
|
||||
pub struct TlsMaterial {
|
||||
|
|
@ -246,7 +246,7 @@ pub fn channel_binding(connection: &rustls::ServerConnection) -> Result<[u8; BIN
|
|||
);
|
||||
anyhow::ensure!(
|
||||
connection.alpn_protocol() == Some(ALPN),
|
||||
"ALPN vnox-lnex/3 required"
|
||||
"ALPN vnox-lnex/4 required"
|
||||
);
|
||||
connection
|
||||
.export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! Black box tests of the gateway TCP listener: TLS 1.3 only, ALPN, legacy rejection,
|
||||
//! certificate fingerprint and the channel bound LNEx v3 handshake.
|
||||
//! certificate fingerprint and the channel bound LNEx v4 handshake.
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
|
|
@ -46,6 +46,9 @@ address = "127.0.0.1"
|
|||
[gateway]
|
||||
bind = "127.0.0.1:{port}"
|
||||
admin_bind = "127.0.0.1:0"
|
||||
[gateway.central_account]
|
||||
issuer = "8a1495ae-7174-4d22-94a5-080f61aa1691"
|
||||
public_key = "{issuer_key}"
|
||||
[voice]
|
||||
bind = "127.0.0.1:0"
|
||||
[storage]
|
||||
|
|
@ -55,7 +58,8 @@ sqlite_path = "{dir}/t.db"
|
|||
[server]
|
||||
mode = "private"
|
||||
"#,
|
||||
dir = directory.display()
|
||||
dir = directory.display(),
|
||||
issuer_key = hex::encode(SigningKey::from_bytes(&[73; 32]).verifying_key().to_bytes())
|
||||
);
|
||||
let cfg: vnox_gateway::domain::config::Config = toml::from_str(&config).unwrap();
|
||||
let task = tokio::spawn(async move {
|
||||
|
|
@ -215,7 +219,7 @@ async fn client_without_alpn_is_rejected_before_any_lnex_byte() {
|
|||
let read = tokio::time::timeout(Duration::from_secs(3), tls.read(&mut byte)).await;
|
||||
assert!(
|
||||
!matches!(read, Ok(Ok(n)) if n > 0),
|
||||
"no LNEx data may be sent without ALPN vnox-lnex/3"
|
||||
"no LNEx data may be sent without ALPN vnox-lnex/4"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -255,12 +259,29 @@ async fn silent_v2_style_client_gets_explicit_version_error() {
|
|||
assert_eq!(id, PacketId::Error as u16);
|
||||
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
|
||||
assert_eq!(error.code, ErrorCode::VersionMismatch as u32);
|
||||
assert!(error.message.contains("LNEx v3"));
|
||||
assert!(error.message.contains("LNEx v4"));
|
||||
}
|
||||
|
||||
fn account_proof(public_key: &[u8; 32]) -> Vec<u8> {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64;
|
||||
let claims = serde_json::to_vec(&serde_json::json!({
|
||||
"version":1,"issuer":"8a1495ae-7174-4d22-94a5-080f61aa1691",
|
||||
"subject":"c3ebd30f-6bb4-4c31-9016-bec57e986c93","public_key":hex::encode(public_key),
|
||||
"issued_at":now,"expires_at":now+600,"audience":"vnox-gateway"
|
||||
}))
|
||||
.unwrap();
|
||||
let mut signed = b"VNOX-CENTRAL-ACCOUNT-v1\0".to_vec();
|
||||
signed.extend_from_slice(&claims);
|
||||
serde_json::to_vec(&serde_json::json!({"claims":hex::encode(claims),"signature":hex::encode(SigningKey::from_bytes(&[73;32]).sign(&signed).to_bytes())})).unwrap()
|
||||
}
|
||||
|
||||
async fn authenticate(
|
||||
tls: &mut tokio_rustls::client::TlsStream<TcpStream>,
|
||||
signing_binding: Option<[u8; 32]>,
|
||||
include_account: bool,
|
||||
) -> (u16, Vec<u8>) {
|
||||
let binding = tls
|
||||
.get_ref()
|
||||
|
|
@ -289,6 +310,11 @@ async fn authenticate(
|
|||
nickname: "tls-test".into(),
|
||||
lnex_version: LNEX_VERSION.into(),
|
||||
signature: Vec::new(),
|
||||
account_proof: if include_account {
|
||||
account_proof(&key.verifying_key().to_bytes())
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
};
|
||||
let signed_with = signing_binding.unwrap_or(binding);
|
||||
let transcript = client_auth_transcript(&signed_with, &payload, &auth.encode_to_vec());
|
||||
|
|
@ -305,7 +331,7 @@ async fn full_handshake_over_tls_creates_a_session() {
|
|||
let server = start().await;
|
||||
let (config, _) = client_config(&[&rustls::version::TLS13], true);
|
||||
let mut tls = connect_tls(&server, config).await.unwrap();
|
||||
let (id, _) = authenticate(&mut tls, None).await;
|
||||
let (id, _) = authenticate(&mut tls, None, true).await;
|
||||
assert_eq!(id, PacketId::Session as u16);
|
||||
}
|
||||
|
||||
|
|
@ -314,8 +340,28 @@ async fn auth_signed_for_another_tls_connection_is_rejected() {
|
|||
let server = start().await;
|
||||
let (config, _) = client_config(&[&rustls::version::TLS13], true);
|
||||
let mut tls = connect_tls(&server, config).await.unwrap();
|
||||
let (id, payload) = authenticate(&mut tls, Some([0x42; 32])).await;
|
||||
let (id, payload) = authenticate(&mut tls, Some([0x42; 32]), true).await;
|
||||
assert_eq!(id, PacketId::Error as u16);
|
||||
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
|
||||
assert_eq!(error.code, ErrorCode::AuthFailed as u32);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn valid_device_signature_without_a_central_account_is_rejected() {
|
||||
let server = start().await;
|
||||
let (config, _) = client_config(&[&rustls::version::TLS13], true);
|
||||
let mut tls = connect_tls(&server, config).await.unwrap();
|
||||
let (id, payload) = authenticate(&mut tls, None, false).await;
|
||||
assert_eq!(id, PacketId::Error as u16);
|
||||
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
|
||||
assert_eq!(error.code, ErrorCode::AuthFailed as u32);
|
||||
assert!(error.message.contains("Central account"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn old_v3_alpn_is_rejected_before_any_lnex_byte() {
|
||||
let server = start().await;
|
||||
let (mut config, _) = client_config(&[&rustls::version::TLS13], true);
|
||||
config.alpn_protocols = vec![b"vnox-lnex/3".to_vec()];
|
||||
assert!(connect_tls(&server, config).await.is_err());
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue