Skip to main content

tuwunel_service/oauth/
server.rs

1mod auth;
2mod client;
3mod device;
4mod jwk;
5mod signing_key;
6mod token;
7
8use std::{
9	fmt::{Debug, Formatter, Result as FmtResult},
10	sync::Arc,
11};
12
13use serde_json::Value as JsonValue;
14use tuwunel_core::{Err, Result, debug_info, debug_warn, err, implement, utils::MutexMap, warn};
15use tuwunel_database::Map;
16
17pub use self::{
18	auth::{AUTH_REQUEST_LIFETIME, AuthCodeSession, AuthRequest},
19	client::{ClientRegistration, DcrRequest},
20	device::{
21		ApprovedDeviceGrant, DEVICE_GRANT_INTERVAL_SECS, DEVICE_GRANT_LIFETIME, DeviceGrant,
22		DeviceGrantPoll, DeviceGrantStatus, format_user_code,
23	},
24	token::IdTokenClaims,
25};
26use self::{
27	jwk::init_jwk,
28	signing_key::{SigningKey, init_signing_key},
29};
30use crate::services::OnceServices;
31
32pub struct Server {
33	services: Arc<OnceServices>,
34	db: Data,
35	jwk: JsonValue,
36	key: SigningKey,
37
38	/// Serializes the read-check-consume of a device grant by its `device_code`
39	/// so concurrent polls of one approved grant cannot each mint a device.
40	device_locks: MutexMap<String, ()>,
41
42	/// Serializes selection, claim and completion of one authorization request
43	/// by its id, holding one entry per request with a holder in flight.
44	auth_request_locks: MutexMap<String, ()>,
45
46	/// Serializes code consumption, retaining one entry per code with active contenders.
47	auth_code_locks: MutexMap<AuthCode, ()>,
48}
49
50#[derive(Clone, Eq, Hash, PartialEq)]
51struct AuthCode(String);
52
53struct Data {
54	oidc_signingkey: Arc<Map>,
55	oidcclientid_registration: Arc<Map>,
56	oidccode_authsession: Arc<Map>,
57	oidcdevicecode_devicegrant: Arc<Map>,
58	oidcusercode_devicecode: Arc<Map>,
59	oidcreqid_authrequest: Arc<Map>,
60}
61
62impl Debug for AuthCode {
63	fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { f.write_str("[redacted]") }
64}
65
66impl Server {
67	pub(super) fn build(args: &crate::Args<'_>) -> Result<Option<Self>> {
68		if !Self::can_build(args) {
69			return Ok(None);
70		}
71
72		let db = Data {
73			oidc_signingkey: args.db["oidc_signingkey"].clone(),
74			oidcclientid_registration: args.db["oidcclientid_registration"].clone(),
75			oidccode_authsession: args.db["oidccode_authsession"].clone(),
76			oidcdevicecode_devicegrant: args.db["oidcdevicecode_devicegrant"].clone(),
77			oidcusercode_devicecode: args.db["oidcusercode_devicecode"].clone(),
78			oidcreqid_authrequest: args.db["oidcreqid_authrequest"].clone(),
79		};
80
81		let key = init_signing_key(&db)?;
82		debug_info!(
83			key = ?key.key_id,
84			"Initializing OIDC server for next-gen auth (MSC2965)"
85		);
86
87		Ok(Some(Self {
88			services: args.services.clone(),
89			db,
90			jwk: init_jwk(&key.key_der, &key.key_id)?,
91			key,
92			device_locks: MutexMap::new(),
93			auth_request_locks: MutexMap::new(),
94			auth_code_locks: MutexMap::new(),
95		}))
96	}
97}
98
99#[implement(Server)]
100fn can_build(args: &crate::Args<'_>) -> bool {
101	let has_idp = !args.server.config.identity_provider.is_empty();
102	let has_cwk = args.server.config.well_known.client.is_some();
103	let native = args.server.config.authentication.oidc.native_auth;
104
105	if (has_idp || native) && !has_cwk {
106		warn!("OIDC server (Next-gen auth) requires `well_known.client` to be configured.");
107
108		return false;
109	}
110
111	if !has_idp && !native {
112		debug_warn!(
113			"OIDC server (Next-gen auth) requires at least one `identity_provider`, or \
114			 `authentication.oidc.native_auth` to be enabled."
115		);
116
117		return false;
118	}
119
120	true
121}
122
123#[implement(Server)]
124pub fn issuer_url(&self) -> Result<String> {
125	self.services
126		.config
127		.well_known
128		.client
129		.as_ref()
130		.map(|url| {
131			let s = url.to_string();
132
133			if s.ends_with('/') { s } else { format!("{s}/") }
134		})
135		.ok_or_else(|| {
136			err!(Config("well_known.client", "well_known.client must be set for OIDC server"))
137		})
138}
139
140/// MSC2967 device-scope prefixes, stable spelling first.
141const DEVICE_SCOPE_PREFIXES: [&str; 2] =
142	["urn:matrix:client:device:", "urn:matrix:org.matrix.msc2967.client:device:"];
143
144/// MSC2967 API-scope prefixes, stable spelling first.
145const API_SCOPE_PREFIXES: [&str; 2] =
146	["urn:matrix:client:api:", "urn:matrix:org.matrix.msc2967.client:api:"];
147
148/// Restricts a requested OAuth scope to supported tokens per RFC 6749 ยง3.3.
149///
150/// Recognized tokens retain their request order, with an MSC2967 device ID
151/// returned separately when present. Unknown tokens are dropped unless `strict`
152/// is set. Multiple device scopes, empty device IDs, and IDs outside the RFC
153/// 6749 scope-token character set return an error.
154pub fn narrow_scope(requested: &str, strict: bool) -> Result<(String, Option<String>)> {
155	let mut granted = String::new();
156	let mut device_id: Option<&str> = None;
157
158	for token in requested.split_whitespace() {
159		let keep = if let Some(id) = DEVICE_SCOPE_PREFIXES
160			.iter()
161			.find_map(|prefix| token.strip_prefix(prefix))
162		{
163			if device_id.is_some() {
164				return Err!(Request(InvalidParam("more than one device scope requested")));
165			}
166			if id.is_empty() || !id.bytes().all(is_scope_char) {
167				return Err!(Request(InvalidParam("device id contains an invalid character")));
168			}
169
170			device_id = Some(id);
171			true
172		} else {
173			token == "openid"
174				|| API_SCOPE_PREFIXES
175					.iter()
176					.any(|prefix| token.starts_with(prefix))
177		};
178
179		if keep {
180			if !granted.is_empty() {
181				granted.push(' ');
182			}
183
184			granted.push_str(token);
185		} else if strict {
186			return Err!(Request(InvalidParam("unsupported scope requested")));
187		}
188	}
189
190	Ok((granted, device_id.map(ToOwned::to_owned)))
191}
192
193/// RFC 6749 appendix A NQCHAR: printable ASCII except space, double quote
194/// and backslash. MSC4108 clients use unpadded base64 device ids.
195#[inline]
196fn is_scope_char(b: u8) -> bool { b.is_ascii_graphic() && !matches!(b, b'"' | b'\\') }
197
198#[cfg(test)]
199mod tests {
200	use super::narrow_scope;
201
202	#[test]
203	fn narrow_scope_keeps_known_drops_unknown() {
204		let requested =
205			"openid urn:matrix:client:api:* urn:matrix:client:device:ABCDEFGHIJ custom:x";
206
207		let (granted, device) = narrow_scope(requested, false).expect("narrows");
208
209		assert_eq!(granted, "openid urn:matrix:client:api:* urn:matrix:client:device:ABCDEFGHIJ");
210		assert_eq!(device.as_deref(), Some("ABCDEFGHIJ"));
211	}
212
213	#[test]
214	fn narrow_scope_strict_rejects_unknown() {
215		narrow_scope("openid custom:x", true).unwrap_err();
216		narrow_scope("openid custom:x", false).unwrap();
217	}
218
219	#[test]
220	fn narrow_scope_accepts_unstable_device_spelling() {
221		let scope = "urn:matrix:org.matrix.msc2967.client:device:DEV0123456";
222		let (_granted, device) = narrow_scope(scope, false).expect("narrows");
223
224		assert_eq!(device.as_deref(), Some("DEV0123456"));
225	}
226
227	#[test]
228	fn narrow_scope_rejects_two_device_scopes() {
229		let two = "urn:matrix:client:device:AAAAAAAAAA urn:matrix:client:device:BBBBBBBBBB";
230
231		narrow_scope(two, false).unwrap_err();
232	}
233
234	#[test]
235	fn narrow_scope_accepts_base64_device_id() {
236		let scope = "urn:matrix:client:device:wjLpTLRqbqBzLs63aYaEv2Boi6cFEbbM/V+afGmU5+0";
237		let (_granted, device) = narrow_scope(scope, false).expect("narrows");
238
239		assert_eq!(device.as_deref(), Some("wjLpTLRqbqBzLs63aYaEv2Boi6cFEbbM/V+afGmU5+0"));
240	}
241
242	#[test]
243	fn narrow_scope_rejects_invalid_device_id() {
244		narrow_scope("urn:matrix:client:device:bad\"id", false).unwrap_err();
245		narrow_scope("urn:matrix:client:device:bad\\id", false).unwrap_err();
246	}
247}