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): room claim patterns, metrics and tests (#17803)
bgrozev6ad79e2f8d72
diff --git a/resources/prosody-plugins/token/util.lib.lua b/resources/prosody-plugins/token/util.lib.luaindex 471fcbfbfb..6f216bb986 100644--- a/resources/prosody-plugins/token/util.lib.lua+++ b/resources/prosody-plugins/token/util.lib.lua@@ -46,6 +46,56 @@ if f thenf:close();end+-- counts the tokens with a verified signature that flag their room claim as a+-- Lua pattern+local measure_regex_room_claim = module:measure('regex_room_claim', 'counter');++--- Tells whether a token asks for its room claim to be used as a Lua pattern,+-- which the context.room.regex field marks.+-- @param room_context the context.room value from the token+-- @return true when the room claim is a pattern+local function is_regex_room_claim(room_context)+ if type(room_context) ~= 'table' then+ return false;+ end++ return room_context['regex'] == true or room_context['regex'] == 'true';+end++--- Counts the quantifiers ('*', '+', '-' and '?') in a Lua pattern.+-- A quantifier is only special outside a character class, so the contents of+-- a class ('[a-z]') are skipped, and so is the character after a '%' escape.+-- @param pattern the Lua pattern to inspect+-- @return the number of quantifiers in the pattern+local function count_pattern_quantifiers(pattern)+ local count = 0;+ local index = 1;+ local length = #pattern;+ local in_class = false;++ while index <= length do+ local char = pattern:sub(index, index);++ if char == '%' then+ -- '%' escapes the next character, so skip both+ index = index + 2;+ else+ if in_class then+ if char == ']' then+ in_class = false;+ end+ elseif char == '[' then+ in_class = true;+ elseif char == '*' or char == '+' or char == '-' or char == '?' then+ count = count + 1;+ end+ index = index + 1;+ end+ end++ return count;+end+local Util = {}Util.__index = Util@@ -103,6 +153,18 @@ function Util.new(module)-- when disabled checking domain name and tenant if available will be skipped, we will check only room name.self.enableDomainVerification = module:get_option_boolean('enable_domain_verification', true);+ --[[+ A room claim that is flagged with context.room.regex is used as a Lua+ pattern. Lua patterns backtrack, so the cost of a match grows as+ (room name length) ^ (number of quantifiers). Both are limited to keep+ the cost of one match bounded, because a match blocks Prosody.+ Measured worst case with the defaults below is about 70ms; lowering+ the quantifier limit to 2 brings that down to about 2ms.+ --]]+ self.regexEnabled = module:get_option_boolean('token_regex_enabled', true);+ self.regexRoomMaxLength = module:get_option_number('token_regex_room_max_length', 128);+ self.regexRoomMaxQuantifiers = module:get_option_number('token_regex_max_quantifiers', 3);+if self.allowEmptyToken == true thenmodule:log("warn", "WARNING - empty tokens allowed");end@@ -359,6 +421,14 @@ function Util:process_and_verify_token(session)endif claims["context"]["room"] ~= nil thensession.jitsi_meet_context_room = claims["context"]["room"]++ -- the signature is verified at this point, so report the tokens+ -- that ask for their room claim to be used as a pattern+ if is_regex_room_claim(claims["context"]["room"]) then+ measure_regex_room_claim(1);+ module:log('info', 'Room claim is a pattern. tenant:%s iss:%s room:%s',+ claims["context"]["tenant"], claims["iss"], claims["room"]);+ endendelseif claims["user_id"] thensession.jitsi_meet_context_user = {};@@ -411,10 +481,17 @@ function Util:verify_room(session, room_address)return true;end+ local auth_room_is_pattern = is_regex_room_claim(session.jitsi_meet_context_room);+local auth_room = session.jitsi_meet_room;if auth_room thenif type(auth_room) == 'string' then- auth_room = string.lower(auth_room);+ -- Room names are lowercase. Lowercase a literal room claim so that+ -- a token with uppercase letters still matches. Keep a pattern as+ -- written: pattern classes are case-sensitive (%d vs %D).+ if not auth_room_is_pattern then+ auth_room = string.lower(auth_room);+ endelsemodule:log('warn', 'session.jitsi_meet_room not string: %s', inspect(auth_room));end@@ -452,8 +529,27 @@ function Util:verify_room(session, room_address)endelse-- no wildcard, so check room against authorized room from the token- if session.jitsi_meet_context_room and (session.jitsi_meet_context_room["regex"] == true or session.jitsi_meet_context_room["regex"] == "true") then+ if auth_room_is_pattern then+ if not self.regexEnabled then+ module:log('warn', 'Room claim patterns are disabled, refusing the claim: %s', auth_room);+ return false, 'invalid-regex', 'Room claim patterns are not enabled';+ end+local match_target = target_room ~= nil and target_room or room_node;++ if #match_target > self.regexRoomMaxLength then+ module:log('warn', 'Room name is longer than %s, not matching it against a pattern: %s',+ self.regexRoomMaxLength, match_target);+ return false, 'invalid-regex', 'Room name is too long to match against the room claim';+ end++ local quantifiers = count_pattern_quantifiers(auth_room);+ if quantifiers > self.regexRoomMaxQuantifiers then+ module:log('warn', 'Room claim has %s quantifiers, more than the limit of %s: %s',+ quantifiers, self.regexRoomMaxQuantifiers, auth_room);+ return false, 'invalid-regex', 'Room claim pattern is too complex';+ end+local ok, result = pcall(string.match, match_target, auth_room);if not ok thenreturn false, 'invalid-regex', 'Room claim is not a valid Lua pattern';diff --git a/tests/prosody/docker/cfg/components.cfg.lua b/tests/prosody/docker/cfg/components.cfg.luaindex a9f40248bd..300b73cf05 100644--- a/tests/prosody/docker/cfg/components.cfg.lua+++ b/tests/prosody/docker/cfg/components.cfg.lua@@ -122,3 +122,15 @@ Component "conference-allowners.localhost" "muc"muc_mapper_domain_base = "localhost"muc_mapper_domain_prefix = "conference"allowners_moderated_rooms = { "moderated-room-1"; "moderated-room-2" }++-- MUC component paired with VirtualHost "noregex.test". Its parent host+-- (derived from the component name by mod_token_verification) sets+-- token_regex_enabled = false, so a join whose token carries a room-claim+-- pattern is refused with <invalid-regex/>.+Component "conference.noregex.test" "muc"+ storage = "memory"+ modules_enabled = {+ "token_verification";+ }+ muc_mapper_domain_base = "noregex.test"+ muc_mapper_domain_prefix = "conference"diff --git a/tests/prosody/docker/cfg/virtualhosts.cfg.lua b/tests/prosody/docker/cfg/virtualhosts.cfg.luaindex ff343d459c..e45a06b9d3 100644--- a/tests/prosody/docker/cfg/virtualhosts.cfg.lua+++ b/tests/prosody/docker/cfg/virtualhosts.cfg.lua@@ -111,6 +111,25 @@ VirtualHost "hs256.localhost"-- Second VirtualHost whose domain is listed in muc_access_whitelist on the-- MUC component below. Clients connecting here get JIDs like-- <random>@whitelist.localhost and are treated as whitelisted.+-- VirtualHost with room-claim patterns turned off (token_regex_enabled), used+-- to test that a token flagged with context.room.regex is refused rather than+-- matched. mod_token_verification reads token options from the PARENT host of+-- the MUC component, so the option must live here and not on the component.+-- muc_mapper_domain_base is set so that verify_room builds the MUC domain of+-- the paired component below, and not the global conference.localhost.+-- The host deliberately sits outside .localhost: mod_muc_domain_mapper is+-- enabled for every host and would read "conference.noregex.localhost" as the+-- multidomain form of "[noregex][email protected]", moving the room+-- off this component entirely.+VirtualHost "noregex.test"+ authentication = "token"+ app_id = "jitsi"+ asap_key_server = "http://localhost:5280/test-observer/asap-keys"+ signature_algorithm = "RS256"+ allow_empty_token = true+ token_regex_enabled = false+ muc_mapper_domain_base = "noregex.test"+-- VirtualHost used by mod_auth_jitsi-anonymous tests.VirtualHost "jitsi-anonymous.localhost"authentication = "jitsi-anonymous"diff --git a/tests/prosody/mod_auth_token_asap_spec.js b/tests/prosody/mod_auth_token_asap_spec.jsindex c9b42330ec..21d8390091 100644--- a/tests/prosody/mod_auth_token_asap_spec.js+++ b/tests/prosody/mod_auth_token_asap_spec.js@@ -227,4 +227,197 @@ describe('mod_auth_token (ASAP / RS256)', () => {'error must contain <invalid-regex/>');});++ // ── Room regex claim: pattern is used as written ──────────────────────────+ //+ // Lua pattern classes are case-sensitive: %d is a digit, %D is anything+ // but a digit. verify_room() must therefore not change the case of a room+ // claim that is flagged as a pattern.++ // Letters only, so that the room name matches %D+ ("not a digit").+ const lettersOnly = () => Date.now()+ .toString(36)+ .replace(/[0-9]/g, 'x');++ it('accepts MUC join when the regex room claim uses an uppercase class', async () => {+ const CONFERENCE = 'conference.localhost';+ const roomJid = `rxcase${lettersOnly()}@${CONFERENCE}`;++ const token = mintAsapToken({+ room: 'rxcase%D+',+ 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.notEqual(presence.attrs.type, 'error',+ `join must succeed: ${presence.toString()}`);+ });++ it('rejects MUC join when the room does not match the regex room claim', async () => {+ const CONFERENCE = 'conference.localhost';+ const roomJid = `rxcase${Date.now()}@${CONFERENCE}`;++ // 'rxcase%D+' does not match a room name that ends in digits.+ const token = mintAsapToken({+ room: 'rxcase%D+',+ 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('room-name-does-not-match'),+ 'error must contain <room-name-does-not-match/>'+ );+ });++ // ── Room regex claim: matching limits ─────────────────────────────────────+ //+ // Lua patterns backtrack, and one match blocks Prosody. verify_room()+ // therefore refuses to match a room name that is longer than+ // token_regex_room_max_length (128), or a pattern that has more than+ // token_regex_max_quantifiers (3) quantifiers. Both refusals report+ // <invalid-regex/>, which distinguishes them from a pattern that was+ // evaluated and did not match (<room-name-does-not-match/>).++ it('accepts MUC join when the regex room claim is at the quantifier limit', async () => {+ const CONFERENCE = 'conference.localhost';+ const roomJid = `rxlimit${lettersOnly()}@${CONFERENCE}`;++ // Three quantifiers is the default limit, and must still be allowed.+ const token = mintAsapToken({+ room: 'rxlimit%D*%D*%D+',+ 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.notEqual(presence.attrs.type, 'error',+ `join must succeed: ${presence.toString()}`);+ });++ it('rejects MUC join when the regex room claim has too many quantifiers', async () => {+ const CONFERENCE = 'conference.localhost';++ // Under the 128-char room-name limit, so the quantifier limit is what+ // must reject this join.+ const roomJid = `${'a'.repeat(90)}${lettersOnly()}@${CONFERENCE}`;++ // The pathological case: four quantifiers over a long run of 'a's, and+ // a trailing '%d' that a letters-only room name can never satisfy, so+ // every combination is tried before the match fails.+ const token = mintAsapToken({+ room: 'a*a*a*a*%d',+ 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'),+ `pattern must be refused unevaluated: ${presence.toString()}`+ );+ });++ it('rejects MUC join when the room name is too long to match a regex claim', async () => {+ const CONFERENCE = 'conference.localhost';++ // Over the 128-char room-name limit.+ const roomJid = `${'x'.repeat(150)}${lettersOnly()}@${CONFERENCE}`;++ // '.*' matches any room name, so without the length limit this join+ // would be allowed.+ const token = mintAsapToken({+ room: '.*',+ 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'),+ `long room name must not be matched: ${presence.toString()}`+ );+ });++ // ── Room regex claim: token_regex_enabled = false ─────────────────────────+ //+ // conference.noregex.test has a parent host that sets+ // token_regex_enabled = false, so a room claim flagged as a pattern is+ // refused instead of matched. The same claim is accepted on+ // conference.localhost, where the option keeps its default.++ it('rejects MUC join with a regex room claim when patterns are disabled', async () => {+ const roomName = `rxoff${lettersOnly()}`;+ const roomJid = `${roomName}@conference.noregex.test`;++ // Matches the room name, so only the disabled option can reject it.+ const token = mintAsapToken({+ room: 'rxoff%D+',+ context: { room: { regex: true } }+ });++ const focus = await joinWithFocus(roomJid);+ const c = await createXmppClient({ domain: 'noregex.test',+ params: { 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'),+ `pattern must be refused: ${presence.toString()}`+ );+ });++ it('accepts the same regex room claim on a host where patterns are enabled', async () => {+ const roomName = `rxoff${lettersOnly()}`;+ const roomJid = `${roomName}@conference.localhost`;++ const token = mintAsapToken({+ room: 'rxoff%D+',+ 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.notEqual(presence.attrs.type, 'error',+ `join must succeed: ${presence.toString()}`);+ });});