Skip to main content

tuwunel_service/integrity/
forbidden_names.rs

1//! Existing names the configuration forbids.
2//!
3//! The forbidden patterns refuse new usernames and aliases only, so a name taken
4//! before a pattern was added stays in use. One check covers users, the other
5//! aliases.
6
7use std::{fmt, str::from_utf8};
8
9use futures::{Stream, TryStreamExt};
10use regex::RegexSet;
11use ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId, RoomAliasId, RoomId, UserId};
12use tuwunel_core::{
13	Result,
14	itertools::Itertools,
15	result::NotFound,
16	utils::{BoolExt, TryReadyExt},
17};
18use tuwunel_database::SEP;
19
20use super::{Check, Report, ScanExt, tally};
21use crate::Services;
22
23pub(super) static USERNAMES: Check = Check {
24	name: "forbidden-usernames",
25	about: "No active local user's localpart matches a forbidden username pattern",
26	quiescent: false,
27	walk: |services, limit| tally(usernames(services), limit),
28};
29
30pub(super) static ALIASES: Check = Check {
31	name: "forbidden-aliases",
32	about: "No local alias of a room this server knows matches a forbidden alias name pattern",
33	quiescent: false,
34	walk: |services, limit| tally(aliases(services), limit),
35};
36
37/// An active local user whose localpart a forbidden username pattern matches.
38///
39/// The account stays usable, so only an admin acting on it clears the finding.
40pub struct Username {
41	/// The user.
42	pub user_id: OwnedUserId,
43
44	/// The patterns the localpart matches, joined by commas.
45	pub patterns: String,
46}
47
48/// A local alias whose name a forbidden alias name pattern matches.
49///
50/// The alias keeps resolving, so only an admin acting on it clears the finding.
51pub struct Alias {
52	/// The room the alias names.
53	pub room_id: OwnedRoomId,
54
55	/// The alias.
56	pub alias: OwnedRoomAliasId,
57
58	/// The patterns the alias name matches, joined by commas.
59	pub patterns: String,
60}
61
62/// Streams each active local user a forbidden username pattern matches.
63///
64/// Every row of `userid_password` is read, and an active user is one whose row
65/// holds a password or the passwordless sentinel. A key that is not a user id is
66/// skipped, as the sentinel passwords check reports one that is not text.
67#[tracing::instrument(level = "trace", skip_all)]
68pub fn usernames(services: &Services) -> impl Stream<Item = Result<Username>> + Send + '_ {
69	let patterns = &services.config.registration.forbidden_usernames;
70
71	services.db["userid_password"]
72		.raw_scan()
73		.scanned(&services.server)
74		.ready_try_filter_map(move |(key, value)| Ok(username(services, patterns, key, value)))
75}
76
77/// Streams each local alias of a known room a forbidden alias name pattern
78/// matches.
79///
80/// Every row of `aliasid_alias` is read, and a matching alias is reported only
81/// when its room has a short id, as a room this server knows does. A row whose
82/// key or value does not parse is skipped.
83#[tracing::instrument(level = "trace", skip_all)]
84pub fn aliases(services: &Services) -> impl Stream<Item = Result<Alias>> + Send + '_ {
85	let patterns = &services.config.rooms.forbidden_alias_names;
86	let rooms = &services.db["roomid_shortroomid"];
87
88	// Serial, so a stop request ends the walk at the row after a finding.
89	services.db["aliasid_alias"]
90		.raw_scan()
91		.scanned(&services.server)
92		.ready_try_filter_map(move |(key, value)| Ok(alias(patterns, key, value)))
93		.try_filter_map(async |alias| {
94			let known = rooms
95				.exists(alias.room_id.as_bytes())
96				.await
97				.optional()?;
98
99			Ok(known.map(|()| alias))
100		})
101}
102
103impl Report for Username {
104	fn kind(&self) -> &'static str { "forbidden-username" }
105}
106
107impl fmt::Display for Username {
108	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109		write!(f, "user {} matches forbidden username patterns {}", self.user_id, self.patterns)
110	}
111}
112
113impl Report for Alias {
114	fn kind(&self) -> &'static str { "forbidden-alias" }
115}
116
117impl fmt::Display for Alias {
118	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119		write!(
120			f,
121			"alias {} of {} matches forbidden alias name patterns {}",
122			self.alias, self.room_id, self.patterns
123		)
124	}
125}
126
127fn username(
128	services: &Services,
129	patterns: &RegexSet,
130	key: &[u8],
131	value: &[u8],
132) -> Option<Username> {
133	let user_id: &UserId = from_utf8(key).ok()?.try_into().ok()?;
134	let active = services.globals.user_is_local(user_id) && !value.is_empty();
135	let patterns = active.and_then(|| matched(patterns, user_id.localpart()))?;
136
137	Some(Username { user_id: user_id.to_owned(), patterns })
138}
139
140fn alias(patterns: &RegexSet, key: &[u8], value: &[u8]) -> Option<Alias> {
141	let at = key.iter().position(|&byte| byte == SEP)?;
142	let (room_id, _) = key.split_at(at);
143	let room_id: &RoomId = from_utf8(room_id).ok()?.try_into().ok()?;
144	let alias: &RoomAliasId = from_utf8(value).ok()?.try_into().ok()?;
145	let patterns = matched(patterns, alias.alias())?;
146	let alias = Alias {
147		room_id: room_id.to_owned(),
148		alias: alias.to_owned(),
149		patterns,
150	};
151
152	Some(alias)
153}
154
155pub(crate) fn matched(patterns: &RegexSet, name: &str) -> Option<String> {
156	let matches = patterns.matches(name);
157
158	matches.matched_any().then(|| {
159		matches
160			.iter()
161			.map(|index| &patterns.patterns()[index])
162			.join(", ")
163	})
164}