tuwunel_service/oauth/server/
device.rs1use std::time::{Duration, SystemTime};
2
3use ruma::{OwnedUserId, UserId};
4use serde::{Deserialize, Serialize};
5use tuwunel_core::{Err, Result, err, implement, smallstr::SmallString, utils};
6use tuwunel_database::{Cbor, Deserialized};
7
8#[derive(Clone, Debug, Deserialize, Serialize)]
12pub struct DeviceGrant {
13 pub device_code: String,
14
15 pub user_code: String,
18
19 pub client_id: String,
20 pub scope: String,
21
22 #[serde(default)]
23 authentication: Option<Authentication>,
24
25 pub status: DeviceGrantStatus,
26 pub attempts: u32,
27 pub created_at: SystemTime,
28 pub expires_at: SystemTime,
29}
30
31#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
32struct Authentication {
33 user_id: OwnedUserId,
34 idp_id: Option<ProviderId>,
35}
36
37#[derive(Clone, Debug, Deserialize, Serialize)]
38pub enum DeviceGrantStatus {
39 Pending,
40 Approved {
41 user_id: OwnedUserId,
42 idp_id: Option<String>,
43 },
44 Denied,
45}
46
47pub struct ApprovedDeviceGrant {
49 pub client_id: String,
50 pub scope: String,
51 pub user_id: OwnedUserId,
52 pub idp_id: Option<String>,
53}
54
55pub enum DeviceGrantPoll {
58 Pending,
59 Approved(ApprovedDeviceGrant),
60 Denied,
61 Expired,
62}
63
64const DEVICE_CODE_LENGTH: usize = 64;
65
66const USER_CODE_LENGTH: usize = 10;
71
72const USER_CODE_CHARSET: &[u8] = b"BCDFGHJKLMNPQRSTVWXZ";
76
77const MAX_VERIFY_ATTEMPTS: u32 = 10;
81type ProviderId = SmallString<[u8; 32]>;
82
83pub const DEVICE_GRANT_LIFETIME: Duration = Duration::from_mins(30);
84pub const DEVICE_GRANT_INTERVAL_SECS: u64 = 5;
85
86#[implement(super::Server)]
87#[must_use]
88pub fn create_device_grant(&self, client_id: &str, scope: &str) -> DeviceGrant {
89 let now = SystemTime::now();
90 let device_code = utils::random_string(DEVICE_CODE_LENGTH);
91 let user_code = utils::random_string_from(USER_CODE_CHARSET, USER_CODE_LENGTH);
92 let grant = DeviceGrant {
93 device_code: device_code.clone(),
94 user_code: user_code.clone(),
95 client_id: client_id.to_owned(),
96 scope: scope.to_owned(),
97 authentication: None,
98 status: DeviceGrantStatus::Pending,
99 attempts: 0,
100 created_at: now,
101 expires_at: now
102 .checked_add(DEVICE_GRANT_LIFETIME)
103 .unwrap_or(now),
104 };
105
106 self.db
107 .oidcdevicecode_devicegrant
108 .raw_put(&*device_code, Cbor(&grant));
109
110 self.db
111 .oidcusercode_devicecode
112 .raw_put(&*user_code, Cbor(&device_code));
113
114 grant
115}
116
117#[implement(super::Server)]
120async fn resolve_device_code(&self, user_code: &str) -> Result<String> {
121 let user_code = normalize_user_code(user_code);
122
123 self.db
124 .oidcusercode_devicecode
125 .get(&user_code)
126 .await
127 .deserialized::<Cbor<_>>()
128 .map(|cbor: Cbor<String>| cbor.0)
129 .map_err(|_| err!(Request(NotFound("Unknown or expired user code"))))
130}
131
132#[implement(super::Server)]
133fn ensure_pending_device_grant(&self, grant: &DeviceGrant) -> Result {
134 if SystemTime::now() > grant.expires_at {
135 self.remove_device_grant(&grant.device_code, &grant.user_code);
136
137 return Err!(Request(NotFound("The device authorization has expired")));
138 }
139
140 if !matches!(grant.status, DeviceGrantStatus::Pending) {
141 return Err!(Request(Forbidden("The device authorization was already resolved")));
142 }
143
144 Ok(())
145}
146
147fn device_authentication_matches(
148 grant: &DeviceGrant,
149 user_id: &UserId,
150 idp_id: Option<&str>,
151) -> bool {
152 grant
153 .authentication
154 .as_ref()
155 .is_some_and(|authentication| {
156 authentication.user_id == user_id && authentication.idp_id.as_deref() == idp_id
157 })
158}
159
160#[implement(super::Server)]
161fn bind_device_authentication(
162 &self,
163 mut grant: DeviceGrant,
164 authentication: Authentication,
165) -> Result<DeviceGrant> {
166 if grant
167 .authentication
168 .as_ref()
169 .is_some_and(|bound| bound != &authentication)
170 {
171 return Err!(Request(Forbidden(
172 "The device authorization was authenticated by another user or provider"
173 )));
174 }
175
176 grant.attempts = grant.attempts.saturating_add(1);
177 if grant.attempts > MAX_VERIFY_ATTEMPTS {
178 self.remove_device_grant(&grant.device_code, &grant.user_code);
179
180 return Err!(Request(Forbidden("Too many attempts; request a new code")));
181 }
182
183 grant.authentication = Some(authentication);
184 Ok(grant)
185}
186
187#[implement(super::Server)]
193pub async fn verify_device_grant(
194 &self,
195 user_code: &str,
196 user_id: &UserId,
197 idp_id: Option<&str>,
198) -> Result<DeviceGrant> {
199 let device_code = self.resolve_device_code(user_code).await?;
200 let _lock = self.device_locks.lock(&device_code).await;
201
202 let grant = self.get_device_grant(&device_code).await?;
203 let authentication = Authentication {
204 user_id: user_id.to_owned(),
205 idp_id: idp_id.map(Into::into),
206 };
207
208 self.ensure_pending_device_grant(&grant)?;
209 let grant = self.bind_device_authentication(grant, authentication)?;
210 self.db
211 .oidcdevicecode_devicegrant
212 .raw_put(&*grant.device_code, Cbor(&grant));
213
214 Ok(grant)
215}
216
217#[implement(super::Server)]
218pub async fn approve_device_grant(
219 &self,
220 user_code: &str,
221 user_id: OwnedUserId,
222 idp_id: Option<String>,
223) -> Result {
224 let device_code = self.resolve_device_code(user_code).await?;
225 let _lock = self.device_locks.lock(&device_code).await;
226 let grant = self.get_device_grant(&device_code).await?;
227
228 self.ensure_pending_device_grant(&grant)?;
229
230 if !device_authentication_matches(&grant, &user_id, idp_id.as_deref()) {
231 return Err!(Request(Forbidden(
232 "The device authorization consent does not match its authenticated session"
233 )));
234 }
235
236 let grant = DeviceGrant {
237 status: DeviceGrantStatus::Approved { user_id, idp_id },
238 ..grant
239 };
240
241 self.db
242 .oidcdevicecode_devicegrant
243 .raw_put(&*grant.device_code, Cbor(&grant));
244
245 Ok(())
246}
247
248#[implement(super::Server)]
249pub async fn deny_device_grant(
250 &self,
251 user_code: &str,
252 user_id: OwnedUserId,
253 idp_id: Option<String>,
254) -> Result {
255 let device_code = self.resolve_device_code(user_code).await?;
256 let _lock = self.device_locks.lock(&device_code).await;
257 let grant = self.get_device_grant(&device_code).await?;
258
259 self.ensure_pending_device_grant(&grant)?;
260
261 if !device_authentication_matches(&grant, &user_id, idp_id.as_deref()) {
262 return Err!(Request(Forbidden(
263 "The device authorization consent does not match its authenticated session"
264 )));
265 }
266
267 let grant = DeviceGrant {
268 status: DeviceGrantStatus::Denied,
269 ..grant
270 };
271
272 self.db
273 .oidcdevicecode_devicegrant
274 .raw_put(&*grant.device_code, Cbor(&grant));
275
276 Ok(())
277}
278
279#[implement(super::Server)]
285#[tracing::instrument(level = "debug", skip_all)]
286pub async fn release_device_grant(
287 &self,
288 user_code: &str,
289 user_id: &UserId,
290 idp_id: Option<&str>,
291) -> Result {
292 let device_code = self.resolve_device_code(user_code).await?;
293 let _lock = self.device_locks.lock(&device_code).await;
294 let grant = self.get_device_grant(&device_code).await?;
295
296 self.ensure_pending_device_grant(&grant)?;
297
298 if !device_authentication_matches(&grant, user_id, idp_id) {
299 return Ok(());
300 }
301
302 let grant = DeviceGrant { authentication: None, ..grant };
303
304 self.db
305 .oidcdevicecode_devicegrant
306 .raw_put(&*grant.device_code, Cbor(&grant));
307
308 Ok(())
309}
310
311#[implement(super::Server)]
314pub async fn poll_device_grant(
315 &self,
316 device_code: &str,
317 client_id: &str,
318) -> Result<DeviceGrantPoll> {
319 let _lock = self.device_locks.lock(device_code).await;
322
323 let grant = self.get_device_grant(device_code).await?;
324
325 if grant.client_id != client_id {
326 return Err!(Request(Forbidden("client_id mismatch")));
327 }
328
329 if SystemTime::now() > grant.expires_at {
330 self.remove_device_grant(&grant.device_code, &grant.user_code);
331
332 return Ok(DeviceGrantPoll::Expired);
333 }
334
335 match grant.status {
336 | DeviceGrantStatus::Pending => Ok(DeviceGrantPoll::Pending),
337 | DeviceGrantStatus::Denied => {
338 self.remove_device_grant(&grant.device_code, &grant.user_code);
339
340 Ok(DeviceGrantPoll::Denied)
341 },
342 | DeviceGrantStatus::Approved { user_id, idp_id } => {
343 self.remove_device_grant(&grant.device_code, &grant.user_code);
344
345 Ok(DeviceGrantPoll::Approved(ApprovedDeviceGrant {
346 client_id: grant.client_id,
347 scope: grant.scope,
348 user_id,
349 idp_id,
350 }))
351 },
352 }
353}
354
355#[implement(super::Server)]
356async fn get_device_grant(&self, device_code: &str) -> Result<DeviceGrant> {
357 self.db
358 .oidcdevicecode_devicegrant
359 .get(device_code)
360 .await
361 .deserialized::<Cbor<_>>()
362 .map(|cbor: Cbor<DeviceGrant>| cbor.0)
363 .map_err(|_| err!(Request(Forbidden("Invalid or expired device code"))))
364}
365
366#[implement(super::Server)]
367fn remove_device_grant(&self, device_code: &str, user_code: &str) {
368 self.db
369 .oidcdevicecode_devicegrant
370 .remove(device_code);
371 self.db.oidcusercode_devicecode.remove(user_code);
372}
373
374fn normalize_user_code(input: &str) -> String {
377 input
378 .bytes()
379 .map(|b| b.to_ascii_uppercase())
380 .filter(|b| USER_CODE_CHARSET.contains(b))
381 .map(char::from)
382 .collect()
383}
384
385#[must_use]
387pub fn format_user_code(code: &str) -> String {
388 code.split_at_checked(code.len() / 2)
389 .filter(|(head, tail)| !head.is_empty() && !tail.is_empty())
390 .map(|(head, tail)| format!("{head}-{tail}"))
391 .unwrap_or_else(|| code.to_owned())
392}
393
394#[cfg(test)]
395mod tests {
396 use std::time::{Duration, SystemTime};
397
398 use serde::Serialize;
399 use tuwunel_database::{Cbor, deserialize_from_slice, serialize_to_vec};
400
401 use super::{
402 DeviceGrant, DeviceGrantStatus, USER_CODE_CHARSET, USER_CODE_LENGTH, format_user_code,
403 normalize_user_code,
404 };
405
406 #[derive(Serialize)]
407 struct LegacyDeviceGrant<'a> {
408 device_code: &'a str,
409 user_code: &'a str,
410 client_id: &'a str,
411 scope: &'a str,
412 status: DeviceGrantStatus,
413 attempts: u32,
414 created_at: SystemTime,
415 expires_at: SystemTime,
416 }
417
418 #[test]
419 fn legacy_grant_defaults_to_no_authentication() {
420 let created_at = SystemTime::UNIX_EPOCH + Duration::from_secs(1);
421 let legacy = LegacyDeviceGrant {
422 device_code: "device",
423 user_code: "BCDFGHJKLM",
424 client_id: "client",
425 scope: "openid",
426 status: DeviceGrantStatus::Pending,
427 attempts: 0,
428 created_at,
429 expires_at: created_at + Duration::from_secs(30),
430 };
431
432 let bytes = serialize_to_vec(Cbor(&legacy)).expect("serialize legacy grant");
433 let Cbor(grant): Cbor<DeviceGrant> =
434 deserialize_from_slice(&bytes).expect("deserialize legacy grant");
435
436 assert!(grant.authentication.is_none());
437 }
438
439 #[test]
440 fn format_then_normalize_round_trips() {
441 let code = "BCDFGHJK";
442
443 assert_eq!(normalize_user_code(&format_user_code(code)), code);
444 }
445
446 #[test]
447 fn normalize_strips_separators_and_uppercases() {
448 assert_eq!(normalize_user_code("bcdf-ghjk"), "BCDFGHJK");
449 assert_eq!(normalize_user_code(" bc df ghjk "), "BCDFGHJK");
450 }
451
452 #[test]
453 fn normalize_drops_out_of_charset_characters() {
454 assert_eq!(normalize_user_code("B0C1DAEF"), "BCDF");
455 }
456
457 #[test]
458 fn format_inserts_a_single_separator() {
459 assert_eq!(format_user_code("BCDFGHJK"), "BCDF-GHJK");
460 }
461
462 #[test]
463 fn charset_is_base20_without_vowels_or_digits() {
464 assert_eq!(USER_CODE_CHARSET.len(), 20);
465 assert_eq!(USER_CODE_LENGTH, 10);
466
467 for excluded in b"AEIOUY0123456789" {
469 assert!(!USER_CODE_CHARSET.contains(excluded));
470 }
471 }
472}