Skip to main content

tuwunel_service/migrations/
fix_hashed_sentinel_passwords.rs

1use std::sync::Arc;
2
3use tuwunel_core::{
4	Result, debug, info,
5	result::NotFound,
6	utils::{TryReadyExt, stream::TryBroadbandExt},
7	warn,
8};
9use tuwunel_database::Map;
10
11use super::tally::{Outcome, Tally};
12use crate::{
13	Services,
14	integrity::userid_password::{Finding, classify, scan},
15	users::PASSWORD_SENTINEL,
16};
17
18/// Rewrites each hashed sentinel back to the sentinel.
19///
20/// With no identity provider configured the pass waits and reports unfinished, so
21/// a provider added later still gets it.
22#[tracing::instrument(level = "debug", skip_all)]
23pub(super) async fn fix_hashed_sentinel_passwords(services: &Services) -> Result<bool> {
24	if services.config.identity_provider.is_empty() {
25		debug!("Skipping sentinel password migration since no SSO IdP configured.");
26		return Ok(false);
27	}
28
29	let db = &services.db;
30	let cork = db.cork_and_sync();
31	let userid_password = &db["userid_password"];
32
33	warn!(sentinel = %PASSWORD_SENTINEL, "Fixing occurrences of hashed sentinel passwords");
34
35	// Each finding names its own row, so the repairs cannot interfere.
36	let tally = scan(services)
37		.broad_and_then(async |finding| repair(userid_password, &finding).await)
38		.ready_try_fold(Tally::default(), |tally, outcome| Ok(tally.record(outcome)))
39		.await?;
40
41	drop(cork);
42	info!(
43		bad = %tally.repaired,
44		stale = %tally.stale,
45		unparsable = %tally.skipped,
46		"Fixed any occurrences of hashed sentinel passwords"
47	);
48
49	userid_password.sort()?;
50
51	Ok(true)
52}
53
54/// Rewrites the password a finding names, if it still hashes the sentinel.
55///
56/// The row is read again and classified as the check does, so a row changed or
57/// removed since the scan is counted stale and left alone.
58#[tracing::instrument(level = "debug", skip_all)]
59async fn repair(userid_password: &Arc<Map>, finding: &Finding) -> Result<Outcome> {
60	let Finding::Hashed { user_id } = finding else {
61		return Ok(Outcome::Skipped);
62	};
63
64	let current = userid_password
65		.get(user_id.as_str())
66		.await
67		.optional()?;
68
69	let hashed = current
70		.as_deref()
71		.and_then(|value| classify(user_id.as_bytes(), value))
72		.is_some_and(|finding| matches!(finding, Finding::Hashed { .. }));
73
74	if !hashed {
75		return Ok(Outcome::Stale);
76	}
77
78	userid_password.insert(user_id.as_str(), PASSWORD_SENTINEL);
79
80	Ok(Outcome::Repaired)
81}