Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 0 additions & 4 deletions rust/crates/keygo-server/src/api/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions rust/crates/keygo-server/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ fn v1() -> Router<AppState> {
Router::new()
.nest("/meta", routes::meta::router())
.nest("/auth", routes::auth::router())
.nest("/devices", routes::devices::router())
}

async fn not_found() -> ServerError {
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/keygo-server/src/api/routes/auth/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -41,7 +41,7 @@ async fn start(
struct FinishRequest {
login_id: LoginId,
credential_finalization: CredentialFinalization,
device: Device,
device: DeviceClaim,
dpop_binding: DpopBinding,
}

Expand Down
8 changes: 7 additions & 1 deletion rust/crates/keygo-server/src/api/routes/auth/logout.rs
Original file line number Diff line number Diff line change
@@ -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<AppState> {
Router::new().route("/", post(logout))
}

async fn logout(
State(state): State<AppState>,
authenticated: Authenticated,
) -> ServerResult<StatusCode> {
Expand Down
7 changes: 2 additions & 5 deletions rust/crates/keygo-server/src/api/routes/auth/mod.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -22,7 +19,7 @@ pub fn router() -> Router<AppState> {
.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))
}
8 changes: 7 additions & 1 deletion rust/crates/keygo-server/src/api/routes/auth/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -30,7 +32,11 @@ impl HttpError for RefreshError {
}
}

pub async fn token(
pub fn router() -> Router<AppState> {
Router::new().route("/", post(token))
}

async fn token(
State(state): State<AppState>,
proof: SingleUseDpopProof,
Json(request): Json<TokenRequest>,
Expand Down
47 changes: 47 additions & 0 deletions rust/crates/keygo-server/src/api/routes/devices.rs
Original file line number Diff line number Diff line change
@@ -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<AppState> {
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<Device>,
}

async fn devices(
State(state): State<AppState>,
authenticated: Authenticated,
) -> ServerResult<Json<Devices>> {
let devices = device::get_devices(&state.db, authenticated.claims().user_id()).await?;
Ok(Json(Devices { devices }))
}

async fn delete_devices(
State(state): State<AppState>,
Path(id): Path<DeviceId>,
authenticated: Authenticated,
) -> ServerResult<StatusCode> {
device::delete_device(&state.db, id, authenticated.claims()).await?;
Ok(StatusCode::NO_CONTENT)
}
1 change: 1 addition & 0 deletions rust/crates/keygo-server/src/api/routes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod auth;
pub mod devices;
pub mod health;
pub mod meta;
74 changes: 73 additions & 1 deletion rust/crates/keygo-server/src/db/devices.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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<i64>,
logged_in: bool,
}

impl TryFrom<DeviceRow> for Device {
type Error = sqlx::Error;

fn try_from(row: DeviceRow) -> sqlx::Result<Self> {
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<Vec<Device>> {
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(())
}
14 changes: 14 additions & 0 deletions rust/crates/keygo-server/src/db/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<DeviceId>> {
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<u64> {
let result = sqlx::query!(
"delete from sessions
Expand Down
Loading
Loading