Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
tests(prosody): add a few more, fix minor input validation issues (#17452)
bgrozev223e6f0941f5
diff --git a/resources/prosody-plugins/mod_filter_iq_jibri.lua b/resources/prosody-plugins/mod_filter_iq_jibri.luaindex 76e9cb79f0..8b908e2dae 100644--- a/resources/prosody-plugins/mod_filter_iq_jibri.lua+++ b/resources/prosody-plugins/mod_filter_iq_jibri.lua@@ -39,13 +39,17 @@ module:hook("pre-iq/full", function(event)local session = event.origin;local token = session.auth_token;local room = get_room_from_jid(room_jid_match_rewrite(jid_bare(stanza.attr.to)));+ if not room then+ session.send(st.error_reply(stanza, 'cancel', 'item-not-found'));+ return true;+ endlocal occupant = room:get_occupant_by_real_jid(stanza.attr.from);local recording_mode_lower = jibri.attr.recording_mode and jibri.attr.recording_mode:lower();local feature = recording_mode_lower == 'file' and 'recording' or 'livestreaming';local is_allowed = is_feature_allowed(feature,session.jitsi_meet_context_features,- occupant.role == 'moderator');+ occupant ~= nil and occupant.role == 'moderator');local action_lower = jibri.attr.action and jibri.attr.action:lower();if action_lower == 'start' or action_lower == 'stop' thendiff --git a/resources/prosody-plugins/mod_jibri_session.lua b/resources/prosody-plugins/mod_jibri_session.luaindex 741a25be64..16431c81bd 100644--- a/resources/prosody-plugins/mod_jibri_session.lua+++ b/resources/prosody-plugins/mod_jibri_session.lua@@ -13,7 +13,7 @@---- Must be loaded on both the main virtual host and the jicofo virtual host.-local json = require 'cjson';+local json = require 'cjson.safe';local util = module:require 'util';local room_jid_match_rewrite = util.room_jid_match_rewrite;@@ -32,7 +32,12 @@ local stanza = event.stanza;local update_app_data = false;local app_data = jibri.attr.app_data;if app_data then- app_data = json.decode(app_data);+ local err;+ app_data, err = json.decode(app_data);+ if err then+ module:log('warn', 'Failed to decode jibri app_data from %s: %s', stanza.attr.from, err);+ return;+ endelseapp_data = {};enddiff --git a/resources/prosody-plugins/mod_measure_message_count.lua b/resources/prosody-plugins/mod_measure_message_count.luaindex 142256f11f..6e744b5de7 100644--- a/resources/prosody-plugins/mod_measure_message_count.lua+++ b/resources/prosody-plugins/mod_measure_message_count.lua@@ -24,6 +24,7 @@ local isBreakoutRoom = module.host == 'breakout.' .. muc_domain_base;local util = module:require 'util';local is_healthcheck_room = util.is_healthcheck_room;local extract_subdomain = util.extract_subdomain;+local get_room_by_name_and_subdomain = util.get_room_by_name_and_subdomain;module:log('info', 'Loading measure message count');diff --git a/resources/prosody-plugins/mod_muc_auth_ban.lua b/resources/prosody-plugins/mod_muc_auth_ban.luaindex 0d4c62b5b2..f21beff98d 100644--- a/resources/prosody-plugins/mod_muc_auth_ban.lua+++ b/resources/prosody-plugins/mod_muc_auth_ban.lua@@ -58,7 +58,7 @@ local function shouldAllow(session)if code == 200 thenlocal r = json.decode(content)- if r['access'] ~= nil and r['access'] == false then+ if r ~= nil and r['access'] == false thenmodule:log("info", "User is banned room:%s tenant:%s user_id:%s group:%s",session.jitsi_web_query_room, session.jitsi_web_query_prefix,inspect(session.jitsi_meet_context_user), session.jitsi_meet_context_group);diff --git a/resources/prosody-plugins/mod_muc_cleanup_backend_services.lua b/resources/prosody-plugins/mod_muc_cleanup_backend_services.luaindex b1f56bc002..23fca61165 100644--- a/resources/prosody-plugins/mod_muc_cleanup_backend_services.lua+++ b/resources/prosody-plugins/mod_muc_cleanup_backend_services.lua@@ -1,5 +1,24 @@--- Module to be enabled under main muc component--- Clean up the room in case it is empty and has only jibri and jigasi-transcriber left in the meeting+-- Module to be enabled under the main MUC component.+-- Destroys a conference room after a configurable timeout (default 20 s,+-- overridable via services_empty_meeting_timeout) when the room is left+-- occupied only by backend services — Jibri recorders or transcribers —+-- with no regular participants remaining.+--+-- Identity is determined by JID prefix (util.lib.lua):+-- is_jibri(): JID starts with 'recorder@recorder.', 'jibria@recorder.',+-- or 'jibrib@recorder.'+-- is_transcriber(): JID starts with 'transcriber@recorder.',+-- 'transcribera@recorder.', or 'transcriberb@recorder.'+-- is_admin(): bare JID is in the Prosody admins list+--+-- Hook summary:+-- muc-occupant-joined (-100) — cancel the destroy timer when a regular user+-- (not jibri, not transcriber) joins.+-- muc-occupant-left (-100) — start the destroy timer when the leaver is a+-- regular user and only backend services remain;+-- skip entirely if the leaver is admin, jibri,+-- or transcriber, or if breakout_rooms_active.+-- muc-room-destroyed (1) — cancel and clear the timer reference.local util = module:require 'util';local is_admin = util.is_admin;diff --git a/resources/prosody-plugins/mod_muc_jigasi_invite.lua b/resources/prosody-plugins/mod_muc_jigasi_invite.luaindex a0af714df5..0c008b337e 100644--- a/resources/prosody-plugins/mod_muc_jigasi_invite.lua+++ b/resources/prosody-plugins/mod_muc_jigasi_invite.lua@@ -76,32 +76,36 @@ local function invite_jigasi(conference, phone_no)local occ = occupant:get_presence();local stats_child = occ:get_child("stats", "http://jitsi.org/protocol/colibri")- local is_sip_jigasi = true;- for stats_tag in stats_child:children() do- if stats_tag.attr.name == 'supports_sip' and stats_tag.attr.value == 'false' then- is_sip_jigasi = false;+ if not stats_child then+ module:log("warn", "Jigasi occupant %s has no stats element, skipping", occupant_jid);+ else+ local is_sip_jigasi = true;+ for stats_tag in stats_child:children() do+ if stats_tag.attr.name == 'supports_sip' and stats_tag.attr.value == 'false' then+ is_sip_jigasi = false;+ endend- end- if is_sip_jigasi then- for stats_tag in stats_child:children() do- if stats_tag.attr.name == 'stress_level' then- local stress_level = tonumber(stats_tag.attr.value);- module:log("debug", "Stressed level %s %s ", stress_level, occupant_jid)- if stress_level < least_stressed_value then- least_stressed_jigasi_occupant = occupant;- least_stressed_value = stress_level+ if is_sip_jigasi then+ for stats_tag in stats_child:children() do+ if stats_tag.attr.name == 'stress_level' then+ local stress_level = tonumber(stats_tag.attr.value);+ module:log("debug", "Stressed level %s %s ", stress_level, occupant_jid)+ if stress_level < least_stressed_value then+ least_stressed_jigasi_occupant = occupant;+ least_stressed_value = stress_level+ endendendendendendend- module:log("debug", "Least stressed jigasi selected jid %s value %s", least_stressed_jigasi_occupant.jid, least_stressed_value)if not least_stressed_jigasi_occupant thenmodule:log("error", "Cannot invite jigasi from room %s", jigasi_brewery_room.jid)return 404, 'Jigasi not found'end+ module:log("debug", "Least stressed jigasi selected jid %s value %s", least_stressed_jigasi_occupant.jid, least_stressed_value)-- invite Jigasi to join the conferencelocal stanza_id = hashes.sha256(random.bytes(8), true);diff --git a/resources/prosody-plugins/mod_muc_meeting_id.lua b/resources/prosody-plugins/mod_muc_meeting_id.luaindex fd6d30ae3d..ebd8fba931 100644--- a/resources/prosody-plugins/mod_muc_meeting_id.lua+++ b/resources/prosody-plugins/mod_muc_meeting_id.lua@@ -255,12 +255,20 @@ local function filterTranscriptionResult(event)end-- TODO what if we have multiple alternative transcriptions not just 1+ if not transcription.transcript[1] then+ module:log('warn', 'Empty transcript array in transcription-result from %s', stanza.attr.from);+ return true;+ endlocal text_message = transcription.transcript[1].text;--do not send empty messagesif text_message == '' thenreturn;end+ if not transcription.participant then+ module:log('warn', 'Missing participant field in transcription-result from %s', stanza.attr.from);+ return true;+ endlocal user_id = transcription.participant.id;local who = room:get_occupant_by_nick(jid.bare(room.jid)..'/'..user_id);diff --git a/resources/prosody-plugins/mod_muc_wait_for_host.lua b/resources/prosody-plugins/mod_muc_wait_for_host.luaindex e37bcc8806..81112c11a0 100644--- a/resources/prosody-plugins/mod_muc_wait_for_host.lua+++ b/resources/prosody-plugins/mod_muc_wait_for_host.lua@@ -1,11 +1,16 @@--- This module is activated under the main muc component--- This will prevent anyone joining the call till jicofo and one moderator join the room--- for the rest of the participants lobby will be turned on and they will be waiting there till--- the main participant joins and lobby will be turned off at that time and rest of the participants will--- join the room. It expects main virtual host to be set to require jwt tokens and guests to use--- the guest domain which is anonymous.--- The module has the option to set participants to moderators when connected via token/when they are authenticated--- This module depends on mod_persistent_lobby.+-- Loaded on the main MUC component.+-- Holds unauthenticated guests in a persistent lobby until an authenticated host joins.+-- A "host" is any session with a JWT auth_token or with PLAIN credentials whose JID+-- domain matches muc_mapper_domain_base. Prosody admins (e.g. jicofo) bypass the check+-- and are not counted as hosts.+-- When the first guest arrives before any host, a persistent lobby room is created via+-- mod_persistent_lobby + mod_muc_lobby_rooms, and guests are held there. When an+-- authenticated host joins the main room the lobby is destroyed and guests are admitted.+-- Once a host has been detected the room.has_host flag is cached on the room object for+-- the lifetime of the room, so subsequent joins skip the host re-check.+-- By default, authenticated users are promoted to owner affiliation on join. Set+-- wait_for_host_disable_auto_owners = true to disable automatic owner promotion.+-- Depends on: mod_persistent_lobby (must be loaded on the main VirtualHost).local jid = require 'util.jid';local util = module:require "util";local is_admin = util.is_admin;diff --git a/resources/prosody-plugins/mod_test_observer_http.lua b/resources/prosody-plugins/mod_test_observer_http.luaindex fb99eeeee5..1f19507902 100644--- a/resources/prosody-plugins/mod_test_observer_http.lua+++ b/resources/prosody-plugins/mod_test_observer_http.lua@@ -19,8 +19,10 @@ local jid_lib = require "util.jid";-- access: false → return {"access": false} (user banned)-- status: any non-200 value → return that HTTP status code with no JSON body-- (simulates HTTP errors; mod_muc_auth_ban fails open on non-200)+-- non_json: true → return a 200 with a plain-text body (not valid JSON)+-- (tests the nil-check bug: json.decode returns nil, r['access'] would crash)-- Reset to the default (allow, 200) between tests via POST /test-observer/access-manager.-local access_manager_state = { access = true, status = 200 };+local access_manager_state = { access = true, status = 200, non_json = false };-- ASAP public key servers: serve test RSA public keys so that Prosody can-- fetch them when verifying RS256 tokens signed by the matching private keys.@@ -333,6 +335,29 @@ module:provides("http", {};end;+ -- POST /test-observer/rooms/breakout-rooms-active+ -- Body: { "jid": "[email protected]", "active": true|false }+ -- Sets room._data.breakout_rooms_active, which mod_muc_cleanup_backend_services+ -- checks to skip the destroy-timer logic when breakout rooms are running.+ ["POST /rooms/breakout-rooms-active"] = function(event)+ local data = json.decode(event.request.body or "{}") or {};+ local room_jid = data.jid;+ local active = data.active;+ if room_jid == nil or active == nil then+ return { status_code = 400; body = '{"error":"missing jid or active"}' };+ end+ local room = (shared.rooms or {})[room_jid];+ if not room then+ return { status_code = 404; body = '{"error":"room not found"}' };+ end+ room._data.breakout_rooms_active = active;+ return {+ status_code = 200;+ headers = { ["Content-Type"] = "application/json" };+ body = '{"ok":true}';+ };+ end;+-- POST /test-observer/rooms/max-occupants-- Body: { "jid": "[email protected]", "max_occupants": 4 }-- Sets room._data.max_occupants so per-room limit tests can override the@@ -366,6 +391,16 @@ module:provides("http", {if access_manager_state.status ~= 200 thenreturn { status_code = access_manager_state.status; body = "error" };end+ if access_manager_state.non_json then+ -- Return a 200 with a non-JSON body to exercise the nil-check+ -- bug in mod_muc_auth_ban: json.decode returns nil, and+ -- r['access'] would crash if the module doesn't guard for nil.+ return {+ status_code = 200;+ headers = { ["Content-Type"] = "text/plain" };+ body = "not-valid-json";+ };+ endreturn {status_code = 200;headers = { ["Content-Type"] = "application/json" };@@ -374,7 +409,7 @@ module:provides("http", {end;-- POST /test-observer/access-manager- -- Body: { "access": true|false, "status": <http-status-code> }+ -- Body: { "access": true|false, "status": <http-status-code>, "non_json": true|false }-- Configures what the mock access manager returns.-- Call this from tests before connecting the client under test.-- Call with { "access": true, "status": 200 } to reset to the default.@@ -386,6 +421,9 @@ module:provides("http", {if data.status ~= nil thenaccess_manager_state.status = tonumber(data.status) or 200;end+ if data.non_json ~= nil then+ access_manager_state.non_json = data.non_json;+ endreturn { status_code = 204 };end;diff --git a/resources/prosody-plugins/mod_token_affiliation.lua b/resources/prosody-plugins/mod_token_affiliation.luaindex df312c879d..a73cd5f586 100644--- a/resources/prosody-plugins/mod_token_affiliation.lua+++ b/resources/prosody-plugins/mod_token_affiliation.lua@@ -44,6 +44,10 @@ local function affiliation_from_token(session)return "member"end+-- Hook priority -3.5: runs after lobby-bypass plugins such as mod_token_lobby_bypass+-- (priority -3), so any affiliation they grant is visible here and can be upgraded+-- to the correct token-derived value. Runs before the lobby gate (-4) and+-- Prosody's built-in members_only check (-5).module:hook("muc-occupant-pre-join", function(event)local room, occupant, session = event.room, event.occupant, event.origin@@ -52,13 +56,10 @@ module:hook("muc-occupant-pre-join", function(event)returnend- -- When lobby is active (members-only) and the user has no pre-existing- -- affiliation, let the lobby gate handle this join attempt. Once a- -- moderator approves them (their affiliation is set to ≥member by the- -- lobby module), the next join attempt will have an existing affiliation- -- and this hook will upgrade it normally.- -- Exception: if the user is bypassing the lobby with the room password,- -- apply affiliation immediately so they keep their moderator role.+ -- When lobby is active (members-only) only proceed when the user already+ -- has a non-none affiliation (admitted by moderator, or granted by a bypass+ -- plugin that ran at priority -3) or is bypassing via the room password.+ -- Otherwise let the lobby gate (-4) block this first join attempt.if room:get_members_only() thenlocal existing = room:get_affiliation(occupant.bare_jid)if not existing or existing == 'none' then@@ -82,4 +83,4 @@ module:hook("muc-occupant-pre-join", function(event)occupant.role = "moderator"endmodule:log(LOGLEVEL, "set affiliation=%s for %s", affiliation, occupant.bare_jid)-end)+end, -3.5)diff --git a/resources/prosody-plugins/token/jwk.lib.lua b/resources/prosody-plugins/token/jwk.lib.luaindex 9216b9f43b..a2864eaa6a 100644--- a/resources/prosody-plugins/token/jwk.lib.lua+++ b/resources/prosody-plugins/token/jwk.lib.lua@@ -91,6 +91,9 @@ end-- Helper function to convert JWK to PEM formatfunction M.jwk_to_pem(jwk)+ if not jwk.n or not jwk.e then+ return nil;+ end-- Decode the modulus (n) and exponent (e) from base64urllocal n_bytes = base64url_decode(jwk.n)local e_bytes = base64url_decode(jwk.e)diff --git a/resources/prosody-plugins/token/util.lib.lua b/resources/prosody-plugins/token/util.lib.luaindex 1df762a675..471fcbfbfb 100644--- a/resources/prosody-plugins/token/util.lib.lua+++ b/resources/prosody-plugins/token/util.lib.lua@@ -148,7 +148,7 @@ function Util.new(module)if content ~= nil thenlocal keys_to_delete = table_shallow_copy(self.cachedKeys);-- Let's convert any certificate to public key- for k, v in pairs(cjson_safe.decode(content)) do+ for k, v in pairs(cjson_safe.decode(content) or {}) do-- JWKS formatif k == "keys" and type(v) == "table" thenfor _, key in ipairs(v) do@@ -453,12 +453,12 @@ function Util:verify_room(session, room_address)else-- no wildcard, so check room against authorized room from the tokenif session.jitsi_meet_context_room and (session.jitsi_meet_context_room["regex"] == true or session.jitsi_meet_context_room["regex"] == "true") then- if target_room ~= nil then- -- room with subdomain- room_to_check = target_room:match(auth_room);- else- room_to_check = room_node:match(auth_room);+ local match_target = target_room ~= nil and target_room or room_node;+ local ok, result = pcall(string.match, match_target, auth_room);+ if not ok then+ return false, 'invalid-regex', 'Room claim is not a valid Lua pattern';end+ room_to_check = result;else-- not a regexroom_to_check = auth_room;diff --git a/resources/prosody-plugins/util.lib.lua b/resources/prosody-plugins/util.lib.luaindex 254d9d498c..6155921fac 100644--- a/resources/prosody-plugins/util.lib.lua+++ b/resources/prosody-plugins/util.lib.lua@@ -255,8 +255,12 @@ function update_presence_identity(stanza, user, group, creator_user, creator_grostanza:tag("identity"):tag("user");for k, v in pairs(user) do- v = tostring(v)- stanza:tag(k):text(v):up();+ -- Skip keys that are not valid XML element names (e.g. contain '<', '>').+ -- Using such keys as tag names crashes LuaXML.+ if k:match("^[%a_][%w%-%.%:_]*$") then+ v = tostring(v)+ stanza:tag(k):text(v):up();+ endendstanza:up();@@ -269,7 +273,9 @@ function update_presence_identity(stanza, user, group, creator_user, creator_groif creator_user thenstanza:tag("creator_user");for k, v in pairs(creator_user) do- stanza:tag(k):text(v):up();+ if k:match("^[%a_][%w%-%.%:_]*$") then+ stanza:tag(k):text(v):up();+ endendstanza:up();diff --git a/tests/prosody/README.md b/tests/prosody/README.mdindex c797a7dead..316b5f1663 100644--- a/tests/prosody/README.md+++ b/tests/prosody/README.md@@ -78,6 +78,24 @@ const state = await getRoomState('[email protected]');assert.equal(state.hidden, true);```+## Test Placement Guidelines++**Pure Lua code (no Prosody API needed)** — test in `lua/` using+[busted](https://lunarmodules.github.io/busted/). These run without Docker and+are fast. A good fit for library files (e.g. `token/jwk.lib.lua`) and any+module logic that can be extracted into plain functions.++**Code that requires Prosody stubs or live server behaviour** — test via the+Docker/JS path (Mocha + `*_spec.js`). This covers anything that calls+`module:hook`, `module:shared`, `prosody.hosts`, MUC APIs, etc.++**Prefer integration over isolation.** When adding a new module under test,+load it on the main VirtualHost or MUC component in+`docker/prosody.cfg.lua` rather than testing it in isolation with stubs.+This exercises real module interactions (hooks fire in the correct order,+shared state is visible across modules) and catches interoperability bugs that+unit tests miss.+## Directory Structure```diff --git a/tests/prosody/docker/Dockerfile b/tests/prosody/docker/Dockerfileindex 4f395f7ce6..ae5035da8c 100644--- a/tests/prosody/docker/Dockerfile+++ b/tests/prosody/docker/Dockerfile@@ -51,3 +51,10 @@ COPY --chown=prosody:prosody tests/prosody/fixtures/test-system-asap-public.pem# reads the config for data_path and the VirtualHost definition.RUN prosodyctl register focus auth.localhost focussecret \&& chown -R prosody:prosody /var/lib/prosody++# Pre-create Jibri and transcriber accounts used by mod_muc_cleanup_backend_services tests.+# [email protected] — is_jibri() matches (starts with 'recorder@recorder.')+# [email protected] — is_transcriber() matches (starts with 'transcriber@recorder.')+RUN prosodyctl register recorder recorder.localhost recordersecret \+ && prosodyctl register transcriber recorder.localhost transcribersecret \+ && chown -R prosody:prosody /var/lib/prosodydiff --git a/tests/prosody/docker/prosody.cfg.lua b/tests/prosody/docker/prosody.cfg.luaindex db864ce8a8..0975df41be 100644--- a/tests/prosody/docker/prosody.cfg.lua+++ b/tests/prosody/docker/prosody.cfg.lua@@ -66,27 +66,33 @@ VirtualHost "localhost"-- reachable. Component HTTP routes end up on HTTPS 5281 due to Prosody's-- virtual-host routing, which does not match Host: localhost on port 5280.modules_enabled = {+ -- test-only: HTTP endpoints and census helpers"test_observer_http";"muc_size";"muc_census";+ -- Module order below follows prod (conference.8x8.vc VirtualHost) so that+ -- same-priority hook execution order matches production."conference_duration";+ "filter_iq_rayo"; -- priority 1 on pre-iq/full; listed before filter_iq_jibri (matches prod)"filter_iq_jibri";- "filter_iq_rayo";+ "muc_lobby_rooms";+ "jiconop";"muc_kick_participant";- "system_chat_message";"muc_jigasi_invite";-- Loaded here so that the global jitsi-access-ban-check event handler-- is registered and mod_auth_token can fire it for token-authenticated-- sessions. muc_prosody_jitsi_access_manager_url points at the mock-- access manager served by mod_test_observer_http on the same host."muc_auth_ban";+ -- test-only"turncredentials_http";- "jiconop";-- Rewrites MUC JIDs between external subdomain form-- ([email protected]) and internal bracket form-- ([sub][email protected]) for all sessions on all hosts."muc_domain_mapper";- "muc_lobby_rooms";+ "persistent_lobby";+ "system_chat_message";+ -- test-only"muc_password_check";}@@ -132,6 +138,16 @@ VirtualHost "auth.localhost"-- Disable SCRAM and force PLAIN (safe on loopback in the test environment).disable_sasl_mechanisms = { "SCRAM-SHA-1", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS" }+-- VirtualHost for Jibri (recorder) and transcriber accounts used by+-- mod_muc_cleanup_backend_services tests. Accounts on this domain get JIDs whose+-- bare form starts with 'recorder@recorder.' or 'transcriber@recorder.', satisfying+-- is_jibri() and is_transcriber() respectively.+-- recorder.localhost is added to muc_access_whitelist on the MUC component so+-- these clients bypass token_verification without needing JWT tokens.+VirtualHost "recorder.localhost"+ authentication = "internal_hashed"+ disable_sasl_mechanisms = { "SCRAM-SHA-1", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS" }+-- VirtualHost for HS256 (shared-secret) token auth tests and mod_presence_identity tests.VirtualHost "hs256.localhost"authentication = "token"@@ -168,22 +184,28 @@ Component "lobby.conference.localhost" "muc"muc_room_default_public_jids = trueComponent "conference.localhost" "muc"+ -- Module order follows prod (conference.8x8.vc) so that same-priority hook+ -- execution order matches production. Test-only modules are inserted at+ -- sensible positions relative to the shared modules they interact with.modules_enabled = {"muc_hide_all";+ "token_verification"; -- prod pos 2: gate check runs before meeting-id / password logic"muc_max_occupants";- "muc_meeting_id";- "muc_resource_validate";+ "muc_resource_validate"; -- test-only: occupant gate, alongside muc_max_occupants"muc_password_whitelist";- "token_verification";- "token_affiliation";+ "token_affiliation"; -- test-only: reads auth_token set by token_verification above+ "muc_meeting_id"; -- prod pos 9: after gate checks"muc_flip";- "muc_displayname";- "test_observer";+ "test_observer"; -- test-only"filter_messages";- -- Listed after filter_messages so that messages already blocked by- -- filter_messages (return true) never reach this hook; they do not- -- count toward the per-room cap.+ "muc_displayname"; -- prod pos 21: after filter_messages+ -- mod_muc_limit_messages registers its message/bare hook at priority -1+ -- (below the default 0 used by filter_messages), so filter_messages+ -- always fires first. Messages it blocks (return true) never reach+ -- muc_limit_messages and do not count toward the per-room cap."muc_limit_messages";+ -- Destroys a room after a short timeout when only Jibri/transcriber remain.+ "muc_cleanup_backend_services";}anonymous_strict = true@@ -194,7 +216,9 @@ Component "conference.localhost" "muc"-- Clients on whitelist.localhost bypass the occupant limit.-- Clients on auth.localhost are the focus (jicofo) admin; they also bypass-- the limit and are not counted against it.- muc_access_whitelist = { "whitelist.localhost", "auth.localhost" }+ -- Clients on recorder.localhost are Jibri/transcriber accounts; they bypass+ -- token_verification (is_jibri / is_transcriber JID prefix checks still apply).+ muc_access_whitelist = { "whitelist.localhost", "auth.localhost", "recorder.localhost" }-- Used by mod_muc_password_whitelist tests: clients from whitelist.localhost-- are injected with the room password and bypass the password check.@@ -208,6 +232,9 @@ Component "conference.localhost" "muc"-- token_verification on both muc-room-pre-create and muc-occupant-pre-join,-- mirroring production where jicofo is a Prosody admin.+ -- mod_muc_cleanup_backend_services: short timeout so tests don't wait 20 s.+ services_empty_meeting_timeout = 1+-- mod_muc_limit_messages: cap per room and honour auth tokens.muc_limit_messages_count = 3muc_limit_messages_check_token = true@@ -255,6 +282,30 @@ Component "metadata.localhost" "room_metadata_component"muc_mapper_domain_base = "localhost"muc_mapper_domain_prefix = "conference"+-- Component for mod_filesharing_component tests. Clients send file-sharing+-- messages here; the component looks up the room from jitsi_web_query_room+-- (set by mod_jitsi_session) and broadcasts add/remove notifications.+Component "filesharing.localhost" "filesharing_component"+ muc_component = "conference.localhost"+ muc_mapper_domain_base = "localhost"+ muc_mapper_domain_prefix = "conference"+-- Plain MUC for mod_presence_identity tests. No token verification and no-- muc_meeting_id lock so any client can join freely without focus.Component "conference-identity.localhost" "muc"++-- Isolated MUC component for mod_muc_wait_for_host tests.+-- No muc_meeting_id, so no jicofo lock — a JWT-authenticated client can join+-- directly as host without focus unlocking the room first.+-- muc_mapper_domain_base is set to "conference.localhost" so that:+-- lobby_muc_component_config = "lobby." .. "conference.localhost"+-- = "lobby.conference.localhost" (already configured above)+-- This means the existing lobby component is reused for the lobby rooms created+-- by this component, and no additional lobby MUC component is needed.+Component "conference-waitforhost.localhost" "muc"+ storage = "memory"+ modules_enabled = {+ "muc_wait_for_host";+ }+ muc_mapper_domain_base = "conference.localhost"+ muc_mapper_domain_prefix = "conference"diff --git a/tests/prosody/helpers/test_context.js b/tests/prosody/helpers/test_context.jsindex e6e56b7f1e..125d6ccd2d 100644--- a/tests/prosody/helpers/test_context.js+++ b/tests/prosody/helpers/test_context.js@@ -1,4 +1,4 @@-import { createXmppClient, joinWithFocus } from './xmpp_client.js';+import { createXmppClient, joinWithFocus, joinWithJibri, joinWithTranscriber } from './xmpp_client.js';/*** Creates a per-test context that tracks connected clients and provides@@ -54,6 +54,39 @@ export function createTestContext() {return c;},+ /**+ * Joins the room as a Jibri recorder ([email protected]).+ * The client's bare JID starts with 'recorder@recorder.' so is_jibri()+ * returns true for this client. Registers the client for cleanup.+ *+ * @param {string} roomJid full room JID, e.g. '[email protected]'+ * @returns {Promise<XmppTestClient>}+ */+ async connectJibri(roomJid) {+ const c = await joinWithJibri(roomJid);++ clients.push(c);++ return c;+ },++ /**+ * Joins the room as a transcriber ([email protected]).+ * The client's bare JID starts with 'transcriber@recorder.' so+ * is_transcriber() returns true for this client. Registers the client+ * for cleanup.+ *+ * @param {string} roomJid full room JID, e.g. '[email protected]'+ * @returns {Promise<XmppTestClient>}+ */+ async connectTranscriber(roomJid) {+ const c = await joinWithTranscriber(roomJid);++ clients.push(c);++ return c;+ },+/*** Disconnects all clients created through this context.*diff --git a/tests/prosody/helpers/test_observer.js b/tests/prosody/helpers/test_observer.jsindex 7ab3229466..5d04d56dfa 100644--- a/tests/prosody/helpers/test_observer.js+++ b/tests/prosody/helpers/test_observer.js@@ -18,13 +18,21 @@ const JIGASI_INVITE_URL = 'http://localhost:5280/invite-jigasi';* @param {number} [opts.status=200] HTTP status code to return.* Non-200 values simulate HTTP errors;* mod_muc_auth_ban fails open on errors.+ * @param {boolean} [opts.nonJson=false] When true, return a 200 with a non-JSON+ * body. Tests the nil-check bug:+ * json.decode returns nil and the module+ * must not crash on r['access'].*/-export async function setAccessManagerResponse({ access = true, status = 200 } = {}) {+export async function setAccessManagerResponse({ access = true, status = 200, nonJson = false } = {}) {const res = await fetch(ACCESS_MANAGER_URL, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ access,- status })+ body: JSON.stringify({+ access,+ status,+ // eslint-disable-next-line camelcase+ non_json: nonJson+ })});if (res.status !== 204) {@@ -77,6 +85,27 @@ export async function setHideDisplayNameForGuests(roomJid, hidden) {}}+/**+ * Sets room._data.breakout_rooms_active for mod_muc_cleanup_backend_services tests.+ * When active is true, the module skips the destroy-timer logic even if only+ * backend services remain. The room must already exist (at least one occupant).+ *+ * @param {string} roomJid e.g. '[email protected]'+ * @param {boolean} active true to simulate active breakout rooms; false to clear+ */+export async function setBreakoutRoomsActive(roomJid, active) {+ const res = await fetch(`${BASE}/rooms/breakout-rooms-active`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ jid: roomJid,+ active })+ });++ if (!res.ok) {+ throw new Error(`setBreakoutRoomsActive failed: ${res.status} ${await res.text()}`);+ }+}+/*** Sets the per-room max_occupants limit for an existing room.* The room must already exist (at least one occupant).diff --git a/tests/prosody/helpers/xmpp_client.js b/tests/prosody/helpers/xmpp_client.jsindex 84ccfd3f90..661908acf7 100644--- a/tests/prosody/helpers/xmpp_client.js+++ b/tests/prosody/helpers/xmpp_client.js@@ -2,6 +2,52 @@ import { client, xml } from '@xmpp/client';let _counter = 0;+/**+ * Connects as the Jibri recorder, joins roomJid with nick 'recorder', and+ * returns the client. Authenticates as [email protected] (internal_hashed).+ * The bare JID starts with 'recorder@recorder.' so is_jibri() returns true,+ * matching the default recorder_prefixes in util.lib.lua.+ *+ * The caller is responsible for disconnecting the returned client.+ *+ * @param {string} roomJid full room JID, e.g. '[email protected]'+ * @returns {Promise<XmppTestClient>}+ */+export async function joinWithJibri(roomJid) {+ const c = await createXmppClient({+ domain: 'recorder.localhost',+ username: 'recorder',+ password: 'recordersecret'+ });++ await c.joinRoom(roomJid, 'recorder');++ return c;+}++/**+ * Connects as the transcriber, joins roomJid with nick 'transcriber', and+ * returns the client. Authenticates as [email protected].+ * The bare JID starts with 'transcriber@recorder.' so is_transcriber() returns+ * true, matching the default transcriber_prefixes in util.lib.lua.+ *+ * The caller is responsible for disconnecting the returned client.+ *+ * @param {string} roomJid full room JID, e.g. '[email protected]'+ * @returns {Promise<XmppTestClient>}+ */+export async function joinWithTranscriber(roomJid) {+ const c = await createXmppClient({+ domain: 'recorder.localhost',+ username: 'transcriber',+ password: 'transcribersecret'+ });++ await c.joinRoom(roomJid, 'transcriber');++ return c;+}+/*** Creates an anonymous XMPP client and joins a Jigasi brewery MUC with a* colibri stats presence extension, simulating a Jigasi SIP gateway instance.@@ -425,6 +471,26 @@ export async function createXmppClient({ host = 'localhost', domain, params, usereturn this.waitForMessage(s => s.attrs.id === id);},+ /**+ * Sends a groupchat message with a <json-message> child to the room.+ * Fire-and-forget — does NOT wait for the MUC reflection stanza.+ * Use when testing hooks that may crash or block the message before it+ * is reflected (waiting for reflection would time out).+ *+ * @param {string} roomJid e.g. '[email protected]'+ * @param {object} payload JSON-serialisable value for the json-message body.+ */+ sendJsonGroupchat(roomJid, payload) {+ return xmpp.send(+ xml('message', { to: roomJid,+ type: 'groupchat',+ id: `jm-${++_counter}` },+ xml('json-message', { xmlns: 'http://jitsi.org/jitmeet' },+ JSON.stringify(payload))+ )+ );+ },+/*** Grants moderator role to the occupant identified by nick.* The caller must be the room owner (e.g. the focus client).@@ -612,6 +678,68 @@ export async function createXmppClient({ host = 'localhost', domain, params, use});},+ /**+ * Sends a file-sharing add message to a component JID.+ * The session must have jitsi_web_query_room set (connect with+ * params: { room: '<roomname>' }) for the component to locate the room.+ *+ * @param {string} componentJid e.g. 'filesharing.localhost'+ * @param {object} fileObj file descriptor; must include fileId+ */+ sendFileSharingAdd(componentJid, fileObj) {+ return xmpp.send(+ xml('message', { to: componentJid,+ id: `fs-${++_counter}` },+ xml('file-sharing', { xmlns: 'http://jitsi.org/jitmeet',+ type: 'add' },+ JSON.stringify(fileObj)+ )+ )+ );+ },++ /**+ * Sends a file-sharing remove message to a component JID.+ *+ * @param {string} componentJid e.g. 'filesharing.localhost'+ * @param {string} fileId ID of the file to remove+ */+ sendFileSharingRemove(componentJid, fileId) {+ return xmpp.send(+ xml('message', { to: componentJid,+ id: `fs-${++_counter}` },+ xml('file-sharing', { xmlns: 'http://jitsi.org/jitmeet',+ type: 'remove',+ fileId })+ )+ );+ },++ /**+ * Sends a raw file-sharing message. Use this to test malformed payloads+ * or non-standard message types (e.g. type='error').+ *+ * @param {string} componentJid e.g. 'filesharing.localhost'+ * @param {object} messageAttrs extra attributes on the outer <message>+ * @param {object} fsAttrs attributes on <file-sharing>+ * @param {string} [body] text body for <file-sharing>+ */+ sendFileSharingRaw(componentJid, messageAttrs, fsAttrs, body) {+ const fsEl = body === undefined+ ? xml('file-sharing', { xmlns: 'http://jitsi.org/jitmeet',+ ...fsAttrs })+ : xml('file-sharing', { xmlns: 'http://jitsi.org/jitmeet',+ ...fsAttrs }, body);++ return xmpp.send(+ xml('message', { to: componentJid,+ id: `fs-${++_counter}`,+ ...messageAttrs },+ fsEl+ )+ );+ },+async disconnect() {try {await xmpp.stop();diff --git a/tests/prosody/lua/jwk_spec.lua b/tests/prosody/lua/jwk_spec.luaindex e12dd468b7..39058e6228 100644--- a/tests/prosody/lua/jwk_spec.lua+++ b/tests/prosody/lua/jwk_spec.lua@@ -139,6 +139,16 @@ describe("jwk.lib", function()assert.truthy(pem:match("^-----BEGIN PUBLIC KEY-----\n"))assert.truthy(pem:match("-----END PUBLIC KEY-----\n$"))end)++ it("returns nil when n is missing", function()+ local pem = M.jwk_to_pem({ e = "Aw" })+ assert.is_nil(pem)+ end)++ it("returns nil when e is missing", function()+ local pem = M.jwk_to_pem({ n = "Dw" })+ assert.is_nil(pem)+ end)end) -- jwk_to_pemend) -- jwk.libdiff --git a/tests/prosody/lua/mod_jibri_session_spec.lua b/tests/prosody/lua/mod_jibri_session_spec.luaindex a44432a68f..8698e14c00 100644--- a/tests/prosody/lua/mod_jibri_session_spec.lua+++ b/tests/prosody/lua/mod_jibri_session_spec.lua@@ -260,10 +260,12 @@ describe("mod_jibri_session", function()-- -----------------------------------------------------------------------describe("malformed app_data", function()- it("propagates a cjson.decode error for invalid JSON in app_data", function()- local jibri = make_jibri_elem({ action = 'start', app_data = '{not valid json{{' })+ it("silently ignores invalid JSON in app_data (cjson.safe: returns nil, no throw)", function()+ local raw = '{not valid json{{'+ local jibri = make_jibri_elem({ action = 'start', app_data = raw })local session = { jitsi_meet_context_user = { id = 'user-1' } }- assert.has_error(function() hooked_fn(make_event(make_iq(jibri), session)) end)+ assert.has_no.errors(function() hooked_fn(make_event(make_iq(jibri), session)) end)+ assert.equal(raw, jibri.attr.app_data) -- unchanged: module returned earlyend)end)diff --git a/tests/prosody/mod_auth_token_asap_spec.js b/tests/prosody/mod_auth_token_asap_spec.jsindex bac734a82e..c9b42330ec 100644--- a/tests/prosody/mod_auth_token_asap_spec.js+++ b/tests/prosody/mod_auth_token_asap_spec.js@@ -2,7 +2,7 @@ import assert from 'assert';import http from 'http';import { mintAsapToken } from './helpers/jwt.js';-import { createXmppClient } from './helpers/xmpp_client.js';+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';/*** Fetches session-info for the given full JID.@@ -182,4 +182,49 @@ describe('mod_auth_token (ASAP / RS256)', () => {clients.push(c);assert.ok(c.jid, 'client should have a JID');});++ // ── Room regex claim: invalid Lua pattern ─────────────────────────────────+ //+ // When context.room.regex == true, util.lib.lua uses the JWT room claim as+ // a Lua pattern via string:match() inside verify_room() at MUC join time.+ // An invalid Lua pattern (e.g. unbalanced parenthesis) must be rejected+ // cleanly rather than crashing Prosody with a Lua error.++ it('does not crash on connect with invalid Lua regex room claim', async () => {+ // process_and_verify_token only stores the claim; it does not evaluate+ // the pattern. The crash path is verify_room(), called at MUC join.+ const token = mintAsapToken({+ room: '(invalid',+ context: { room: { regex: true } }+ });+ const c = await asapClient({ token });++ clients.push(c);+ assert.ok(c.jid, 'connection must succeed: pattern not evaluated at auth time');+ });++ it('rejects MUC join with invalid Lua regex room claim', async () => {+ const CONFERENCE = 'conference.localhost';+ const roomJid = `regex-invalid-${Date.now()}@${CONFERENCE}`;++ // '(invalid' is an unbalanced Lua pattern capture — string:match() would+ // raise "unfinished capture" without the pcall guard in verify_room().+ const token = mintAsapToken({+ room: '(invalid',+ context: { room: { regex: true } }+ });++ const focus = await joinWithFocus(roomJid);+ const c = await asapClient({ token });++ clients.push(focus, c);++ const presence = await c.joinRoom(roomJid);++ assert.equal(presence.attrs.type, 'error', 'join must be rejected');+ assert.ok(+ presence.getChild('error')?.getChild('invalid-regex'),+ 'error must contain <invalid-regex/>'+ );+ });});diff --git a/tests/prosody/mod_filesharing_component_spec.js b/tests/prosody/mod_filesharing_component_spec.jsnew file mode 100644index 0000000000..0190a132fc--- /dev/null+++ b/tests/prosody/mod_filesharing_component_spec.js@@ -0,0 +1,476 @@+/**+ * Integration tests for mod_filesharing_component.+ *+ * The module runs as a Prosody component (filesharing.localhost). Clients send+ * <file-sharing xmlns='http://jitsi.org/jitmeet' type='add|remove'> messages+ * to it; the component looks up the room from jitsi_web_query_room (set by+ * mod_jitsi_session from the ?room= WebSocket URL parameter), validates that+ * the sender is a room occupant, applies a feature gate, and then:+ *+ * add — stores the file in room.jitsi_shared_files and broadcasts a+ * json-message with event='add' to all non-admin, non-sender occupants.+ * remove — deletes the file from room.jitsi_shared_files and broadcasts+ * event='remove' to all non-admin, non-sender occupants.+ *+ * When a new occupant joins a room that already has shared files, the+ * muc-occupant-joined hook sends them a json-message with event='list'+ * containing the current file set.+ *+ * Author fields (authorParticipantId, authorParticipantJid, authorParticipantName)+ * in add payloads are overwritten by Prosody from the real session state,+ * preventing clients from spoofing each other's identity.+ *+ * Feature gate: the sender must have jitsi_meet_context_features containing+ * file-upload=true. The is_owner fallback in is_feature_allowed is effectively+ * unreachable in this environment because mod_jitsi_permissions (auto-loaded by+ * muc_meeting_id) always sets at least default_permissions on moderator sessions,+ * making jitsi_meet_context_features truthy before the fallback is evaluated.+ */++import assert from 'assert';++import { setRoomMaxOccupants, setSessionContext } from './helpers/test_observer.js';+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';++const CONFERENCE = 'conference.localhost';+const FILESHARING_COMPONENT = 'filesharing.localhost';+const JITMEET_NS = 'http://jitsi.org/jitmeet';++let _counter = 0;+const nextRoom = () => `fs-${++_counter}@${CONFERENCE}`;++// ── Helpers ───────────────────────────────────────────────────────────────────++/**+ * Connects an anonymous client on the main VirtualHost with ?room=<roomName>+ * so that mod_jitsi_session sets jitsi_web_query_room. The filesharing+ * component requires this field before processing any message.+ *+ * @param {string} roomJid full room JID, e.g. '[email protected]'+ * @returns {Promise<XmppTestClient>}+ */+function connect(roomJid) {+ const roomName = roomJid.split('@')[0];++ return createXmppClient({ params: { room: roomName } });+}++/**+ * Returns true when stanza is a filesharing broadcast from the component+ * (a <message> carrying a <json-message xmlns='http://jitsi.org/jitmeet'> child).+ *+ * @param {object} stanza+ */+function isFilesharingBroadcast(stanza) {+ return stanza.name === 'message'+ && stanza.attrs.from === FILESHARING_COMPONENT+ && stanza.getChild('json-message', JITMEET_NS) !== undefined;+}++/**+ * Parses the JSON payload from a filesharing broadcast stanza.+ * Returns the decoded object: { type, event, file?, files?, fileId? }+ *+ * @param {object} stanza+ * @returns {object|null}+ */+function parseBroadcast(stanza) {+ const text = stanza.getChild('json-message', JITMEET_NS)?.getText();++ return text ? JSON.parse(text) : null;+}++/**+ * Waits for a filesharing broadcast stanza on the given client.+ *+ * @param {object} client+ * @param {number} [timeout=3000]+ * @returns {Promise<object>}+ */+function waitForFilesharing(client, timeout = 3000) {+ return client.waitForMessage(isFilesharingBroadcast, timeout);+}++/**+ * Asserts that no filesharing broadcast arrives within the given window.+ * Throws if one does arrive.+ *+ * @param {object} client+ * @param {number} [timeout=1000]+ */+async function assertNoFilesharing(client, timeout = 1000) {+ try {+ await client.waitForMessage(isFilesharingBroadcast, timeout);+ throw new Error('received unexpected filesharing broadcast');+ } catch (err) {+ if (err.message.includes('Timeout')) {+ return; // expected — no broadcast+ }+ throw err;+ }+}++// ── Tests ─────────────────────────────────────────────────────────────────────++describe('mod_filesharing_component', () => {++ const clients = [];++ afterEach(async () => {+ await Promise.all(clients.map(c => c.disconnect()));+ clients.length = 0;+ });++ // ── add file ──────────────────────────────────────────────────────────────++ describe('add file', () => {++ it('broadcasts add event to other occupants', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);+ const receiver = await connect(r);++ clients.push(foc, sender, receiver);+ await sender.joinRoom(r);+ await receiver.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1',+ name: 'test.pdf' });++ const broadcast = await waitForFilesharing(receiver);+ const payload = parseBroadcast(broadcast);++ assert.equal(payload.type, 'file-sharing');+ assert.equal(payload.event, 'add');+ assert.equal(payload.file.fileId, 'file1');+ });++ it('does not send broadcast back to sender', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);+ const receiver = await connect(r);++ clients.push(foc, sender, receiver);+ await sender.joinRoom(r);+ await receiver.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1',+ name: 'test.pdf' });++ // Wait for receiver to confirm Prosody processed the add, then+ // assert sender received nothing.+ await waitForFilesharing(receiver);+ await assertNoFilesharing(sender);+ });++ it('does not send broadcast to admin (focus)', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);++ clients.push(foc, sender);+ await sender.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1',+ name: 'test.pdf' });++ await assertNoFilesharing(foc);+ });++ it('overwrites author fields to prevent spoofing', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);+ const receiver = await connect(r);++ clients.push(foc, sender, receiver);+ await sender.joinRoom(r);+ await receiver.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, {+ fileId: 'file1',+ authorParticipantId: 'FAKE_ID',+ authorParticipantJid: '[email protected]'+ });++ const { file } = parseBroadcast(await waitForFilesharing(receiver));++ assert.notEqual(file.authorParticipantId, 'FAKE_ID',+ 'authorParticipantId must be overwritten by Prosody');+ assert.notEqual(file.authorParticipantJid, '[email protected]',+ 'authorParticipantJid must be overwritten by Prosody');+ assert.ok(file.authorParticipantId, 'authorParticipantId must be set');+ assert.ok(file.authorParticipantJid, 'authorParticipantJid must be set');+ });++ });++ // ── remove file ───────────────────────────────────────────────────────────++ describe('remove file', () => {++ it('broadcasts remove event to other occupants', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);+ const receiver = await connect(r);++ clients.push(foc, sender, receiver);+ await sender.joinRoom(r);+ await receiver.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });++ // Add first, wait for add broadcast to confirm it landed.+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1',+ name: 'test.pdf' });+ await waitForFilesharing(receiver);++ // Now remove.+ sender.sendFileSharingRemove(FILESHARING_COMPONENT, 'file1');++ const broadcast = await waitForFilesharing(receiver);+ const payload = parseBroadcast(broadcast);++ assert.equal(payload.type, 'file-sharing');+ assert.equal(payload.event, 'remove');+ assert.equal(payload.fileId, 'file1');+ });++ it('removed file is not delivered to subsequent joiners', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);++ // Raise the limit: need sender + watcher + late joiner (3 regular occupants).+ await setRoomMaxOccupants(r, 10);++ const sender = await connect(r);+ const watcher = await connect(r);++ clients.push(foc, sender, watcher);+ await sender.joinRoom(r);+ await watcher.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });++ // Add then remove — observe both broadcasts on watcher so we know+ // Prosody has fully processed them before the late joiner connects.+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1',+ name: 'test.pdf' });+ await waitForFilesharing(watcher);++ sender.sendFileSharingRemove(FILESHARING_COMPONENT, 'file1');+ await waitForFilesharing(watcher);++ const late = await connect(r);++ clients.push(late);+ await late.joinRoom(r);++ await assertNoFilesharing(late);+ });++ });++ // ── new joiner receives file list ─────────────────────────────────────────++ describe('new joiner receives file list', () => {++ it('joiner receives list of existing files', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);++ // Raise the limit: need sender + watcher + late joiner (3 regular occupants).+ await setRoomMaxOccupants(r, 10);++ const sender = await connect(r);+ const watcher = await connect(r);++ clients.push(foc, sender, watcher);+ await sender.joinRoom(r);+ await watcher.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });++ // Add a file and wait for it to land before the late joiner connects.+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1',+ name: 'test.pdf' });+ await waitForFilesharing(watcher);++ const late = await connect(r);++ clients.push(late);+ await late.joinRoom(r);++ const broadcast = await waitForFilesharing(late);+ const payload = parseBroadcast(broadcast);++ assert.equal(payload.type, 'file-sharing');+ assert.equal(payload.event, 'list');+ assert.ok(payload.files?.file1, 'file list must include the added file');+ });++ it('joiner receives nothing when no files have been shared', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const first = await connect(r);+ const late = await connect(r);++ clients.push(foc, first, late);+ await first.joinRoom(r);+ await late.joinRoom(r);++ await assertNoFilesharing(late);+ });++ });++ // ── authorization ─────────────────────────────────────────────────────────++ describe('authorization', () => {++ it('non-occupant message is silently ignored', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const nonOccupant = await connect(r); // connected but NOT joined+ const receiver = await connect(r);++ clients.push(foc, nonOccupant, receiver);+ await receiver.joinRoom(r);++ await setSessionContext(nonOccupant.jid, 'user-a', { 'file-upload': true });+ nonOccupant.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1' });++ await assertNoFilesharing(receiver);+ });++ it('message without jitsi_web_query_room is silently ignored', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const noRoom = await createXmppClient(); // no ?room= param+ const receiver = await connect(r);++ clients.push(foc, noRoom, receiver);+ await receiver.joinRoom(r);++ noRoom.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1' });++ await assertNoFilesharing(receiver);+ });++ it('non-owner with no token features receives forbidden error', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const member = await connect(r);++ clients.push(foc, member);+ await member.joinRoom(r);++ // No setSessionContext — no features, member affiliation.++ member.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1' });++ const err = await member.waitForMessage(s => s.attrs.type === 'error', 3000);++ assert.equal(err.attrs.type, 'error');+ assert.ok(+ err.getChild('error')?.getChild('forbidden'),+ 'expected <forbidden/> in error stanza'+ );+ });++ it('client with file-upload feature can add file', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);+ const receiver = await connect(r);++ clients.push(foc, sender, receiver);+ await sender.joinRoom(r);+ await receiver.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, { fileId: 'file1',+ name: 'test.pdf' });++ const broadcast = await waitForFilesharing(receiver);++ assert.equal(parseBroadcast(broadcast).event, 'add');+ });++ });++ // ── invalid payloads ──────────────────────────────────────────────────────++ describe('invalid payloads', () => {++ it('add without fileId in JSON body is dropped silently', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);+ const receiver = await connect(r);++ clients.push(foc, sender, receiver);+ await sender.joinRoom(r);+ await receiver.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });+ sender.sendFileSharingAdd(FILESHARING_COMPONENT, { name: 'no-id.pdf' }); // no fileId++ await assertNoFilesharing(receiver);+ });++ it('remove without fileId attribute is dropped silently', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);+ const receiver = await connect(r);++ clients.push(foc, sender, receiver);+ await sender.joinRoom(r);+ await receiver.joinRoom(r);++ await setSessionContext(sender.jid, 'user-a', { 'file-upload': true });++ // Remove stanza with no fileId attribute — the module logs an error+ // and returns true without firing any event.+ sender.sendFileSharingRaw(FILESHARING_COMPONENT, {}, { type: 'remove' });++ await assertNoFilesharing(receiver);+ });++ it('error-type message is ignored without triggering a reply', async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const sender = await connect(r);++ clients.push(foc, sender);+ await sender.joinRoom(r);++ // type='error' stanzas must be silently dropped (early return in on_message).+ sender.sendFileSharingRaw(+ FILESHARING_COMPONENT,+ { type: 'error' },+ { type: 'add' },+ JSON.stringify({ fileId: 'f1' })+ );++ // Module must not reply with another error (would cause a loop).+ try {+ await sender.waitForMessage(s => s.attrs.type === 'error', 1000);+ assert.fail('received unexpected error reply to error stanza');+ } catch (err) {+ assert.ok(err.message.includes('Timeout'),+ `unexpected error: ${err.message}`);+ }+ });++ });++});diff --git a/tests/prosody/mod_filter_iq_jibri_spec.js b/tests/prosody/mod_filter_iq_jibri_spec.jsindex c57f20f1c0..3163375ca9 100644--- a/tests/prosody/mod_filter_iq_jibri_spec.js+++ b/tests/prosody/mod_filter_iq_jibri_spec.js@@ -188,6 +188,67 @@ describe('mod_filter_iq_jibri (feature-based authorization)', () => {});});+ // ─── robustness: nil room ─────────────────────────────────────────────────+ //+ // mod_filter_iq_jibri calls get_room_from_jid() on the IQ target and then+ // immediately dereferences the result with room:get_occupant_by_real_jid().+ // If the room does not exist, get_room_from_jid returns nil and the next+ // line crashes. This test verifies the session survives such an IQ.++ describe('robustness', () => {++ it('session survives a Jibri start IQ targeting a non-existent room', async () => {+ // We need a connected client but the IQ target room must never have+ // been created. Use a wildcard token so the connection is accepted.+ const token = mintAsapToken({ room: '*' });+ const c = await createXmppClient({ params: { token } });++ clients.push(c);++ // Target a room that has never been created — get_room_from_jid+ // returns nil, which would crash room:get_occupant_by_real_jid.+ const ghost = '[email protected]';++ await clearJibriIqs();+ await c.sendJibriIq(ghost, 'start', 'file');++ // Give Prosody time to process the stanza.+ await new Promise(r => setTimeout(r, 400));++ // If the hook crashed and killed the session this resolves immediately;+ // we expect it to time out (session still alive).+ const disconnected = await c.waitForDisconnect(400).then(() => true, () => false);++ assert.strictEqual(disconnected, false,+ 'client session must remain alive after IQ to non-existent room');+ });++ it('returns item-not-found error reply for Jibri IQ targeting a non-existent room', async () => {+ // When the room does not exist, get_room_from_jid should return <item-not-found/> (as opposed to nil which+ // may be returned if an internal error is triggered).+ const token = mintAsapToken({ room: '*' });+ const c = await createXmppClient({ params: { token } });++ clients.push(c);++ const ghost = '[email protected]';++ await c.sendJibriIq(ghost, 'start', 'file');++ const reply = await c.waitForIq(s => s.attrs.type === 'error', 2000);++ assert.strictEqual(reply.attrs.type, 'error');+ const error = reply.getChild('error');++ assert.ok(error, 'expected <error/> child in IQ reply');+ assert.ok(+ error.getChild('item-not-found'),+ 'expected <item-not-found/> error condition — room does not exist'+ );+ });++ });+// ─── attribute case normalisation ────────────────────────────────────────describe('attribute case normalisation', () => {diff --git a/tests/prosody/mod_muc_auth_ban_spec.js b/tests/prosody/mod_muc_auth_ban_spec.jsindex 291ab6b3d2..e60675271f 100644--- a/tests/prosody/mod_muc_auth_ban_spec.js+++ b/tests/prosody/mod_muc_auth_ban_spec.js@@ -1,5 +1,6 @@import assert from 'assert';+import { getContainer } from './helpers/container.js';import { mintAsapToken } from './helpers/jwt.js';import { setAccessManagerResponse } from './helpers/test_observer.js';import { createXmppClient } from './helpers/xmpp_client.js';@@ -166,4 +167,72 @@ describe('mod_muc_auth_ban', () => {await c.disconnect();});+ // ── Non-JSON 200 — should fail open without crashing ─────────────────────+ //+ // When the access manager returns HTTP 200 but with a non-JSON body,+ // json.decode() returns nil. mod_muc_auth_ban then calls r['access'] on+ // nil, which crashes the callback. The crash must not affect the session+ // (fail open: user stays connected).++ it('non-JSON 200 from access manager does not crash or ban the user (fail open)', async () => {+ await setAccessManagerResponse({ nonJson: true });++ const token = freshToken();+ const c = await createVpaasClient(token);++ // Wait long enough for the async HTTP callback to have fired and crashed.+ await new Promise(resolve => setTimeout(resolve, 500));++ // Session must still be alive despite the callback crash.+ const disconnected = await c.waitForDisconnect(300).then(() => true, () => false);++ assert.strictEqual(disconnected, false,+ 'session must remain alive when access manager returns non-JSON 200');++ await c.disconnect();+ });++ // ── Non-JSON 200 — Lua error in callback ─────────────────────────────────+ //+ // cjson.safe returns nil (not an error) for invalid JSON, so json.decode()+ // returns nil when the access manager body is not JSON. Without a nil guard,+ // r['access'] on the nil value crashes the callback with "attempt to index+ // a nil value". This test catches that crash by asserting that no such error+ // appears in the Prosody log during the test window.++ it('non-JSON 200 does not produce a Lua error in the HTTP callback', async () => {+ const since = Math.floor(Date.now() / 1000);++ await setAccessManagerResponse({ nonJson: true });+ const token = freshToken();+ const c = await createVpaasClient(token);++ // Give the async HTTP callback time to fire (and crash if the bug is present).+ await new Promise(resolve => setTimeout(resolve, 600));+ await c.disconnect();++ // Collect Prosody log output from this test's window.+ const until = Math.floor(Date.now() / 1000) + 1;+ const container = getContainer();+ const stream = await container.logs({ since,+ until });+ const logs = await new Promise((resolve, reject) => {+ const chunks = [];+ const timer = setTimeout(() => resolve(chunks.join('')), 2000);++ stream.on('data', chunk => chunks.push(chunk.toString()));+ stream.on('end', () => {+ clearTimeout(timer);+ resolve(chunks.join(''));+ });+ stream.on('error', reject);+ });++ assert.ok(+ !logs.includes('attempt to index a nil value'),+ 'mod_muc_auth_ban HTTP callback must not crash on non-JSON 200 response '+ + '(missing nil guard on json.decode result)'+ );+ });+});diff --git a/tests/prosody/mod_muc_cleanup_backend_services_spec.js b/tests/prosody/mod_muc_cleanup_backend_services_spec.jsnew file mode 100644index 0000000000..27cec03f0e--- /dev/null+++ b/tests/prosody/mod_muc_cleanup_backend_services_spec.js@@ -0,0 +1,165 @@+import assert from 'assert';++import { createTestContext } from './helpers/test_context.js';+import { getRoomState, setBreakoutRoomsActive } from './helpers/test_observer.js';++const CONFERENCE = 'conference.localhost';++let _roomCounter = 0;+const room = () => `cleanup-svc-${++_roomCounter}@${CONFERENCE}`;++/** Resolves after ms milliseconds. */+const sleep = ms => new Promise(r => setTimeout(r, ms));++// services_empty_meeting_timeout is set to 1 s in prosody.cfg.lua.+// We wait TIMER_MS + BUFFER_MS to be sure the timer has either fired or not.+const TIMER_MS = 1000;+const BUFFER_MS = 1000;++describe('mod_muc_cleanup_backend_services', () => {+ let ctx;++ beforeEach(() => {+ ctx = createTestContext();+ });++ afterEach(() => ctx.cleanup());++ it('destroys room when last regular user leaves and only jibri remains', async () => {+ const r = room();++ await ctx.connectFocus(r);+ await ctx.connectJibri(r);+ const user = await ctx.connect();++ await user.joinRoom(r);+ await user.disconnect();++ await sleep(TIMER_MS + BUFFER_MS);++ const state = await getRoomState(r);++ assert.equal(state, null, 'room should be destroyed after timeout');+ });++ it('destroys room when last regular user leaves and only transcriber remains', async () => {+ const r = room();++ await ctx.connectFocus(r);+ await ctx.connectTranscriber(r);+ const user = await ctx.connect();++ await user.joinRoom(r);+ await user.disconnect();++ await sleep(TIMER_MS + BUFFER_MS);++ const state = await getRoomState(r);++ assert.equal(state, null, 'room should be destroyed after timeout');+ });++ it('does not destroy room when a second regular user is still present', async () => {+ const r = room();++ await ctx.connectFocus(r);+ await ctx.connectJibri(r);+ const user1 = await ctx.connect();+ const user2 = await ctx.connect();++ await user1.joinRoom(r);+ await user2.joinRoom(r);+ await user1.disconnect();++ await sleep(TIMER_MS + BUFFER_MS);++ const state = await getRoomState(r);++ assert.ok(state, 'room should still exist — user2 is still a regular participant');+ });++ it('cancels the destroy timer when a regular user joins after timer starts', async () => {+ const r = room();++ await ctx.connectFocus(r);+ await ctx.connectJibri(r);+ const user = await ctx.connect();++ await user.joinRoom(r);++ // user leaves — timer starts counting down+ await user.disconnect();++ // a new regular user joins immediately, which must cancel the timer+ const user2 = await ctx.connect();++ await user2.joinRoom(r);++ await sleep(TIMER_MS + BUFFER_MS);++ const state = await getRoomState(r);++ assert.ok(state, 'room should survive — destroy timer was cancelled by user2 joining');+ });++ it('does not start timer when jibri leaves and a regular user is still present', async () => {+ const r = room();++ await ctx.connectFocus(r);+ const jibri = await ctx.connectJibri(r);+ const user = await ctx.connect();++ await user.joinRoom(r);++ // jibri leaves — muc-occupant-left hook returns early (leaver is jibri)+ await jibri.disconnect();++ await sleep(TIMER_MS + BUFFER_MS);++ const state = await getRoomState(r);++ assert.ok(state, 'room should survive — timer is not started when jibri is the leaver');+ });++ it('does not start timer when focus (admin) leaves', async () => {+ const r = room();++ const focus = await ctx.connectFocus(r);++ await ctx.connectJibri(r);+ const user = await ctx.connect();++ await user.joinRoom(r);++ // admin leaves — muc-occupant-left hook returns early (leaver is admin)+ await focus.disconnect();++ await sleep(TIMER_MS + BUFFER_MS);++ const state = await getRoomState(r);++ assert.ok(state, 'room should survive — timer is not started when an admin leaves');+ });++ it('does not start timer when breakout rooms are active', async () => {+ const r = room();++ await ctx.connectFocus(r);+ await ctx.connectJibri(r);+ const user = await ctx.connect();++ await user.joinRoom(r);++ // Simulate active breakout rooms — hook returns early when this flag is set.+ await setBreakoutRoomsActive(r, true);++ // user leaves — would normally start the timer, but breakout_rooms_active prevents it+ await user.disconnect();++ await sleep(TIMER_MS + BUFFER_MS);++ const state = await getRoomState(r);++ assert.ok(state, 'room should survive — breakout_rooms_active prevents the destroy timer');+ });+});diff --git a/tests/prosody/mod_muc_jigasi_invite_spec.js b/tests/prosody/mod_muc_jigasi_invite_spec.jsindex 2691e99a2f..1d7d20723b 100644--- a/tests/prosody/mod_muc_jigasi_invite_spec.js+++ b/tests/prosody/mod_muc_jigasi_invite_spec.js@@ -2,7 +2,7 @@ import assert from 'assert';import { mintAsapToken, mintSystemToken } from './helpers/jwt.js';import { inviteJigasi } from './helpers/test_observer.js';-import { joinWithFocus, joinWithJigasi } from './helpers/xmpp_client.js';+import { createXmppClient, joinWithFocus, joinWithJigasi } from './helpers/xmpp_client.js';const CONFERENCE = 'conference.localhost';@@ -194,6 +194,43 @@ describe('mod_muc_jigasi_invite', () => {const BREWERY = '[email protected]';+ it('returns 404 when brewery occupant has no stats element', async () => {+ // Bug: stats_child:children() crashed when stats element absent.+ // Fixed: occupants without stats are now skipped with a warn log.+ const { roomJid, focus } = await createRoom();++ // Join brewery without any colibri stats extensions.+ const noStats = await createXmppClient();++ await noStats.joinRoom(BREWERY);++ try {+ const { status } = await inviteJigasi(roomJid, '+15550000001', mintSystemToken());++ assert.strictEqual(status, 404,+ 'must return 404 (no eligible Jigasi) not crash');+ } finally {+ await disconnectAll(focus, noStats);+ }+ });++ it('returns 404 when no SIP-capable Jigasi is in the brewery', async () => {+ // Bug: log line accessed least_stressed_jigasi_occupant.jid before+ // the nil check, crashing when all occupants have supports_sip=false.+ // Fixed: nil check moved before the log.+ const { roomJid, focus } = await createRoom();+ const nonSip = await joinWithJigasi(BREWERY, undefined, { supportsSip: false });++ try {+ const { status } = await inviteJigasi(roomJid, '+15550000002', mintSystemToken());++ assert.strictEqual(status, 404,+ 'must return 404 (no SIP Jigasi) not crash');+ } finally {+ await disconnectAll(focus, nonSip);+ }+ });+it('sends a Rayo dial IQ to the Jigasi and returns 200', async () => {const { roomJid, focus } = await createRoom();const jigasi = await joinWithJigasi(BREWERY);diff --git a/tests/prosody/mod_muc_limit_messages_spec.js b/tests/prosody/mod_muc_limit_messages_spec.jsindex 6ed1db5337..6a73773182 100644--- a/tests/prosody/mod_muc_limit_messages_spec.js+++ b/tests/prosody/mod_muc_limit_messages_spec.js@@ -295,18 +295,19 @@ describe('mod_muc_limit_messages', () => {'anonymous sender must still hit the cap with check_token=true');});- // ── priority-race regression detector ─────────────────────────────────────+ // ── filter_messages fires before muc_limit_messages (priority guard) ────────//- // mod_filter_messages and mod_muc_limit_messages both hook message/bare at- // the default priority (0). Lua's table.sort is not stable for equal keys,- // so the firing order is non-deterministic across Prosody restarts (but- // fixed for the lifetime of a single Prosody process).+ // mod_filter_messages hooks message/bare at the default priority (0).+ // mod_muc_limit_messages hooks message/bare at priority -1 (explicit).+ // Higher priority fires first in Prosody, so filter_messages always runs+ // before muc_limit_messages — the order is deterministic and does not depend+ // on module load order or Prosody's internal sort stability.//- // When muc_limit_messages fires first it increments the room counter before- // filter_messages swallows the message, so the LIMIT blocked messages- // silently exhaust the cap. The very next real message then trips it.+ // Regression guard: if muc_limit_messages ever reverts to the default+ // priority (0) the ordering becomes non-deterministic and blocked messages+ // could silently exhaust the cap.- it('[race] muc_limit_messages must not count messages already blocked by filter_messages', async () => {+ it('muc_limit_messages must not count messages already blocked by filter_messages', async () => {const r = nextRoom();const focus = await joinWithFocus(r);const mod = await connectModerator(r);@@ -316,32 +317,31 @@ describe('mod_muc_limit_messages', () => {await mod.joinRoom(r);await anon.joinRoom(r);- // Restrict chat; filter_messages should swallow every anon message.+ // Restrict chat; filter_messages (priority 0) swallows every anon message+ // before muc_limit_messages (priority -1) can increment the counter.await restrictChat(mod, r);- // Send exactly LIMIT messages. If muc_limit_messages runs first on all- // of them the counter hits the cap without any real message delivered.+ // Send exactly LIMIT messages — all blocked by filter_messages; the room+ // counter must stay at zero.for (let i = 0; i < LIMIT; i++) {await anon.sendGroupchat(r, `blocked ${i + 1}`);}await unrestrictChat(mod, r);- // With correct ordering the counter is still 0 and this passes.- // With the race the counter is already LIMIT, this triggers the cap- // and is rejected with <not-allowed/>.+ // Counter is still 0, so this message must pass through.const reply = await anon.sendGroupchat(r, 'should pass');assert.notEqual(reply.attrs.type, 'error',- 'race: muc_limit_messages counted filter_messages-blocked messages');+ 'muc_limit_messages must not count messages blocked by filter_messages');});// ── filter_messages × muc_limit_messages hook-ordering interaction ────────//- // filter_messages is listed before muc_limit_messages in modules_enabled so- // its message/bare hook fires first. When filter_messages blocks a message it- // returns true, ending the hook chain — muc_limit_messages never runs and the- // room counter is not incremented. Verifies correct ordering.+ // mod_muc_limit_messages registers its message/bare hook at priority -1 so+ // that modules at the default priority (0) — including filter_messages — run+ // first. When filter_messages blocks a message (returns true) the hook chain+ // ends; muc_limit_messages never runs and the room counter is not incremented.it('messages blocked by filter_messages do not count toward the cap', async () => {const r = nextRoom();diff --git a/tests/prosody/mod_muc_meeting_id_spec.js b/tests/prosody/mod_muc_meeting_id_spec.jsindex 507abe0c26..3739a3a00f 100644--- a/tests/prosody/mod_muc_meeting_id_spec.js+++ b/tests/prosody/mod_muc_meeting_id_spec.js@@ -1,6 +1,7 @@import assert from 'assert';import { createTestContext } from './helpers/test_context.js';+import { joinWithTranscriber } from './helpers/xmpp_client.js';import { isAvailablePresence } from './helpers/xmpp_utils.js';const CONFERENCE = 'conference.localhost';@@ -53,6 +54,77 @@ describe('mod_muc_meeting_id', () => {// users arrive after the room is unlocked.});+ // -------------------------------------------------------------------------+ // transcription filter robustness+ // -------------------------------------------------------------------------+ //+ // filterTranscriptionResult() in mod_muc_meeting_id processes groupchat+ // messages from transcribers. Two nil-deref bugs exist:+ // 1. transcript[1].text crashes when transcript is an empty array.+ // 2. participant.id crashes when the participant field is absent.+ // Both are reached only from transcriber JIDs (is_transcriber() guard).+ // Tests verify the session survives both malformed payloads.++ describe('transcription filter robustness', () => {++ it('session survives a transcription-result with an empty transcript array', async () => {+ const r = room();++ await ctx.connectFocus(r);+ const transcriber = await joinWithTranscriber(r);++ try {+ // transcript: [] → transcript[1] is nil → .text crashes+ await transcriber.sendJsonGroupchat(r, {+ type: 'transcription-result',+ transcript: [],+ participant: { id: 'p1',+ name: 'Alice' },+ // eslint-disable-next-line camelcase+ is_interim: false+ });++ await new Promise(resolve => setTimeout(resolve, 400));++ const disconnected = await transcriber.waitForDisconnect(300)+ .then(() => true, () => false);++ assert.strictEqual(disconnected, false,+ 'transcriber session must survive empty transcript array');+ } finally {+ await transcriber.disconnect();+ }+ });++ it('session survives a transcription-result with a missing participant field', async () => {+ const r = room();++ await ctx.connectFocus(r);+ const transcriber = await joinWithTranscriber(r);++ try {+ // participant absent → participant.id crashes+ await transcriber.sendJsonGroupchat(r, {+ type: 'transcription-result',+ transcript: [ { text: 'hello world' } ],+ // eslint-disable-next-line camelcase+ is_interim: false+ });++ await new Promise(resolve => setTimeout(resolve, 400));++ const disconnected = await transcriber.waitForDisconnect(300)+ .then(() => true, () => false);++ assert.strictEqual(disconnected, false,+ 'transcriber session must survive missing participant field');+ } finally {+ await transcriber.disconnect();+ }+ });++ });+// -------------------------------------------------------------------------// health check rooms// -------------------------------------------------------------------------diff --git a/tests/prosody/mod_muc_wait_for_host_spec.js b/tests/prosody/mod_muc_wait_for_host_spec.jsnew file mode 100644index 0000000000..6115623f48--- /dev/null+++ b/tests/prosody/mod_muc_wait_for_host_spec.js@@ -0,0 +1,213 @@+import assert from 'assert';++import { mintAsapToken } from './helpers/jwt.js';+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';+import { isAvailablePresence } from './helpers/xmpp_utils.js';++// Uses a dedicated MUC component that has muc_wait_for_host loaded and no+// muc_meeting_id, so there is no jicofo lock — a JWT-authenticated client can+// join and create a room directly without focus unlocking it first.+// muc_mapper_domain_base = "conference.localhost" causes muc_wait_for_host to+// use lobby.conference.localhost as the lobby component.+const CONFERENCE = 'conference-waitforhost.localhost';+const MUC_NS = 'http://jabber.org/protocol/muc#user';++let _roomCounter = 0;+const room = () => `wfh-${++_roomCounter}@${CONFERENCE}`;++describe('mod_muc_wait_for_host', () => {++ let clients;++ beforeEach(() => {+ clients = [];+ });++ afterEach(async () => {+ await Promise.all(clients.map(c => c.disconnect()));+ });++ /**+ * Connects an anonymous client and registers it for cleanup.+ * @param {object} [opts] Options forwarded to createXmppClient.+ * @returns {Promise<XmppTestClient>}+ */+ async function connect(opts) {+ const c = await createXmppClient(opts);++ clients.push(c);++ return c;+ }++ /**+ * Joins as focus (jicofo admin) and registers the client for cleanup.+ * @param {string} roomJid Full room JID.+ * @returns {Promise<XmppTestClient>}+ */+ async function focusJoin(roomJid) {+ const c = await joinWithFocus(roomJid);++ clients.push(c);++ return c;+ }++ /**+ * Connects as a JWT-authenticated user. The session receives auth_token,+ * making it recognised as a host by muc_wait_for_host.+ *+ * @param {string} roomName Local part of the room JID (e.g. 'wfh-1').+ * @returns {Promise<XmppTestClient>}+ */+ async function connectAsHost(roomName) {+ const token = mintAsapToken({ room: roomName });+ const c = await createXmppClient({ params: { token } });++ clients.push(c);++ return c;+ }++ // -------------------------------------------------------------------------+ // No host present — lobby gate+ // -------------------------------------------------------------------------+ describe('no host present', () => {++ it('guest is blocked with registration-required', async () => {+ const r = room();++ // Focus creates and unlocks the room first. Without this the guest+ // would be the room creator and Prosody grants creators a free pass+ // (XEP-0045 §10.1.3 locked-room bypass) regardless of members_only.+ await focusJoin(r);++ const guest = await connect();+ const presence = await guest.joinRoom(r);++ assert.equal(presence.attrs.type, 'error', 'join must be rejected');+ assert.ok(+ presence.getChild('error')?.getChild('registration-required'),+ 'error condition must be registration-required'+ );+ });++ it('focus joining does not satisfy the host requirement', async () => {+ const r = room();++ // Focus is a Prosody admin and bypasses the pre-join check, so it+ // joins successfully. But it is not counted as an authenticated host,+ // so the next anonymous guest should still be blocked.+ await focusJoin(r);++ const guest = await connect();+ const presence = await guest.joinRoom(r);++ assert.equal(presence.attrs.type, 'error',+ 'join must be rejected even when focus is in the room');+ assert.ok(+ presence.getChild('error')?.getChild('registration-required'),+ 'error condition must be registration-required'+ );+ });+ });++ // -------------------------------------------------------------------------+ // Host present — guests admitted+ // -------------------------------------------------------------------------+ describe('host present', () => {++ it('guest is admitted when a JWT host has already joined', async () => {+ const r = room();+ const roomName = r.split('@')[0];++ const host = await connectAsHost(roomName);++ await host.joinRoom(r);++ const guest = await connect();+ const presence = await guest.joinRoom(r);++ assert.ok(isAvailablePresence(presence),+ 'guest should be admitted after JWT host joins');+ });++ it('room.has_host is cached: guest is admitted after the host leaves', async () => {+ const r = room();+ const roomName = r.split('@')[0];++ const host = await connectAsHost(roomName);++ await host.joinRoom(r);++ // A guest joins while the host is present. This sets room.has_host = true+ // via the existing-occupants loop in muc-occupant-pre-join.+ const guest1 = await connect();++ await guest1.joinRoom(r);++ // Host leaves. guest1 remains, keeping the room alive.+ await host.disconnect();++ // A new guest should still join because room.has_host is cached.+ const guest2 = await connect();+ const presence = await guest2.joinRoom(r);++ assert.ok(isAvailablePresence(presence),+ 'guest should join after host leaves because room.has_host is cached');+ });+ });++ // -------------------------------------------------------------------------+ // Host arrives after lobby is triggered+ // -------------------------------------------------------------------------++ it('JWT host arriving after lobby is triggered opens the room for new guests', async () => {+ const r = room();+ const roomName = r.split('@')[0];++ // Focus creates and unlocks the room so the guest is not the creator+ // (XEP-0045 locked-room bypass would otherwise admit the first joiner).+ await focusJoin(r);++ // First guest triggers the lobby; the join is blocked.+ const guest1 = await connect();+ const blocked = await guest1.joinRoom(r);++ assert.equal(blocked.attrs.type, 'error', 'pre-host guest must be blocked');++ // JWT host joins — lobby is destroyed and room opens.+ const host = await connectAsHost(roomName);++ await host.joinRoom(r);++ // A new guest can now join freely.+ const guest2 = await connect();+ const presence = await guest2.joinRoom(r);++ assert.ok(isAvailablePresence(presence),+ 'guest should be admitted after JWT host arrives');+ });++ // -------------------------------------------------------------------------+ // Auto-owner+ // -------------------------------------------------------------------------++ it('JWT authenticated user receives owner affiliation on join', async () => {+ const r = room();+ const roomName = r.split('@')[0];++ const host = await connectAsHost(roomName);++ await host.joinRoom(r);++ // muc-occupant-joined fires after the join and calls room:set_affiliation('owner'),+ // which sends a subsequent presence update carrying the new affiliation.+ const update = await host.waitForPresence(+ p => p.getChild('x', MUC_NS)?.getChild('item')?.attrs.affiliation === 'owner'+ );++ assert.ok(update,+ 'JWT host should receive an owner-affiliation presence update after joining');+ });+});diff --git a/tests/prosody/mod_presence_identity_spec.js b/tests/prosody/mod_presence_identity_spec.jsindex f624509351..488c129b11 100644--- a/tests/prosody/mod_presence_identity_spec.js+++ b/tests/prosody/mod_presence_identity_spec.js@@ -166,6 +166,59 @@ describe('mod_presence_identity', () => {});});+ // -------------------------------------------------------------------------+ // malformed JWT context.user keys+ // -------------------------------------------------------------------------+ //+ // update_presence_identity() iterates over JWT context.user keys and uses+ // each key as an XML element name: presence:tag(key):text(tostring(value)).+ // Fixed in 2e8980d2b: keys that do not match the XML name pattern+ // ^[%a_][%w%-%.%:_]*$ are now silently skipped before reaching tag().+ // This test verifies that bad keys are dropped and valid keys are preserved.++ describe('malformed JWT context.user keys', () => {++ it('survives context.user keys that contain XML-special characters', async () => {+ const r = room();++ // Key names with '<' and '>' — these become XML element names.+ // Prosody / LuaXML may escape, drop, or crash on them.+ const identity = await hs256Client(r, {+ context: {+ user: {+ id: 'safe-id',+ 'bad<key>': 'value'+ }+ }+ });++ clients.push(identity);+ await identity.joinRoom(r);++ const observer = await createXmppClient();++ clients.push(observer);+ await observer.joinRoom(r);++ // If Prosody crashed the hook the join presence would never arrive.+ const presence = await waitForOtherPresence(observer, r, observer.nick);++ assert.ok(presence, 'join presence must arrive even with unusual key names');++ // The safe 'id' element must be present and correct.+ const identityEl = presence.getChild('identity');++ assert.ok(identityEl, 'presence must still contain <identity>');+ assert.strictEqual(+ identityEl.getChild('user')?.getChild('id')+ ?.text(),+ 'safe-id',+ 'safe id field must be present and unmodified'+ );+ });++ });+// -------------------------------------------------------------------------// spoofing prevention// -------------------------------------------------------------------------diff --git a/tests/prosody/mod_room_metadata_component_spec.js b/tests/prosody/mod_room_metadata_component_spec.jsindex e52f2fa6dd..ce0444d05a 100644--- a/tests/prosody/mod_room_metadata_component_spec.js+++ b/tests/prosody/mod_room_metadata_component_spec.js@@ -444,6 +444,259 @@ describe('mod_room_metadata_component', () => {});+ // ── allow-moderation hook (mod_filter_iq_rayo interop) ───────────────────+ //+ // mod_filter_iq_rayo hooks 'jitsi-metadata-allow-moderation' on the main+ // VirtualHost and controls access to the 'recording' metadata key:+ //+ // • has features + transcription=true → allow; sanitize to only+ // isTranscribingEnabled / isRecordingRequested+ // • no features + is moderator → allow; full data passed through+ // • has features + transcription=false → deny (return false), even for moderators+ // • no features + not moderator → deny (hook returns nil → default moderator check)+ //+ // For any other key the hook returns nil, falling through to the default+ // moderator-only access check.++ describe('allow-moderation hook (mod_filter_iq_rayo interop)', () => {++ /**+ * Non-moderator client whose JWT carries the given context features.+ * No user.moderator flag — mod_token_affiliation will not grant owner/moderator role.+ *+ * @param {string} roomJid+ * @param {object} features e.g. { transcription: true }+ */+ function connectWithFeatures(roomJid, features) {+ const roomName = roomJid.split('@')[0];++ return createXmppClient({+ params: {+ room: roomName,+ token: mintAsapToken({ room: roomName,+ context: { features } })+ }+ });+ }++ /**+ * Moderator client (user.moderator=true) whose JWT also carries context features.+ * mod_token_affiliation grants owner/moderator role in the MUC, but the hook+ * checks features first, so the moderator role cannot override a feature-level deny.+ *+ * @param {string} roomJid+ * @param {object} features e.g. { transcription: false }+ */+ function connectModeratorWithFeatures(roomJid, features) {+ const roomName = roomJid.split('@')[0];++ return createXmppClient({+ params: {+ room: roomName,+ token: mintAsapToken({ room: roomName,+ context: { user: { moderator: true },+ features } })+ }+ });+ }++ // ── Allow cases ───────────────────────────────────────────────────────++ it('non-moderator with transcription feature can set recording.isTranscribingEnabled',+ async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const c = await connectWithFeatures(r, { transcription: true });++ clients.push(foc, c);+ await c.joinRoom(r);+ await drainInitialMetadata(c);++ c.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', { isTranscribingEnabled: true });++ const broadcast = await waitForMetadata(c);++ assert.deepEqual(parseBroadcast(broadcast).metadata.recording, { isTranscribingEnabled: true });+ });++ it('non-moderator with transcription feature can set recording.isRecordingRequested',+ async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const c = await connectWithFeatures(r, { transcription: true });++ clients.push(foc, c);+ await c.joinRoom(r);+ await drainInitialMetadata(c);++ c.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', { isRecordingRequested: true });++ const broadcast = await waitForMetadata(c);++ assert.deepEqual(parseBroadcast(broadcast).metadata.recording, { isRecordingRequested: true });+ });++ it('non-moderator with transcription feature can set both recording fields simultaneously',+ async () => {+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const c = await connectWithFeatures(r, { transcription: true });++ clients.push(foc, c);+ await c.joinRoom(r);+ await drainInitialMetadata(c);++ c.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording',+ { isTranscribingEnabled: true,+ isRecordingRequested: true });++ const broadcast = await waitForMetadata(c);++ assert.deepEqual(parseBroadcast(broadcast).metadata.recording,+ { isTranscribingEnabled: true,+ isRecordingRequested: true });+ });++ it('moderator without features can set recording.isTranscribingEnabled', async () => {+ // No context.features in JWT → session.jitsi_meet_context_features is nil.+ // Hook falls to: not features AND is moderator → allow full data.+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const mod = await connectModerator(r);++ clients.push(foc, mod);+ await mod.joinRoom(r);+ await drainInitialMetadata(mod);++ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', { isTranscribingEnabled: true });++ const broadcast = await waitForMetadata(mod);++ assert.deepEqual(parseBroadcast(broadcast).metadata.recording, { isTranscribingEnabled: true });+ });++ // ── Deny cases ────────────────────────────────────────────────────────++ it('non-moderator without features cannot set recording.isTranscribingEnabled', async () => {+ // No features → hook falls through to default moderator check → non-moderator denied.+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const member = await connectMember(r);++ clients.push(foc, member);+ await member.joinRoom(r);+ await drainInitialMetadata(member);++ member.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', { isTranscribingEnabled: true });++ await assertNoMetadata(member);+ });++ it('non-moderator with transcription=false cannot set recording.isTranscribingEnabled',+ async () => {+ // Features present but transcription is false → hook returns false → hard deny.+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const c = await connectWithFeatures(r, { transcription: false });++ clients.push(foc, c);+ await c.joinRoom(r);+ await drainInitialMetadata(c);++ c.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', { isTranscribingEnabled: true });++ await assertNoMetadata(c);+ });++ it('moderator with transcription=false is denied despite moderator role', async () => {+ // Features take precedence: having features but transcription=false → hook returns+ // false, which short-circuits before the moderator role check.+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const mod = await connectModeratorWithFeatures(r, { transcription: false });++ clients.push(foc, mod);+ await mod.joinRoom(r);+ await drainInitialMetadata(mod);++ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', { isTranscribingEnabled: true });++ await assertNoMetadata(mod);+ });++ it('non-moderator with transcription feature cannot set unrelated metadata keys', async () => {+ // Hook returns nil for non-recording keys; default moderator check then applies.+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const c = await connectWithFeatures(r, { transcription: true });++ clients.push(foc, c);+ await c.joinRoom(r);+ await drainInitialMetadata(c);++ c.sendMetadataUpdate(METADATA_COMPONENT, r, 'someOtherKey', 'value');++ await assertNoMetadata(c);+ });++ // ── Sanitization ──────────────────────────────────────────────────────++ it('extra fields in recording payload are stripped when set via transcription feature',+ async () => {+ // The hook builds the stored value as { isTranscribingEnabled, isRecordingRequested }+ // only; any other fields in the client payload are discarded.+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const c = await connectWithFeatures(r, { transcription: true });++ clients.push(foc, c);+ await c.joinRoom(r);+ await drainInitialMetadata(c);++ c.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', {+ isTranscribingEnabled: true,+ isRecordingRequested: false,+ evil: 'payload'+ });++ const broadcast = await waitForMetadata(c);+ const { recording } = parseBroadcast(broadcast).metadata;++ assert.strictEqual(recording.isTranscribingEnabled, true, 'isTranscribingEnabled must be stored');+ assert.strictEqual(recording.isRecordingRequested, false, 'isRecordingRequested must be stored');+ assert.strictEqual(recording.evil, undefined, 'extra fields must be stripped');+ });++ // ── Edge case: recording with only unrecognized fields ─────────────────++ it('recording with only unrecognized fields falls through to the default moderator check',+ async () => {+ // When data has neither isTranscribingEnabled nor isRecordingRequested the+ // outer `if` in the hook is false → returns nil → default moderator-only check.+ const r = nextRoom();+ const foc = await joinWithFocus(r);+ const mod = await connectModerator(r);+ const member = await connectMember(r);++ clients.push(foc, mod, member);+ await mod.joinRoom(r);+ await member.joinRoom(r);+ await drainInitialMetadata(mod);+ await drainInitialMetadata(member);++ // Non-moderator must be denied.+ member.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', { someUnrelatedField: 'x' });+ await assertNoMetadata(member);++ // Moderator must be allowed.+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'recording', { someUnrelatedField: 'y' });+ const broadcast = await waitForMetadata(mod);++ assert.strictEqual(parseBroadcast(broadcast).metadata.recording.someUnrelatedField, 'y');+ });++ });+// ── Invalid payloads ─────────────────────────────────────────────────────describe('invalid payloads', () => {diff --git a/tests/prosody/mod_system_chat_message_spec.js b/tests/prosody/mod_system_chat_message_spec.jsindex 17826daf57..9c328ef927 100644--- a/tests/prosody/mod_system_chat_message_spec.js+++ b/tests/prosody/mod_system_chat_message_spec.js@@ -280,6 +280,26 @@ describe('mod_system_chat_message', () => {}});+ it('returns 200 when connectionJIDs contains a JID not in the room (no occupancy validation)', async () => {+ // mod_system_chat_message routes stanzas to every JID in+ // connectionJIDs without verifying they are room occupants.+ // This test documents the current behaviour: the call succeeds+ // (200) even for non-occupant JIDs.+ const { roomJid, focus } = await createRoom();++ try {+ const token = mintSystemToken();+ const nonOccupant = 'nobody@localhost/ghost-resource';+ const { status } = await sendSystemChatMessage(+ roomJid, [ nonOccupant ], 'hello', token);++ assert.strictEqual(status, 200,+ 'module must not crash when connectionJIDs contains a non-occupant JID');+ } finally {+ await disconnectAll(focus);+ }+ });+it('delivers to multiple recipients', async () => {const { roomJid, focus } = await createRoom();const alice = await createXmppClient();diff --git a/tests/prosody/package.json b/tests/prosody/package.jsonindex 55d7496568..3c93f5a4a6 100644--- a/tests/prosody/package.json+++ b/tests/prosody/package.json@@ -7,7 +7,7 @@"test:lua": "rm -f allure-results/*-result.json allure-results/TEST-lua-unit.xml 2>/dev/null; mkdir -p allure-results && if command -v busted > /dev/null 2>&1; then BUSTED=${HOME}/.luarocks/bin/busted; command -v \"$BUSTED\" > /dev/null 2>&1 || BUSTED=busted; SPEC_DIR=\"$(pwd)\"; (cd ../../resources/prosody-plugins && LUA_PATH=\"$SPEC_DIR/?.lua;;\" ALLURE_RESULTS_DIR=\"$SPEC_DIR/allure-results\" \"$BUSTED\" --output busted_allure \"$SPEC_DIR/lua/\"); fi","test:integration": "DEBUG=testcontainers,testcontainers:containers,testcontainers:build mocha","test:report": "npx allure generate allure-results --clean -o allure-report && node fix-allure-report.cjs",- "test": "npm run test:lua && npm run test:integration; RC=$?; npm run test:report; exit $RC",+ "test": "npm run test:lua; LRC=$?; npm run test:integration; IRC=$?; npm run test:report; exit $(( LRC != 0 || IRC != 0 ))","test:one": "mocha --no-config --require ./setup.js --timeout 120000"},"dependencies": {