Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pkgs/id/src/world/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ pub(crate) enum WorldCommand {
Input {
token: JoinCapability,
input: Vec<u8>,
session_id: Option<SessionId>,
/// The player-signed move event bytes for this input (#2814), when
/// the participant plays signed. `None` is the unsigned path,
/// which refuses participants with a bound author key.
Expand Down Expand Up @@ -325,6 +326,9 @@ pub(crate) struct WorldActor {
/// The participant whose input is being processed. Requests the program
/// makes in response are checked against that participant's scopes.
pub(crate) acting: Option<u64>,
/// The connection whose input is being processed. Ephemeral actor context;
/// it is deliberately absent from `WorldEvent` and the journal.
pub(crate) acting_session: Option<SessionId>,
}

impl WorldActor {
Expand Down Expand Up @@ -363,6 +367,7 @@ impl WorldActor {
self.metrics.record_command(started.elapsed());
self.after_change().await;
self.acting = None;
self.acting_session = None;
}
}

Expand Down Expand Up @@ -1295,6 +1300,7 @@ impl WorldActor {
WorldCommand::Input {
token,
input,
session_id,
signed_move,
reply,
} => {
Expand All @@ -1320,6 +1326,7 @@ impl WorldActor {
)),
Ok((candidate, signed)) if self.program_healthy => {
self.acting = Some(candidate.participant_id);
self.acting_session = session_id;
match self
.program
.update(&candidate)
Expand Down Expand Up @@ -2070,6 +2077,7 @@ impl WorldActor {
ticks: BTreeMap::new(),
overdue_at_open,
acting: None,
acting_session: None,
auth: crate::directory_auth::DirectoryAuth::default(),
metrics: WorldMetrics::default(),
}
Expand Down
23 changes: 23 additions & 0 deletions pkgs/id/src/world/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ impl WorldHandle {
ticks: BTreeMap::new(),
overdue_at_open,
acting: None,
acting_session: None,
auth: crate::directory_auth::DirectoryAuth::default(),
};
tokio::spawn(actor.run(receiver));
Expand Down Expand Up @@ -682,11 +683,32 @@ impl WorldHandle {

/// Submit bounded opaque game input.
pub async fn input(&self, token: JoinCapability, input: Vec<u8>) -> Result<WorldEvent> {
self.input_with_session(token, input, None).await
}

/// Submit bounded opaque game input from a live session connection.
pub(crate) async fn input_from_session(
&self,
token: JoinCapability,
input: Vec<u8>,
session_id: SessionId,
) -> Result<WorldEvent> {
self.input_with_session(token, input, Some(session_id))
.await
}

async fn input_with_session(
&self,
token: JoinCapability,
input: Vec<u8>,
session_id: Option<SessionId>,
) -> Result<WorldEvent> {
let (reply, response) = oneshot::channel();
self.commands
.send(WorldCommand::Input {
token,
input,
session_id,
signed_move: None,
reply,
})
Expand Down Expand Up @@ -732,6 +754,7 @@ impl WorldHandle {
.send(WorldCommand::Input {
token,
input,
session_id: None,
signed_move: Some(signed_move),
reply,
})
Expand Down
11 changes: 11 additions & 0 deletions pkgs/id/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,17 @@ pub(crate) use util::{
sanitize_display_name, token_digest,
};

/// Identity of one live connection. It stays in memory only and is never part
/// of a world event or journal entry.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub(crate) struct SessionId(u64);

impl SessionId {
pub(crate) const fn new(value: u64) -> Self {
Self(value)
}
}

/// A chat participant may send at most this many lines during the rolling window.
pub(crate) const CHAT_RATE_BURST: u8 = 50;
pub(crate) const CHAT_RATE_WINDOW: std::time::Duration = std::time::Duration::from_secs(10);
Expand Down
52 changes: 52 additions & 0 deletions pkgs/id/src/world/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5481,6 +5481,7 @@ mod schedule_tests {
.handle(WorldCommand::Input {
token: token.clone(),
input: document.to_string().into_bytes(),
session_id: None,
signed_move: None,
reply,
})
Expand All @@ -5490,6 +5491,57 @@ mod schedule_tests {
let _ = response.await.unwrap().unwrap();
}

#[tokio::test]
async fn input_session_attribution_is_ephemeral_and_distinguishes_connections() {
let (mut actor, _, token, journal) = scheduling_actor("sessions", &[], false);
const SESSION_A: u64 = 0x5eed_cafe_0000_0001;
const SESSION_B: u64 = 0x5eed_cafe_0000_0002;
let session_ids = [SessionId::new(SESSION_A), SessionId::new(SESSION_B)];
let mut participant = None;

for session_id in session_ids {
let (reply, response) = tokio::sync::oneshot::channel();
actor
.handle(WorldCommand::Input {
token: token.clone(),
input: b"{}".to_vec(),
session_id: Some(session_id),
signed_move: None,
reply,
})
.await;

let acting = actor
.acting
.expect("input participant is set while processing");
if let Some(first) = participant {
assert_eq!(acting, first);
} else {
participant = Some(acting);
}
assert!(actor.acting_session == Some(session_id));
response.await.unwrap().unwrap();
actor.after_change().await;
actor.acting = None;
actor.acting_session = None;
}

let committed: Vec<_> = journal
.entries()
.into_iter()
.filter(|entry| matches!(entry, JournalEntry::Committed { .. }))
.collect();
assert_eq!(committed.len(), 2);
for entry in committed {
let value = serde_json::to_value(entry).unwrap();
assert_eq!(value.as_object().unwrap().len(), 2);
assert!(value.get("session_id").is_none());
let serialized = value.to_string();
assert!(!serialized.contains(&SESSION_A.to_string()));
assert!(!serialized.contains(&SESSION_B.to_string()));
}
}

/// The records the program last published.
fn records(actor: &WorldActor) -> Arc<Records> {
actor.records_sender.borrow().1.clone()
Expand Down
24 changes: 20 additions & 4 deletions pkgs/id/src/world_session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
//! is (an Iroh node ID); that never grants world authority.

use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;

use anyhow::Context as _;
Expand All @@ -30,8 +31,8 @@ use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock, Semaphore, broadcast};
use crate::directory_auth::Signed;
use crate::time::unix_ms;
use crate::world::{
Authority, CapabilityBounds, FileScope, Isolation, JoinCapability, Participant, WorldHandle,
WorldMetrics, WorldPolicy, WorldScopes,
Authority, CapabilityBounds, FileScope, Isolation, JoinCapability, Participant, SessionId,
WorldHandle, WorldMetrics, WorldPolicy, WorldScopes,
};
use crate::world_compile::Compiler;
#[cfg(feature = "sandbox")]
Expand Down Expand Up @@ -64,6 +65,11 @@ pub use types::{
};

impl WorldService {
/// Allocate an ephemeral identity for one accepted connection.
pub(crate) fn next_session_id(&self) -> SessionId {
SessionId::new(self.next_session_id.fetch_add(1, Ordering::Relaxed))
}

/// Require module artifacts to carry a valid signature from one of these
/// Ed25519 public keys. An empty list preserves the legacy unsigned path.
#[must_use]
Expand Down Expand Up @@ -193,6 +199,7 @@ impl WorldService {
mail: None,
outbox: None,
profile_operation: Arc::new(Mutex::new(())),
next_session_id: Arc::new(std::sync::atomic::AtomicU64::new(1)),
}
}

Expand Down Expand Up @@ -2109,6 +2116,7 @@ async fn joined<I: SessionIo>(
screen_patches: bool,
) {
let world = service.world();
let session_id = service.next_session_id();
// Subscribe before taking the snapshot so no event can fall in the gap;
// events at or below the cursor are skipped when delivered.
let mut events = world.subscribe();
Expand Down Expand Up @@ -2230,6 +2238,7 @@ async fn joined<I: SessionIo>(
&text,
&mut viewport,
cursor,
session_id,
&mut view_state,
screen_patches,
&mut pending_view_deadline,
Expand Down Expand Up @@ -2501,6 +2510,7 @@ async fn handle_client_frame<I: SessionIo>(
text: &str,
viewport: &mut Option<Viewport>,
sequence: u64,
session_id: SessionId,
view_state: &mut ViewRevisionState,
screen_patches: bool,
pending_view_deadline: &mut Option<tokio::time::Instant>,
Expand Down Expand Up @@ -2591,10 +2601,16 @@ async fn handle_client_frame<I: SessionIo>(
)
.await;
};
world.input(token.clone(), bytes).await
world
.input_from_session(token.clone(), bytes, session_id)
.await
}
ClientFrame::Input { data_hex } => match decode_hex(&data_hex) {
Some(data) => world.input(token.clone(), data).await,
Some(data) => {
world
.input_from_session(token.clone(), data, session_id)
.await
}
None => {
return send_error(service.frame_meter(), io, "input data must be hexadecimal")
.await;
Expand Down
8 changes: 8 additions & 0 deletions pkgs/id/src/world_session/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,14 @@ mod tests {
assert_eq!(records["sequence"], 1);
}

#[tokio::test]
async fn cloned_service_allocates_distinct_ids_for_connections() {
let service = service(None);
let another_connection = service.clone();

assert!(service.next_session_id() != another_connection.next_session_id());
}

#[tokio::test]
async fn execution_profile_change_is_admin_only_and_does_not_replace_live_program() {
struct MarkerProgram;
Expand Down
7 changes: 5 additions & 2 deletions pkgs/id/src/world_session/types.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::time::Duration;

use iroh_blobs::api::{Store, TempTag};
Expand All @@ -8,8 +9,8 @@ use tokio::sync::{Mutex, RwLock, Semaphore};

use crate::directory_auth::Signed;
use crate::world::{
CapabilityBounds, FileScope, Isolation, MetricsSnapshot, WorldEvent, WorldHandle, WorldMetrics,
WorldPolicy, WorldSnapshot,
CapabilityBounds, FileScope, Isolation, MetricsSnapshot, SessionId, WorldEvent, WorldHandle,
WorldMetrics, WorldPolicy, WorldSnapshot,
};
use crate::world_compile::Compiler;
use crate::world_hub::WorldInfo;
Expand Down Expand Up @@ -546,6 +547,8 @@ pub struct WorldService {
/// The world's host metrics registry (F11.7), shared with the actor:
/// the session layer records the frame bytes it sends into it.
pub(crate) metrics: WorldMetrics,
/// Monotonic, process-local IDs for live connections to this service.
pub(crate) next_session_id: Arc<AtomicU64>,
}

impl std::fmt::Debug for WorldService {
Expand Down
Loading