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.

3 changes: 2 additions & 1 deletion rust/crates/keygo-server/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ fn single_header<A: AsHeaderName>(headers: &HeaderMap, name: A) -> Option<&Heade
#[cfg(test)]
mod tests {
use super::*;
use crate::cache::LoginStates;
use crate::cache::{LoginStates, StepUpStates};
use crate::domain::InvitePepper;
use crate::service::registration::Signup;
use axum::body::Body;
Expand Down Expand Up @@ -90,6 +90,7 @@ mod tests {
db: sqlx::postgres::PgPoolOptions::new()
.connect_lazy_with(sqlx::postgres::PgConnectOptions::new()),
login_states: LoginStates::new(),
step_up_states: StepUpStates::new(),
dpop_verifier: Arc::new(DpopVerifier::new()),
token_issuer: Arc::new(crate::testing::token_issuer()),
}
Expand Down
57 changes: 57 additions & 0 deletions rust/crates/keygo-server/src/api/routes/auth/handshake.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use crate::api::{ErrorCode, HttpError};
use crate::domain::LoginId;
use crate::service::handshake;
use keygo_opaque::CredentialResponse;
use serde::Serialize;

// Sign-in and step-up run the same OPAQUE login, so they share its error codes and bodies.
impl HttpError for handshake::Error {
fn code(&self) -> ErrorCode {
match self {
Self::Expired => ErrorCode::LoginExpired,
Self::Opaque(err) => err.code(),
Self::Db(_) => ErrorCode::Internal,
}
}
}

#[derive(Serialize)]
pub struct StartResponse {
login_id: LoginId,
credential_response: CredentialResponse,
expires_in: u64,
}

impl From<handshake::Started> for StartResponse {
fn from(started: handshake::Started) -> Self {
Self {
login_id: started.login_id,
credential_response: started.credential_response,
expires_in: started.expires_in.as_secs(),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::api::error::render;
use axum::http::StatusCode;
use keygo_opaque::OpaqueError;

#[tokio::test]
async fn expired_logins_are_bad_requests() {
let (status, body) = render(handshake::Error::Expired).await;

assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body["code"], "login_expired");
}

#[tokio::test]
async fn failed_login_finish_matches_failed_start() {
let (status, body) = render(handshake::Error::Opaque(OpaqueError::InvalidLogin)).await;

assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body["code"], "invalid_credentials");
}
}
49 changes: 6 additions & 43 deletions rust/crates/keygo-server/src/api/routes/auth/login.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use crate::api::dpop::SingleUseDpopProof;
use crate::api::routes::auth::handshake::StartResponse;
use crate::api::routes::auth::session::Session;
use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult};
use crate::api::{AppState, Json, ServerResult};
use crate::domain::{Device, LoginId, UserId, Username};
use crate::service::login::{self, FinishLogin, StartLogin};
use axum::Router;
use axum::extract::State;
use axum::routing::post;
use keygo_opaque::{CredentialFinalization, CredentialRequest, CredentialResponse, DpopBinding};
use keygo_opaque::{CredentialFinalization, CredentialRequest, DpopBinding};
use serde::{Deserialize, Serialize};

pub fn router() -> Router<AppState> {
Expand All @@ -15,30 +16,13 @@ pub fn router() -> Router<AppState> {
.route("/finish", post(finish))
}

impl HttpError for login::Error {
fn code(&self) -> ErrorCode {
match self {
Self::Expired => ErrorCode::LoginExpired,
Self::Opaque(err) => err.code(),
Self::Db(_) => ErrorCode::Internal,
}
}
}

#[derive(Deserialize)]
struct StartRequest {
/// Parsed in the handler so a bad name answers `invalid_username`, not `invalid_request`.
username: String,
credential_request: CredentialRequest,
}

#[derive(Serialize)]
struct StartResponse {
login_id: LoginId,
credential_response: CredentialResponse,
expires_in: u64,
}

async fn start(
State(state): State<AppState>,
Json(request): Json<StartRequest>,
Expand All @@ -50,11 +34,7 @@ async fn start(

let started = login::start(&state.db, &state.login_states, &state.opaque_state, input).await?;

Ok(Json(StartResponse {
login_id: started.login_id,
credential_response: started.credential_response,
expires_in: started.expires_in.as_secs(),
}))
Ok(Json(started.into()))
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -98,13 +78,12 @@ async fn finish(
#[cfg(test)]
mod tests {
use super::*;
use crate::api::error::render;
use crate::testing::{
PASSWORD, app_state, count, device_json, post_to, post_with_proof, proof_post, prover,
register, replayable_post, send,
};
use axum::http::StatusCode;
use keygo_opaque::OpaqueError;
use keygo_opaque::CredentialResponse;
use keygo_opaque::client::ClientLogin;
use keygo_opaque::server::ServerSetup;
use serde_json::{Value, json};
Expand Down Expand Up @@ -140,30 +119,14 @@ mod tests {
})
}

#[tokio::test]
async fn expired_logins_are_bad_requests() {
let (status, body) = render(login::Error::Expired).await;

assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body["code"], "login_expired");
}

#[tokio::test]
async fn failed_login_finish_matches_failed_start() {
let (status, body) = render(login::Error::Opaque(OpaqueError::InvalidLogin)).await;

assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body["code"], "invalid_credentials");
}

#[sqlx::test]
async fn logs_in_over_http(db: PgPool) {
let setup = ServerSetup::generate();
let state = app_state(&db, &setup);
let user_id = register(&db, &setup, "ada").await;
let (client, started) = start_over_http(&state, "Ada").await;

assert_eq!(started["expires_in"], login::TTL.as_secs());
assert_eq!(started["expires_in"], state.login_states.ttl().as_secs());
let prover = prover();
let body = finish_body(&started["login_id"], client, &started, prover.jkt());

Expand Down
55 changes: 9 additions & 46 deletions rust/crates/keygo-server/src/api/routes/auth/logout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,66 +16,29 @@ pub async fn logout(
mod tests {
use crate::api::AppState;
use crate::domain::RefreshToken;
use crate::service::session::Issued;
use crate::testing::{app_state, insert_device, issue_session, post_with_proof, prover, send};
use crate::testing::{
app_state, post_with_proof, prover, send_with_nonce, signed_in, with_proof,
};
use axum::body::Body;
use axum::http::header::AUTHORIZATION;
use axum::http::{Request, StatusCode};
use keygo_dpop::DpopProver;
use keygo_dpop::testing::TestSigner;
use keygo_dpop::{DpopProver, Htm, ProofRequest};
use keygo_opaque::server::ServerSetup;
use serde_json::{Value, json};
use sqlx::PgPool;

const LOGOUT: &str = "/api/v1/auth/logout";

async fn signed_in(db: &PgPool, prover: &DpopProver<TestSigner>) -> (AppState, Issued) {
let state = app_state(db, &ServerSetup::generate());
let (user_id, device_id) = insert_device(db).await;
let issued = issue_session(db, user_id, device_id, prover.jkt()).await;
(state, issued)
}

fn logout_request(
state: &AppState,
prover: &DpopProver<TestSigner>,
access_token: &str,
nonce: Option<&str>,
) -> Request<Body> {
let htu = state.public_url.join(LOGOUT).unwrap();
let proof = prover
.proof(&ProofRequest {
htm: Htm::Post,
htu: htu.as_str(),
access_token: Some(access_token),
nonce,
})
.unwrap();
Request::post(LOGOUT)
.header(AUTHORIZATION, format!("DPoP {access_token}"))
.header("dpop", proof)
.body(Body::empty())
.unwrap()
}

/// Logs out with a fresh proof and answers a nonce challenge once, like a real client.
async fn logout(
state: &AppState,
prover: &DpopProver<TestSigner>,
access_token: &str,
) -> (StatusCode, Value) {
let (status, headers, body) =
send(state, logout_request(state, prover, access_token, None)).await;
if body["code"] != "use_dpop_nonce" {
return (status, body);
}
let nonce = headers["dpop-nonce"].to_str().unwrap();
let (status, _, body) = send(
state,
logout_request(state, prover, access_token, Some(nonce)),
)
.await;
(status, body)
send_with_nonce(state, |nonce| {
let request = Request::post(LOGOUT).body(Body::empty()).unwrap();
with_proof(state, prover, request, Some(access_token), nonce)
})
.await
}

fn token_body(refresh_token: &RefreshToken) -> Value {
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/keygo-server/src/api/routes/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ use axum::Router;
use axum::extract::DefaultBodyLimit;
use axum::routing::post;

mod handshake;
mod login;
mod logout;
mod register;
mod session;
mod step_up;
mod token;

/// Every auth endpoint is reachable without a token, so a body beyond the largest legitimate one (a
Expand All @@ -19,6 +21,7 @@ pub fn router() -> Router<AppState> {
Router::new()
.nest("/register", register::router())
.nest("/login", login::router())
.nest("/step-up", step_up::router())
.route("/token", post(token))
.route("/logout", post(logout))
.layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
Expand Down
22 changes: 18 additions & 4 deletions rust/crates/keygo-server/src/api/routes/auth/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,25 @@ use crate::service::session::Issued;
use serde::Serialize;

#[derive(Serialize)]
pub struct Session {
device_id: DeviceId,
pub struct Access {
access_token: AccessToken,
access_expires_in: u64,
}

impl From<AccessToken> for Access {
fn from(access_token: AccessToken) -> Self {
Self {
access_token,
access_expires_in: ACCESS_TOKEN_LIFETIME.as_secs(),
}
}
}

#[derive(Serialize)]
pub struct Session {
device_id: DeviceId,
#[serde(flatten)]
access: Access,
refresh_token: RefreshToken,
refresh_expires_in: u64,
}
Expand All @@ -15,8 +30,7 @@ impl From<Issued> for Session {
fn from(value: Issued) -> Self {
Self {
device_id: value.device_id,
access_token: value.access_token,
access_expires_in: ACCESS_TOKEN_LIFETIME.as_secs(),
access: value.access_token.into(),
refresh_token: value.refresh_token,
refresh_expires_in: value.refresh_expires_in.as_secs(),
}
Expand Down
Loading
Loading