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
fix(prosody): scope refreshed token claims to the joined conference (#17769)
Дамян Минков16e687c8ccc8
diff --git a/resources/prosody-plugins/README.md b/resources/prosody-plugins/README.mdindex 65ea1f60fc..866742ed1e 100644--- a/resources/prosody-plugins/README.md+++ b/resources/prosody-plugins/README.md@@ -95,6 +95,7 @@- jitsi_meet_context_features - The features from the context, added after token verify.- jitsi_meet_context_room - The room settings from the jwt context, added after token verify.- jitsi_meet_room - The room name in jwt token, added after token verify.+- jitsi_meet_verified_room - The jid of the room the session was verified for on join. Set by mod_token_verification.lua and used to re-check claims that are refreshed later, when a resuming connection presents a different token.- jitsi_meet_str_tenant - The tenant in the context. Added after token verify.- jitsi_meet_domain - The domain in the jwt ('sub' claim). Added after token verify. Can be the domain if not tenant is used or the tenant itself in lowercase.- customusername - from a query parameter to be used with combination with "pre-jitsi-authentication" event to pre-set a known jid to a session.diff --git a/resources/prosody-plugins/mod_auth_token.lua b/resources/prosody-plugins/mod_auth_token.luaindex b47e9aa589..08f22de983 100644--- a/resources/prosody-plugins/mod_auth_token.lua+++ b/resources/prosody-plugins/mod_auth_token.lua@@ -20,6 +20,22 @@ local measure_verify_fail = module:measure('verify_fail', 'counter');local measure_success = module:measure('success', 'counter');local measure_ban = module:measure('ban', 'counter');local measure_post_auth_fail = module:measure('post_auth_fail', 'counter');+local measure_resume_room_mismatch = module:measure('resume_room_mismatch', 'counter');++-- The JWT-derived authorization state that c2s-session-updated refreshes from+-- the connection that resumes a hibernating session.+local TOKEN_CLAIM_FIELDS = {+ 'auth_token';+ 'jitsi_meet_context_user';+ 'jitsi_meet_context_group';+ 'jitsi_meet_context_features';+ 'jitsi_meet_context_room';+ 'jitsi_meet_room';+ 'jitsi_meet_str_tenant';+ 'jitsi_meet_domain';+ 'jitsi_meet_tenant_mismatch';+ 'jitsi_meet_auth_issuer';+};-- define auth providerlocal provider = {};@@ -181,6 +197,24 @@ module:hook_global('c2s-session-updated', function (event)return;end+ -- The room claim is scoped to a conference on muc-room-pre-create and+ -- muc-occupant-pre-join, which do not run again for a session that is past+ -- its join, so the claims coming from the resuming connection are scoped+ -- here instead: the ones verified on join are snapshotted before anything+ -- below mutates the session, and are kept when the refreshed ones do not+ -- cover the conference the session is in. The check belongs to whichever+ -- module owns room verification (mod_token_verification, on the MUC+ -- component); with nothing answering the event the claims are refreshed+ -- as they come, the same way a join is not room-checked without it.+ local reverify_rooms = session.auth_token ~= from_session.auth_token;+ local verified_claims = {};++ if reverify_rooms then+ for _, field in ipairs(TOKEN_CLAIM_FIELDS) do+ verified_claims[field] = session[field];+ end+ end+-- we care to handle sessions from other hosts (anonymous hosts)-- Skip if from_session was already authenticated by its own token-auth module-- (indicated by _jitsi_auth_done=true), to avoid a second module instance@@ -220,4 +254,19 @@ module:hook_global('c2s-session-updated', function (event)session.jitsi_meet_str_tenant = from_session.jitsi_meet_str_tenant;session.jitsi_meet_domain = from_session.jitsi_meet_domain;session.jitsi_meet_tenant_mismatch = from_session.jitsi_meet_tenant_mismatch;++ if reverify_rooms then+ local result = prosody.events.fire_event('jitsi-verify-session-rooms', { session = session; });++ if result and result.res == false then+ module:log('warn',+ 'Token presented on resume does not authorize room:%s err:%s reason:%s, keeping claims from join',+ result.room, result.error, result.reason);+ measure_resume_room_mismatch(1);++ for _, field in ipairs(TOKEN_CLAIM_FIELDS) do+ session[field] = verified_claims[field];+ end+ end+ endend, 1);diff --git a/resources/prosody-plugins/mod_test_observer_http.lua b/resources/prosody-plugins/mod_test_observer_http.luaindex e2748cbd11..dd14990069 100644--- a/resources/prosody-plugins/mod_test_observer_http.lua+++ b/resources/prosody-plugins/mod_test_observer_http.lua@@ -484,6 +484,40 @@ module:provides("http", {};end;+ -- GET /test-observer/session-live?jid=user@localhost/resource+ -- Returns the CURRENT values of the JWT-derived fields on the live c2s+ -- session, read straight from prosody.full_sessions. Unlike+ -- /session-info (a snapshot taken at resource-bind) this reflects+ -- changes made after the session was established -- notably the claim+ -- refresh performed by mod_auth_token on XEP-0198 stream resumption,+ -- which never binds a new resource.+ ["GET /session-live"] = function(event)+ local params = parse_query(event.request.url.query);+ local jid = params["jid"];+ if not jid then+ return { status_code = 400; body = '{"error":"missing jid param"}' };+ end+ local session = prosody.full_sessions[jid];+ if not session then+ return { status_code = 404; body = '{"error":"session not found"}' };+ end+ return {+ status_code = 200;+ headers = { ["Content-Type"] = "application/json" };+ body = json.encode({+ auth_token = session.auth_token,+ jitsi_web_query_room = session.jitsi_web_query_room,+ jitsi_web_query_prefix = session.jitsi_web_query_prefix,+ jitsi_meet_room = session.jitsi_meet_room,+ jitsi_meet_domain = session.jitsi_meet_domain,+ jitsi_meet_str_tenant = session.jitsi_meet_str_tenant,+ jitsi_meet_context_user = session.jitsi_meet_context_user,+ jitsi_meet_context_group = session.jitsi_meet_context_group,+ jitsi_meet_context_features = session.jitsi_meet_context_features,+ });+ };+ end;+-- POST /test-observer/rooms/lobby-- Body: { "jid": "[email protected]", "enabled": true|false }-- Enables or disables the lobby for the given room by firing thediff --git a/resources/prosody-plugins/mod_token_verification.lua b/resources/prosody-plugins/mod_token_verification.luaindex c6526d9315..bdf3a870f1 100644--- a/resources/prosody-plugins/mod_token_verification.lua+++ b/resources/prosody-plugins/mod_token_verification.lua@@ -5,6 +5,10 @@-- are exempt. Anonymous users (no token) are allowed through. When-- token_verification_require_token_for_moderation is set, also blocks room-- config IQs (e.g. granting moderator status) from unauthenticated users.+-- Records the verified conference on the session (jitsi_meet_verified_room) and+-- answers the 'jitsi-verify-session-rooms' event, so that a session whose JWT+-- claims are refreshed after the join (mod_auth_token, on stream resumption) is+-- re-checked against it.-- Token authentication-- Copyright (C) 2021-present 8x8, Inc.@@ -105,6 +109,12 @@ local function verify_user(session, stanza)return false; -- we need to just return non nilendif DEBUG then module:log("debug", "allowed: %s to enter/create room: %s", user_jid, stanza.attr.to); end++ -- Remember the conference this session was verified for, so claims that are+ -- refreshed later (mod_auth_token, on stream resumption) can be checked+ -- against it without going through a join again.+ session.jitsi_meet_verified_room = jid_bare(stanza.attr.to);+return true;end@@ -128,6 +138,39 @@ module:hook("muc-occupant-pre-join", function(event)measure_success(1);end, 99);+-- Verifies the token claims currently on a session against the conference it+-- was verified for on join. Fired by mod_auth_token when a connection resuming+-- a hibernating session (XEP-0198) presents a different token, which refreshes+-- the claims of the live session: the hooks above only run at join time, so+-- this applies the same room check to a session that is already in a room.+-- Answering with res=false makes mod_auth_token keep the claims that were+-- verified on join.+module:hook_global('jitsi-verify-session-rooms', function(event)+ local session = event.session;+ local room_jid = session.jitsi_meet_verified_room;++ if not room_jid then+ return;+ end++ -- Being an occupant is deliberately not required: a session that moved into+ -- a breakout room has left the main room it joined, and that main room is+ -- still the conference its claims have to cover. Only a room that is gone+ -- (everyone left while the session was hibernating) is skipped.+ if not prosody.hosts[host].modules.muc.get_room_from_jid(room_jid) then+ return;+ end++ local res, err, reason = token_util:verify_room(session, room_jid);++ if not res then+ measure_fail(1);+ return { res = false; room = room_jid; error = err; reason = reason; };+ end++ measure_success(1);+end);+for event_name, method in pairs {-- Normal room interactions["iq-set/bare/http://jabber.org/protocol/muc#owner:query"] = "handle_owner_query_set_to_room" ;diff --git a/tests/prosody/helpers/xmpp_client.js b/tests/prosody/helpers/xmpp_client.jsindex 3aa0aa67ac..9cec9c4337 100644--- a/tests/prosody/helpers/xmpp_client.js+++ b/tests/prosody/helpers/xmpp_client.js@@ -1062,6 +1062,25 @@ export async function createXmppClient({ host = 'localhost', domain, params, use}));},+ /**+ * Leaves a MUC room (XEP-0045 §7.14) and resolves with the self+ * unavailable presence echoed back by the room.+ *+ * @param {string} roomJid e.g. '[email protected]'+ * @param {string} [nick] defaults to the nick used by joinRoom+ * @param {object} [opts]+ * @param {number} [opts.timeout=5000]+ */+ async leaveRoom(roomJid, nick, { timeout = 5000 } = {}) {+ const n = nick ?? this.nick;++ await xmpp.send(xml('presence', { to: `${roomJid}/${n}`,+ type: 'unavailable' }));++ return this.waitForPresenceFrom(`${roomJid}/${n}`, { type: 'unavailable',+ timeout });+ },+/*** Sends a <breakout_rooms> control message to the breakout rooms component.* The session must have jitsi_web_query_room set (connect with@@ -1159,22 +1178,33 @@ export async function createXmppClient({ host = 'localhost', domain, params, use** xmpp.socket – @xmpp/websocket Socket wrapper* xmpp.socket.socket – underlying ws.WebSocket instance with terminate()+ *+ * @param {object} [urlParams] Query parameters to set on the reconnect+ * URL (e.g. { token: '<rotated jwt>' }).*/- dropConnection() {+ dropConnection(urlParams = {}) {// Patch the reconnect URL to carry ?previd=<smacks-id> so that// mod_jitsi_session.lua sets session.previd and mod_auth_token.lua// can preserve session.username across the SASL exchange, allowing// mod_smacks.lua's registry lookup to succeed.+ //+ // `urlParams` overrides query parameters on the reconnect URL only —+ // the hibernating session keeps whatever it was given on the first+ // connection. Use it to resume while presenting a different ?token=,+ // which is how a client rotates its JWT across a reconnect.const smId = xmpp.streamManagement?.id;- if (smId) {- try {- const serviceUrl = new URL(xmpp.options.service);+ try {+ const serviceUrl = new URL(xmpp.options.service);+ if (smId) {serviceUrl.searchParams.set('previd', smId);- xmpp.options.service = serviceUrl.toString();- } catch { /* ignore */ }- }+ }+ for (const [ k, v ] of Object.entries(urlParams)) {+ serviceUrl.searchParams.set(k, v);+ }+ xmpp.options.service = serviceUrl.toString();+ } catch { /* ignore */ }try {const ws = xmpp.socket?.socket;diff --git a/tests/prosody/mod_auth_token_spec.js b/tests/prosody/mod_auth_token_spec.jsindex f1b88d78f8..9a1b57df11 100644--- a/tests/prosody/mod_auth_token_spec.js+++ b/tests/prosody/mod_auth_token_spec.js@@ -1,18 +1,20 @@import assert from 'assert';import http from 'http';-import { mintToken } from './helpers/jwt.js';-import { createXmppClient } from './helpers/xmpp_client.js';+import { mintAsapToken, mintToken } from './helpers/jwt.js';+import { prosodyShell } from './helpers/prosody_shell.js';+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';/**- * Fetches session-info for the given full JID.+ * GETs a test-observer endpoint and parses the JSON response.*- * @param {string} jid+ * @param {string} route e.g. 'session-info'+ * @param {string} jid full JID to look up* @returns {Promise<object>}*/-function getSessionInfo(jid) {+function getObserverJson(route, jid) {return new Promise((resolve, reject) => {- const url = `http://localhost:5280/test-observer/session-info?jid=${encodeURIComponent(jid)}`;+ const url = `http://localhost:5280/test-observer/${route}?jid=${encodeURIComponent(jid)}`;http.get(url, res => {let body = '';@@ -22,20 +24,42 @@ function getSessionInfo(jid) {});res.on('end', () => {if (res.statusCode !== 200) {- reject(new Error(`session-info returned ${res.statusCode}: ${body}`));+ reject(new Error(`${route} returned ${res.statusCode}: ${body}`));return;}try {resolve(JSON.parse(body));} catch (e) {- reject(new Error(`session-info bad JSON: ${body}`));+ reject(new Error(`${route} bad JSON: ${body}`));}});}).on('error', reject);});}+/**+ * Fetches the session fields snapshotted at resource-bind time.+ *+ * @param {string} jid+ * @returns {Promise<object>}+ */+function getSessionInfo(jid) {+ return getObserverJson('session-info', jid);+}++/**+ * Fetches the CURRENT JWT-derived fields of a live session. Needed after a+ * XEP-0198 resume, which refreshes the claims without binding a new resource+ * (so the /session-info snapshot is not updated).+ *+ * @param {string} jid+ * @returns {Promise<object>}+ */+function getSessionLive(jid) {+ return getObserverJson('session-live', jid);+}+/** Connects to the HS256 VirtualHost. */function hs256Client(params) {return createXmppClient({ domain: 'hs256.localhost',@@ -124,3 +148,301 @@ describe('mod_auth_token (HS256 shared secret)', () => {assert.strictEqual(info.jitsi_meet_room, 'testroom');});});++/**+ * XEP-0198 stream resumption re-runs SASL on the new connection, so a client+ * may present a different JWT than the one it joined with. mod_auth_token+ * refreshes the hibernating session's claims from that token — that is how a+ * client rotates an expiring token across a reconnect — and the claims it+ * adopts have to stay scoped to the conference the session is an occupant of,+ * the same way the room claim is scoped at join time.+ *+ * The room claim of the refreshed token is therefore re-checked against the+ * rooms the session already occupies (mod_token_verification answers the+ * 'jitsi-verify-session-rooms' event), and the claims verified on join are kept+ * when it does not cover them. The file-sharing component is used here as the+ * observable effect of context.features on a live session.+ */+describe('mod_auth_token (claims on XEP-0198 resumption)', () => {++ const CONFERENCE = 'conference.localhost';+ const BREAKOUT_MUC = 'breakout.conference.localhost';+ const FILESHARING_COMPONENT = 'filesharing.localhost';+ const JITMEET_NS = 'http://jitsi.org/jitmeet';++ const clients = [];+ let roomCounter = 0;++ afterEach(async () => {+ await Promise.all(clients.map(c => c.disconnect()));+ clients.length = 0;+ });++ /** Connects a client carrying ?room= and ?token= on the token VirtualHost. */+ function tokenClient(roomName, token) {+ return createXmppClient({ params: { room: roomName,+ token } });+ }++ /** Mints an RS256 login token scoped to `room`, optionally with features. */+ function tokenFor(room, features) {+ return mintAsapToken({+ room,+ context: {+ user: { id: 'user-a',+ name: 'user-a' },+ ...features ? { features } : {}+ }+ });+ }++ /**+ * Sends a file-sharing add with a caller-chosen stanza id, so the reply can+ * be matched by id. After a resume the server flushes the unacked stanzas+ * queued during hibernation, so an earlier error can be redelivered.+ */+ function addFile(client, id, fileId) {+ return client.sendFileSharingRaw(+ FILESHARING_COMPONENT,+ { id },+ { type: 'add' },+ JSON.stringify({ fileId,+ name: 'shared.txt',+ size: 0,+ type: 'text/plain' })+ );+ }++ /** Waits for the reply to the stanza with the given id. */+ function waitForReply(client, id, timeout = 3000) {+ return client.waitForMessage(s => s.attrs.id === id, timeout);+ }++ /** Asserts a reply is an auth/forbidden error. */+ function assertForbidden(stanza, message) {+ assert.equal(stanza.attrs.type, 'error', message);+ assert.ok(stanza.getChild('error')?.getChild('forbidden'),+ `${message} (expected <forbidden/>, got ${stanza.toString()})`);+ }++ /** Resolves with the filesharing broadcast payload received by `client`. */+ async function waitForBroadcast(client, timeout = 3000) {+ const stanza = await client.waitForMessage(+ s => s.attrs.from === FILESHARING_COMPONENT && s.getChild('json-message', JITMEET_NS) !== undefined,+ timeout);++ return JSON.parse(stanza.getChild('json-message', JITMEET_NS).getText());+ }++ /** Asserts that no filesharing broadcast reaches `client` within the window. */+ async function assertNoBroadcast(client, timeout = 1000) {+ try {+ await waitForBroadcast(client, timeout);+ } catch (err) {+ if (err.message.includes('Timeout')) {+ return;+ }+ throw err;+ }+ throw new Error('unexpected file-sharing broadcast');+ }++ /**+ * Sets up a meeting with a participant holding a token that grants no+ * features, plus a second occupant that receives the room's broadcasts.+ */+ async function setupMeeting() {+ const roomName = `resume-${++roomCounter}`;+ const roomJid = `${roomName}@${CONFERENCE}`;+ const focus = await joinWithFocus(roomJid);+ const participant = await tokenClient(roomName, tokenFor(roomName));+ const other = await tokenClient(roomName, tokenFor(roomName));++ clients.push(focus, participant, other);+ await participant.joinRoom(roomJid);+ await other.joinRoom(roomJid);++ // Baseline: without a file-upload feature the operation is refused.+ addFile(participant, 'baseline-1', 'file-before-resume');+ assertForbidden(await waitForReply(participant, 'baseline-1'),+ 'file-upload must be refused before the token swap');+ await assertNoBroadcast(other);++ return { roomName,+ roomJid,+ participant,+ other };+ }++ it('ignores features from a token issued for a different room', async () => {+ const { roomName, participant, other } = await setupMeeting();++ // Same tenant, scoped to another room, and granting file-upload there.+ const otherRoomToken = tokenFor(`${roomName}-other`, { 'file-upload': true });++ const reconnected = participant.waitForReconnect();++ participant.dropConnection({ token: otherRoomToken });+ await reconnected;++ const session = await getSessionLive(participant.jid);++ assert.equal(session.jitsi_meet_room, roomName,+ 'room claim of a token that does not cover the joined conference must not be adopted');+ assert.ok(!session.jitsi_meet_context_features?.['file-upload'],+ 'features of a token that does not cover the joined conference must not be adopted');++ addFile(participant, 'after-1', 'file-after-resume');+ assertForbidden(await waitForReply(participant, 'after-1'),+ 'file-upload must still be refused after resuming with a token for another room');+ await assertNoBroadcast(other);+ });++ it('adopts the claims of a rotated token issued for the same room', async () => {+ const { roomName, participant, other } = await setupMeeting();++ // Same conference, new token: this is the token rotation the+ // c2s-session-updated handler exists for, and it must keep working.+ const rotatedToken = tokenFor(roomName, { 'file-upload': true });++ const reconnected = participant.waitForReconnect();++ participant.dropConnection({ token: rotatedToken });+ await reconnected;++ const session = await getSessionLive(participant.jid);++ assert.equal(session.jitsi_meet_context_features['file-upload'], true,+ 'features of a token covering the joined conference must be adopted');++ addFile(participant, 'after-2', 'file-after-resume');++ const payload = await waitForBroadcast(other);++ assert.equal(payload.event, 'add');+ assert.equal(payload.file.fileId, 'file-after-resume');+ });++ /**+ * Sets up a meeting whose moderator has moved into a breakout room: it+ * joins the main room, registers a breakout room, joins it and then leaves+ * the main room, which is what the client does when switching rooms.+ *+ * The session is left occupying only the breakout room, while the+ * conference its claims have to cover is still the main room.+ */+ async function setupBreakout() {+ const roomName = `resume-br-${++roomCounter}`;+ const mainJid = `${roomName}@${CONFERENCE}`;+ const focus = await joinWithFocus(mainJid);+ const moderator = await tokenClient(+ roomName,+ mintAsapToken({ room: roomName,+ context: { user: { moderator: true } } }));++ clients.push(focus, moderator);+ await moderator.joinRoom(mainJid);++ // Register a breakout room, then let focus create it on the breakout+ // component (restrict_room_creation allows only Prosody admins there).+ moderator.sendBreakoutRoomsMessage(BREAKOUT_MUC, 'features/breakout-rooms/add',+ { subject: 'Breakout 1' });++ const update = await moderator.waitForMessage(s2 => {+ const jm = s2.getChild('json-message', JITMEET_NS);++ return jm !== undefined && JSON.parse(jm.getText()).type === 'breakout_rooms';+ }, 6000);+ const rooms = JSON.parse(update.getChild('json-message', JITMEET_NS).getText()).rooms;+ const breakoutJid = Object.values(rooms).find(r => !r.isMainRoom)?.jid;++ assert.ok(breakoutJid, 'breakout room JID must be in the update broadcast');+ await focus.joinRoom(breakoutJid, 'focus');++ const presence = await moderator.joinRoom(breakoutJid);++ assert.notEqual(presence.attrs.type, 'error', 'moderator must be able to join the breakout room');++ // Moving into a breakout room means leaving the main room.+ await moderator.leaveRoom(mainJid);++ return { roomName,+ mainJid,+ breakoutJid,+ moderator };+ }++ it('ignores a token for another room while the session sits in a breakout room', async () => {+ // A participant that moved into a breakout room is no longer an+ // occupant of the main room, but the conference it belongs to — and so+ // the room its token has to cover — is still the main room.+ const { roomName, moderator } = await setupBreakout();++ const reconnected = moderator.waitForReconnect();++ moderator.dropConnection({ token: tokenFor(`${roomName}-other`, { 'file-upload': true }) });+ await reconnected;++ const session = await getSessionLive(moderator.jid);++ assert.equal(session.jitsi_meet_room, roomName,+ 'claims of a token that does not cover the main room must not be adopted in a breakout room');+ assert.ok(!session.jitsi_meet_context_features?.['file-upload'],+ 'features of a token that does not cover the main room must not be adopted in a breakout room');+ });++ it('adopts the claims of a rotated token for the main room while the session sits in a breakout room',+ async () => {+ // The counterpart of the check above: the room the claims are+ // verified against is the main room the session joined, not the+ // breakout room it currently occupies, so a token that does cover+ // that main room has to be adopted. Without this, a rotation that+ // named the breakout room instead would fail closed and token+ // rotation would silently stop working inside breakout rooms.+ const { roomName, moderator } = await setupBreakout();++ const rotatedToken = mintAsapToken({+ room: roomName,+ context: {+ user: { moderator: true },+ features: { 'file-upload': true }+ }+ });++ const reconnected = moderator.waitForReconnect();++ moderator.dropConnection({ token: rotatedToken });+ await reconnected;++ const session = await getSessionLive(moderator.jid);++ assert.equal(session.jitsi_meet_room, roomName,+ 'the room claim of a token covering the main room must be adopted in a breakout room');+ assert.equal(session.jitsi_meet_context_features['file-upload'], true,+ 'features of a token covering the main room must be adopted in a breakout room');+ });++ it('refreshes the claims unverified when no module answers the verification event', async () => {+ // mod_token_verification owns room verification: without it a join is+ // not room-checked either, so there is nothing to answer the+ // 'jitsi-verify-session-rooms' event with and the refreshed claims are+ // taken as they come.+ const { roomName, participant } = await setupMeeting();++ await prosodyShell(`module:unload("token_verification", "${CONFERENCE}")`);++ try {+ const reconnected = participant.waitForReconnect();++ participant.dropConnection({ token: tokenFor(`${roomName}-other`, { 'file-upload': true }) });+ await reconnected;++ const session = await getSessionLive(participant.jid);++ assert.equal(session.jitsi_meet_room, `${roomName}-other`,+ 'with no verifier loaded the refreshed claims are adopted as-is');+ } finally {+ await prosodyShell(`module:load("token_verification", "${CONFERENCE}")`);+ }+ });+});