From 51a5ba3da7125c8a3498652259cbe912b49188b0 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 5 Nov 2026 08:46:53 -0500 Subject: [PATCH 1/2] bound Community room sessions to the person's session --- .../src/api/gateway_home_shared_content.rs | 11 +- .../src/api/gateway_home_token.rs | 137 +++++- .../src/api/gateway_passkey_step_up.rs | 50 +- .../elastos-server/src/api/gateway_room.rs | 87 +++- .../src/api/gateway_tests/room.rs | 156 +++++++ .../crates/elastos-server/src/room_service.rs | 442 ++++++++++++++++-- 6 files changed, 817 insertions(+), 66 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_shared_content.rs b/elastos/crates/elastos-server/src/api/gateway_home_shared_content.rs index b6ceddbe1..ec1d4c802 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_shared_content.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_shared_content.rs @@ -438,6 +438,15 @@ pub(super) async fn home_shared_content_check( return reply("not_contact", extra); }; let now = now_ts(); + let expires_at = match gateway_home_token::grant_bound_token_expiry( + &state.data_dir, + &home, + now, + SHARED_CONTENT_CHECK_TTL_SECS, + ) { + Ok(expires_at) => expires_at, + Err(err) => return (StatusCode::FORBIDDEN, err.to_string()).into_response(), + }; let online = match state.collaboration_presence_product_port.as_ref() { Some(port) => port .authorized_snapshot(now) @@ -456,7 +465,7 @@ pub(super) async fn home_shared_content_check( cid: cid.clone(), peer_did, message: source, - expires_at: now + SHARED_CONTENT_CHECK_TTL_SECS, + expires_at, }, now, )); diff --git a/elastos/crates/elastos-server/src/api/gateway_home_token.rs b/elastos/crates/elastos-server/src/api/gateway_home_token.rs index 65e3f39ce..9d1c1c01a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_token.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_token.rs @@ -90,6 +90,7 @@ pub(in crate::api) struct RequiredHomeLaunchToken { pub(in crate::api) launch_id: String, pub(in crate::api) launch_context: HomeLaunchContext, pub(in crate::api) context: HomeLaunchTokenContext, + pub(in crate::api) expires_at: u64, } /// Runtime-owned Wallet authority produced only after launch-token validation. @@ -244,15 +245,18 @@ pub(crate) fn issue_home_launch_token_for_auth_grant( if !grant.apps.iter().any(|allowed| allowed == app) { anyhow::bail!("auth session grant is not authorized for app"); } - issue_home_launch_token_with_context( + // Recovery prepares tokens before it atomically commits the new grant. + issue_home_launch_token_at( data_dir, - app, + &HomeLaunchContext::direct(app), &HomeLaunchTokenContext { principal_id: grant.principal_id.clone(), session_id: grant.session_id.clone(), proof_binding_id: Some(grant.proof_binding_id.clone()), grant_id: grant.grant_id.clone(), }, + now_ts(), + Some(grant.expires_at), ) } @@ -261,7 +265,13 @@ pub(in crate::api) fn issue_home_launch_token_with_context( app: &str, context: &HomeLaunchTokenContext, ) -> anyhow::Result { - issue_home_launch_token_at(data_dir, &HomeLaunchContext::direct(app), context, now_ts()) + issue_home_launch_token_at( + data_dir, + &HomeLaunchContext::direct(app), + context, + now_ts(), + None, + ) } pub(in crate::api) fn issue_home_projection_launch_token_with_context( @@ -275,6 +285,7 @@ pub(in crate::api) fn issue_home_projection_launch_token_with_context( &HomeLaunchContext::projection(selected_resource, executable_actor), context, now_ts(), + None, ) } @@ -283,6 +294,7 @@ fn issue_home_launch_token_at( launch_context: &HomeLaunchContext, context: &HomeLaunchTokenContext, issued_at: u64, + grant_expires_at: Option, ) -> anyhow::Result { launch_context.validate()?; if context.principal_id.trim().is_empty() @@ -291,6 +303,12 @@ fn issue_home_launch_token_at( { anyhow::bail!("home launch token is missing authority context"); } + let expires_at = match grant_expires_at { + Some(expiry) => issued_at + .saturating_add(HOME_LAUNCH_TOKEN_TTL_SECS) + .min(expiry), + None => grant_bound_token_expiry(data_dir, context, issued_at, HOME_LAUNCH_TOKEN_TTL_SECS)?, + }; let (signing_key, _did) = elastos_identity::load_or_create_did(data_dir)?; let envelope = HomeLaunchTokenEnvelope { payload: HomeLaunchTokenPayload { @@ -298,7 +316,7 @@ fn issue_home_launch_token_at( launch_id: format!("launch:{}", uuid_like_token()), launch_context: launch_context.clone(), iat: issued_at, - exp: issued_at.saturating_add(HOME_LAUNCH_TOKEN_TTL_SECS), + exp: expires_at, principal_id: context.principal_id.clone(), session_id: context.session_id.clone(), proof_binding_id: context.proof_binding_id.clone(), @@ -322,6 +340,31 @@ fn issue_home_launch_token_at( Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_vec(&envelope)?)) } +pub(super) fn grant_bound_token_expiry( + data_dir: &std::path::Path, + context: &HomeLaunchTokenContext, + issued_at: u64, + ttl_secs: u64, +) -> anyhow::Result { + let expires_at = issued_at.saturating_add(ttl_secs); + let Some(proof_binding_id) = context.proof_binding_id.as_deref() else { + return Ok(expires_at); + }; + let grant = crate::auth::load_active_session_grant( + &home_launch_auth_data_dir(data_dir), + &context.session_id, + now_ts(), + ) + .map_err(|_| anyhow::anyhow!("home launch token auth session is not active"))?; + if grant.principal_id != context.principal_id + || grant.proof_binding_id != proof_binding_id + || grant.grant_id != context.grant_id + { + anyhow::bail!("home launch token authority context mismatch"); + } + Ok(expires_at.min(grant.expires_at)) +} + #[cfg(test)] pub(crate) fn issue_expired_home_launch_token_with_context( data_dir: &std::path::Path, @@ -333,6 +376,7 @@ pub(crate) fn issue_expired_home_launch_token_with_context( &HomeLaunchContext::direct(app), context, now_ts().saturating_sub(HOME_LAUNCH_TOKEN_TTL_SECS + 1), + None, ) } @@ -349,6 +393,14 @@ pub(crate) fn require_home_launch_token_context( headers: &HeaderMap, expected_app: &str, ) -> anyhow::Result { + require_home_launch_grant(data_dir, headers, expected_app).map(|required| required.context) +} + +pub(super) fn require_home_launch_grant( + data_dir: &std::path::Path, + headers: &HeaderMap, + expected_app: &str, +) -> anyhow::Result { require_home_launch_token_for_any_from_with_origin( data_dir, headers, @@ -356,7 +408,6 @@ pub(crate) fn require_home_launch_token_context( None, HomeLaunchOriginPolicy::Browser, ) - .map(|required| required.context) } pub(crate) fn require_home_launch_token_for_any_context( @@ -754,6 +805,7 @@ fn require_home_launch_token_value_from_expected_did( } } Ok(RequiredHomeLaunchToken { + expires_at: envelope.payload.exp, launch_id: envelope.payload.launch_id, launch_context: envelope.payload.launch_context, context: HomeLaunchTokenContext { @@ -1018,6 +1070,21 @@ mod tests { .encode(serde_json::to_vec(&envelope).unwrap()) } + fn sign_context_for_test( + data_dir: &std::path::Path, + launch_context: HomeLaunchContext, + context: &HomeLaunchTokenContext, + ) -> String { + let token = issue_home_launch_token(data_dir, &launch_context.executable_actor).unwrap(); + let mut envelope = decode_launch_token(&token); + envelope.payload.launch_context = launch_context; + envelope.payload.principal_id = context.principal_id.clone(); + envelope.payload.session_id = context.session_id.clone(); + envelope.payload.proof_binding_id = context.proof_binding_id.clone(); + envelope.payload.grant_id = context.grant_id.clone(); + sign_launch_token_for_test(data_dir, envelope, HOME_LAUNCH_TOKEN_DOMAIN) + } + #[test] fn home_sessions_are_isolated_between_localhost_ports() { let first = tempfile::tempdir().unwrap(); @@ -1300,6 +1367,41 @@ mod tests { .contains("authority context mismatch")); } + #[test] + fn proof_bound_tokens_end_with_the_grant() { + let data = tempfile::tempdir().unwrap(); + let now = now_ts(); + let grant = elastos_runtime::auth::AuthSessionGrantV1 { + schema: elastos_runtime::auth::AuthSessionGrantV1::SCHEMA.to_string(), + grant_id: "grant:expiry".into(), + session_id: "auth:expiry".into(), + principal_id: "person:local:expiry".into(), + proof_binding_id: "proof:expiry".into(), + issued_at: now, + expires_at: now + 300, + apps: vec![HOME_CAPSULE_ID.into()], + }; + let context = HomeLaunchTokenContext { + principal_id: grant.principal_id.clone(), + session_id: grant.session_id.clone(), + proof_binding_id: Some(grant.proof_binding_id.clone()), + grant_id: grant.grant_id.clone(), + }; + let direct = + issue_home_launch_token_for_auth_grant(data.path(), HOME_CAPSULE_ID, &grant).unwrap(); + crate::auth::store_session_grant(data.path(), grant.clone()).unwrap(); + let projection = issue_home_projection_launch_token_with_context( + data.path(), + "chat-room", + "chat-room", + &context, + ) + .unwrap(); + for token in [direct, projection] { + assert_eq!(decode_launch_token(&token).payload.exp, grant.expires_at); + } + } + #[test] fn launch_token_rejects_expiry_stale_schema_and_mixed_shape() { let data_dir = tempfile::tempdir().unwrap(); @@ -1451,9 +1553,17 @@ mod tests { principal_id: "person:local:bob".to_string(), ..stored.clone() }; - let token = - issue_home_launch_token_with_context(data_dir.path(), SYSTEM_CAPSULE_ID, &substituted) - .unwrap(); + assert!(issue_home_launch_token_with_context( + data_dir.path(), + SYSTEM_CAPSULE_ID, + &substituted + ) + .is_err()); + let token = sign_context_for_test( + data_dir.path(), + HomeLaunchContext::direct(SYSTEM_CAPSULE_ID), + &substituted, + ); assert!(require_home_launch_token_context( data_dir.path(), &capsule_headers(&token), @@ -1477,12 +1587,17 @@ mod tests { ..stored.clone() }, ] { - let token = issue_home_launch_token_with_context( + assert!(issue_home_launch_token_with_context( data_dir.path(), SYSTEM_CAPSULE_ID, - &substituted, + &substituted ) - .unwrap(); + .is_err()); + let token = sign_context_for_test( + data_dir.path(), + HomeLaunchContext::direct(SYSTEM_CAPSULE_ID), + &substituted, + ); let error = require_home_launch_token_context( data_dir.path(), &capsule_headers(&token), diff --git a/elastos/crates/elastos-server/src/api/gateway_passkey_step_up.rs b/elastos/crates/elastos-server/src/api/gateway_passkey_step_up.rs index e206044bd..c44cd7b8c 100644 --- a/elastos/crates/elastos-server/src/api/gateway_passkey_step_up.rs +++ b/elastos/crates/elastos-server/src/api/gateway_passkey_step_up.rs @@ -165,6 +165,7 @@ pub(in crate::api) struct PasskeyStepUpEffectIdentity { struct IssuedPasskeyStepUp { token: String, step_up_id: String, + expires_at: u64, } pub(super) async fn passkey_step_up_begin( @@ -709,7 +710,17 @@ fn issue_step_up_token( operation: pending.operation.clone(), request_sha256: pending.request_sha256.clone(), iat: issued_at, - exp: issued_at.saturating_add(PASSKEY_STEP_UP_TTL_SECS), + exp: gateway_home_token::grant_bound_token_expiry( + data_dir, + &HomeLaunchTokenContext { + principal_id: pending.principal_id.clone(), + session_id: pending.session_id.clone(), + proof_binding_id: Some(pending.proof_binding_id.clone()), + grant_id: pending.grant_id.clone(), + }, + issued_at, + PASSKEY_STEP_UP_TTL_SECS, + )?, non_delegatable: true, }; payload.validate(issued_at, PASSKEY_STEP_UP_TTL_SECS)?; @@ -726,6 +737,7 @@ fn issue_step_up_token( signer_did, }; Ok(IssuedPasskeyStepUp { + expires_at: envelope.payload.exp, token: URL_SAFE_NO_PAD.encode(serde_json::to_vec(&envelope)?), step_up_id, }) @@ -741,7 +753,7 @@ fn complete_step_up( Ok(PasskeyStepUpCompleteResponse { schema: PASSKEY_STEP_UP_COMPLETE_RESULT_SCHEMA.to_string(), step_up_token: issued.token, - expires_at: completed_at.saturating_add(PASSKEY_STEP_UP_TTL_SECS), + expires_at: issued.expires_at, }) } @@ -1543,6 +1555,27 @@ mod tests { } } + #[test] + fn proof_bound_step_up_ends_with_the_grant() { + let fixture = fixture(); + let now = now_ts(); + let mut grant = crate::auth::load_active_session_grant( + fixture.data_dir.path(), + &fixture.context.session_id, + now, + ) + .unwrap(); + grant.expires_at = now + 30; + crate::auth::store_session_grant(fixture.data_dir.path(), grant.clone()).unwrap(); + let pending = pending_for(&fixture, "ceremony:expiry".into(), now); + let completed = complete_step_up(fixture.data_dir.path(), &pending, now).unwrap(); + let envelope: PasskeyStepUpEnvelope = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(completed.step_up_token).unwrap()) + .unwrap(); + assert_eq!(envelope.payload.exp, grant.expires_at); + assert_eq!(completed.expires_at, grant.expires_at); + } + fn consumed_for( fixture: &StepUpFixture, step_up_id: String, @@ -2332,14 +2365,25 @@ mod tests { format!("passkey:step-up:{}", gateway_home_token::uuid_like_token()), now, ); + let issued = issue_step_up_token(fixture.data_dir.path(), &pending, now).unwrap(); let auth_state = crate::auth::auth_state_path(fixture.data_dir.path()).unwrap(); std::fs::remove_file(&auth_state).unwrap(); std::fs::create_dir(&auth_state).unwrap(); - let error = complete_step_up(fixture.data_dir.path(), &pending, now).unwrap_err(); + let error = append_step_up_completion_audit( + fixture.data_dir.path(), + &pending, + &issued.step_up_id, + now, + ) + .unwrap_err(); assert!(error .to_string() .contains("failed to persist passkey step-up completion audit")); + assert!(complete_step_up(fixture.data_dir.path(), &pending, now) + .unwrap_err() + .to_string() + .contains("auth session is not active")); } #[test] diff --git a/elastos/crates/elastos-server/src/api/gateway_room.rs b/elastos/crates/elastos-server/src/api/gateway_room.rs index 91930f4c4..6ab29d0d2 100644 --- a/elastos/crates/elastos-server/src/api/gateway_room.rs +++ b/elastos/crates/elastos-server/src/api/gateway_room.rs @@ -764,11 +764,15 @@ pub(super) async fn chat_room_session_start( State(state): State, headers: HeaderMap, ) -> Response { - let context = - match require_home_launch_token_context(&state.data_dir, &headers, CHAT_ROOM_CAPSULE_ID) { - Ok(context) => context, - Err(err) => return room_service_error_response(err), - }; + let launch = match gateway_home_token::require_home_launch_grant( + &state.data_dir, + &headers, + CHAT_ROOM_CAPSULE_ID, + ) { + Ok(context) => context, + Err(err) => return room_service_error_response(err), + }; + let context = launch.context.clone(); // Chat asks once, on Community open; a refusal or an open card is kept. let _ = gateway_collaboration_presence::request_community_presence(&state, &context, false); let community_presence = @@ -784,9 +788,9 @@ pub(super) async fn chat_room_session_start( }; match tokio::task::spawn_blocking(move || -> anyhow::Result<_> { let output = if port.is_some() { - start_configured_chat_room_session(&data_dir, &context)? + start_configured_chat_room_session(&data_dir, &launch)? } else { - start_chat_room_session(&data_dir, &context)? + start_chat_room_session(&data_dir, &launch)? }; let configured = port.is_some(); let mut poll = match port { @@ -1287,8 +1291,9 @@ struct ChatRoomSessionGrant { fn start_chat_room_session( data_dir: &std::path::Path, - context: &HomeLaunchTokenContext, + launch: &RequiredHomeLaunchToken, ) -> anyhow::Result { + let context = &launch.context; let (did, handle) = trusted_local_chat_room_principal(data_dir, context)?; let session = crate::room_service::start_local_principal_runtime_session( data_dir, @@ -1296,14 +1301,16 @@ fn start_chat_room_session( &context.principal_id, &handle, "ElastOS shell", + &room_session_authorization(launch), )?; Ok(chat_room_session_grant(session)) } fn start_configured_chat_room_session( data_dir: &std::path::Path, - context: &HomeLaunchTokenContext, + launch: &RequiredHomeLaunchToken, ) -> anyhow::Result { + let context = &launch.context; let (did, handle) = trusted_configured_chat_profile(data_dir, context)?; let session = crate::room_service::start_configured_collaboration_principal_session( data_dir, @@ -1311,10 +1318,24 @@ fn start_configured_chat_room_session( &context.principal_id, &handle, "ElastOS shell", + &room_session_authorization(launch), )?; Ok(chat_room_session_grant(session)) } +fn room_session_authorization( + launch: &RequiredHomeLaunchToken, +) -> crate::room_service::RoomSessionAuthorization { + crate::room_service::RoomSessionAuthorization { + principal_id: launch.context.principal_id.clone(), + session_id: launch.context.session_id.clone(), + proof_binding_id: launch.context.proof_binding_id.clone(), + grant_id: launch.context.grant_id.clone(), + authority_actor: launch.launch_context.authority_actor.clone(), + expires_at: launch.expires_at, + } +} + fn trusted_local_chat_room_principal( data_dir: &std::path::Path, context: &HomeLaunchTokenContext, @@ -1874,11 +1895,16 @@ pub(super) async fn room_service_session_leave( let secure = request_uses_tls(&headers); let data_dir = state.data_dir.clone(); if state.collaboration_chat_product_port.is_some() { - let context = - match require_home_launch_token_context(&data_dir, &headers, CHAT_ROOM_CAPSULE_ID) { - Ok(context) => context, - Err(err) => return room_service_error_response(err), - }; + let launch = match gateway_home_token::require_home_launch_grant( + &data_dir, + &headers, + CHAT_ROOM_CAPSULE_ID, + ) { + Ok(context) => context, + Err(err) => return room_service_error_response(err), + }; + let context = launch.context.clone(); + let authorization = room_session_authorization(&launch); let (did, _) = match trusted_configured_chat_profile(&data_dir, &context) { Ok(principal) => principal, Err(err) => return room_service_error_response(err), @@ -1889,6 +1915,7 @@ pub(super) async fn room_service_session_leave( &data_dir, &did, &principal_id, + &authorization, ) }) .await; @@ -1959,7 +1986,7 @@ pub(super) async fn room_service_poll( let mut reader_profile = None; let token = match port.as_ref() { Some(_) => { - let context = match require_home_launch_token_context( + let launch = match gateway_home_token::require_home_launch_grant( &data_dir, &headers, CHAT_ROOM_CAPSULE_ID, @@ -1967,6 +1994,7 @@ pub(super) async fn room_service_poll( Ok(context) => context, Err(err) => return room_service_error_response(err), }; + let context = launch.context.clone(); launch_context = Some(context.clone()); let profile = match trusted_chat_room_profile_authority(&data_dir, &context) { Ok(profile) => profile, @@ -1979,6 +2007,7 @@ pub(super) async fn room_service_poll( &data_dir, &did, &context.principal_id, + &room_session_authorization(&launch), ) { Ok(session) => session, Err(err) => return room_service_error_response(err), @@ -2088,15 +2117,20 @@ pub(super) async fn room_service_objects_send( } let data_dir = state.data_dir.clone(); let port = state.collaboration_chat_product_port.clone(); - let context = match port.as_ref() { + let launch = match port.as_ref() { Some(_) => { - match require_home_launch_token_context(&data_dir, &headers, CHAT_ROOM_CAPSULE_ID) { + match gateway_home_token::require_home_launch_grant( + &data_dir, + &headers, + CHAT_ROOM_CAPSULE_ID, + ) { Ok(context) => Some(context), Err(err) => return room_service_error_response(err), } } None => None, }; + let context = launch.as_ref().map(|launch| launch.context.clone()); let profile = match context.as_ref() { Some(context) => { match gateway_home_system::load_profile_authority_for_context(&data_dir, context) { @@ -2111,8 +2145,8 @@ pub(super) async fn room_service_objects_send( } None => None, }; - let token = match context.as_ref() { - Some(context) => match start_configured_chat_room_session(&data_dir, context) { + let token = match launch.as_ref() { + Some(launch) => match start_configured_chat_room_session(&data_dir, launch) { Ok(session) => session.token, Err(err) => return room_service_error_response(err), }, @@ -2312,11 +2346,15 @@ pub(super) async fn chat_room_attach_library( attach_library_error_body("unsupported", "Files can be posted only in Community."), ); }; - let context = match require_home_launch_token_context(&data_dir, &headers, CHAT_ROOM_CAPSULE_ID) - { + let launch = match gateway_home_token::require_home_launch_grant( + &data_dir, + &headers, + CHAT_ROOM_CAPSULE_ID, + ) { Ok(context) => context, Err(err) => return attach_library_chat_error(err), }; + let context = launch.context.clone(); let profile = match gateway_home_system::load_profile_authority_for_context(&data_dir, &context) { Ok(Some(profile)) => profile, @@ -2325,7 +2363,7 @@ pub(super) async fn chat_room_attach_library( } Err(err) => return attach_library_chat_error(err), }; - let token = match start_configured_chat_room_session(&data_dir, &context) { + let token = match start_configured_chat_room_session(&data_dir, &launch) { Ok(session) => session.token, Err(err) => return attach_library_chat_error(err), }; @@ -2584,8 +2622,9 @@ fn chat_room_access_token_from_headers( headers: &HeaderMap, ) -> anyhow::Result { if headers.contains_key("x-elastos-home-token") { - let context = require_home_launch_token_context(data_dir, headers, CHAT_ROOM_CAPSULE_ID)?; - return Ok(start_chat_room_session(data_dir, &context)?.token); + let launch = + gateway_home_token::require_home_launch_grant(data_dir, headers, CHAT_ROOM_CAPSULE_ID)?; + return Ok(start_chat_room_session(data_dir, &launch)?.token); } room_session_token_from_headers(headers) } diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/room.rs b/elastos/crates/elastos-server/src/api/gateway_tests/room.rs index 5e4843d9b..9c2303dff 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/room.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/room.rs @@ -1,5 +1,161 @@ use super::*; +#[tokio::test] +async fn room_session_bound_to_frame_expiry() { + room_session_bound_fixture(300, "active", false).await; +} + +#[tokio::test] +async fn room_session_bound_preserves_twelve_hours() { + room_session_bound_fixture(12 * 60 * 60, "active", false).await; +} + +#[tokio::test] +async fn room_session_bound_rejects_revoked_grant_on_poll() { + room_session_bound_fixture(300, "revoked", false).await; +} + +#[tokio::test] +async fn room_session_bound_rejects_sign_out_on_poll() { + room_session_bound_fixture(300, "signed-out", false).await; +} + +#[tokio::test] +async fn room_session_bound_rejects_expired_grant_on_poll() { + room_session_bound_fixture(300, "expired", false).await; +} + +#[tokio::test] +async fn room_session_bound_configured_community() { + for outcome in ["active", "revoked", "signed-out", "expired"] { + room_session_bound_fixture(300, outcome, true).await; + } + room_session_bound_fixture(12 * 60 * 60, "active", true).await; +} + +async fn room_session_bound_fixture(frame_lifetime: u64, outcome: &str, configured: bool) { + use base64::Engine as _; + let dir = tempfile::tempdir().unwrap(); + let authority = passkey_authority_with_profile(dir.path(), "owner"); + let context = HomeLaunchTokenContext { + principal_id: authority.principal_id.clone(), + session_id: authority.session_id.clone(), + proof_binding_id: Some(authority.proof_binding_id.clone()), + grant_id: authority.grant_id.clone(), + }; + let mut grant = crate::auth::load_active_session_grant( + dir.path(), + &authority.session_id, + crate::auth::now_ts(), + ) + .unwrap(); + grant.expires_at = crate::auth::now_ts() + 24 * 60 * 60; + crate::auth::renew_session_grant(dir.path(), grant).unwrap(); + let token = issue_home_projection_launch_token_with_context( + dir.path(), + CHAT_ROOM_CAPSULE_ID, + CHAT_ROOM_CAPSULE_ID, + &context, + ) + .unwrap(); + let codec = base64::engine::general_purpose::URL_SAFE_NO_PAD; + let mut envelope: serde_json::Value = + serde_json::from_slice(&codec.decode(token).unwrap()).unwrap(); + let now = crate::auth::now_ts(); + let frame_expiry = envelope["payload"]["iat"].as_u64().unwrap() + frame_lifetime; + envelope["payload"]["exp"] = frame_expiry.into(); + let (key, _) = elastos_identity::load_or_create_did(dir.path()).unwrap(); + let (signature, signer_did) = crate::crypto::domain_separated_sign( + &key, + HOME_LAUNCH_TOKEN_DOMAIN, + serde_json::to_string(&envelope["payload"]) + .unwrap() + .as_bytes(), + ); + envelope["signature"] = signature.into(); + envelope["signer_did"] = signer_did.into(); + let token = codec.encode(serde_json::to_vec(&envelope).unwrap()); + let mut state = test_state(dir.path()); + if configured { + state.collaboration_chat_product_port = + Some(crate::collaboration_product::test_chat_product_port( + dir.path(), + "room-bound-network", + "room-bound-community", + )); + } + let app = gateway_router(state.clone()); + let start = app + .clone() + .oneshot( + test_browser_request("localhost:61180", "null") + .method("POST") + .uri("/api/apps/chat-room/session/start") + .header("x-elastos-home-token", token.as_str()) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(start.status(), StatusCode::OK); + let cookie = room_cookie_header(&start); + let body = axum::body::to_bytes(start.into_body(), usize::MAX) + .await + .unwrap(); + let payload: serde_json::Value = serde_json::from_slice(&body).unwrap(); + if outcome == "active" { + assert!(payload["expires_at"].as_u64().unwrap() <= frame_expiry); + assert!(payload["expires_at"].as_u64().unwrap() >= frame_expiry - 1); + } else if outcome == "signed-out" { + let response = app + .clone() + .oneshot( + test_browser_request("localhost:61180", "http://localhost:61180") + .method("POST") + .uri("/api/auth/sessions/sign-out") + .header("x-elastos-home-token", &authority.home_token) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + } else if outcome == "revoked" { + crate::auth::revoke_session_grant(dir.path(), &authority.session_id, now).unwrap(); + } else { + let mut grant = + crate::auth::load_active_session_grant(dir.path(), &authority.session_id, now).unwrap(); + grant.expires_at = now; + crate::auth::store_session_grant(dir.path(), grant).unwrap(); + } + // Use only the room cookie: frame validation cannot mask a room-session gap. + let mut headers = HeaderMap::new(); + headers.insert(COOKIE, cookie.parse().unwrap()); + if configured { + headers.insert(HOST, "localhost:61180".parse().unwrap()); + headers.insert("origin", "null".parse().unwrap()); + headers.insert("x-elastos-home-token", token.parse().unwrap()); + } + let poll = room_service_poll( + State(state), + headers, + Json(serde_json::from_value(json!({"since": 0})).unwrap()), + ) + .await; + if outcome == "active" { + assert_eq!(poll.status(), StatusCode::OK); + } else { + assert!( + matches!( + poll.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ), + "{}", + poll.status() + ); + } +} + mod contact_request; mod direct; diff --git a/elastos/crates/elastos-server/src/room_service.rs b/elastos/crates/elastos-server/src/room_service.rs index bf592fa55..e1ac7855f 100644 --- a/elastos/crates/elastos-server/src/room_service.rs +++ b/elastos/crates/elastos-server/src/room_service.rs @@ -790,6 +790,54 @@ struct SessionRecord { approved_at: u64, expires_at: u64, last_seen_at: u64, + #[serde(default)] + authorization: Option, +} + +/// Runtime authority retained for every use of a person's room session. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RoomSessionAuthorization { + pub principal_id: String, + pub session_id: String, + pub proof_binding_id: Option, + pub grant_id: String, + pub authority_actor: String, + pub expires_at: u64, +} + +impl RoomSessionAuthorization { + fn same_grant(&self, other: &Self) -> bool { + self.principal_id == other.principal_id + && self.session_id == other.session_id + && self.proof_binding_id == other.proof_binding_id + && self.grant_id == other.grant_id + && self.authority_actor == other.authority_actor + } + + fn validate(&self, data_dir: &Path, actor_id: &str) -> anyhow::Result { + let now = now_ts(); + if self.expires_at <= now || local_principal_room_actor_id(&self.principal_id)? != actor_id + { + anyhow::bail!("invalid or expired session authority"); + } + if let Some(proof) = self.proof_binding_id.as_deref() { + let grant = crate::auth::load_active_session_grant( + &crate::api::gateway::home_launch_auth_data_dir(data_dir), + &self.session_id, + now, + ) + .map_err(|_| anyhow::anyhow!("invalid or expired session authority"))?; + if grant.principal_id != self.principal_id + || grant.proof_binding_id != proof + || grant.grant_id != self.grant_id + || !grant.apps.iter().any(|app| app == &self.authority_actor) + { + anyhow::bail!("invalid or expired session authority"); + } + return Ok(self.expires_at.min(grant.expires_at)); + } + Ok(self.expires_at) + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -2049,7 +2097,14 @@ pub fn start_local_runtime_session_with_transport( display_name: &str, device_label: &str, ) -> anyhow::Result { - start_local_runtime_session_for_actor(data_dir, member_did, None, display_name, device_label) + start_local_runtime_session_for_actor( + data_dir, + member_did, + None, + display_name, + device_label, + None, + ) } pub fn start_local_principal_runtime_session( @@ -2058,14 +2113,17 @@ pub fn start_local_principal_runtime_session( principal_id: &str, display_name: &str, device_label: &str, + authorization: &RoomSessionAuthorization, ) -> anyhow::Result { let actor_id = local_principal_room_actor_id(principal_id)?; + authorization.validate(data_dir, &actor_id)?; Ok(start_local_runtime_session_for_actor( data_dir, member_did, Some(actor_id), display_name, device_label, + Some(authorization), )? .session) } @@ -2076,9 +2134,11 @@ pub(crate) fn start_configured_collaboration_principal_session( principal_id: &str, display_name: &str, device_label: &str, + authorization: &RoomSessionAuthorization, ) -> anyhow::Result { let member_did = normalize_member_did(member_did)?; let actor_id = local_principal_room_actor_id(principal_id)?; + let expires_at = authorization.validate(data_dir, &actor_id)?; let display_name = normalize_display_name(display_name)?; let device_label = normalize_device_label(device_label); @@ -2086,22 +2146,32 @@ pub(crate) fn start_configured_collaboration_principal_session( let now = now_ts(); state.sessions.retain(|session| { session.actor_id != actor_id - || session.member_did.as_deref() == Some(member_did.as_str()) + || (session.authorization.is_some() + && session.member_did.as_deref() == Some(member_did.as_str())) }); let canonical_token = state .sessions .iter() .filter(|session| { session.actor_id == actor_id + && session + .authorization + .as_ref() + .is_some_and(|saved| saved.same_grant(authorization)) && session.member_did.as_deref() == Some(member_did.as_str()) }) .max_by_key(|session| (session.last_seen_at, session.expires_at)) .map(|session| session.token.clone()); if let Some(token) = canonical_token { - state - .sessions - .retain(|session| session.actor_id != actor_id || session.token == token); + state.sessions.retain(|session| { + session.actor_id != actor_id + || !session + .authorization + .as_ref() + .is_some_and(|saved| saved.same_grant(authorization)) + || session.token == token + }); let session = state .sessions .iter_mut() @@ -2112,7 +2182,8 @@ pub(crate) fn start_configured_collaboration_principal_session( session.member_did = Some(member_did); session.capabilities = room_access_capabilities(); session.last_seen_at = now; - session.expires_at = now + SESSION_TTL_SECS; + session.expires_at = now.saturating_add(SESSION_TTL_SECS).min(expires_at); + session.authorization = Some(authorization.clone()); return Ok(LocalRuntimeSessionOutput { token: session.token.clone(), display_name: session.display_name.clone(), @@ -2122,7 +2193,7 @@ pub(crate) fn start_configured_collaboration_principal_session( } let capabilities = room_access_capabilities(); - let session = create_session_record_with_actor( + let mut session = create_session_record_with_actor( &display_name, &device_label, Some(member_did), @@ -2130,6 +2201,8 @@ pub(crate) fn start_configured_collaboration_principal_session( capabilities.clone(), now, ); + session.expires_at = session.expires_at.min(expires_at); + session.authorization = Some(authorization.clone()); let output = LocalRuntimeSessionOutput { token: session.token.clone(), display_name: session.display_name.clone(), @@ -2145,12 +2218,18 @@ pub(crate) fn resolve_configured_collaboration_principal_session( data_dir: &Path, member_did: &str, principal_id: &str, + authorization: &RoomSessionAuthorization, ) -> anyhow::Result { let member_did = normalize_member_did(member_did)?; let actor_id = local_principal_room_actor_id(principal_id)?; + authorization.validate(data_dir, &actor_id)?; with_read_state(data_dir, |state| { let mut matches = state.sessions.iter().filter(|session| { session.actor_id == actor_id + && session + .authorization + .as_ref() + .is_some_and(|saved| saved.same_grant(authorization)) && session.member_did.as_deref() == Some(member_did.as_str()) }); let session = matches @@ -2159,6 +2238,7 @@ pub(crate) fn resolve_configured_collaboration_principal_session( if matches.next().is_some() { anyhow::bail!("configured Chat session is ambiguous"); } + validate_session_authority(data_dir, session)?; if session.expires_at <= now_ts() || session.capabilities != room_access_capabilities() || session.token.len() != 64 @@ -2182,13 +2262,19 @@ pub(crate) fn leave_configured_collaboration_principal_session( data_dir: &Path, member_did: &str, principal_id: &str, + authorization: &RoomSessionAuthorization, ) -> anyhow::Result> { let member_did = normalize_member_did(member_did)?; let actor_id = local_principal_room_actor_id(principal_id)?; + authorization.validate(data_dir, &actor_id)?; with_locked_state(data_dir, |_, state| { let mut removed = None; state.sessions.retain(|session| { let matches = session.actor_id == actor_id + && session + .authorization + .as_ref() + .is_some_and(|saved| saved.same_grant(authorization)) && session.member_did.as_deref() == Some(member_did.as_str()); if matches && removed.is_none() { removed = Some(LocalRuntimeSessionOutput { @@ -2210,14 +2296,17 @@ pub fn start_local_principal_runtime_session_with_transport( principal_id: &str, display_name: &str, device_label: &str, + authorization: &RoomSessionAuthorization, ) -> anyhow::Result { let actor_id = local_principal_room_actor_id(principal_id)?; + authorization.validate(data_dir, &actor_id)?; start_local_runtime_session_for_actor( data_dir, member_did, Some(actor_id), display_name, device_label, + Some(authorization), ) } @@ -2227,7 +2316,14 @@ fn start_local_runtime_session_for_actor( actor_id: Option, display_name: &str, device_label: &str, + authorization: Option<&RoomSessionAuthorization>, ) -> anyhow::Result { + let expires_at = match authorization { + Some(authorization) => { + authorization.validate(data_dir, actor_id.as_deref().unwrap_or_default())? + } + None => u64::MAX, + }; let member_did = normalize_member_did(member_did)?; let display_name = normalize_display_name(display_name)?; let device_label = normalize_device_label(device_label); @@ -2268,7 +2364,14 @@ fn start_local_runtime_session_for_actor( .sessions .iter() .filter(|session| match actor_id.as_deref() { - Some(actor_id) => session.actor_id == actor_id, + Some(actor_id) => { + session.actor_id == actor_id + && session + .authorization + .as_ref() + .zip(authorization) + .is_some_and(|(saved, current)| saved.same_grant(current)) + } None => { session.member_did.as_deref() == Some(member_did.as_str()) || (session.member_did.is_none() && session.device_label == device_label) @@ -2285,7 +2388,15 @@ fn start_local_runtime_session_for_actor( if let Some(token) = canonical_local_token { state.sessions.retain(|session| match actor_id.as_deref() { - Some(actor_id) => session.actor_id != actor_id || session.token == token, + Some(actor_id) => { + session.actor_id != actor_id + || !session + .authorization + .as_ref() + .zip(authorization) + .is_some_and(|(saved, current)| saved.same_grant(current)) + || session.token == token + } None => { !(session.member_did.as_deref() == Some(member_did.as_str()) || (session.member_did.is_none() && session.device_label == device_label)) @@ -2305,7 +2416,8 @@ fn start_local_runtime_session_for_actor( existing.member_did = session_member_did.clone(); existing.capabilities = capabilities.clone(); existing.last_seen_at = now; - existing.expires_at = now + SESSION_TTL_SECS; + existing.expires_at = now.saturating_add(SESSION_TTL_SECS).min(expires_at); + existing.authorization = authorization.cloned(); return Ok(LocalRuntimeSessionWithTransportOutput { session: LocalRuntimeSessionOutput { token: existing.token.clone(), @@ -2325,7 +2437,7 @@ fn start_local_runtime_session_for_actor( (None, Some(did)) => active_local_session_count(state, did) > 0, _ => false, }; - let session = create_session_record_with_actor( + let mut session = create_session_record_with_actor( &display_name, &device_label, session_member_did.clone(), @@ -2333,6 +2445,8 @@ fn start_local_runtime_session_for_actor( capabilities.clone(), now, ); + session.expires_at = session.expires_at.min(expires_at); + session.authorization = authorization.cloned(); let output = LocalRuntimeSessionOutput { token: session.token.clone(), display_name: session.display_name.clone(), @@ -2488,6 +2602,7 @@ fn create_session_record_with_actor( approved_at: now, expires_at: now + SESSION_TTL_SECS, last_seen_at: now, + authorization: None, } } @@ -2713,7 +2828,7 @@ pub fn session_view(data_dir: &Path, token: &str) -> anyhow::Result with_locked_state(data_dir, |_, state| { let room_slug = state.room_slug.clone(); let (display_name, expires_at, capabilities, current_session) = { - let session = validate_session(state, token)?; + let session = validate_session(data_dir, state, token)?; ( session.display_name.clone(), session.expires_at, @@ -2748,6 +2863,7 @@ pub fn leave_session_with_transport( token: &str, ) -> anyhow::Result { with_locked_state(data_dir, |paths, state| { + validate_session(data_dir, state, token)?; let now = now_ts(); let session_index = state .sessions @@ -2796,7 +2912,7 @@ pub fn conversation_feed( ) -> anyhow::Result { with_locked_state(data_dir, |_, state| { let current_session = { - let session = validate_session(state, token)?; + let session = validate_session(data_dir, state, token)?; current_session_identity(session) }; let objects = state @@ -2818,7 +2934,7 @@ pub fn room_poll(data_dir: &Path, token: &str, since: u64) -> anyhow::Result { - let session = validate_session(state, token)?; + let session = validate_session(data_dir, state, token)?; if session.member_did.as_deref() != Some(sender_member_did.as_str()) { anyhow::bail!( "room session does not match the collaboration sender Profile DID" @@ -3165,7 +3281,7 @@ pub(crate) fn collaboration_room_poll( ) -> anyhow::Result { let scope = collaboration_object_scope(network_id, conversation_id)?; with_expired_read_state(data_dir, |state| { - collaboration_poll_from_state(state, token, &scope, since) + collaboration_poll_from_state(data_dir, state, token, &scope, since) }) } @@ -3250,7 +3366,7 @@ pub(crate) fn collaboration_room_poll_with_delivery( let result = (|| { let mut state = load_state(&paths)?; let _ = expire_state_in_place(&mut state); - let session = validate_session_for_read(&state, token)?; + let session = validate_session_for_read(data_dir, &state, token)?; if session.member_did.as_deref() != Some(reader.as_str()) { anyhow::bail!("Chat delivery reader does not match the room Profile"); } @@ -3305,19 +3421,20 @@ pub(crate) fn collaboration_room_poll_with_delivery( if changed { write_json_atomic(&paths.objects_path, &state.objects)?; } - collaboration_poll_from_state(&state, token, &scope, since) + collaboration_poll_from_state(data_dir, &state, token, &scope, since) })(); unlock_state_file(lock)?; result } fn collaboration_poll_from_state( + data_dir: &Path, state: &RoomState, token: &str, scope: &CollaborationObjectScope, since: u64, ) -> anyhow::Result { - let session = validate_session_for_read(state, token)?; + let session = validate_session_for_read(data_dir, state, token)?; let current_session = current_session_identity(session); let participants = participant_views_from_state(state, Some(¤t_session), Some(scope)); let scoped = state.objects.iter().filter(|item| { @@ -3477,7 +3594,7 @@ pub fn append_attachment_object_with_transport( with_locked_state(data_dir, |paths, state| { let (sender, sender_member_did, sender_actor_id, current_session) = { - let session = validate_session(state, token)?; + let session = validate_session(data_dir, state, token)?; session.last_seen_at = now_ts(); ( session.display_name.clone(), @@ -3526,10 +3643,11 @@ pub fn start_attachment_upload( } with_locked_state(data_dir, |paths, state| { - let session = validate_session(state, token)?; + let session = validate_session(data_dir, state, token)?; session.last_seen_at = now_ts(); let now = now_ts(); + let expires_at = now.saturating_add(UPLOAD_TTL_SECS).min(session.expires_at); let upload_id = random_hex(16); fs::create_dir_all(&paths.uploads_dir)?; fs::write(upload_staging_path(paths, &upload_id), [])?; @@ -3541,13 +3659,13 @@ pub fn start_attachment_upload( size_bytes, received_bytes: 0, created_at: now, - expires_at: now + UPLOAD_TTL_SECS, + expires_at, }); Ok(AttachmentUploadStartOutput { upload_id, chunk_size_bytes: ATTACHMENT_UPLOAD_CHUNK_BYTES, received_bytes: 0, - expires_at: now + UPLOAD_TTL_SECS, + expires_at, }) }) } @@ -3570,7 +3688,7 @@ pub fn append_attachment_upload_chunk( } with_locked_state(data_dir, |paths, state| { - let session = validate_session(state, token)?; + let session = validate_session(data_dir, state, token)?; session.last_seen_at = now_ts(); let upload = find_upload_mut(state, token, upload_id)?; @@ -3616,7 +3734,7 @@ pub fn finish_attachment_upload( ) -> anyhow::Result { let (output, staged_path) = with_locked_state(data_dir, |paths, state| { let (sender, sender_member_did, sender_actor_id, current_session) = { - let session = validate_session(state, token)?; + let session = validate_session(data_dir, state, token)?; session.last_seen_at = now_ts(); ( session.display_name.clone(), @@ -3676,7 +3794,7 @@ pub fn read_attachment( attachment_id: &str, ) -> anyhow::Result<(AttachmentView, Vec)> { let attachment = with_locked_state(data_dir, |_, state| { - let session = validate_session(state, token)?; + let session = validate_session(data_dir, state, token)?; session.last_seen_at = now_ts(); state .objects @@ -3691,7 +3809,23 @@ pub fn read_attachment( Ok((attachment, bytes)) } +fn validate_session_authority(data_dir: &Path, session: &SessionRecord) -> anyhow::Result<()> { + if session.expires_at <= now_ts() { + anyhow::bail!("invalid or expired session"); + } + match session.authorization.as_ref() { + Some(authorization) => authorization + .validate(data_dir, &session.actor_id) + .map(|_| ()), + None if session.actor_id.starts_with("principal:") => { + anyhow::bail!("invalid or expired session authority") + } + None => Ok(()), + } +} + fn validate_session<'a>( + data_dir: &Path, state: &'a mut RoomState, token: &str, ) -> anyhow::Result<&'a mut SessionRecord> { @@ -3701,6 +3835,7 @@ fn validate_session<'a>( .find(|item| item.token == token) .ok_or_else(|| anyhow::anyhow!("invalid or expired session"))?; ensure_session_actor_id(session); + validate_session_authority(data_dir, session)?; if !session .capabilities .iter() @@ -3712,6 +3847,7 @@ fn validate_session<'a>( } fn validate_session_for_read<'a>( + data_dir: &Path, state: &'a RoomState, token: &str, ) -> anyhow::Result<&'a SessionRecord> { @@ -3720,6 +3856,7 @@ fn validate_session_for_read<'a>( .iter() .find(|item| item.token == token && item.expires_at > now_ts()) .ok_or_else(|| anyhow::anyhow!("invalid or expired session"))?; + validate_session_authority(data_dir, session)?; if !session .capabilities .iter() @@ -5715,6 +5852,233 @@ fn unlock_state_file(lock: FileLock) -> anyhow::Result<()> { mod tests { use super::*; + fn test_room_authorization(principal: &str) -> RoomSessionAuthorization { + RoomSessionAuthorization { + principal_id: principal.into(), + session_id: "local:fixture".into(), + proof_binding_id: None, + grant_id: "grant:local:fixture".into(), + authority_actor: "chat-room".into(), + expires_at: now_ts() + 24 * 60 * 60, + } + } + + fn grant_room_authorization(data: &Path) -> RoomSessionAuthorization { + let authorization = RoomSessionAuthorization { + principal_id: "person:local:room".into(), + session_id: "auth:room".into(), + proof_binding_id: Some("proof:room".into()), + grant_id: "grant:room".into(), + authority_actor: "home".into(), + expires_at: now_ts() + 300, + }; + crate::auth::store_session_grant( + data, + elastos_runtime::auth::AuthSessionGrantV1 { + schema: elastos_runtime::auth::AuthSessionGrantV1::SCHEMA.into(), + principal_id: authorization.principal_id.clone(), + session_id: authorization.session_id.clone(), + proof_binding_id: authorization.proof_binding_id.clone().unwrap(), + grant_id: authorization.grant_id.clone(), + issued_at: now_ts(), + expires_at: authorization.expires_at, + apps: vec!["home".into()], + }, + ) + .unwrap(); + authorization + } + + #[test] + fn room_session_bound_checks_all_use_paths() { + for configured in [false, true] { + for refusal in ["revoked", "expired", "replaced", "legacy"] { + let data = tempfile::tempdir().unwrap(); + let authorization = grant_room_authorization(data.path()); + let start = if configured { + start_configured_collaboration_principal_session + } else { + start_local_principal_runtime_session + }; + let session = start( + data.path(), + "did:key:z6room", + &authorization.principal_id, + "Room person", + "Browser", + &authorization, + ) + .unwrap(); + let token = &session.token; + let upload = + start_attachment_upload(data.path(), token, "test.txt", "text/plain", 1) + .unwrap(); + assert!(upload.expires_at <= session.expires_at); + let attachment = + append_attachment_object(data.path(), token, "test.txt", "text/plain", b"x") + .unwrap(); + let attachment_id = attachment.attachment.unwrap().attachment_id; + assert!(collaboration_room_poll(data.path(), token, "network", "room", 0).is_ok()); + match refusal { + "revoked" => crate::auth::revoke_session_grant( + data.path(), + &authorization.session_id, + now_ts(), + ) + .unwrap(), + "legacy" => with_locked_state(data.path(), |_, state| { + state + .sessions + .iter_mut() + .find(|s| s.token == *token) + .unwrap() + .authorization = None; + Ok(()) + }) + .unwrap(), + _ => { + let mut grant = crate::auth::load_active_session_grant( + data.path(), + &authorization.session_id, + now_ts(), + ) + .unwrap(); + if refusal == "expired" { + grant.expires_at = now_ts(); + } else { + grant.grant_id = "grant:replacement".into(); + } + crate::auth::store_session_grant(data.path(), grant).unwrap(); + } + } + let before = room_state_snapshot(data.path()); + for result in [ + session_view(data.path(), token).map(|_| ()), + room_poll(data.path(), token, 0).map(|_| ()), + conversation_feed(data.path(), token, 0).map(|_| ()), + collaboration_room_poll(data.path(), token, "network", "room", 0).map(|_| ()), + append_object(data.path(), token, "message").map(|_| ()), + append_attachment_object(data.path(), token, "file.txt", "text/plain", b"x") + .map(|_| ()), + start_attachment_upload(data.path(), token, "file.txt", "text/plain", 1) + .map(|_| ()), + append_attachment_upload_chunk(data.path(), token, &upload.upload_id, 0, b"x") + .map(|_| ()), + finish_attachment_upload(data.path(), token, &upload.upload_id).map(|_| ()), + read_attachment(data.path(), token, &attachment_id).map(|_| ()), + leave_session(data.path(), token).map(|_| ()), + ] { + assert!( + result + .unwrap_err() + .to_string() + .contains("invalid or expired session"), + "{configured} {refusal}" + ); + } + assert_eq!(room_state_snapshot(data.path()), before); + } + } + } + + #[test] + fn room_session_bound_renewal_and_distinct_grants() { + for configured in [false, true] { + let data = tempfile::tempdir().unwrap(); + let mut authorization = grant_room_authorization(data.path()); + let start = if configured { + start_configured_collaboration_principal_session + } else { + start_local_principal_runtime_session + }; + let first = start( + data.path(), + "did:key:z6room", + &authorization.principal_id, + "Room person", + "Browser", + &authorization, + ) + .unwrap(); + let mut grant = crate::auth::load_active_session_grant( + data.path(), + &authorization.session_id, + now_ts(), + ) + .unwrap(); + grant.expires_at += 300; + crate::auth::renew_session_grant(data.path(), grant.clone()).unwrap(); + authorization.expires_at = grant.expires_at; + let renewed = start( + data.path(), + "did:key:z6room", + &authorization.principal_id, + "Room person", + "Browser", + &authorization, + ) + .unwrap(); + assert_eq!(renewed.token, first.token); + assert_eq!(renewed.expires_at, authorization.expires_at); + let old = authorization.clone(); + grant.session_id = "auth:second".into(); + grant.grant_id = "grant:second".into(); + crate::auth::store_session_grant(data.path(), grant.clone()).unwrap(); + authorization.session_id = grant.session_id; + authorization.grant_id = grant.grant_id; + // Even a frame with a later deadline stays within its stored grant. + authorization.expires_at += 300; + let second = start( + data.path(), + "did:key:z6room", + &authorization.principal_id, + "Room person", + "Browser", + &authorization, + ) + .unwrap(); + assert_ne!(second.token, first.token); + assert_eq!(second.expires_at, grant.expires_at); + let mut long_grant = crate::auth::load_active_session_grant( + data.path(), + &authorization.session_id, + now_ts(), + ) + .unwrap(); + long_grant.expires_at = now_ts() + 24 * 60 * 60; + crate::auth::renew_session_grant(data.path(), long_grant.clone()).unwrap(); + authorization.expires_at = long_grant.expires_at; + let before = now_ts(); + let full = start( + data.path(), + "did:key:z6room", + &authorization.principal_id, + "Room person", + "Browser", + &authorization, + ) + .unwrap(); + assert!(full.expires_at >= before + SESSION_TTL_SECS); + assert!(full.expires_at <= now_ts() + SESSION_TTL_SECS); + if configured { + assert_eq!( + resolve_configured_collaboration_principal_session( + data.path(), + "did:key:z6room", + &authorization.principal_id, + &authorization + ) + .unwrap() + .token, + second.token + ); + } + crate::auth::revoke_session_grant(data.path(), &old.session_id, now_ts()).unwrap(); + assert!(room_poll(data.path(), &first.token, 0).is_err()); + assert!(room_poll(data.path(), &second.token, 0).is_ok()); + } + } + struct RoomTestActor { profile_did: String, profile: crate::collaboration_profile_authority::VerifiedCollaborationProfileDocument, @@ -6858,6 +7222,7 @@ mod tests { "principal-one", "Alice", "ElastOS shell", + &test_room_authorization("principal-one"), ) .unwrap(); let replay = start_configured_collaboration_principal_session( @@ -6866,6 +7231,7 @@ mod tests { "principal-one", "Alice", "ElastOS shell", + &test_room_authorization("principal-one"), ) .unwrap(); assert_eq!(replay.token, first.token); @@ -6881,6 +7247,8 @@ mod tests { room_access_capabilities(), now, )); + state.sessions.last_mut().unwrap().authorization = + Some(test_room_authorization("principal-one")); state.sessions.push(create_session_record_with_actor( "Alice stale device", "ElastOS shell", @@ -6889,6 +7257,8 @@ mod tests { room_access_capabilities(), now, )); + state.sessions.last_mut().unwrap().authorization = + Some(test_room_authorization("principal-one")); Ok(()) }) .unwrap(); @@ -6899,6 +7269,7 @@ mod tests { "principal-one", "Alice", "ElastOS shell", + &test_room_authorization("principal-one"), ) .unwrap(); assert_ne!(rotated.token, first.token); @@ -6920,6 +7291,8 @@ mod tests { room_access_capabilities(), now, )); + state.sessions.last_mut().unwrap().authorization = + Some(test_room_authorization("principal-one")); Ok(()) }) .unwrap(); @@ -6928,6 +7301,7 @@ mod tests { tmp.path(), "did:key:z6device-two", "principal-one", + &test_room_authorization("principal-one"), ) .unwrap() .is_some()); @@ -6952,6 +7326,7 @@ mod tests { "principal-one", "Alice", "ElastOS shell", + &test_room_authorization("principal-one"), ) .unwrap(); let paths = storage_paths(tmp.path()).unwrap(); @@ -6961,6 +7336,7 @@ mod tests { tmp.path(), "did:key:z6device-one", "principal-one", + &test_room_authorization("principal-one"), ) .unwrap(); assert_eq!(resolved.token, session.token); @@ -6969,12 +7345,14 @@ mod tests { tmp.path(), "did:key:z6device-other", "principal-one", + &test_room_authorization("principal-one"), ) .is_err()); assert!(resolve_configured_collaboration_principal_session( tmp.path(), "did:key:z6device-one", "principal-other", + &test_room_authorization("principal-other"), ) .is_err()); @@ -6994,6 +7372,7 @@ mod tests { tmp.path(), "did:key:z6device-one", "principal-one", + &test_room_authorization("principal-one"), ) .unwrap_err() .to_string() @@ -7020,6 +7399,7 @@ mod tests { tmp.path(), "did:key:z6device-one", "principal-one", + &test_room_authorization("principal-one"), ) .is_err()); } @@ -7199,6 +7579,7 @@ mod tests { "person:local:admin", "Admin", "ElastOS shell", + &test_room_authorization("person:local:admin"), ) .unwrap(); let guest = start_local_principal_runtime_session( @@ -7207,6 +7588,7 @@ mod tests { "person:local:guest", "Guest", "ElastOS shell", + &test_room_authorization("person:local:guest"), ) .unwrap(); @@ -7317,6 +7699,7 @@ mod tests { "person:local:admin", "Admin", "ElastOS shell", + &test_room_authorization("person:local:admin"), ) .unwrap(); let guest = start_local_principal_runtime_session( @@ -7325,6 +7708,7 @@ mod tests { "person:local:guest", "Guest", "ElastOS shell", + &test_room_authorization("person:local:guest"), ) .unwrap(); @@ -8267,6 +8651,7 @@ mod tests { "principal-one", "Alice", "ElastOS shell", + &test_room_authorization("principal-one"), ) .unwrap(); let profile = RoomProfileCardView { @@ -8331,6 +8716,7 @@ mod tests { "principal-one", "Alice", "ElastOS shell", + &test_room_authorization("principal-one"), ) .unwrap(); let profile = RoomProfileCardView { @@ -8394,6 +8780,7 @@ mod tests { "principal-one", "Alice", "ElastOS shell", + &test_room_authorization("principal-one"), ) .unwrap(); assert!(collaboration_room_poll( @@ -8409,6 +8796,7 @@ mod tests { tmp.path(), "did:key:z6configured", "principal-one", + &test_room_authorization("principal-one"), ) .unwrap(); } else { From a9431475be1a32139a708edd1184e74786661593 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 5 Nov 2026 09:54:50 -0500 Subject: [PATCH 2/2] refuse legacy room sessions without an authority and map a lapsed grant to 401 --- .../src/api/gateway_home_runtime.rs | 64 ++++++++++++++++++- .../crates/elastos-server/src/room_service.rs | 60 ++++++++++++++--- 2 files changed, 115 insertions(+), 9 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs index 45b91a598..589b998ba 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs @@ -1,5 +1,16 @@ use super::*; +fn home_projection_token_error(err: anyhow::Error) -> (StatusCode, Json) { + if err.to_string() == "home launch token auth session is not active" { + ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({ "error": "invalid or expired session" })), + ) + } else { + gateway_internal_error(err) + } +} + pub(super) async fn home_launch( State(state): State, headers: HeaderMap, @@ -117,7 +128,7 @@ pub(super) async fn home_launch( executable_actor, &context, ) - .map_err(gateway_internal_error)?; + .map_err(home_projection_token_error)?; let expires_at = gateway_home_token::require_carried_home_launch_token( &state.data_dir, &token, @@ -1881,6 +1892,57 @@ async fn home_list_runtime_capsules( mod tests { use super::*; + #[test] + fn home_token_projection_lapsed_grant_returns_unauthorized() { + let data = tempfile::tempdir().unwrap(); + let context = HomeLaunchTokenContext { + principal_id: "person:local:alice".into(), + session_id: "auth:alice".into(), + proof_binding_id: Some("proof:alice".into()), + grant_id: "grant:alice".into(), + }; + let mut grant = elastos_runtime::auth::AuthSessionGrantV1 { + schema: elastos_runtime::auth::AuthSessionGrantV1::SCHEMA.into(), + principal_id: context.principal_id.clone(), + session_id: context.session_id.clone(), + proof_binding_id: context.proof_binding_id.clone().unwrap(), + grant_id: context.grant_id.clone(), + issued_at: now_ts(), + expires_at: now_ts() + 300, + apps: vec![HOME_CAPSULE_ID.into()], + }; + crate::auth::store_session_grant(data.path(), grant.clone()).unwrap(); + let token = + issue_home_launch_token_with_context(data.path(), HOME_CAPSULE_ID, &context).unwrap(); + let mut headers = HeaderMap::new(); + headers.insert("host", "localhost:61180".parse().unwrap()); + headers.insert("origin", "http://localhost:61180".parse().unwrap()); + headers.insert("x-elastos-home-token", token.parse().unwrap()); + let validated = + require_home_launch_token_context(data.path(), &headers, HOME_CAPSULE_ID).unwrap(); + // Expire the stored grant after frame validation, before projection minting. + grant.expires_at = now_ts(); + crate::auth::store_session_grant(data.path(), grant).unwrap(); + let (status, Json(body)) = issue_home_projection_launch_token_with_context( + data.path(), + CHAT_ROOM_CAPSULE_ID, + CHAT_ROOM_CAPSULE_ID, + &validated, + ) + .map_err(home_projection_token_error) + .unwrap_err(); + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["error"], "invalid or expired session"); + } + + #[test] + fn home_token_projection_internal_error_keeps_server_status() { + let (status, Json(body)) = + home_projection_token_error(anyhow::anyhow!("failed to load signing key")); + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!(body["error"], "failed to load signing key"); + } + #[tokio::test] async fn native_shell_metadata_refuses_generic_home_launch_before_runtime_start() { let directory = tempfile::tempdir().unwrap(); diff --git a/elastos/crates/elastos-server/src/room_service.rs b/elastos/crates/elastos-server/src/room_service.rs index e1ac7855f..79f5f822c 100644 --- a/elastos/crates/elastos-server/src/room_service.rs +++ b/elastos/crates/elastos-server/src/room_service.rs @@ -2606,12 +2606,6 @@ fn create_session_record_with_actor( } } -fn ensure_session_actor_id(session: &mut SessionRecord) { - if session.actor_id.trim().is_empty() { - session.actor_id = random_hex(16); - } -} - fn current_session_identity(session: &SessionRecord) -> CurrentSessionIdentity { CurrentSessionIdentity { actor_id: session.actor_id.clone(), @@ -3810,7 +3804,7 @@ pub fn read_attachment( } fn validate_session_authority(data_dir: &Path, session: &SessionRecord) -> anyhow::Result<()> { - if session.expires_at <= now_ts() { + if session.expires_at <= now_ts() || session.actor_id.trim().is_empty() { anyhow::bail!("invalid or expired session"); } match session.authorization.as_ref() { @@ -3834,7 +3828,6 @@ fn validate_session<'a>( .iter_mut() .find(|item| item.token == token) .ok_or_else(|| anyhow::anyhow!("invalid or expired session"))?; - ensure_session_actor_id(session); validate_session_authority(data_dir, session)?; if !session .capabilities @@ -5889,6 +5882,57 @@ mod tests { authorization } + #[test] + fn room_session_bound_refuses_stored_legacy_authority_and_allows_restart() { + for missing in [ + vec!["actor_id"], + vec!["authorization"], + vec!["actor_id", "authorization"], + ] { + let data = tempfile::tempdir().unwrap(); + let authorization = grant_room_authorization(data.path()); + let start = || { + start_local_principal_runtime_session( + data.path(), + "did:key:z6room", + &authorization.principal_id, + "Room person", + "Browser", + &authorization, + ) + .unwrap() + }; + let session = start(); + let path = storage_paths(data.path()).unwrap().sessions_path; + let mut records: serde_json::Value = + serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + for field in &missing { + records[0].as_object_mut().unwrap().remove(*field); + } + fs::write(&path, serde_json::to_vec(&records).unwrap()).unwrap(); + let before = room_state_snapshot(data.path()); + // Exercise both the read-only and mutable validators after deserialization. + for result in [ + collaboration_room_poll(data.path(), &session.token, "network", "room", 0) + .map(|_| ()), + room_poll(data.path(), &session.token, 0).map(|_| ()), + append_object(data.path(), &session.token, "legacy message").map(|_| ()), + ] { + assert!( + result.is_err_and(|error| error + .to_string() + .contains("invalid or expired session")), + "legacy session accepted with missing {missing:?}" + ); + } + assert_eq!(room_state_snapshot(data.path()), before); + let replacement = start(); + assert_ne!(replacement.token, session.token); + assert!(room_poll(data.path(), &replacement.token, 0).is_ok()); + assert!(append_object(data.path(), &replacement.token, "new message").is_ok()); + } + } + #[test] fn room_session_bound_checks_all_use_paths() { for configured in [false, true] {