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
1 change: 1 addition & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ harness = false
[dependencies]
async-trait = { version = "0.1" }
axum = { version = "0.8", features = ["macros"] }
base64 = { version = "0.22" }
base64 = "0.22"
bcrypt = { version = "0.17", features = ["alloc"] }
bytes = { version = "1.10" }
chrono = { version = "0.4" }
Expand Down Expand Up @@ -60,6 +60,7 @@ utoipa-axum = { version = "0.2" }
utoipa-swagger-ui = { version = "9.0", features = ["axum", "vendored"], default-features = false }
uuid = { version = "1.18", features = ["v4"] }
webauthn-rs = { version = "0.5", features = ["danger-allow-state-serialisation"] }
webauthn-rs-proto = "0.5.2"

[dev-dependencies]
criterion = { version = "0.7", features = ["async_tokio"] }
Expand Down
4 changes: 4 additions & 0 deletions src/api/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ pub enum KeystoneApiError {
source: serde_json::Error,
},

/// Base64 decoding error.
#[error(transparent)]
Base64Decode(#[from] base64::DecodeError),

#[error("domain id or name must be present")]
DomainIdOrName,

Expand Down
62 changes: 56 additions & 6 deletions src/api/v4/user/passkey/register_finish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@ use axum::{
http::StatusCode,
response::IntoResponse,
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE};
use mockall_double::double;
use serde_json::Value;
use tracing::debug;
use webauthn_rs::prelude::*;

use crate::api::auth::Auth;
use crate::api::error::{KeystoneApiError, WebauthnError};
use crate::api::v4::user::types::passkey::UserPasskeyRegistrationFinishRequest;
use crate::api::v4::user::types::passkey::{
AuthenticatorTransport, CredentialProtectionPolicy, UserPasskeyRegistrationFinishRequest,
};
use crate::identity::IdentityApi;
use crate::keystone::ServiceState;
#[double]
Expand Down Expand Up @@ -57,7 +58,7 @@ pub(super) async fn finish(
Path(user_id): Path<String>,
State(state): State<ServiceState>,
mut policy: Policy,
Json(req): Json<Value>,
Json(req): Json<UserPasskeyRegistrationFinishRequest>,
) -> Result<impl IntoResponse, KeystoneApiError> {
let user = state
.provider
Expand Down Expand Up @@ -86,8 +87,10 @@ pub(super) async fn finish(
.get_user_passkey_registration_state(&state.db, &user_id)
.await?
{
let v: RegisterPublicKeyCredential = serde_json::from_value(req)?;
match state.webauthn.finish_passkey_registration(&v, &s) {
match state
.webauthn
.finish_passkey_registration(&req.try_into()?, &s)
{
Ok(sk) => {
state
.provider
Expand All @@ -110,3 +113,50 @@ pub(super) async fn finish(
}
Ok((StatusCode::CREATED).into_response())
}

impl TryFrom<UserPasskeyRegistrationFinishRequest>
for webauthn_rs::prelude::RegisterPublicKeyCredential
{
type Error = KeystoneApiError;
fn try_from(val: UserPasskeyRegistrationFinishRequest) -> Result<Self, Self::Error> {
Ok(webauthn_rs::prelude::RegisterPublicKeyCredential {
id: val.id,
raw_id: URL_SAFE.decode(val.raw_id)?.into(),
type_: val.type_,
response: webauthn_rs_proto::attest::AuthenticatorAttestationResponseRaw {
attestation_object: URL_SAFE.decode(val.response.attestation_object)?.into(),
client_data_json: URL_SAFE.decode(val.response.client_data_json)?.into(),
transports: val.response.transports.map(|i| {
i.into_iter()
.map(|t| match t {
AuthenticatorTransport::Usb => webauthn_rs_proto::options::AuthenticatorTransport::Usb,
AuthenticatorTransport::Nfc => webauthn_rs_proto::options::AuthenticatorTransport::Nfc,
AuthenticatorTransport::Ble => webauthn_rs_proto::options::AuthenticatorTransport::Ble,
AuthenticatorTransport::Internal => webauthn_rs_proto::options::AuthenticatorTransport::Internal,
AuthenticatorTransport::Hybrid => webauthn_rs_proto::options::AuthenticatorTransport::Hybrid,
AuthenticatorTransport::Test => webauthn_rs_proto::options::AuthenticatorTransport::Test,
AuthenticatorTransport::Unknown => webauthn_rs_proto::options::AuthenticatorTransport::Unknown,

})
.collect::<Vec<_>>()
}),
},
extensions: webauthn_rs_proto::extensions::RegistrationExtensionsClientOutputs {
appid: val.extensions.appid,
cred_props: val
.extensions
.cred_props
.map(|x| webauthn_rs_proto::extensions::CredProps { rk: x.rk }),
hmac_secret: val.extensions.hmac_secret,
cred_protect: val.extensions.cred_protect.map(|x| {
match x {
CredentialProtectionPolicy::UserVerificationOptional => webauthn_rs_proto::extensions::CredentialProtectionPolicy::UserVerificationOptional,
CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIDList => webauthn_rs_proto::extensions::CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIDList,
CredentialProtectionPolicy::UserVerificationRequired => webauthn_rs_proto::extensions::CredentialProtectionPolicy::UserVerificationRequired
}
}),
min_pin_length: val.extensions.min_pin_length,
},
})
}
}
148 changes: 146 additions & 2 deletions src/api/v4/user/passkey/register_start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,22 @@ use axum::{
extract::{Path, State},
response::IntoResponse,
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE};
use mockall_double::double;
use tracing::debug;
use webauthn_rs::prelude::*;

use crate::api::auth::Auth;
use crate::api::error::{KeystoneApiError, WebauthnError};
use crate::api::v4::user::types::passkey::UserPasskeyRegistrationStartResponse;
use crate::api::v4::user::types::passkey::{
AttestationConveyancePreference, AttestationFormat, AuthenticatorAttachment,
AuthenticatorSelectionCriteria, AuthenticatorTransport, CredProtect,
CredentialProtectionPolicy, PubKeyCredParams, PublicKeyCredentialCreationOptions,
PublicKeyCredentialDescriptor, PublicKeyCredentialHints, RelyingParty,
RequestRegistrationExtensions, ResidentKeyRequirement, User,
UserPasskeyRegistrationStartRequest, UserPasskeyRegistrationStartResponse,
UserVerificationPolicy,
};
use crate::identity::IdentityApi;
use crate::keystone::ServiceState;
#[double]
Expand All @@ -37,6 +46,7 @@ use crate::policy::Policy;
post,
path = "/register_start",
operation_id = "/user/passkey/register:start",
request_body = UserPasskeyRegistrationStartRequest,
params(
("user_id" = String, Path, description = "The ID of the user.")
),
Expand All @@ -57,6 +67,7 @@ pub(super) async fn start(
Path(user_id): Path<String>,
mut policy: Policy,
State(state): State<ServiceState>,
Json(req): Json<UserPasskeyRegistrationStartRequest>,
) -> Result<impl IntoResponse, KeystoneApiError> {
let user = state
.provider
Expand Down Expand Up @@ -99,7 +110,7 @@ pub(super) async fn start(
.get_identity_provider()
.save_user_passkey_registration_state(&state.db, &user_id, reg_state)
.await?;
Json(ccr)
Json(UserPasskeyRegistrationStartResponse::try_from(ccr)?)
}
Err(e) => {
debug!("challenge_register -> {:?}", e);
Expand All @@ -109,3 +120,136 @@ pub(super) async fn start(

Ok(res)
}

impl TryFrom<webauthn_rs::prelude::CreationChallengeResponse>
for UserPasskeyRegistrationStartResponse
{
type Error = KeystoneApiError;
fn try_from(val: webauthn_rs::prelude::CreationChallengeResponse) -> Result<Self, Self::Error> {
Ok(UserPasskeyRegistrationStartResponse {
public_key: PublicKeyCredentialCreationOptions {
attestation: val.public_key.attestation.map(|att| match att {
webauthn_rs_proto::options::AttestationConveyancePreference::Direct => {
AttestationConveyancePreference::Direct
}
webauthn_rs_proto::options::AttestationConveyancePreference::Indirect => {
AttestationConveyancePreference::Indirect
}
webauthn_rs_proto::options::AttestationConveyancePreference::None => {
AttestationConveyancePreference::None
}
}),
attestation_formats: val
.public_key
.attestation_formats
.map(|afs| {
afs.into_iter().map(|fmt| match fmt {
webauthn_rs_proto::options::AttestationFormat::AndroidKey => {
AttestationFormat::AndroidKey
}
webauthn_rs_proto::options::AttestationFormat::AndroidSafetyNet => {
AttestationFormat::AndroidSafetyNet
}
webauthn_rs_proto::options::AttestationFormat::AppleAnonymous => {
AttestationFormat::AppleAnonymous
}
webauthn_rs_proto::options::AttestationFormat::FIDOU2F => {
AttestationFormat::FIDOU2F
}
webauthn_rs_proto::options::AttestationFormat::None => {
AttestationFormat::None
}
webauthn_rs_proto::options::AttestationFormat::Packed => {
AttestationFormat::Packed
}
webauthn_rs_proto::options::AttestationFormat::Tpm => {
AttestationFormat::Tpm
}
})
.collect::<Vec<_>>()
}),
authenticator_selection: val.public_key.authenticator_selection.map(|authn| {
AuthenticatorSelectionCriteria {
authenticator_attachment: authn.authenticator_attachment.map(|attach| {
match attach {
webauthn_rs_proto::options::AuthenticatorAttachment::CrossPlatform => AuthenticatorAttachment::CrossPlatform,
webauthn_rs_proto::options::AuthenticatorAttachment::Platform => AuthenticatorAttachment::Platform,
}
}),
require_resident_key: authn.require_resident_key,
resident_key: authn.resident_key.map(|rk|
match rk {
webauthn_rs_proto::options::ResidentKeyRequirement::Discouraged => ResidentKeyRequirement::Discouraged,
webauthn_rs_proto::options::ResidentKeyRequirement::Preferred => ResidentKeyRequirement::Preferred,
webauthn_rs_proto::options::ResidentKeyRequirement::Required => ResidentKeyRequirement::Required,
}
),
user_verification: match authn.user_verification {
webauthn_rs_proto::options::UserVerificationPolicy::Preferred => UserVerificationPolicy::Preferred,
webauthn_rs_proto::options::UserVerificationPolicy::Required => UserVerificationPolicy::Required,
webauthn_rs_proto::options::UserVerificationPolicy::Discouraged_DO_NOT_USE => UserVerificationPolicy::DiscouragedDoNotUse,
}
}
}),
challenge: URL_SAFE.encode(&val.public_key.challenge),
exclude_credentials: val.public_key.exclude_credentials.map(|ecs| ecs.into_iter().map(|descr| {
PublicKeyCredentialDescriptor{
type_: descr.type_,
id: URL_SAFE.encode(&descr.id),
transports: descr.transports.map(|transports| transports.into_iter().map(|tr|{
match tr {
webauthn_rs_proto::options::AuthenticatorTransport::Ble => AuthenticatorTransport::Ble,
webauthn_rs_proto::options::AuthenticatorTransport::Hybrid => AuthenticatorTransport::Hybrid,
webauthn_rs_proto::options::AuthenticatorTransport::Internal => AuthenticatorTransport::Internal,
webauthn_rs_proto::options::AuthenticatorTransport::Nfc => AuthenticatorTransport::Nfc,
webauthn_rs_proto::options::AuthenticatorTransport::Usb => AuthenticatorTransport::Usb,
webauthn_rs_proto::options::AuthenticatorTransport::Test => AuthenticatorTransport::Test,
webauthn_rs_proto::options::AuthenticatorTransport::Unknown => AuthenticatorTransport::Unknown,
}
}).collect::<Vec<_>>())
}
}).collect::<Vec<_>>()),
extensions: val.public_key.extensions.map(|ext| RequestRegistrationExtensions{
cred_props: ext.cred_props,
cred_protect: ext.cred_protect.map(|cp|
{
CredProtect {
credential_protection_policy: match cp.credential_protection_policy {
webauthn_rs_proto::extensions::CredentialProtectionPolicy::UserVerificationOptional => CredentialProtectionPolicy::UserVerificationOptional,
webauthn_rs_proto::extensions::CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIDList => CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIDList,
webauthn_rs_proto::extensions::CredentialProtectionPolicy::UserVerificationRequired => CredentialProtectionPolicy::UserVerificationRequired,

},
enforce_credential_protection_policy: cp.enforce_credential_protection_policy,
}
}),
hmac_create_secret: ext.hmac_create_secret,
min_pin_length: ext.min_pin_length,
uvm: ext.uvm,
}),
hints: val.public_key.hints.map(|hints| hints.into_iter().map(|hint|{
match hint {
webauthn_rs_proto::options::PublicKeyCredentialHints::ClientDevice => PublicKeyCredentialHints::ClientDevice,
webauthn_rs_proto::options::PublicKeyCredentialHints::Hybrid => PublicKeyCredentialHints::Hybrid,
webauthn_rs_proto::options::PublicKeyCredentialHints::SecurityKey => PublicKeyCredentialHints::SecurityKey,
} }).collect::<Vec<_>>()),
pub_key_cred_params: val.public_key.pub_key_cred_params.into_iter().map(|pkcp| {
PubKeyCredParams{
alg: pkcp.alg,
type_: pkcp.type_
}
}).collect::<Vec<_>>(),
rp: RelyingParty{
id: val.public_key.rp.id,
name: val.public_key.rp.name,
},
timeout: val.public_key.timeout,
user: User {
id: URL_SAFE.encode(&val.public_key.user.id),
name: val.public_key.user.name,
display_name: val.public_key.user.display_name,
}
},
})
}
}
Loading