Skip to main content

tuwunel_service/oauth/server/
auth.rs

1use std::time::{Duration, SystemTime};
2
3use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD as b64};
4use ruma::OwnedUserId;
5use serde::{Deserialize, Serialize};
6use tuwunel_core::{
7	Err, Result, err, implement,
8	utils::{self, hash::sha256, string::is_unreserved},
9};
10use tuwunel_database::{Cbor, Deserialized};
11
12use super::AuthCode;
13
14/// A pending authorization request, kept from the authorize redirect until the
15/// completion that mints its code.
16///
17/// Native sign-in binds it to one upstream provider or claims it for the local
18/// branch, and completion takes it exactly once.
19#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
20pub struct AuthRequest {
21	pub client_id: String,
22
23	pub redirect_uri: String,
24
25	pub scope: String,
26
27	pub state: Option<String>,
28
29	pub nonce: Option<String>,
30
31	pub code_challenge: Option<String>,
32
33	pub code_challenge_method: Option<String>,
34
35	/// The identity provider ID used to authenticate the user for this
36	/// authorization request. Stored so it can be propagated to the device
37	/// at token exchange time and used for UIAA SSO provider binding.
38	pub idp_id: Option<String>,
39
40	/// Whether a local login or registration has claimed this request.
41	///
42	/// A claim excludes provider selection, as `idp_id` excludes the local
43	/// branch.
44	#[serde(default)]
45	pub local_auth_selected: bool,
46
47	pub response_mode: Option<String>,
48
49	pub created_at: SystemTime,
50
51	pub expires_at: SystemTime,
52}
53
54#[derive(Clone, Debug, Deserialize, Serialize)]
55pub struct AuthCodeSession {
56	pub code: String,
57
58	pub client_id: String,
59
60	pub redirect_uri: String,
61
62	pub scope: String,
63
64	pub state: Option<String>,
65
66	pub nonce: Option<String>,
67
68	pub code_challenge: Option<String>,
69
70	pub code_challenge_method: Option<String>,
71
72	pub user_id: OwnedUserId,
73
74	/// Propagated from the originating AuthRequest; identifies which IdP
75	/// authenticated the user so the device can be tagged at token exchange.
76	pub idp_id: Option<String>,
77
78	pub created_at: SystemTime,
79
80	pub expires_at: SystemTime,
81}
82
83pub const AUTH_REQUEST_LIFETIME: Duration = Duration::from_mins(10);
84const AUTH_CODE_LIFETIME: Duration = Duration::from_mins(10);
85const AUTH_CODE_LENGTH: usize = 64;
86
87#[implement(super::Server)]
88#[must_use]
89pub fn create_auth_code(&self, auth_req: &AuthRequest, user_id: OwnedUserId) -> String {
90	let now = SystemTime::now();
91	let code = utils::random_string(AUTH_CODE_LENGTH);
92	let session = AuthCodeSession {
93		code: code.clone(),
94		client_id: auth_req.client_id.clone(),
95		redirect_uri: auth_req.redirect_uri.clone(),
96		scope: auth_req.scope.clone(),
97		state: auth_req.state.clone(),
98		nonce: auth_req.nonce.clone(),
99		code_challenge: auth_req.code_challenge.clone(),
100		code_challenge_method: auth_req.code_challenge_method.clone(),
101		user_id,
102		idp_id: auth_req.idp_id.clone(),
103		created_at: now,
104		expires_at: now.checked_add(AUTH_CODE_LIFETIME).unwrap_or(now),
105	};
106
107	self.db
108		.oidccode_authsession
109		.raw_put(&*code, Cbor(&session));
110
111	code
112}
113
114#[implement(super::Server)]
115pub fn store_auth_request(&self, req_id: &str, request: &AuthRequest) {
116	self.db
117		.oidcreqid_authrequest
118		.raw_put(req_id, Cbor(request));
119}
120
121/// Read an authorization request without consuming it.
122///
123/// A flow that pauses for a user gesture reads the request to decide what to
124/// show, then takes it with `take_auth_request` or retires it with
125/// `retire_auth_request` once the gesture arrives. An unknown or expired request
126/// is a `NotFound`, and an expired one is evicted as it is found, so no caller
127/// ever renders against a stale request.
128#[implement(super::Server)]
129pub async fn peek_auth_request(&self, req_id: &str) -> Result<AuthRequest> {
130	let request = self
131		.db
132		.oidcreqid_authrequest
133		.get(req_id)
134		.await
135		.deserialized()
136		.map(|cbor: Cbor<AuthRequest>| cbor.0)
137		.map_err(|_| err!(Request(NotFound("Unknown or expired authorization request"))))?;
138
139	if SystemTime::now() > request.expires_at {
140		self.remove_auth_request(req_id);
141
142		return Err!(Request(NotFound("Authorization request has expired")));
143	}
144
145	Ok(request)
146}
147
148/// Bind a native authorization request to one selected upstream provider.
149///
150/// A different provider or a local claim is refused, so one request cannot
151/// complete through two branches. Choosing the same provider again is
152/// harmless, so a repeated click still redirects.
153#[implement(super::Server)]
154pub async fn bind_auth_request_to_provider(&self, req_id: &str, provider_id: &str) -> Result {
155	self.update_auth_request(req_id, |request| {
156		no_other_provider(request, Some(provider_id))
157			.and_then(local_unclaimed)
158			.map(|request| AuthRequest {
159				idp_id: Some(provider_id.to_owned()),
160				..request
161			})
162	})
163	.await
164}
165
166/// Check that a pending request may still complete through the local branch.
167///
168/// A request bound to an upstream provider is refused. One the local branch
169/// already claimed passes, so a resubmitted form still completes.
170#[implement(super::Server)]
171pub async fn check_local_auth_request(&self, req_id: &str) -> Result {
172	self.peek_auth_request(req_id)
173		.await
174		.and_then(|request| no_other_provider(request, None))
175		.map(drop)
176}
177
178/// Claim the local branch of a native authorization request.
179///
180/// A request already bound to a provider is refused. Repeating the claim is
181/// harmless, so a resubmitted form still completes, and the request stays
182/// single-use when it is taken.
183#[implement(super::Server)]
184pub async fn bind_auth_request_to_local(&self, req_id: &str) -> Result {
185	self.update_auth_request(req_id, |request| {
186		no_other_provider(request, None)
187			.map(|request| AuthRequest { local_auth_selected: true, ..request })
188	})
189	.await
190}
191
192/// Take a pending request exactly once, removing it.
193///
194/// A request that changed since the caller read it is refused. The lock is the
195/// one provider selection and local claims acquire, so neither can change the
196/// request between the comparison and the removal.
197#[implement(super::Server)]
198pub async fn take_auth_request(
199	&self,
200	req_id: &str,
201	expected: &AuthRequest,
202) -> Result<AuthRequest> {
203	let _lock = self.auth_request_locks.lock(req_id).await;
204	let request = self.peek_auth_request(req_id).await?;
205
206	if &request != expected {
207		return Err!(Request(Forbidden("Authorization request changed during sign-in")));
208	}
209
210	self.remove_auth_request(req_id);
211
212	Ok(request)
213}
214
215/// Retire a pending request under its lock without reading it.
216///
217/// A refusal needs nothing from the request, and holding the lock keeps a
218/// concurrent provider selection from writing it back.
219#[implement(super::Server)]
220pub async fn retire_auth_request(&self, req_id: &str) {
221	let _lock = self.auth_request_locks.lock(req_id).await;
222
223	self.remove_auth_request(req_id);
224}
225
226/// Remove a pending authorization request without taking its lock.
227///
228/// The request is single-use, so a flow removes it before minting anything
229/// against it. Removing a key that is already gone is a no-op.
230#[implement(super::Server)]
231pub fn remove_auth_request(&self, req_id: &str) { self.db.oidcreqid_authrequest.remove(req_id); }
232
233/// Consumes an authorization code at most once within this server.
234///
235/// Reading and removing a code are serialized independently of authorization
236/// request selection. A decoded code is removed before validating its expiry,
237/// client, redirect URI, or PKCE verifier.
238#[implement(super::Server)]
239pub async fn exchange_auth_code(
240	&self,
241	code: &str,
242	client_id: &str,
243	redirect_uri: &str,
244	code_verifier: Option<&str>,
245	require_pkce: bool,
246) -> Result<AuthCodeSession> {
247	let key = AuthCode(code.to_owned());
248	let lock = self.auth_code_locks.lock(&key).await;
249	let session: AuthCodeSession = self
250		.db
251		.oidccode_authsession
252		.get(code)
253		.await
254		.deserialized::<Cbor<_>>()
255		.map(|cbor: Cbor<AuthCodeSession>| cbor.0)
256		.map_err(|_| err!(Request(Forbidden("Invalid or expired authorization code"))))?;
257
258	self.db.oidccode_authsession.remove(code);
259	drop(lock);
260
261	if SystemTime::now() > session.expires_at {
262		return Err!(Request(Forbidden("Authorization code has expired")));
263	}
264	if session.client_id != client_id {
265		return Err!(Request(Forbidden("client_id mismatch")));
266	}
267	if session.redirect_uri != redirect_uri {
268		return Err!(Request(Forbidden("redirect_uri mismatch")));
269	}
270
271	let Some(challenge) = &session.code_challenge else {
272		// Reject a challenge-less code when PKCE is required: the knob is
273		// reloadable and codes outlive an off->on flip of it.
274		if require_pkce {
275			return Err!(Request(Forbidden(
276				"the authorization request carried no PKCE code_challenge"
277			)));
278		}
279
280		return Ok(session);
281	};
282
283	let Some(verifier) = code_verifier else {
284		return Err!(Request(Forbidden("code_verifier required for PKCE")));
285	};
286
287	validate_code_verifier(verifier)?;
288
289	let method = session
290		.code_challenge_method
291		.as_deref()
292		.unwrap_or("S256");
293
294	// Only S256 is advertised in discovery metadata; reject plain to avoid
295	// downgrade attacks (plain challenge == verifier, trivially intercepted).
296	let computed = match method {
297		| "S256" => b64.encode(sha256::hash(verifier.as_bytes())),
298		| _ => return Err!(Request(InvalidParam("Unsupported code_challenge_method"))),
299	};
300
301	if computed != *challenge {
302		return Err!(Request(Forbidden("PKCE verification failed")));
303	}
304
305	Ok(session)
306}
307
308/// Rewrite a pending request under its lock.
309///
310/// A selection decided against one read cannot then be lost to a concurrent
311/// one.
312#[implement(super::Server)]
313async fn update_auth_request<F>(&self, req_id: &str, update: F) -> Result
314where
315	F: FnOnce(AuthRequest) -> Result<AuthRequest> + Send,
316{
317	let _lock = self.auth_request_locks.lock(req_id).await;
318	let request = self
319		.peek_auth_request(req_id)
320		.await
321		.and_then(update)?;
322
323	self.store_auth_request(req_id, &request);
324
325	Ok(())
326}
327
328/// Refuse a request bound to any provider other than `provider`.
329///
330/// The local branch passes `None`, so every provider binding refuses it.
331fn no_other_provider(request: AuthRequest, provider: Option<&str>) -> Result<AuthRequest> {
332	if request
333		.idp_id
334		.as_deref()
335		.is_some_and(|bound| Some(bound) != provider)
336	{
337		return Err!(Request(Forbidden("Authorization request already selected a provider")));
338	}
339
340	Ok(request)
341}
342
343/// Refuse a request the local branch has already claimed.
344///
345/// A claim excludes provider selection but not a repeated local claim.
346fn local_unclaimed(request: AuthRequest) -> Result<AuthRequest> {
347	if request.local_auth_selected {
348		return Err!(Request(Forbidden(
349			"A local sign-in already claimed this authorization request"
350		)));
351	}
352
353	Ok(request)
354}
355
356/// Validate code_verifier per RFC 7636 Section 4.1: must be 43-128
357/// characters using only unreserved characters [A-Z] / [a-z] / [0-9] /
358/// "-" / "." / "_" / "~".
359fn validate_code_verifier(verifier: &str) -> Result {
360	if !(43..=128).contains(&verifier.len()) {
361		return Err!(Request(InvalidParam("code_verifier must be 43-128 characters")));
362	}
363
364	if !is_unreserved(verifier) {
365		return Err!(Request(InvalidParam("code_verifier contains invalid characters")));
366	}
367
368	Ok(())
369}