Skip to main content

tuwunel_service/migrations/
account_status.rs

1use std::sync::Arc;
2
3use futures::TryStreamExt;
4use ruma::OwnedUserId;
5use tuwunel_core::{Error, Result, err, info, warn};
6use tuwunel_database::{KeyBuf, Map};
7
8use crate::{
9	Services,
10	integrity::account_status::{
11		Columns, Named, Subject, columns, deactivations, hash_kept, subjects,
12		unmarked_passwordless,
13	},
14	users::{PASSWORD_DISABLED, PASSWORD_SENTINEL},
15};
16
17/// Reconciles account states a foreign database keeps outside the password
18/// column.
19///
20/// Some databases mark deactivation in a column of its own while leaving the
21/// hash in place, and spell an account authenticated elsewhere as an empty
22/// hash. This server reads both states from the password alone, so until they
23/// are adopted a deactivated account reads as active and an externally
24/// authenticated one reads as deactivated. Adoption happens once, because
25/// local administration writes the same column afterward and a second pass
26/// would undo it.
27#[tracing::instrument(level = "debug", skip_all)]
28pub(super) async fn migrate_account_status(services: &Services) -> Result {
29	let Columns { deactivated, subjects } = columns(services)?;
30
31	if let Some(deactivated) = deactivated.as_ref() {
32		adopt_deactivations(services, deactivated).await?;
33	}
34
35	if let Some(subjects) = subjects.as_ref() {
36		adopt_passwordless(services, subjects, deactivated.as_ref()).await?;
37	}
38
39	Ok(())
40}
41
42/// Empties the password of every account a foreign column marks deactivated.
43///
44/// The marker is invisible here while the surviving hash reads as an active
45/// account, restoring a login the origin had already withdrawn. An empty
46/// password is the same state spelled locally, and costs the foreign hash,
47/// which decides nothing for an account deactivated on both sides.
48#[tracing::instrument(level = "debug", skip_all)]
49pub(super) async fn adopt_deactivations(services: &Services, deactivated: &Arc<Map>) -> Result {
50	let userid_password = &services.db["userid_password"];
51	let cork = services.db.cork_and_sync();
52
53	// One account at a time, each decided against its row as it is written.
54	let (adopted, unreadable) = deactivations(services, deactivated)
55		.try_fold((0_usize, 0_usize), async |counts, account| {
56			let adoptable = match account {
57				| Ok(Named { user_id, .. }) => hash_kept(services, &user_id)
58					.await
59					.map(|kept| kept.then_some(user_id)),
60				| Err(key) => Err(unparsable("deactivated account", &key)),
61			};
62
63			Ok(write_password(userid_password, PASSWORD_DISABLED, counts, adoptable))
64		})
65		.await?;
66
67	drop(cork);
68
69	if adopted > 0 {
70		info!(%adopted, "Adopted deactivated accounts from a foreign database");
71	}
72
73	unreadable
74		.eq(&0)
75		.then_some(())
76		.ok_or_else(|| err!(Database("{unreadable} accounts could not be read")))
77}
78
79/// Restores the sentinel password on accounts an identity provider
80/// authenticates.
81///
82/// A foreign database spells "no local password" as an empty hash, which reads
83/// here as deactivated and refuses the account every login flow. Only accounts
84/// carrying a provider subject are restored, because an empty hash on its own
85/// cannot be told apart from a deactivation this server wrote.
86///
87/// The sentinel carries that meaning locally, leaving the account active with
88/// no password to verify against, while an account the foreign column marks
89/// deactivated keeps its deactivation.
90#[tracing::instrument(level = "debug", skip_all)]
91pub(super) async fn adopt_passwordless(
92	services: &Services,
93	subjects_column: &Arc<Map>,
94	deactivated: Option<&Arc<Map>>,
95) -> Result {
96	let userid_password = &services.db["userid_password"];
97	let cork = services.db.cork_and_sync();
98
99	// One account at a time, each decided against its row as it is written.
100	let (adopted, unreadable) = subjects(services, subjects_column)
101		.try_fold((0_usize, 0_usize), async |counts, subject| {
102			let adoptable = match subject {
103				| Subject::UnusableLocalpart { .. } => Ok(None),
104				| Subject::Account(Named { user_id, .. }) =>
105					unmarked_passwordless(services, deactivated, &user_id)
106						.await
107						.map(|due| due.then_some(user_id)),
108				| Subject::Unparsable { key } => Err(unparsable("provider subject", &key)),
109			};
110
111			Ok(write_password(userid_password, PASSWORD_SENTINEL, counts, adoptable))
112		})
113		.await?;
114
115	drop(cork);
116
117	if adopted > 0 {
118		info!(%adopted, "Restored accounts authenticated elsewhere from a foreign database");
119	}
120
121	unreadable
122		.eq(&0)
123		.then_some(())
124		.ok_or_else(|| err!(Database("{unreadable} accounts could not be read")))
125}
126
127/// Writes one adoptable account, tallying it against the rows that could not be
128/// read.
129///
130/// An account the adoption leaves alone is not counted, while a row that could
131/// not be read is logged and withholds the marker.
132fn write_password(
133	userid_password: &Arc<Map>,
134	password: &str,
135	(adopted, unreadable): (usize, usize),
136	account: Result<Option<OwnedUserId>>,
137) -> (usize, usize) {
138	match account {
139		| Ok(None) => (adopted, unreadable),
140		| Ok(Some(user_id)) => {
141			userid_password.insert(&user_id, password);
142
143			(adopted.saturating_add(1), unreadable)
144		},
145		| Err(e) => {
146			warn!(error = %e, "an account could not be read");
147
148			(adopted, unreadable.saturating_add(1))
149		},
150	}
151}
152
153fn unparsable(row: &str, key: &KeyBuf) -> Error {
154	let key = key.escape_ascii();
155
156	err!(Database("{row} {key} could not be read"))
157}