Reject stale predecessors when creating or editing channels

This commit is contained in:
omar committed 2026-11-27 03:48:48 +03:00
1 parent b3f73c389d
commit 95ebf37f0b
4 files changed
+62 -10

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
## Unreleased
- When creating a channel, changing its parent clears the previous insertion point. The picker lists only children of the new parent; leaving the position unset lets the server choose it.
Creating or editing now also checks the selected predecessor at submission and refuses the change if it moved to another parent or disappeared.
- Moving a channel to its current parent and explicit position returns an unchanged result without sending a server command.
+57 -8
View File
@@ -1,17 +1,25 @@
//! Session integration of server/channel administration (`admin.rs`, `docs/bridge.md` §4.6).
use super::*;
fn check_predecessor(
channel: Option<u64>, parent: u64, order: Option<u64>,
position_of: impl Fn(u64) -> Option<(u64, u64)>,
) -> Result<(), ErrorObj> {
if let Some(after) = order.filter(|id| *id != 0) {
if Some(after) == channel || position_of(after).map(|p| p.0) != Some(parent) {
return Err(ErrorObj::new(ErrorCode::TargetChanged, "preceding channel is no longer a sibling; reload the channel tree"));
}
}
Ok(())
}
fn move_changes_position(
moving: u64, parent: u64, order: Option<u64>, channel_count: usize,
position_of: impl Fn(u64) -> Option<(u64, u64)>,
) -> Result<bool, ErrorObj> {
let (old_parent, old_order) = position_of(moving)
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel is no longer visible"))?;
if let Some(after) = order.filter(|id| *id != 0) {
if after == moving || position_of(after).map(|p| p.0) != Some(parent) {
return Err(ErrorObj::new(ErrorCode::TargetChanged, "preceding channel is no longer a sibling; reopen the move dialog"));
}
}
check_predecessor(Some(moving), parent, order, &position_of)?;
let mut ancestor = parent;
// Even an inconsistent book with a parent cycle must finish without a network write.
for _ in 0..channel_count {
@@ -25,11 +33,51 @@ fn move_changes_position(
}
}
fn check_property_position(cmd: &admin::AdminCommand, position_of: impl Fn(u64) -> Option<(u64, u64)>) -> Result<(), ErrorObj> {
let (channel, parent, properties) = match cmd {
admin::AdminCommand::ChannelCreate { parent_id, properties, .. } => (None, Some(*parent_id), properties),
admin::AdminCommand::ChannelEdit { channel_id, properties, .. } => (Some(*channel_id), None, properties),
_ => return Ok(()),
};
let Some((_, order)) = properties.iter().find(|(key, _)| *key == "channel_order") else { return Ok(()) };
let order = order.parse::<u64>().map_err(|_| ErrorObj::new(ErrorCode::BadRequest, "invalid channel_order"))?;
if order == 0 { return Ok(()) }
let parent = parent.or_else(|| channel.and_then(&position_of).map(|p| p.0))
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel is no longer visible"))?;
check_predecessor(channel, parent, Some(order), position_of)
}
#[cfg(test)]
mod move_tests {
use super::*;
use std::collections::HashMap;
#[test]
fn channel_property_order_rechecks_current_siblings() {
use admin::{AdminCommand, Properties};
let commands = |order: Option<u64>| {
let mut fields = serde_json::Map::from_iter([("channel_name".into(), json!("Example"))]);
if let Some(order) = order { fields.insert("channel_order".into(), json!(order)); }
[AdminCommand::ChannelCreate { generation: 1, parent_id: 8, properties: Properties::channel_create(fields.clone()).unwrap() },
AdminCommand::ChannelEdit { generation: 1, channel_id: 42, properties: Properties::channel_edit(fields).unwrap() }]
};
let mut tree = HashMap::from([(8, (0, 0)), (42, (8, 0)), (13, (8, 42))]);
let ordered = commands(Some(13));
for cmd in &ordered { check_property_position(cmd, |id| tree.get(&id).copied()).unwrap(); }
for next in [Some((0, 8)), None] {
if let Some(pos) = next { tree.insert(13, pos); } else { tree.remove(&13); }
for cmd in &ordered {
assert_eq!(check_property_position(cmd, |id| tree.get(&id).copied()).unwrap_err().code, ErrorCode::TargetChanged);
}
}
let [create, edit] = commands(Some(42));
check_property_position(&create, |id| tree.get(&id).copied()).unwrap();
assert_eq!(check_property_position(&edit, |id| tree.get(&id).copied()).unwrap_err().code, ErrorCode::TargetChanged);
for cmd in commands(None).into_iter().chain(commands(Some(0))) {
check_property_position(&cmd, |_| panic!("no predecessor to look up")).unwrap();
}
}
#[test]
fn channel_move_rechecks_parent_and_predecessor_at_dispatch() {
let mut parents = HashMap::from([(42, 0), (8, 0), (13, 8), (99, 42)]);
@@ -62,11 +110,12 @@ impl Session {
}
}
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
let position_of = |id| book.channels.get(&ChannelId(id)).map(|ch| (ch.parent.0, ch.order.0));
if let admin::AdminCommand::ChannelMove { channel_id, parent_id, order, .. } = &cmd {
let changes = move_changes_position(*channel_id, *parent_id, *order, book.channels.len(), |id| {
book.channels.get(&ChannelId(id)).map(|channel| (channel.parent.0, channel.order.0))
})?;
let changes = move_changes_position(*channel_id, *parent_id, *order, book.channels.len(), position_of)?;
if !changes { return Ok(Some(json!({"changed": false}))); }
} else {
check_property_position(&cmd, position_of)?;
}
let (command, reply) = match &cmd {
admin::AdminCommand::Context => (menu::command("permissionlist", &[]), admin::Reply::Context),
+2 -2
View File
@@ -665,8 +665,8 @@ For an isolated Windows beta14 fixture at `127.0.0.1:19987`, set `TEAMSPEACH_QA_
| Command | Arguments / result |
|---|---|
| `channel_create` | `{generation,parent_id,properties}` → `{channel_id}` from own channel-created event |
| `channel_edit` | `{generation,channel_id,properties}` |
| `channel_create` | `{generation,parent_id,properties}` → `{channel_id}` from own channel-created event. A nonzero `channel_order` must still be a child of `parent_id` at dispatch. |
| `channel_edit` | `{generation,channel_id,properties}`; a nonzero `channel_order` must still be a sibling distinct from the edited channel. A stale predecessor returns `target_changed` without sending the edit. |
| `channel_move` | `{generation,channel_id,parent_id,order?}`; parent 0 means server root, order 0 means first. A nonzero predecessor must still belong to the destination parent. A missing or cyclic destination ancestry, a destination below the moving channel, or a stale predecessor is refused before sending. An exact match of parent and explicit predecessor returns `{"changed":false}` locally, without a server request. An omitted order does not qualify. |
| `channel_delete` | `{generation,channel_id,force,confirm}`; confirm exact current channel name |
| `channel_subscribe` / `channel_subscribe_all` | `{channel_id,subscribe}` / `{subscribe}` |
+2
View File
@@ -4,6 +4,8 @@
## Возврат к разработке на ПК, 2026-11-26
Windows, база `b3f73c3`: ядро сверяет ненулевой `channel_order` при создании и редактировании канала с текущим деревом перед отправкой. Удалённый или перемещённый в другую ветку сосед и ссылка редактируемого канала на себя отклоняются. Четыре адресных теста ядра прошли; сетевой запрос и ответ сервера в этом прогоне не проверялись.
Windows, база `3c828e3`: при создании канала смена родителя очищает позицию и ограничивает список предшественников его детьми. Тест Slint проверил три команды для родителя 8: без `channel_order`, с явным 0 и с ID 13 второго одноимённого соседа. Прошли шесть адресных тестов. Применение этих команд сервером в этом прогоне не проверялось.
Windows, база `8930007`: завершена сверка `channel.crud` с установленным TS6. Ядро возвращает `{"changed":false}` без сетевой команды только при совпадении родителя и явного предшественника. Три адресных теста прошли. Положительный ответ сервера на перенос и удаление этой сверкой не подтверждён.