From 90c28eedbb2a6716b7ba73ff8e55bec062a494f3 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 27 Nov 2026 06:28:57 +0300 Subject: [PATCH] Require one distinct usable privilege key in creation replies --- CHANGELOG.md | 2 ++ core/src/admin.rs | 45 +++++++++++++++++++++++++++--------- docs/bridge.md | 2 +- docs/mobile-port-progress.md | 2 ++ 4 files changed, 39 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b4994f..bdaf9c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Creating a privilege key no longer reports success with an empty or ambiguous key. A repeated notification for the same key is accepted. + - Client information requests recheck the participant's UID when the server acknowledges the request. A stale client number cannot return another participant's details. - Client database ID lookup now checks the returned UID and rejects conflicting IDs instead of passing unrelated notification rows to callers. diff --git a/core/src/admin.rs b/core/src/admin.rs index 47bda60..2e60612 100644 --- a/core/src/admin.rs +++ b/core/src/admin.rs @@ -715,7 +715,7 @@ pub enum Reply { /// Only an unambiguous creation by our client under the requested parent identifies the new channel. Created { name: String, parent: u64, invoker: u16, channel_id: Option, ambiguous: bool }, /// `tokenadd`: the key comes from `notifytokenadd`. - Token { token: Option }, + Token { token: Option, ambiguous: bool }, GroupCreated { notify: &'static str, key: &'static str, name: String, group_type: u8, existing: std::collections::HashSet, group_id: Option, ambiguous: bool }, /// `channelgetdescription`: the description comes from `notifychanneledited`. Description { channel_id: u64, description: Option }, @@ -789,8 +789,15 @@ impl Reply { } } } - Reply::Token { token } if raw.name == "notifytokenadd" => { - *token = raw.items.first().and_then(|i| i.get("token")).cloned(); + Reply::Token { token, ambiguous } if raw.name == "notifytokenadd" && !*ambiguous => { + for value in raw.items.iter().filter_map(|row| row.get("token")) { + if value.trim().is_empty() || value.chars().count() > 255 || value.chars().any(char::is_control) { continue; } + match token { + Some(previous) if previous != value => { *ambiguous = true; break; } + None => *token = Some(value.clone()), + _ => {} + } + } } Reply::Description { channel_id, description } if matches!(raw.name.as_str(), "notifychanneledited" | "notifychanneldescriptionchanged") => { for row in &raw.items { @@ -826,10 +833,10 @@ pub fn finish(reply: Reply) -> Result { Reply::ChannelInfo { .. } | Reply::ClientInfo(_) => Err(ErrorObj::new(ErrorCode::Internal, "target information is answered by the session")), Reply::Created { channel_id: Some(id), ambiguous: false, .. } => Ok(json!({ "channel_id": id })), Reply::Created { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "channel was accepted but its ID was not uniquely returned; reload channels before continuing").with_detail(json!({"created": true}))), - Reply::Token { token: Some(token) } => Ok(json!({ "token": token })), - Reply::Token { token: None } => Err(ErrorObj::new( + Reply::Token { token: Some(token), ambiguous: false } => Ok(json!({ "token": token })), + Reply::Token { .. } => Err(ErrorObj::new( ErrorCode::ServerError, - "the server accepted the privilege key but did not send it; reload the list", + "the server accepted the privilege key but did not return one unique key; reload the list", ) .with_detail(json!({ "created": true }))), Reply::Description { description, .. } => Ok(json!({ "description": description })), @@ -937,7 +944,7 @@ pub fn build(cmd: &AdminCommand, live: &Live) -> Result<(OutCommand, Reply), Err if *channel_id != 0 { channel_exists(live, *channel_id, "channel")?; } let kind = match kind { PrivilegeKeyKind::ServerGroup => "0", PrivilegeKeyKind::ChannelGroup => "1" }; let a = [("tokentype", kind.into()), ("tokenid1", s(*group_id)), ("tokenid2", s(*channel_id)), ("tokendescription", description.clone())]; - (menu::command("tokenadd", &a), Reply::Token { token: None }) + (menu::command("tokenadd", &a), Reply::Token { token: None, ambiguous: false }) } C::PrivilegeKeyDelete { token, confirm: c, .. } => { confirm(c, token)?; @@ -1324,9 +1331,25 @@ mod tests { c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=13 cpid=0 channel_name=A\sb invokerid=7").unwrap()); assert_eq!(finish(c).unwrap_err().code, ErrorCode::ServerError); - assert!(finish(Reply::Token { token: None }).is_err(), "no fake success without the key"); - let mut t = Reply::Token { token: None }; - t.collect(&crate::rawcmd::parse(br"notifytokenadd token=abc").unwrap()); - assert_eq!(finish(t).unwrap(), json!({"token": "abc"})); + } + + #[test] + fn token_add_requires_one_distinct_usable_key() { + let result = |packets: &[&[u8]]| { + let mut reply = Reply::Token { token: None, ambiguous: false }; + for packet in packets { reply.collect(&crate::rawcmd::parse(packet).unwrap()); } + finish(reply) + }; + let empty = br"notifytokenadd token".as_slice(); + let one = br"notifytokenadd token|token=sample".as_slice(); + let other = br"notifytokenadd token=different".as_slice(); + assert_eq!(result(&[empty]).unwrap_err().detail, Some(json!({"created":true}))); + assert_eq!(result(&[one, empty, one]).unwrap(), json!({"token":"sample"})); + for error in [result(&[one,other,one]), result(&[br"notifytokenadd token=sample|token=different"])] { + let error = error.unwrap_err(); + assert_eq!(error.code, ErrorCode::ServerError); + assert_eq!(error.detail, Some(json!({"created":true}))); + assert!(!error.message.contains("sample") && !error.message.contains("different")); + } } } diff --git a/docs/bridge.md b/docs/bridge.md index d32856a..f0076bb 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -688,7 +688,7 @@ Pass `-- --client-info` to read the guest's client version and platform and veri | `ban_add` | `{generation,ip?,name?,uid?,duration_s,reason?}`; at least one target; 0 seconds permanent | | `ban_delete` / `ban_delete_all` | `{generation,ban_id,confirm}` / `{generation,confirm}`; confirm decimal ID / `all_bans` | | `privilege_key_list` | `{}` | -| `privilege_key_add` | `{generation,kind:"server_group"|"channel_group",group_id,channel_id?,description?}`; channel ID iff channel group; → `{token}` | +| `privilege_key_add` | `{generation,kind:"server_group"|"channel_group",group_id,channel_id?,description?}`; channel ID iff channel group. Returns `{token}` only for one distinct usable key. Repeated reports of that key are accepted; missing or conflicting keys after acknowledgement give an error with `created: true`. Reload the list before taking further action. | | `privilege_key_use` / `privilege_key_delete` | `{generation,token}` / `{generation,token,confirm}`; confirm exact token | | `temp_password_list` | `{}` | | `temp_password_add` | `{generation,password,description?,duration_s,channel_id?,channel_password?}`; positive duration | diff --git a/docs/mobile-port-progress.md b/docs/mobile-port-progress.md index 370a7da..8f039d5 100644 --- a/docs/mobile-port-progress.md +++ b/docs/mobile-port-progress.md @@ -4,6 +4,8 @@ ## Возврат к разработке на ПК, 2026-11-26 +Windows, база `533b2b2`: ядро обрабатывает все строки `notifytokenadd` до подтверждения. Пустая строка не затирает полученный ключ, повтор одного значения допустим, два разных значения не выдаются как успешный результат. Три адресных теста ядра прошли с тестовыми значениями. Живая выдача ключей и проверка формы остаются открытыми. + Windows, база `509bbb8`: тест `participant_info_menu_rejects_a_previous_session_target` прошёл через меню Slint на loopback beta14. В двух последовательных сессиях показаны версия и платформа своего участника; при отключении старые сведения очищены. После подключения второй identity действие из первой сессии получило видимую ошибку `target_changed`. Стенд остановлен. Разрыв соединения до прихода ответа в этом тесте не моделировался. Windows, база `c849105`: `client_info` сверяет номер и UID участника до отправки и при подтверждении. На beta14 `channel_admin_qa --client-info` получил версию и платформу; подстановка другого UID отклонена локально. Три теста ядра и один тест нативного клиента прошли. Стенд остановлен; повторное использование номера при ожидании ответа проверено тестом ядра, а не живым переподключением.