From 5233649ebdffcd8079e1c0bc42af49e9f32675fa Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 17 Sep 2026 15:59:57 -0500 Subject: [PATCH] fix(streaming): join the session the caller asked for An unnamed join stopped at the first pool member holding a live session, so a desktop, another platform's game, the caller's own session or a ROM they cannot see masked the session they were offered and the join answered 404 or handed back somebody else's room. The walk now skips a member that fails the same filter the joinable listing applies and keeps looking, and the Join button carries the container of the row it came from into the stream URL so the join names its session outright. --- backend/endpoints/streaming.py | 17 +++- backend/handler/streaming/access.py | 6 +- backend/tests/endpoints/test_streaming.py | 81 +++++++++++++++++++ .../v2/components/Home/LiveSessionCard.vue | 1 + .../composables/useGameActions/index.test.ts | 13 ++- .../v2/composables/useGameActions/index.ts | 1 + .../useJoinStreamConfirm/index.test.ts | 18 ++++- .../composables/useJoinStreamConfirm/index.ts | 7 +- frontend/src/v2/views/Player/Stream.test.ts | 40 ++++++++- frontend/src/v2/views/Player/Stream.vue | 10 ++- 10 files changed, 179 insertions(+), 15 deletions(-) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 375cc9fc6..390208979 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -93,6 +93,7 @@ from handler.streaming.session_store import ( release_own_session, session_disc_id, session_is_stale, + session_platform_matches, session_redis_key, set_session_disc, stamp_launched, @@ -1096,9 +1097,19 @@ async def join_session( session = await get_live_session(candidate.key) if session is None: continue - if session.get("multiplayer"): - found = (candidate, session) - break + # Same filter the joinable listing applies, so the button and the + # join agree on what is joinable. A member that fails it is not the + # answer and must not mask a later one that is. + if not session.get("multiplayer"): + continue + if not session_platform_matches(session, platform): + continue + if session.get("user_id") == request.user.id: + continue + if not access.session_rom_is_visible(request, session): + continue + found = (candidate, session) + break if found is None: raise HTTPException( diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index 8fbe2c55d..a79517735 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -54,7 +54,7 @@ def rom_is_visible(request: Request, rom: Rom | None) -> bool: return get_permissions(request).can_see_rom(rom.id, rom.platform_id) -def _session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool: +def session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool: """Can the caller see the ROM a session is running?""" rom_id = session.get("rom_id") if rom_id is None: @@ -66,14 +66,14 @@ def assert_session_rom_visible( request: Request, session: dict[str, Any], *, not_found_detail: str ) -> None: """Raise 404 when the session's ROM is hidden from the caller.""" - if not _session_rom_is_visible(request, session): + if not session_rom_is_visible(request, session): raise HTTPException(status_code=404, detail=not_found_detail) def visible_rom_name(request: Request, session: dict[str, Any]) -> str | None: """The name of the ROM a session is running, blanked when the caller cannot see that ROM. "Busy" is safe to report to anyone; what is running is not.""" - if not session or not _session_rom_is_visible(request, session): + if not session or not session_rom_is_visible(request, session): return None name = session.get("rom_name") return str(name) if name else None diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index b57c12b27..f108dade2 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -6679,6 +6679,87 @@ def test_joining_a_rom_on_a_hidden_platform_is_404_masked( join_broker.assert_not_called() +def _ws_pool_member(rom: Rom, index: int, **overrides) -> dict: + """One member of a pool of webstation containers, the broker a joiner + needs. Distinct hosts, so the room URL says which member answered.""" + return _webstation( + **{ + "host": f"http://192.168.1.1{index}:3000", + "broker_host": f"http://192.168.1.1{index}:8000", + "platforms": {rom.platform_slug: "pcsx2"}, + **overrides, + } + ) + + +def _joined_room(url: str = "/webstation/?token=abc"): + return patch("handler.streaming.webstation.join", return_value={"url": url}) + + +def test_joining_walks_past_a_session_whose_rom_is_hidden( + client, + access_token, + editor_access_token, + viewer_access_token, + viewer_user: User, + rom: Rom, + second_rom: Rom, +): + """A hidden ROM earlier in the pool is not the caller's answer, so it must + not mask the joinable session behind it.""" + _hide(PermEntity.ROMS, rom.id, viewer_user.id) + with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)): + _claim_multiplayer(client, access_token, rom.id) + _claim_multiplayer(client, editor_access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_walks_past_the_callers_own_session( + client, access_token, viewer_access_token, rom: Rom, second_rom: Rom +): + """Joining is for somebody else's game: the caller's own session is the one + they already hold, and the listing leaves it out for the same reason.""" + with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)): + _claim_multiplayer(client, viewer_access_token, rom.id) + _claim_multiplayer(client, access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_walks_past_a_session_on_another_platform( + client, + access_token, + editor_access_token, + viewer_access_token, + rom: Rom, + second_rom: Rom, +): + """A container serves several platforms and holds one session, so a member + busy with another platform is not this platform's session to join.""" + member = _ws_pool_member( + rom, 0, platforms={rom.platform_slug: "pcsx2", "ngc": "dolphin"} + ) + with _streaming(member, _ws_pool_member(rom, 1)): + _claim_multiplayer(client, access_token, rom.id) + key = session_store.session_redis_key(_key_of(member)) + session = json.loads(asyncio.run(async_cache.get(key))) + session["platform"] = "ngc" + asyncio.run(async_cache.set(key, json.dumps(session))) + _claim_multiplayer(client, editor_access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + def test_joining_a_solo_session_finds_nothing_to_join( client, access_token, viewer_access_token, rom: Rom ): diff --git a/frontend/src/v2/components/Home/LiveSessionCard.vue b/frontend/src/v2/components/Home/LiveSessionCard.vue index cdd53ac6c..732160240 100644 --- a/frontend/src/v2/components/Home/LiveSessionCard.vue +++ b/frontend/src/v2/components/Home/LiveSessionCard.vue @@ -57,6 +57,7 @@ async function join(): Promise { romId, romName: title.value, hostUsername: props.session.host_username ?? null, + container: props.session.container, }); } diff --git a/frontend/src/v2/composables/useGameActions/index.test.ts b/frontend/src/v2/composables/useGameActions/index.test.ts index 89decddb2..6efafe753 100644 --- a/frontend/src/v2/composables/useGameActions/index.test.ts +++ b/frontend/src/v2/composables/useGameActions/index.test.ts @@ -15,7 +15,7 @@ const canPlayPico8 = { value: false }; const canPlayRuffle = { value: false }; const streamContainer = { value: null as object | null }; const joinableSession = { - value: null as { host_username: string | null } | null, + value: null as { host_username: string | null; container?: string } | null, }; // Granted action keys — `null` means "everything" (the default). const grantedActions: { value: Set | null } = { value: null }; @@ -142,7 +142,10 @@ beforeEach(() => { describe("useGameActions.joinStream", () => { beforeEach(() => { streamContainer.value = { host: "http://stream" }; - joinableSession.value = { host_username: "ada" }; + joinableSession.value = { + host_username: "ada", + container: "http://box:8000", + }; }); it("does not navigate until the user confirms", async () => { @@ -161,7 +164,11 @@ describe("useGameActions.joinStream", () => { await actions.joinStream(); - expect(push).toHaveBeenCalledWith("/rom/1/stream?join=1"); + // The joinable row names the container, and a pool needs it: the stream + // view would otherwise walk the pool and could land on another session. + expect(push).toHaveBeenCalledWith( + "/rom/1/stream?join=1&container=http%3A%2F%2Fbox%3A8000", + ); }); it("names the host in the confirmation", async () => { diff --git a/frontend/src/v2/composables/useGameActions/index.ts b/frontend/src/v2/composables/useGameActions/index.ts index ee751d860..32a3caf2c 100644 --- a/frontend/src/v2/composables/useGameActions/index.ts +++ b/frontend/src/v2/composables/useGameActions/index.ts @@ -376,6 +376,7 @@ export function useGameActions( romId: rom.id, romName: rom.name ?? rom.fs_name_no_ext ?? "", hostUsername: joinHostLabel.value || null, + container: joinableSession.value?.container ?? null, }, ); } diff --git a/frontend/src/v2/composables/useJoinStreamConfirm/index.test.ts b/frontend/src/v2/composables/useJoinStreamConfirm/index.test.ts index 1fcbdef04..501e34353 100644 --- a/frontend/src/v2/composables/useJoinStreamConfirm/index.test.ts +++ b/frontend/src/v2/composables/useJoinStreamConfirm/index.test.ts @@ -14,7 +14,12 @@ vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirmFn, })); -const target = { romId: 1, romName: "Chrono Trigger", hostUsername: "ada" }; +const target = { + romId: 1, + romName: "Chrono Trigger", + hostUsername: "ada", + container: null, +}; describe("useJoinStreamConfirm", () => { beforeEach(() => { @@ -40,6 +45,17 @@ describe("useJoinStreamConfirm", () => { expect(push).toHaveBeenCalledWith("/rom/1/stream?join=1"); }); + it("carries the container into the join URL", async () => { + confirmFn.mockResolvedValue(true); + const { joinStream } = useJoinStreamConfirm(); + + await joinStream({ ...target, container: "http://box:8000" }); + + expect(push).toHaveBeenCalledWith( + "/rom/1/stream?join=1&container=http%3A%2F%2Fbox%3A8000", + ); + }); + it("names the host in the confirmation", async () => { confirmFn.mockResolvedValue(false); const { joinStream } = useJoinStreamConfirm(); diff --git a/frontend/src/v2/composables/useJoinStreamConfirm/index.ts b/frontend/src/v2/composables/useJoinStreamConfirm/index.ts index 0d219317e..5496222c2 100644 --- a/frontend/src/v2/composables/useJoinStreamConfirm/index.ts +++ b/frontend/src/v2/composables/useJoinStreamConfirm/index.ts @@ -11,6 +11,9 @@ export interface JoinStreamTarget { romId: number; romName: string; hostUsername: string | null; + // A pool holds a session per container, so the one being joined has to be + // named rather than left to the backend to pick. + container: string | null; } interface JoinStreamDeps { @@ -35,7 +38,9 @@ export async function confirmJoinStream( confirmText: t("rom.join-session"), }); if (!ok) return; - void router.push(`/rom/${target.romId}/stream?join=1`); + const query = new URLSearchParams({ join: "1" }); + if (target.container) query.set("container", target.container); + void router.push(`/rom/${target.romId}/stream?${query}`); } export function useJoinStreamConfirm() { diff --git a/frontend/src/v2/views/Player/Stream.test.ts b/frontend/src/v2/views/Player/Stream.test.ts index a2f751c4d..6ecd6eb3e 100644 --- a/frontend/src/v2/views/Player/Stream.test.ts +++ b/frontend/src/v2/views/Player/Stream.test.ts @@ -1,5 +1,5 @@ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { defineComponent } from "vue"; import type { SaveSchema } from "@/__generated__"; import type { DetailedRom } from "@/stores/roms"; @@ -14,11 +14,13 @@ const mocks = vi.hoisted(() => ({ getRom: vi.fn(), fetchSessionStatus: vi.fn(), heartbeatSession: vi.fn(), + joinSession: vi.fn(), releaseSession: vi.fn(), releaseSessionKeepalive: vi.fn(), container: null as Record | null, presenceTick: null as (() => Promise) | null, socketHandlers: {} as Record unknown>, + query: {} as Record, })); vi.mock("vue-i18n", () => ({ @@ -27,7 +29,7 @@ vi.mock("vue-i18n", () => ({ vi.mock("vue-router", () => ({ onBeforeRouteLeave: vi.fn(), - useRoute: () => ({ params: { rom: "3" }, query: {} }), + useRoute: () => ({ params: { rom: "3" }, query: mocks.query }), useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), })); @@ -69,7 +71,7 @@ vi.mock("@/stores/streaming", () => ({ fetchSessionStatus: mocks.fetchSessionStatus, forgetJoinableSession: vi.fn(), heartbeatSession: mocks.heartbeatSession, - joinSession: vi.fn(), + joinSession: mocks.joinSession, releaseSession: mocks.releaseSession, releaseSessionKeepalive: mocks.releaseSessionKeepalive, saveAndExit: vi.fn(), @@ -566,3 +568,35 @@ describe("Stream launch recovery", () => { wrapper.unmount(); }); }); + +describe("Stream join", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.joinSession.mockResolvedValue({ host: "http://box:3000/room/x" }); + mocks.query = { join: "1", container: "http://box:8000" }; + }); + + afterEach(() => { + mocks.query = {}; + }); + + it("joins the session on the container the game page named", async () => { + // A pool has several sessions on one platform, so without the container + // the join lands on whichever the backend walks to first. + const wrapper = await launch({ picker: false }); + await flushPromises(); + + expect(mocks.joinSession).toHaveBeenCalledWith("gba", "http://box:8000"); + expect(vmOf(wrapper).playerState).toBe("playing"); + wrapper.unmount(); + }); + + it("joins without one when the page had no container to name", async () => { + mocks.query = { join: "1" }; + const wrapper = await launch({ picker: false }); + await flushPromises(); + + expect(mocks.joinSession).toHaveBeenCalledWith("gba", undefined); + wrapper.unmount(); + }); +}); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 4cfe3952e..3485aa607 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -137,6 +137,11 @@ useStageActive(gameRunning); // host's session out from under them. const isJoining = route.query.join === "1"; +// Named by the row that offered the join: a pool holds a session per container, +// and an unnamed join takes whichever one the backend walks to first. +const joinContainer = + typeof route.query.container === "string" ? route.query.container : undefined; + // True only while this tab's own claim is held. The teardown paths key off // this rather than the player state, because a joiner reaches "playing" too. const holdsClaim = ref(false); @@ -817,7 +822,10 @@ async function onPlay(cardImport?: MemoryCardImport): Promise { try { if (isJoining) { - const joined = await streamingStore.joinSession(rom.value.platform_slug); + const joined = await streamingStore.joinSession( + rom.value.platform_slug, + joinContainer, + ); await flourish; if ((playerState.value as PlayerState) === "exited") return; containerHost.value = joined.host;