diff --git a/rust/crates/keygo-server/.sqlx/query-40d35a1e67be2c6ef0bcb40f57cf55327b9755adfd81e7d043fdfd0d4532cd03.json b/rust/crates/keygo-server/.sqlx/query-40d35a1e67be2c6ef0bcb40f57cf55327b9755adfd81e7d043fdfd0d4532cd03.json new file mode 100644 index 000000000..5872ef141 --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-40d35a1e67be2c6ef0bcb40f57cf55327b9755adfd81e7d043fdfd0d4532cd03.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "delete from devices where id = $1 and user_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "40d35a1e67be2c6ef0bcb40f57cf55327b9755adfd81e7d043fdfd0d4532cd03" +} diff --git a/rust/crates/keygo-server/.sqlx/query-c26f79cb348e2531a834259034f5acfeda1d8d435f8efccc1ef3ce8da9e512c6.json b/rust/crates/keygo-server/.sqlx/query-c26f79cb348e2531a834259034f5acfeda1d8d435f8efccc1ef3ce8da9e512c6.json new file mode 100644 index 000000000..563c3209c --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-c26f79cb348e2531a834259034f5acfeda1d8d435f8efccc1ef3ce8da9e512c6.json @@ -0,0 +1,92 @@ +{ + "db_name": "PostgreSQL", + "query": "select d.id,\n d.name,\n d.platform,\n d.app_version,\n extract(epoch from d.created_at)::int8 as \"created_at!\",\n extract(epoch from d.last_seen_at)::int8 as \"last_seen_at!\",\n extract(epoch from s.auth_time)::int8 as \"auth_time?\",\n s.id is not null as \"logged_in!\"\n from devices d\n left join sessions s on s.device_id = d.id and s.revoked_at is null and s.expires_at > now()\n where d.user_id = $1\n order by d.created_at", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "devices", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "devices", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "platform", + "type_info": "Text", + "origin": { + "Table": { + "table": "devices", + "name": "platform" + } + } + }, + { + "ordinal": 3, + "name": "app_version", + "type_info": "Text", + "origin": { + "Table": { + "table": "devices", + "name": "app_version" + } + } + }, + { + "ordinal": 4, + "name": "created_at!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 5, + "name": "last_seen_at!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "auth_time?", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 7, + "name": "logged_in!", + "type_info": "Bool", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + null, + null, + null, + null + ] + }, + "hash": "c26f79cb348e2531a834259034f5acfeda1d8d435f8efccc1ef3ce8da9e512c6" +} diff --git a/rust/crates/keygo-server/.sqlx/query-c8589b2275ef641393706157d4968692b1c998f782a23621877eb835b186f003.json b/rust/crates/keygo-server/.sqlx/query-c8589b2275ef641393706157d4968692b1c998f782a23621877eb835b186f003.json new file mode 100644 index 000000000..e6d12ccd0 --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-c8589b2275ef641393706157d4968692b1c998f782a23621877eb835b186f003.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "select device_id from sessions where id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "device_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "sessions", + "name": "device_id" + } + } + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "c8589b2275ef641393706157d4968692b1c998f782a23621877eb835b186f003" +} diff --git a/rust/crates/keygo-server/src/api/error.rs b/rust/crates/keygo-server/src/api/error.rs index 5f2cc9fe5..36a05ca7d 100644 --- a/rust/crates/keygo-server/src/api/error.rs +++ b/rust/crates/keygo-server/src/api/error.rs @@ -26,10 +26,6 @@ pub enum ErrorCode { RegistrationExpired, LoginExpired, // session - #[cfg_attr( - not(test), - expect(dead_code, reason = "no route requires a fresh sign-in yet") - )] FreshAuthRequired, InvalidToken, RefreshExpired, diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index 52755e291..136421785 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -33,6 +33,7 @@ fn v1() -> Router { Router::new() .nest("/meta", routes::meta::router()) .nest("/auth", routes::auth::router()) + .nest("/devices", routes::devices::router()) } async fn not_found() -> ServerError { diff --git a/rust/crates/keygo-server/src/api/routes/auth/login.rs b/rust/crates/keygo-server/src/api/routes/auth/login.rs index 8c0b1a4c4..841c6c37f 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/login.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/login.rs @@ -2,7 +2,7 @@ use crate::api::dpop::SingleUseDpopProof; use crate::api::routes::auth::handshake::StartResponse; use crate::api::routes::auth::session::Session; use crate::api::{AppState, Json, ServerResult}; -use crate::domain::{Device, LoginId, UserId, Username}; +use crate::domain::{DeviceClaim, LoginId, UserId, Username}; use crate::service::login::{self, FinishLogin, StartLogin}; use axum::Router; use axum::extract::State; @@ -41,7 +41,7 @@ async fn start( struct FinishRequest { login_id: LoginId, credential_finalization: CredentialFinalization, - device: Device, + device: DeviceClaim, dpop_binding: DpopBinding, } diff --git a/rust/crates/keygo-server/src/api/routes/auth/logout.rs b/rust/crates/keygo-server/src/api/routes/auth/logout.rs index 583b3df84..4ba7ba4f0 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/logout.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/logout.rs @@ -1,10 +1,16 @@ use crate::api::authenticated::Authenticated; use crate::api::{AppState, ServerResult}; use crate::service::session; +use axum::Router; use axum::extract::State; use axum::http::StatusCode; +use axum::routing::post; -pub async fn logout( +pub fn router() -> Router { + Router::new().route("/", post(logout)) +} + +async fn logout( State(state): State, authenticated: Authenticated, ) -> ServerResult { diff --git a/rust/crates/keygo-server/src/api/routes/auth/mod.rs b/rust/crates/keygo-server/src/api/routes/auth/mod.rs index 6150d1b0b..bfa789773 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/mod.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/mod.rs @@ -1,9 +1,6 @@ use crate::api::AppState; -use crate::api::routes::auth::logout::logout; -use crate::api::routes::auth::token::token; use axum::Router; use axum::extract::DefaultBodyLimit; -use axum::routing::post; mod handshake; mod login; @@ -22,7 +19,7 @@ pub fn router() -> Router { .nest("/register", register::router()) .nest("/login", login::router()) .nest("/step-up", step_up::router()) - .route("/token", post(token)) - .route("/logout", post(logout)) + .nest("/token", token::router()) + .nest("/logout", logout::router()) .layer(DefaultBodyLimit::max(MAX_BODY_BYTES)) } diff --git a/rust/crates/keygo-server/src/api/routes/auth/token.rs b/rust/crates/keygo-server/src/api/routes/auth/token.rs index c64fa16f4..0dc798253 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/token.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/token.rs @@ -4,7 +4,9 @@ use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; use crate::domain::{RefreshToken, RevokeReason}; use crate::service::session; use crate::service::session::RefreshError; +use axum::Router; use axum::extract::State; +use axum::routing::post; use serde::Deserialize; #[derive(Deserialize)] @@ -30,7 +32,11 @@ impl HttpError for RefreshError { } } -pub async fn token( +pub fn router() -> Router { + Router::new().route("/", post(token)) +} + +async fn token( State(state): State, proof: SingleUseDpopProof, Json(request): Json, diff --git a/rust/crates/keygo-server/src/api/routes/devices.rs b/rust/crates/keygo-server/src/api/routes/devices.rs new file mode 100644 index 000000000..e29733805 --- /dev/null +++ b/rust/crates/keygo-server/src/api/routes/devices.rs @@ -0,0 +1,47 @@ +use crate::api::authenticated::Authenticated; +use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; +use crate::domain::{Device, DeviceId}; +use crate::service::device; +use crate::service::device::DeleteDeviceError; +use axum::Router; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum::routing::{delete, get}; +use serde::Serialize; + +pub fn router() -> Router { + Router::new() + .route("/", get(devices)) + .route("/{id}", delete(delete_devices)) +} + +impl HttpError for DeleteDeviceError { + fn code(&self) -> ErrorCode { + match self { + Self::FreshAuthRequired => ErrorCode::FreshAuthRequired, + Self::Db(_) => ErrorCode::Internal, + } + } +} + +#[derive(Serialize)] +struct Devices { + devices: Vec, +} + +async fn devices( + State(state): State, + authenticated: Authenticated, +) -> ServerResult> { + let devices = device::get_devices(&state.db, authenticated.claims().user_id()).await?; + Ok(Json(Devices { devices })) +} + +async fn delete_devices( + State(state): State, + Path(id): Path, + authenticated: Authenticated, +) -> ServerResult { + device::delete_device(&state.db, id, authenticated.claims()).await?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/rust/crates/keygo-server/src/api/routes/mod.rs b/rust/crates/keygo-server/src/api/routes/mod.rs index 5c7ed0e16..8d63b5fa7 100644 --- a/rust/crates/keygo-server/src/api/routes/mod.rs +++ b/rust/crates/keygo-server/src/api/routes/mod.rs @@ -1,3 +1,4 @@ pub mod auth; +pub mod devices; pub mod health; pub mod meta; diff --git a/rust/crates/keygo-server/src/db/devices.rs b/rust/crates/keygo-server/src/db/devices.rs index 7c8dc805f..7f56f5f52 100644 --- a/rust/crates/keygo-server/src/db/devices.rs +++ b/rust/crates/keygo-server/src/db/devices.rs @@ -1,5 +1,7 @@ -use crate::domain::{DeviceId, DeviceInfo, UserId}; +use crate::db::corrupt; +use crate::domain::{Device, DeviceId, DeviceInfo, UserId}; use sqlx::PgConnection; +use uuid::Uuid; pub async fn insert( conn: &mut PgConnection, @@ -43,3 +45,73 @@ pub async fn attach( Ok(result.rows_affected() == 1) } + +struct DeviceRow { + id: Uuid, + name: String, + platform: String, + app_version: String, + created_at: i64, + last_seen_at: i64, + auth_time: Option, + logged_in: bool, +} + +impl TryFrom for Device { + type Error = sqlx::Error; + + fn try_from(row: DeviceRow) -> sqlx::Result { + Ok(Self { + id: row.id.into(), + info: DeviceInfo { + name: row.name.try_into().map_err(corrupt)?, + platform: row.platform.parse().map_err(corrupt)?, + app_version: row.app_version.try_into().map_err(corrupt)?, + }, + created_at: u64::try_from(row.created_at).map_err(corrupt)?, + last_seen_at: u64::try_from(row.last_seen_at).map_err(corrupt)?, + auth_time: row + .auth_time + .map(u64::try_from) + .transpose() + .map_err(corrupt)?, + logged_in: row.logged_in, + }) + } +} + +pub async fn list(conn: &mut PgConnection, user_id: UserId) -> sqlx::Result> { + sqlx::query_as!( + DeviceRow, + r#"select d.id, + d.name, + d.platform, + d.app_version, + extract(epoch from d.created_at)::int8 as "created_at!", + extract(epoch from d.last_seen_at)::int8 as "last_seen_at!", + extract(epoch from s.auth_time)::int8 as "auth_time?", + s.id is not null as "logged_in!" + from devices d + left join sessions s on s.device_id = d.id and s.revoked_at is null and s.expires_at > now() + where d.user_id = $1 + order by d.created_at"#, + user_id.as_uuid(), + ) + .fetch_all(conn) + .await? + .into_iter() + .map(Device::try_from) + .collect() +} + +pub async fn delete(conn: &mut PgConnection, id: DeviceId, user_id: UserId) -> sqlx::Result<()> { + sqlx::query!( + "delete from devices where id = $1 and user_id = $2", + id.as_uuid(), + user_id.as_uuid(), + ) + .execute(conn) + .await?; + + Ok(()) +} diff --git a/rust/crates/keygo-server/src/db/sessions.rs b/rust/crates/keygo-server/src/db/sessions.rs index 7c40fbeed..796ad014f 100644 --- a/rust/crates/keygo-server/src/db/sessions.rs +++ b/rust/crates/keygo-server/src/db/sessions.rs @@ -109,6 +109,20 @@ pub async fn state(conn: &mut PgConnection, session_id: SessionId) -> sqlx::Resu }) } +pub async fn device_id( + conn: &mut PgConnection, + session_id: SessionId, +) -> sqlx::Result> { + let device_id = sqlx::query_scalar!( + "select device_id from sessions where id = $1", + session_id.as_uuid(), + ) + .fetch_optional(conn) + .await?; + + Ok(device_id.map(DeviceId::from)) +} + pub async fn delete_ended(conn: &mut PgConnection, retention: Duration) -> sqlx::Result { let result = sqlx::query!( "delete from sessions diff --git a/rust/crates/keygo-server/src/domain/access_token.rs b/rust/crates/keygo-server/src/domain/access_token.rs index c4ab0f57f..879f29b10 100644 --- a/rust/crates/keygo-server/src/domain/access_token.rs +++ b/rust/crates/keygo-server/src/domain/access_token.rs @@ -163,10 +163,6 @@ impl Claims { &self.cnf.jkt } - #[cfg_attr( - not(test), - expect(dead_code, reason = "no route requires a fresh sign-in yet") - )] pub fn is_fresh(&self) -> bool { self.is_fresh_at(unix_now()) } diff --git a/rust/crates/keygo-server/src/domain/device.rs b/rust/crates/keygo-server/src/domain/device.rs index 60d04781f..1bff999e5 100644 --- a/rust/crates/keygo-server/src/domain/device.rs +++ b/rust/crates/keygo-server/src/domain/device.rs @@ -1,19 +1,12 @@ use super::DeviceId; -use serde::Deserialize; +use super::string_enum::string_enum; +use serde::{Deserialize, Serialize}; use thiserror::Error; use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Platform { - Android, -} - -impl Platform { - pub const fn as_str(self) -> &'static str { - match self { - Self::Android => "android", - } +string_enum! { + pub enum Platform { + Android => "android", } } @@ -27,7 +20,7 @@ pub enum DeviceNameError { InvalidCharacter(char), } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(try_from = "String")] pub struct DeviceName(String); @@ -80,7 +73,7 @@ pub enum AppVersionError { InvalidCharacter(char), } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(try_from = "String")] pub struct AppVersion(String); @@ -113,7 +106,7 @@ impl TryFrom for AppVersion { } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct DeviceInfo { pub name: DeviceName, pub platform: Platform, @@ -121,13 +114,24 @@ pub struct DeviceInfo { } #[derive(Debug, Deserialize)] -pub struct Device { +pub struct DeviceClaim { #[serde(rename = "device_id")] pub id: Option, #[serde(flatten)] pub info: DeviceInfo, } +#[derive(Debug, Serialize)] +pub struct Device { + pub id: DeviceId, + #[serde(flatten)] + pub info: DeviceInfo, + pub created_at: u64, + pub last_seen_at: u64, + pub auth_time: Option, + pub logged_in: bool, +} + #[cfg(test)] mod tests { use super::*; @@ -217,4 +221,34 @@ mod tests { assert!(serde_json::from_value::(bad_name).is_err()); assert!(serde_json::from_value::(bad_platform).is_err()); } + + #[test] + fn device_serializes_flat() { + let id = DeviceId::random(); + let device = Device { + id, + info: serde_json::from_value( + json!({ "name": "Pixel 9", "platform": "android", "app_version": "2.3.0" }), + ) + .unwrap(), + created_at: 1_700_000_000, + last_seen_at: 1_800_000_000, + auth_time: None, + logged_in: false, + }; + + assert_eq!( + serde_json::to_value(device).unwrap(), + json!({ + "id": id, + "name": "Pixel 9", + "platform": "android", + "app_version": "2.3.0", + "created_at": 1_700_000_000, + "last_seen_at": 1_800_000_000, + "auth_time": null, + "logged_in": false, + }), + ); + } } diff --git a/rust/crates/keygo-server/src/domain/mod.rs b/rust/crates/keygo-server/src/domain/mod.rs index 816c254d1..06a4b73bc 100644 --- a/rust/crates/keygo-server/src/domain/mod.rs +++ b/rust/crates/keygo-server/src/domain/mod.rs @@ -5,13 +5,14 @@ mod invite_code; mod invite_hash; mod invite_id; mod session; +mod string_enum; mod time; mod username; #[cfg(test)] pub use access_token::FRESH_AUTH_WINDOW; pub use access_token::{ACCESS_TOKEN_LIFETIME, AccessToken, AccessTokenKey, Claims, TokenIssuer}; -pub use device::{Device, DeviceInfo}; +pub use device::{Device, DeviceClaim, DeviceInfo}; pub use ids::{DeviceId, LoginId, RegistrationId, SessionId, UserId}; pub use invite_code::{InviteCode, InvitePepper}; pub use invite_hash::InviteHash; diff --git a/rust/crates/keygo-server/src/domain/session.rs b/rust/crates/keygo-server/src/domain/session.rs index 18fdceef6..1c79ccca3 100644 --- a/rust/crates/keygo-server/src/domain/session.rs +++ b/rust/crates/keygo-server/src/domain/session.rs @@ -1,3 +1,4 @@ +use super::string_enum::string_enum; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -16,45 +17,12 @@ const TOKEN_BYTES: usize = 32; const ENCODED_LEN: usize = PREFIX.len() + base64::encoded_len(TOKEN_BYTES, false).expect("encoded length can be represented by usize"); -macro_rules! revoke_reasons { - ($($name:ident => $str:literal),+ $(,)?) => { - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - pub enum RevokeReason { - $($name,)+ - } - - impl RevokeReason { - #[cfg(test)] - pub const ALL: &[Self] = &[$(Self::$name,)+]; - - pub const fn as_str(self) -> &'static str { - match self { - $(Self::$name => $str,)+ - } - } - } - - #[derive(Debug, Error)] - #[error("unknown revoke reason {0:?}")] - pub struct UnknownRevokeReason(String); - - impl FromStr for RevokeReason { - type Err = UnknownRevokeReason; - - fn from_str(s: &str) -> Result { - match s { - $($str => Ok(Self::$name),)+ - _ => Err(UnknownRevokeReason(s.to_owned())), - } - } - } - }; -} - -revoke_reasons! { - Replaced => "replaced", - ReuseDetected => "reuse_detected", - Logout => "logout", +string_enum! { + pub enum RevokeReason { + Replaced => "replaced", + ReuseDetected => "reuse_detected", + Logout => "logout", + } } #[derive(Zeroize, ZeroizeOnDrop)] diff --git a/rust/crates/keygo-server/src/domain/string_enum.rs b/rust/crates/keygo-server/src/domain/string_enum.rs new file mode 100644 index 000000000..39f3ffdcb --- /dev/null +++ b/rust/crates/keygo-server/src/domain/string_enum.rs @@ -0,0 +1,98 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +#[error("unknown {kind} {value:?}")] +pub struct UnknownVariant { + kind: &'static str, + value: String, +} + +impl UnknownVariant { + pub(super) fn new(kind: &'static str, value: &str) -> Self { + Self { + kind, + value: value.to_owned(), + } + } +} + +macro_rules! string_enum { + ( + $(#[$attr:meta])* + $vis:vis enum $name:ident { $($variant:ident => $str:literal),+ $(,)? } + ) => { + $(#[$attr])* + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + $vis enum $name { + $($variant,)+ + } + + impl $name { + #[cfg(test)] + #[allow(dead_code, reason = "only enums with a round-trip test iterate their variants")] + pub const ALL: &[Self] = &[$(Self::$variant,)+]; + + pub const fn as_str(self) -> &'static str { + match self { + $(Self::$variant => $str,)+ + } + } + } + + impl ::std::str::FromStr for $name { + type Err = $crate::domain::string_enum::UnknownVariant; + + fn from_str(s: &str) -> Result { + match s { + $($str => Ok(Self::$variant),)+ + _ => Err($crate::domain::string_enum::UnknownVariant::new(stringify!($name), s)), + } + } + } + + impl ::serde::Serialize for $name { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.as_str()) + } + } + + impl<'de> ::serde::Deserialize<'de> for $name { + fn deserialize>(deserializer: D) -> Result { + ::deserialize(deserializer)? + .parse() + .map_err(::serde::de::Error::custom) + } + } + }; +} + +pub(super) use string_enum; + +#[cfg(test)] +mod tests { + use serde_json::json; + + string_enum! { + enum Fruit { + Apple => "apple", + BloodOrange => "blood_orange", + } + } + + #[test] + fn every_variant_round_trips_through_str_and_json() { + for &fruit in Fruit::ALL { + assert_eq!(fruit.as_str().parse::().unwrap(), fruit); + + let encoded = serde_json::to_value(fruit).unwrap(); + assert_eq!(encoded, json!(fruit.as_str())); + assert_eq!(serde_json::from_value::(encoded).unwrap(), fruit); + } + } + + #[test] + fn unknown_names_are_rejected() { + assert!("pear".parse::().is_err()); + assert!(serde_json::from_value::(json!("BloodOrange")).is_err()); + } +} diff --git a/rust/crates/keygo-server/src/service/device.rs b/rust/crates/keygo-server/src/service/device.rs index 93f792d26..1c02efaea 100644 --- a/rust/crates/keygo-server/src/service/device.rs +++ b/rust/crates/keygo-server/src/service/device.rs @@ -1,11 +1,12 @@ use crate::db::{devices, sessions}; -use crate::domain::{Device, DeviceId, DeviceInfo, RevokeReason, UserId}; -use sqlx::PgTransaction; +use crate::domain::{Claims, Device, DeviceClaim, DeviceId, DeviceInfo, RevokeReason, UserId}; +use sqlx::{PgPool, PgTransaction}; +use thiserror::Error; pub async fn attach_or_create( tx: &mut PgTransaction<'_>, user_id: UserId, - requested: Device, + requested: DeviceClaim, ) -> sqlx::Result { if let Some(id) = requested.id && devices::attach(tx, id, user_id, &requested.info).await? @@ -28,16 +29,48 @@ pub async fn create( Ok(device_id) } +pub async fn get_devices(db: &PgPool, user_id: UserId) -> sqlx::Result> { + let mut conn = db.acquire().await?; + devices::list(&mut conn, user_id).await +} + +#[derive(Debug, Error)] +pub enum DeleteDeviceError { + #[error("recent sign-in required")] + FreshAuthRequired, + #[error("database error")] + Db(#[from] sqlx::Error), +} + +pub async fn delete_device( + db: &PgPool, + device_id: DeviceId, + claims: &Claims, +) -> Result<(), DeleteDeviceError> { + let mut conn = db.acquire().await?; + let own = sessions::device_id(&mut conn, claims.session_id()).await?; + if own != Some(device_id) && !claims.is_fresh() { + return Err(DeleteDeviceError::FreshAuthRequired); + } + + devices::delete(&mut conn, device_id, claims.user_id()).await?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; use crate::db::users; - use crate::testing::{JKT, count, device, insert_device, issue_session, username}; + use crate::domain::{FRESH_AUTH_WINDOW, unix_now}; + use crate::service::session::Issued; + use crate::testing::{ + JKT, count, device_claim, device_info, insert_device, issue_session, token_issuer, username, + }; use serde_json::json; use sqlx::PgPool; use uuid::Uuid; - async fn claim_once(db: &PgPool, user_id: UserId, requested: Device) -> DeviceId { + async fn claim_once(db: &PgPool, user_id: UserId, requested: DeviceClaim) -> DeviceId { let mut tx = db.begin().await.unwrap(); let device_id = attach_or_create(&mut tx, user_id, requested).await.unwrap(); tx.commit().await.unwrap(); @@ -56,7 +89,7 @@ mod tests { async fn no_id_creates_a_device(db: PgPool) { let (user_id, existing) = insert_device(&db).await; - let device_id = claim_once(&db, user_id, device(None)).await; + let device_id = claim_once(&db, user_id, device_claim(None)).await; assert_ne!(device_id, existing); assert_eq!(count(&db, "devices").await, 2); @@ -69,7 +102,7 @@ mod tests { json!({ "name": "Pixel 10", "platform": "android", "app_version": "2.4.0" }), ) .unwrap(); - let requested = Device { + let requested = DeviceClaim { id: Some(existing), info, }; @@ -90,7 +123,7 @@ mod tests { let (user_id, existing) = insert_device(&db).await; issue_session(&db, user_id, existing, &JKT).await; - claim_once(&db, user_id, device(Some(existing))).await; + claim_once(&db, user_id, device_claim(Some(existing))).await; assert_eq!( revoke_reasons(&db, existing).await, @@ -107,7 +140,7 @@ mod tests { .await .unwrap(); - claim_once(&db, user_id, device(Some(existing))).await; + claim_once(&db, user_id, device_claim(Some(existing))).await; assert_eq!( revoke_reasons(&db, existing).await, @@ -125,7 +158,7 @@ mod tests { .await .unwrap(); - let device_id = claim_once(&db, user_id, device(Some(foreign))).await; + let device_id = claim_once(&db, user_id, device_claim(Some(foreign))).await; assert_ne!(device_id, foreign); assert_eq!(revoke_reasons(&db, foreign).await, [None]); @@ -143,9 +176,126 @@ mod tests { let (user_id, _) = insert_device(&db).await; let unknown = DeviceId::random(); - let device_id = claim_once(&db, user_id, device(Some(unknown))).await; + let device_id = claim_once(&db, user_id, device_claim(Some(unknown))).await; assert_ne!(device_id, unknown); assert_eq!(count(&db, "devices").await, 2); } + + #[sqlx::test] + async fn listed_device_reflects_only_its_live_session(db: PgPool) { + let (user_id, existing) = insert_device(&db).await; + issue_session(&db, user_id, existing, &JKT).await; + claim_once(&db, user_id, device_claim(Some(existing))).await; + issue_session(&db, user_id, existing, &JKT).await; + + let listed = get_devices(&db, user_id).await.unwrap(); + + assert_eq!(listed.len(), 1); + assert!(listed[0].logged_in); + assert!(listed[0].auth_time.is_some()); + } + + #[sqlx::test] + async fn logged_out_device_is_still_listed(db: PgPool) { + let (user_id, existing) = insert_device(&db).await; + issue_session(&db, user_id, existing, &JKT).await; + sqlx::query("update sessions set revoked_at = now(), revoke_reason = 'logout'") + .execute(&db) + .await + .unwrap(); + + let listed = get_devices(&db, user_id).await.unwrap(); + + assert_eq!(listed.len(), 1); + assert!(!listed[0].logged_in); + assert_eq!(listed[0].auth_time, None); + } + + fn fresh_claims(issued: &Issued) -> Claims { + token_issuer().verify(issued.access_token.expose()).unwrap() + } + + fn stale_claims(issued: &Issued) -> Claims { + let issuer = token_issuer(); + let claims = fresh_claims(issued); + let auth_time = unix_now() - FRESH_AUTH_WINDOW.as_secs() - 1; + let token = issuer.issue(claims.user_id(), claims.session_id(), auth_time, &JKT); + issuer.verify(token.expose()).unwrap() + } + + /// A signed-in device and a second device of the same user. + async fn two_devices(db: &PgPool) -> (Issued, DeviceId) { + let (user_id, own) = insert_device(db).await; + let issued = issue_session(db, user_id, own, &JKT).await; + let other = DeviceId::random(); + let mut conn = db.acquire().await.unwrap(); + devices::insert(&mut conn, other, user_id, &device_info()) + .await + .unwrap(); + (issued, other) + } + + async fn device_exists(db: &PgPool, device_id: DeviceId) -> bool { + sqlx::query_scalar("select exists (select 1 from devices where id = $1)") + .bind(device_id.as_uuid()) + .fetch_one(db) + .await + .unwrap() + } + + #[sqlx::test] + async fn stale_session_removes_its_own_device(db: PgPool) { + let (issued, _) = two_devices(&db).await; + + delete_device(&db, issued.device_id, &stale_claims(&issued)) + .await + .unwrap(); + + assert!(!device_exists(&db, issued.device_id).await); + assert_eq!(count(&db, "sessions").await, 0); + } + + #[sqlx::test] + async fn stale_session_cannot_remove_another_device(db: PgPool) { + let (issued, other) = two_devices(&db).await; + + let result = delete_device(&db, other, &stale_claims(&issued)).await; + + assert!(matches!(result, Err(DeleteDeviceError::FreshAuthRequired))); + assert!(device_exists(&db, other).await); + } + + #[sqlx::test] + async fn fresh_session_removes_another_device(db: PgPool) { + let (issued, other) = two_devices(&db).await; + + delete_device(&db, other, &fresh_claims(&issued)) + .await + .unwrap(); + + assert!(!device_exists(&db, other).await); + assert!(device_exists(&db, issued.device_id).await); + } + + #[sqlx::test] + async fn another_users_device_is_not_removed(db: PgPool) { + let (_, foreign) = insert_device(&db).await; + let user_id = UserId::random(); + let mut conn = db.acquire().await.unwrap(); + users::insert(&mut conn, user_id, &username("bob")) + .await + .unwrap(); + let own = DeviceId::random(); + devices::insert(&mut conn, own, user_id, &device_info()) + .await + .unwrap(); + let issued = issue_session(&db, user_id, own, &JKT).await; + + delete_device(&db, foreign, &fresh_claims(&issued)) + .await + .unwrap(); + + assert!(device_exists(&db, foreign).await); + } } diff --git a/rust/crates/keygo-server/src/service/login/finish.rs b/rust/crates/keygo-server/src/service/login/finish.rs index 7931c3242..6863f5ec8 100644 --- a/rust/crates/keygo-server/src/service/login/finish.rs +++ b/rust/crates/keygo-server/src/service/login/finish.rs @@ -1,6 +1,6 @@ use crate::cache::LoginStates; use crate::db::users; -use crate::domain::{Device, LoginId, TokenIssuer, UserId, Username}; +use crate::domain::{DeviceClaim, LoginId, TokenIssuer, UserId, Username}; use crate::service; use crate::service::handshake::{self, Error}; use crate::service::session::Issued; @@ -10,7 +10,7 @@ use sqlx::PgPool; pub struct FinishLogin { pub login_id: LoginId, pub credential_finalization: CredentialFinalization, - pub device: Device, + pub device: DeviceClaim, pub binding: DpopBinding, pub jkt: [u8; 32], } @@ -69,7 +69,7 @@ mod tests { use super::*; use crate::domain::DeviceId; use crate::testing::{ - PASSWORD, device, finish_login, register, start_login, token_issuer, username, + PASSWORD, device_claim, finish_login, register, start_login, token_issuer, username, }; use keygo_opaque::server::ServerSetup; use std::time::Duration; @@ -82,7 +82,7 @@ mod tests { &input.credential_finalization.to_bytes(), ) .unwrap(), - device: device(None), + device: device_claim(None), binding: DpopBinding::from_bytes(&input.binding.to_bytes()).unwrap(), jkt: input.jkt, } diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index 31ba55091..f7ff52114 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -2,8 +2,8 @@ use crate::api::{AppState, router}; use crate::cache::{LoginStates, StepUpStates}; use crate::db::{devices, invites, sessions, users}; use crate::domain::{ - AccessTokenKey, Device, DeviceId, DeviceInfo, InviteHash, InvitePepper, SessionId, TokenIssuer, - UserId, Username, + AccessTokenKey, DeviceClaim, DeviceId, DeviceInfo, InviteHash, InvitePepper, SessionId, + TokenIssuer, UserId, Username, }; use crate::service::login::{self, FinishLogin, StartLogin}; use crate::service::registration::{self, FinishRegistration, Signup, StartRegistration}; @@ -41,8 +41,8 @@ pub fn device_json() -> Value { pub fn device_info() -> DeviceInfo { serde_json::from_value(device_json()).unwrap() } -pub fn device(id: Option) -> Device { - Device { +pub fn device_claim(id: Option) -> DeviceClaim { + DeviceClaim { id, info: device_info(), } @@ -160,7 +160,7 @@ pub fn finish_login( FinishLogin { login_id: started.login_id, credential_finalization: finish.finalization, - device: device(device_id), + device: device_claim(device_id), binding: finish.session_key.dpop_binding(&JKT), jkt: JKT, }