Skip to main content

tuwunel_service/oauth/
providers.rs

1use std::collections::BTreeMap;
2
3use serde_json::{Map as JsonObject, Value as JsonValue};
4use tokio::sync::RwLock;
5pub use tuwunel_core::config::IdentityProvider as Provider;
6use tuwunel_core::{Err, Result, debug, debug::INFO_SPAN_LEVEL, err, implement};
7use url::Url;
8
9use crate::{SelfServices, client::read_response_capped};
10
11/// Discovered providers
12#[derive(Default)]
13pub struct Providers {
14	services: SelfServices,
15	providers: RwLock<BTreeMap<ProviderId, Provider>>,
16}
17
18/// Identity Provider ID
19pub type ProviderId = String;
20
21#[implement(Providers)]
22pub(super) fn build(args: &crate::Args<'_>) -> Self {
23	Self {
24		services: args.services.clone(),
25		..Default::default()
26	}
27}
28
29/// Get the Provider configuration after any discovery and adjustments
30/// made on top of the admin's configuration. This incurs network-based
31/// discovery on the first call but responds from cache on subsequent calls.
32#[implement(Providers)]
33#[tracing::instrument(level = "debug", skip(self))]
34pub async fn get(&self, id: &str) -> Result<Provider> {
35	if let Some(provider) = self.get_cached(id).await {
36		return Ok(provider);
37	}
38
39	let config = self.get_config(id)?;
40	let id = config.id().to_owned();
41	let mut map = self.providers.write().await;
42	let provider = self.configure(config).await?;
43
44	debug!(?id, ?provider);
45	_ = map.insert(id, provider.clone());
46
47	Ok(provider)
48}
49
50/// Clone the admin-configured Provider matching `id`.
51///
52/// It predates reconciliation with well-known discovery and follows a config
53/// reload; `find_config` documents how `id` resolves.
54#[implement(Providers)]
55pub fn get_config(&self, id: &str) -> Result<Provider> { self.find_config(id).cloned() }
56
57/// Borrow the admin-configured Provider matching `id`.
58///
59/// A provider whose client_id matches wins; otherwise `id` is taken as a brand,
60/// which resolves only when exactly one provider carries it. Anything else is
61/// `NotFound`, and a caller that only reads a field avoids cloning the whole
62/// configuration.
63#[implement(Providers)]
64pub fn find_config(&self, id: &str) -> Result<&Provider> {
65	let providers = &self.services.config.identity_provider;
66	let brand = |config: &&Provider| config.brand.eq_ignore_ascii_case(id);
67
68	providers
69		.values()
70		.find(|config| config.id() == id)
71		.or_else(|| {
72			providers
73				.values()
74				.find(brand)
75				.filter(|_| providers.values().filter(brand).count().eq(&1))
76		})
77		.ok_or_else(|| err!(Request(NotFound("Unrecognized Identity Provider"))))
78}
79
80/// Get the ID of the provider considered "default" as selected by the admin or
81/// by fallback.
82#[implement(Providers)]
83pub fn get_default_id(&self) -> Option<String> {
84	self.find_default_config()
85		.map(Provider::id)
86		.map(ToOwned::to_owned)
87}
88
89/// Borrow the admin-configured Provider preferred among those `admit` accepts.
90///
91/// The provider `find_default_config` selects wins when accepted; otherwise the
92/// first accepted one in configured order stands in.
93#[implement(Providers)]
94pub fn find_preferred_config<Admit>(&self, admit: Admit) -> Option<&Provider>
95where
96	Admit: Fn(&Provider) -> bool,
97{
98	let providers = &self.services.config.identity_provider;
99
100	self.find_default_config()
101		.filter(|provider| admit(provider))
102		.or_else(|| {
103			providers
104				.values()
105				.find(|provider| admit(provider))
106		})
107}
108
109/// Borrow the admin-configured Provider considered "default".
110///
111/// The provider marked `default` wins; otherwise the first configured one
112/// stands in, and `None` means no provider is configured.
113#[implement(Providers)]
114pub fn find_default_config(&self) -> Option<&Provider> {
115	let providers = &self.services.config.identity_provider;
116
117	providers
118		.values()
119		.find(|idp| idp.default)
120		.or_else(|| providers.values().next())
121}
122
123/// Get the discovered provider from the runtime cache. ID may be client_id or
124/// brand if brand is unique among provider configurations.
125#[implement(Providers)]
126async fn get_cached(&self, id: &str) -> Option<Provider> {
127	let providers = self.providers.read().await;
128
129	if let Some(provider) = providers.get(id).cloned() {
130		return Some(provider);
131	}
132
133	providers
134		.values()
135		.find(|provider| provider.brand.eq_ignore_ascii_case(id))
136		.filter(|_| {
137			providers
138				.values()
139				.filter(|provider| provider.brand.eq_ignore_ascii_case(id))
140				.count()
141				.eq(&1)
142		})
143		.cloned()
144}
145
146/// Configure an identity provider; takes the admin-configured instance from the
147/// server's config, queries the provider for discovery, and then returns an
148/// updated config based on the proper reconciliation. This final config is then
149/// cached in memory to avoid repeating this process.
150#[implement(Providers)]
151#[tracing::instrument(
152	level = INFO_SPAN_LEVEL,
153	ret(level = "debug"),
154	skip(self),
155)]
156async fn configure(&self, mut provider: Provider) -> Result<Provider> {
157	_ = provider
158		.name
159		.get_or_insert_with(|| provider.brand.clone());
160
161	if provider.issuer_url.is_none() {
162		_ = provider
163			.issuer_url
164			.replace(match provider.brand.as_str() {
165				| "github" => "https://github.com/login/oauth".try_into()?,
166				| "gitlab" => "https://gitlab.com".try_into()?,
167				| "google" => "https://accounts.google.com".try_into()?,
168				| _ => return Err!(Config("issuer_url", "Required for this provider.")),
169			});
170	}
171
172	// MAS rejects `profile`; its userinfo returns only `sub` and `username`.
173	if provider.scope.is_empty() && provider.brand == "mas" {
174		provider.scope = ["openid".to_owned()].into();
175	}
176
177	let response = self
178		.discover(&provider)
179		.await
180		.and_then(|response| {
181			response.as_object().cloned().ok_or_else(|| {
182				err!(Request(NotJson("Expecting JSON object for discovery response")))
183			})
184		})
185		.and_then(|response| check_issuer(response, &provider))?;
186
187	if provider.authorization_url.is_none() {
188		response
189			.get("authorization_endpoint")
190			.and_then(JsonValue::as_str)
191			.map(Url::parse)
192			.transpose()?
193			.or_else(|| make_url(&provider, "authorize").ok())
194			.map(|url| provider.authorization_url.replace(url));
195	}
196
197	if provider.revocation_url.is_none() {
198		response
199			.get("revocation_endpoint")
200			.and_then(JsonValue::as_str)
201			.map(Url::parse)
202			.transpose()?
203			.or_else(|| make_url(&provider, "revocation").ok())
204			.map(|url| provider.revocation_url.replace(url));
205	}
206
207	if provider.introspection_url.is_none() {
208		response
209			.get("introspection_endpoint")
210			.and_then(JsonValue::as_str)
211			.map(Url::parse)
212			.transpose()?
213			.or_else(|| make_url(&provider, "introspection").ok())
214			.map(|url| provider.introspection_url.replace(url));
215	}
216
217	if provider.userinfo_url.is_none() {
218		response
219			.get("userinfo_endpoint")
220			.and_then(JsonValue::as_str)
221			.map(Url::parse)
222			.transpose()?
223			.or_else(|| match provider.brand.as_str() {
224				| "github" => "https://api.github.com/user".try_into().ok(),
225				| _ => make_url(&provider, "userinfo").ok(),
226			})
227			.map(|url| provider.userinfo_url.replace(url));
228	}
229
230	if provider.token_url.is_none() {
231		response
232			.get("token_endpoint")
233			.and_then(JsonValue::as_str)
234			.map(Url::parse)
235			.transpose()?
236			.or_else(|| {
237				let path = if provider.brand == "github" {
238					"access_token"
239				} else {
240					"token"
241				};
242
243				make_url(&provider, path).ok()
244			})
245			.map(|url| provider.token_url.replace(url));
246	}
247
248	if provider.callback_url.is_none()
249		&& let Some(server_url) = self.services.config.well_known.client.as_ref()
250	{
251		let callback_path =
252			format!("_matrix/client/unstable/login/sso/callback/{}", provider.client_id);
253
254		provider.callback_url = Some(server_url.join(&callback_path)?);
255	}
256
257	Ok(provider)
258}
259
260/// Send a network request to a provider at the computed location of the
261/// `.well-known/openid-configuration`, returning the configuration.
262#[implement(Providers)]
263#[tracing::instrument(level = "debug", ret(level = "trace"), skip(self))]
264pub async fn discover(&self, provider: &Provider) -> Result<JsonValue> {
265	let limit = self
266		.services
267		.config
268		.network
269		.http
270		.max_response_size;
271
272	let response = self
273		.services
274		.client
275		.oauth
276		.get(discovery_url(provider)?)
277		.send()
278		.await?
279		.error_for_status()?;
280
281	let body = read_response_capped(response, limit).await?;
282
283	serde_json::from_slice(&body).map_err(Into::into)
284}
285
286/// Compute the location of the `/.well-known/openid-configuration` based on the
287/// local provider config.
288fn discovery_url(provider: &Provider) -> Result<Url> {
289	let default_url = provider
290		.discovery
291		.then(|| make_url(provider, ".well-known/openid-configuration"))
292		.transpose()?;
293
294	let Some(url) = provider
295		.discovery_url
296		.clone()
297		.filter(|_| provider.discovery)
298		.or(default_url)
299	else {
300		return Err!(Config(
301			"discovery_url",
302			"Failed to determine URL for discovery of provider {}",
303			provider.id()
304		));
305	};
306
307	Ok(url)
308}
309
310/// Validate that the locally configured `issuer_url` matches the issuer claimed
311/// in any response. todo: cryptographic validation is not yet implemented here.
312fn check_issuer(
313	response: JsonObject<String, JsonValue>,
314	provider: &Provider,
315) -> Result<JsonObject<String, JsonValue>> {
316	let expected = provider
317		.issuer_url
318		.as_ref()
319		.map(Url::as_str)
320		.map(|url| url.trim_end_matches('/'));
321
322	let responded = response
323		.get("issuer")
324		.and_then(JsonValue::as_str)
325		.map(|url| url.trim_end_matches('/'));
326
327	if expected != responded {
328		return Err!(Request(Unauthorized(
329			"Configured issuer_url {expected:?} does not match discovered {responded:?}",
330		)));
331	}
332
333	Ok(response)
334}
335
336/// Generate a full URL for a request to the idp based on the idp's derived
337/// configuration.
338fn make_url(provider: &Provider, path: &str) -> Result<Url> {
339	let mut suffix = provider.base_path.clone().unwrap_or_default();
340
341	suffix.push_str(path);
342	let issuer = provider.issuer_url.as_ref().ok_or_else(|| {
343		let id = &provider.client_id;
344		err!(Config("issuer_url", "Provider {id:?} required field"))
345	})?;
346	let issuer_path = issuer.path();
347
348	if issuer_path.ends_with('/') {
349		Ok(issuer.join(suffix.as_str())?)
350	} else {
351		let mut url = issuer.to_owned();
352		url.set_path(&format!("{issuer_path}/"));
353		Ok(url.join(&suffix)?)
354	}
355}