fix(net): reject stale session switches by generation

switch_slot_session released the slot lock while set_session_id ran and
then re-acquired it to write active_session_id, with no check that the
slot still belonged to the same activation. A deactivation or
re-activation in that window put the old session id onto the new
occupant's snapshot, and persist_session_identity then copied it into
that profile's sticky session.

Capture the generation alongside the client in the first critical
section and compare before writing. The write-back is extracted into
commit_session_id so the invariant can be tested directly rather than
raced.

Refs: F-17 (audit P2-1).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
这个提交存在于:
YokiiroBW 2026-07-27 00:12:32 +08:00
父节点 b2ecd1f3a4
当前提交 06312447aa

查看文件

@ -166,6 +166,22 @@ fn ensure_generation(runtime: &SlotRuntime, expected: u64) -> Result<(), Runtime
} }
} }
/// Publishes a session switch onto the generation that requested it.
///
/// The slot lock is released while `set_session_id` runs. Without this check a
/// deactivation or re-activation in that window would have the old session id
/// written onto the new occupant's snapshot, and `persist_session_identity`
/// would then copy it into that profile's sticky session.
fn commit_session_id(
runtime: &mut SlotRuntime,
expected: u64,
session_id: String,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
ensure_generation(runtime, expected)?;
runtime.snapshot.active_session_id = Some(session_id);
Ok(runtime.snapshot.clone())
}
impl DualSlotRuntime { impl DualSlotRuntime {
pub fn new() -> Self { pub fn new() -> Self {
let (event_tx, event_rx) = mpsc::channel(256); let (event_tx, event_rx) = mpsc::channel(256);
@ -530,9 +546,10 @@ impl DualSlotRuntime {
if session_id.trim().is_empty() { if session_id.trim().is_empty() {
return Err(RuntimeCommandError::validation("session_id is required.")); return Err(RuntimeCommandError::validation("session_id is required."));
} }
let client = { let (client, generation) = {
let guard = self.inner.lock().await; let guard = self.inner.lock().await;
match slot_ref(&guard, slot).client.as_ref() { let runtime = slot_ref(&guard, slot);
let client = match runtime.client.as_ref() {
Some(ActiveClient::AstrBot(client)) => client.clone(), Some(ActiveClient::AstrBot(client)) => client.clone(),
Some(ActiveClient::Desktop(_)) => { Some(ActiveClient::Desktop(_)) => {
return Err(RuntimeCommandError::validation( return Err(RuntimeCommandError::validation(
@ -544,16 +561,15 @@ impl DualSlotRuntime {
"Activate the connection before switching sessions.", "Activate the connection before switching sessions.",
)); ));
} }
} };
(client, runtime.generation)
}; };
client client
.set_session_id(session_id.clone()) .set_session_id(session_id.clone())
.await .await
.map_err(|_| RuntimeCommandError::validation("The session id is invalid."))?; .map_err(|_| RuntimeCommandError::validation("The session id is invalid."))?;
let mut guard = self.inner.lock().await; let mut guard = self.inner.lock().await;
let runtime = slot_mut(&mut guard, slot); commit_session_id(slot_mut(&mut guard, slot), generation, session_id)
runtime.snapshot.active_session_id = Some(session_id);
Ok(runtime.snapshot.clone())
} }
pub async fn slot_capabilities( pub async fn slot_capabilities(
@ -985,6 +1001,31 @@ mod tests {
assert!(companion.profile_id.is_none()); assert!(companion.profile_id.is_none());
} }
#[test]
fn a_stale_session_switch_does_not_write_into_a_new_generation() {
let mut runtime = SlotRuntime::empty_with_generation(SlotKind::Companion, 7);
let error = commit_session_id(&mut runtime, 6, "session-old".into())
.expect_err("a switch from a superseded generation must be rejected");
assert_eq!(error.code, "cancelled");
assert!(runtime.snapshot.active_session_id.is_none());
}
#[test]
fn a_current_session_switch_updates_the_snapshot() {
let mut runtime = SlotRuntime::empty_with_generation(SlotKind::Companion, 7);
let snapshot = commit_session_id(&mut runtime, 7, "session-new".into())
.expect("a switch from the current generation should be published");
assert_eq!(snapshot.active_session_id.as_deref(), Some("session-new"));
assert_eq!(
runtime.snapshot.active_session_id.as_deref(),
Some("session-new")
);
}
#[tokio::test] #[tokio::test]
async fn rejects_astrbot_activation_without_username_or_key() { async fn rejects_astrbot_activation_without_username_or_key() {
let runtime = DualSlotRuntime::new(); let runtime = DualSlotRuntime::new();