Skip to content

PM-23654: Map CXF totp #381

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Aug 14, 2025
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
123 changes: 120 additions & 3 deletions crates/bitwarden-exporters/src/cxf/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use chrono::{DateTime, Utc};
use credential_exchange_format::{
Account as CxfAccount, AddressCredential, ApiKeyCredential, BasicAuthCredential, Credential,
CreditCardCredential, DriversLicenseCredential, IdentityDocumentCredential, Item,
NoteCredential, PasskeyCredential, PassportCredential, PersonNameCredential, WifiCredential,
NoteCredential, PasskeyCredential, PassportCredential, PersonNameCredential, TotpCredential,
WifiCredential,
};

use crate::{
Expand Down Expand Up @@ -72,11 +73,12 @@ pub(crate) fn parse_item(value: Item) -> Vec<ImportingCipher> {
let note_content = grouped.note.first().map(extract_note_content);

// Login credentials
if !grouped.basic_auth.is_empty() || !grouped.passkey.is_empty() {
if !grouped.basic_auth.is_empty() || !grouped.passkey.is_empty() || !grouped.totp.is_empty() {
let basic_auth = grouped.basic_auth.first();
let passkey = grouped.passkey.first();
let totp = grouped.totp.first();

let login = to_login(creation_date, basic_auth, passkey, scope);
let login = to_login(creation_date, basic_auth, passkey, totp, scope);

output.push(ImportingCipher {
folder_id: None, // TODO: Handle folders
Expand Down Expand Up @@ -253,6 +255,10 @@ fn group_credentials_by_type(credentials: Vec<Credential>) -> GroupedCredentials
Credential::CreditCard(credit_card) => Some(credit_card.as_ref()),
_ => None,
}),
totp: filter_credentials(&credentials, |c| match c {
Credential::Totp(totp) => Some(totp.as_ref()),
_ => None,
}),
wifi: filter_credentials(&credentials, |c| match c {
Credential::Wifi(wifi) => Some(wifi.as_ref()),
_ => None,
Expand Down Expand Up @@ -289,6 +295,7 @@ struct GroupedCredentials {
basic_auth: Vec<BasicAuthCredential>,
passkey: Vec<PasskeyCredential>,
credit_card: Vec<CreditCardCredential>,
totp: Vec<TotpCredential>,
wifi: Vec<WifiCredential>,
address: Vec<AddressCredential>,
passport: Vec<PassportCredential>,
Expand Down Expand Up @@ -489,4 +496,114 @@ mod tests {
assert_eq!(card.brand, Some("Mastercard".to_string()));
assert_eq!(card.number, Some("1234 5678 9012 3456".to_string()));
}

#[test]
fn test_totp() {
use credential_exchange_format::{OTPHashAlgorithm, TotpCredential};

let item = Item {
id: [0, 1, 2, 3, 4, 5, 6].as_ref().into(),
creation_at: Some(1706613834),
modified_at: Some(1706623773),
title: "My TOTP".to_string(),
subtitle: None,
favorite: None,
credentials: vec![Credential::Totp(Box::new(TotpCredential {
secret: "Hello World!".as_bytes().to_vec().into(),
period: 30,
digits: 6,
username: Some("[email protected]".to_string()),
algorithm: OTPHashAlgorithm::Sha1,
issuer: Some("Example Service".to_string()),
}))],
tags: None,
extensions: None,
scope: None,
};

let ciphers: Vec<ImportingCipher> = parse_item(item);
assert_eq!(ciphers.len(), 1);
let cipher = ciphers.first().unwrap();

assert_eq!(cipher.folder_id, None);
assert_eq!(cipher.name, "My TOTP");
assert_eq!(cipher.notes, None);
assert!(!cipher.favorite);
assert_eq!(cipher.reprompt, 0);
assert_eq!(cipher.fields, vec![]);

let login = match &cipher.r#type {
CipherType::Login(login) => login,
_ => panic!("Expected login cipher for TOTP"),
};

// TOTP should be mapped to login.totp as otpauth URI
assert!(login.totp.is_some());
let otpauth = login.totp.as_ref().unwrap();

// Verify the otpauth URI format and content
assert!(
otpauth.starts_with("otpauth://totp/Example%20Service:test%40example%2Ecom?secret=")
);
assert!(otpauth.contains("&issuer=Example%20Service"));

// Default values should not be present in URI
assert!(!otpauth.contains("&period=30"));
assert!(!otpauth.contains("&digits=6"));
assert!(!otpauth.contains("&algorithm=SHA1"));

// Other login fields should be None since only TOTP was provided
assert_eq!(login.username, None);
assert_eq!(login.password, None);
assert_eq!(login.login_uris, vec![]);
}

#[test]
fn test_totp_combined_with_basic_auth() {
use credential_exchange_format::{BasicAuthCredential, OTPHashAlgorithm, TotpCredential};

let item = Item {
id: [0, 1, 2, 3, 4, 5, 6].as_ref().into(),
creation_at: Some(1706613834),
modified_at: Some(1706623773),
title: "Login with TOTP".to_string(),
subtitle: None,
favorite: None,
credentials: vec![
Credential::BasicAuth(Box::new(BasicAuthCredential {
username: Some("myuser".to_string().into()),
password: Some("mypass".to_string().into()),
})),
Credential::Totp(Box::new(TotpCredential {
secret: "totpkey".as_bytes().to_vec().into(),
period: 30,
digits: 6,
username: Some("totpuser".to_string()),
algorithm: OTPHashAlgorithm::Sha1,
issuer: Some("Service".to_string()),
})),
],
tags: None,
extensions: None,
scope: None,
};

let ciphers: Vec<ImportingCipher> = parse_item(item);
assert_eq!(ciphers.len(), 1);
let cipher = ciphers.first().unwrap();

let login = match &cipher.r#type {
CipherType::Login(login) => login,
_ => panic!("Expected login cipher"),
};

// Should have both basic auth and TOTP
assert_eq!(login.username, Some("myuser".to_string()));
assert_eq!(login.password, Some("mypass".to_string()));
assert!(login.totp.is_some());

let otpauth = login.totp.as_ref().unwrap();
assert!(otpauth.starts_with("otpauth://totp/Service:totpuser?secret="));
assert!(otpauth.contains("&issuer=Service"));
}
}
6 changes: 4 additions & 2 deletions crates/bitwarden-exporters/src/cxf/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ use bitwarden_fido::{string_to_guid_bytes, InvalidGuid};
use bitwarden_vault::FieldType;
use chrono::{DateTime, Utc};
use credential_exchange_format::{
AndroidAppIdCredential, BasicAuthCredential, CredentialScope, PasskeyCredential,
AndroidAppIdCredential, BasicAuthCredential, CredentialScope, PasskeyCredential, TotpCredential,
};
use thiserror::Error;

use super::totp::totp_credential_to_totp;
use crate::{Fido2Credential, Field, Login, LoginUri};

/// Prefix that indicates the URL is an Android app scheme.
Expand All @@ -22,13 +23,14 @@ pub(super) fn to_login(
creation_date: DateTime<Utc>,
basic_auth: Option<&BasicAuthCredential>,
passkey: Option<&PasskeyCredential>,
totp: Option<&TotpCredential>,
scope: Option<&CredentialScope>,
) -> Login {
Login {
username: basic_auth.and_then(|v| v.username.clone().map(|v| v.into())),
password: basic_auth.and_then(|v| v.password.clone().map(|u| u.into())),
login_uris: scope.map(to_uris).unwrap_or_default(),
totp: None,
totp: totp.map(|t| totp_credential_to_totp(t).to_string()),
fido2_credentials: passkey.map(|p| {
vec![Fido2Credential {
credential_id: format!("b64.{}", p.credential_id),
Expand Down
1 change: 1 addition & 0 deletions crates/bitwarden-exporters/src/cxf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ mod editable_field;
mod identity;
mod login;
mod note;
mod totp;
mod wifi;
151 changes: 151 additions & 0 deletions crates/bitwarden-exporters/src/cxf/totp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
use bitwarden_vault::{Totp, TotpAlgorithm};
use credential_exchange_format::{OTPHashAlgorithm, TotpCredential};

/// Convert CXF TotpCredential to Bitwarden's Totp struct
/// This ensures we use the exact same encoding and formatting as Bitwarden's core implementation
pub(super) fn totp_credential_to_totp(cxf_totp: &TotpCredential) -> Totp {
let algorithm = match cxf_totp.algorithm {
OTPHashAlgorithm::Sha1 => TotpAlgorithm::Sha1,
OTPHashAlgorithm::Sha256 => TotpAlgorithm::Sha256,
OTPHashAlgorithm::Sha512 => TotpAlgorithm::Sha512,
OTPHashAlgorithm::Unknown(ref algo) if algo == "steam" => TotpAlgorithm::Steam,
OTPHashAlgorithm::Unknown(_) | _ => TotpAlgorithm::Sha1, /* Default to SHA1 for unknown
* algorithms */
};

let secret_bytes: Vec<u8> = cxf_totp.secret.clone().into();

Totp {
account: cxf_totp.username.clone(),
algorithm,
digits: cxf_totp.digits as u32,
issuer: cxf_totp.issuer.clone(),
period: cxf_totp.period as u32,
secret: secret_bytes,
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_cxf_sample_totp_mapping() {
use std::fs;

use crate::cxf::import::parse_cxf_spec;

// Load the actual CXF example file
let cxf_data = fs::read_to_string("resources/cxf_example.json")
.expect("Should be able to read cxf_example.json");

let items = parse_cxf_spec(cxf_data).expect("Should be able to parse CXF");

// Find the item with TOTP - should be the "GitHub Login" item
let totp_item = items
.iter()
.find(|item| item.name == "GitHub Login")
.expect("Should find GitHub Login item");

// Verify it's a Login type with TOTP
match &totp_item.r#type {
crate::CipherType::Login(login) => {
// Verify the TOTP field is properly mapped
assert!(login.totp.is_some());
let totp_uri = login.totp.as_ref().unwrap();

// Verify it's a proper otpauth URI
assert!(totp_uri.starts_with("otpauth://totp/"));

// Verify it contains the expected components from the CXF sample:
// - secret: "JBSWY3DPEHPK3PXP"
// - issuer: "Google"
// - algorithm: "sha256" (non-default, should appear as SHA256)
// - username: "[email protected]" (in the URI label)
// - period: 30 (default, so should NOT appear in URI)
// - digits: 6 (default, so should NOT appear in URI)
assert!(totp_uri.contains("secret=JBSWY3DPEHPK3PXP"));
assert!(totp_uri.contains("issuer=Google"));
assert!(totp_uri.contains("algorithm=SHA256"));
assert!(totp_uri.contains("Google:jane%2Esmith%40example%2Ecom"));

// Should NOT contain default values
assert!(!totp_uri.contains("period=30"));
assert!(!totp_uri.contains("digits=6"));

// Verify the Login structure is complete
assert!(login.username.is_some()); // From basic auth credential
assert!(login.password.is_some()); // From basic auth credential
assert!(!login.login_uris.is_empty()); // From item scope
assert!(login.totp.is_some()); // From TOTP credential

// Expected URI format using official Bitwarden TOTP implementation:
// otpauth://totp/Google:jane%2Esmith%40example%2Ecom?secret=JBSWY3DPEHPK3PXP&
// issuer=Google&algorithm=SHA256
}
_ => panic!("GitHub Login item should be a Login type"),
}
}

#[test]
fn test_totp_credential_to_totp_basic() {
let totp = TotpCredential {
secret: "Hello World!".as_bytes().to_vec().into(),
period: 30,
digits: 6,
username: Some("[email protected]".to_string()),
algorithm: OTPHashAlgorithm::Sha1,
issuer: Some("Example".to_string()),
};

let bitwarden_totp = totp_credential_to_totp(&totp);
let otpauth = bitwarden_totp.to_string();

assert!(otpauth.starts_with("otpauth://totp/Example:test%40example%2Ecom?secret="));
assert!(otpauth.contains("&issuer=Example"));
// Default period (30) and digits (6) and algorithm (SHA1) should not be included
assert!(!otpauth.contains("&period=30"));
assert!(!otpauth.contains("&digits=6"));
assert!(!otpauth.contains("&algorithm=SHA1"));
}

#[test]
fn test_totp_credential_to_totp_custom_parameters() {
let totp = TotpCredential {
secret: "Hello World!".as_bytes().to_vec().into(),
period: 60,
digits: 8,
username: Some("user".to_string()),
algorithm: OTPHashAlgorithm::Sha256,
issuer: Some("Custom Issuer".to_string()),
};

let bitwarden_totp = totp_credential_to_totp(&totp);
let otpauth = bitwarden_totp.to_string();

assert!(otpauth.contains("Custom%20Issuer:user"));
assert!(otpauth.contains("&issuer=Custom%20Issuer"));
assert!(otpauth.contains("&period=60"));
assert!(otpauth.contains("&digits=8"));
assert!(otpauth.contains("&algorithm=SHA256"));
}

#[test]
fn test_totp_credential_to_totp_sha512() {
let totp = TotpCredential {
secret: "secret123".as_bytes().to_vec().into(),
period: 30,
digits: 6,
username: Some("user".to_string()),
algorithm: OTPHashAlgorithm::Sha512,
issuer: None,
};

let bitwarden_totp = totp_credential_to_totp(&totp);
let otpauth = bitwarden_totp.to_string();

assert!(otpauth.starts_with("otpauth://totp/user?secret="));
assert!(otpauth.contains("&algorithm=SHA512"));
assert!(!otpauth.contains("&issuer="));
}
}
Loading