Skip to main content

tuwunel_admin/query/oauth/
associate.rs

1use futures::StreamExt;
2use ruma::OwnedUserId;
3use tuwunel_core::{
4	Err, Result, apply, err,
5	itertools::Itertools,
6	utils::{BoolExt, stream::ReadyExt},
7};
8
9use crate::admin_command;
10
11#[admin_command]
12pub(super) async fn oauth_associate(
13	&self,
14	provider: String,
15	user_id: OwnedUserId,
16	claim: Vec<String>,
17	force: bool,
18) -> Result {
19	if !self.services.globals.user_is_local(&user_id) {
20		return Err!(Request(NotFound("User {user_id:?} does not belong to this server.")));
21	}
22
23	if !self.services.users.exists(&user_id).await {
24		return Err!(Request(NotFound("User {user_id:?} is not registered")));
25	}
26
27	let provider = self
28		.services
29		.oauth
30		.providers
31		.get(&provider)
32		.await?;
33
34	let claim = claim
35		.iter()
36		.map(|kv| {
37			let (key, val) = kv
38				.split_once('=')
39				.ok_or_else(|| err!("Missing '=' in --claim {kv}=???"))?;
40
41			if !key.is_empty() && !val.is_empty() {
42				Ok((key, val))
43			} else {
44				Err!("Missing key or value in --claim=key=value argument")
45			}
46		})
47		.map_ok(apply!(2, ToOwned::to_owned))
48		.collect::<Result<_>>()?;
49
50	let committed = self
51		.services
52		.oauth
53		.user_sessions(&user_id)
54		.ready_filter_map(Result::ok)
55		.count()
56		.await;
57
58	if committed > 0 && !force {
59		return Err!(
60			"{user_id} already has {committed} committed OAuth session(s); the pending claim \
61			 would be shadowed at login. Re-run with --force to replace existing sessions, or \
62			 run `query oauth delete {user_id} --force` first."
63		);
64	}
65
66	let deletions = committed
67		.gt(&0)
68		.then_async(|| self.services.oauth.delete_user_sessions(&user_id))
69		.await
70		.transpose()?
71		.unwrap_or_default();
72
73	// A session the delete kept would shadow the claim at login.
74	if deletions.unreadable > 0 {
75		return Err!(
76			"Deleted {} of {user_id}'s OAuth session(s), but {} could not be read and were \
77			 kept; see the log. The pending association was not added.",
78			deletions.deleted(),
79			deletions.unreadable,
80		);
81	}
82
83	let replaced = self
84		.services
85		.oauth
86		.sessions
87		.set_user_association_pending(provider.id(), &user_id, claim);
88
89	let lead = match committed {
90		| 0 => format!("Pending association {}", replaced.map_or("added", |_| "replaced")),
91		| n => format!(
92			"Replaced {n} committed session(s) across all providers and added pending \
93			 association"
94		),
95	};
96
97	writeln!(self, "{lead} for {user_id} on provider {}.", provider.id()).await
98}