mirror of
https://github.com/dani-garcia/vaultwarden.wiki.git
synced 2026-10-23 08:38:10 +03:00
Implement V2 key rotation support
This commit is contained in:
11 files changed
+891
-231
No files matched your search
+530
-52
@@ -11,7 +11,7 @@ use serde_json::Value;
|
|||||||
use crate::{
|
use crate::{
|
||||||
CONFIG,
|
CONFIG,
|
||||||
api::{
|
api::{
|
||||||
AnonymousNotify, ApiResult, EmptyResult, JsonResult, Notify, PasswordOrOtpData, UpdateType,
|
AnonymousNotify, ApiResult, EmptyResult, JsonResult, LogOutReason, Notify, PasswordOrOtpData, UpdateType,
|
||||||
core::{accept_org_invite, log_user_event, two_factor::email},
|
core::{accept_org_invite, log_user_event, two_factor::email},
|
||||||
master_password_policy, register_push_device, unregister_push_device,
|
master_password_policy, register_push_device, unregister_push_device,
|
||||||
},
|
},
|
||||||
@@ -48,8 +48,10 @@ pub fn routes() -> Vec<rocket::Route> {
|
|||||||
post_password,
|
post_password,
|
||||||
post_set_password,
|
post_set_password,
|
||||||
post_kdf,
|
post_kdf,
|
||||||
|
get_key_rotation_data,
|
||||||
post_rotatekey,
|
post_rotatekey,
|
||||||
post_user_key,
|
post_user_key,
|
||||||
|
post_rotate_user_keys,
|
||||||
post_sstamp,
|
post_sstamp,
|
||||||
post_email_token,
|
post_email_token,
|
||||||
post_email,
|
post_email,
|
||||||
@@ -302,6 +304,35 @@ impl AccountKeysData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WrappedAccountCryptographicState {
|
||||||
|
/// This shape is v2-only: the key pairs and security state were already required by the
|
||||||
|
/// deserializer, so only the values still need checking. A missing signed public key or an
|
||||||
|
/// unknown algorithm has to be an error rather than a fallback to v1, which would silently turn
|
||||||
|
/// a rotation into a downgrade.
|
||||||
|
fn validate(self) -> ApiResult<ValidatedAccountKeys> {
|
||||||
|
let Some(signed_public_key) = self.public_key_encryption_key_pair.signed_public_key else {
|
||||||
|
err!("No signed public key provided for a v2 account")
|
||||||
|
};
|
||||||
|
let Some(signature_algorithm) = SignatureAlgorithm::from_str(&self.signature_key_pair.signature_algorithm)
|
||||||
|
else {
|
||||||
|
err!(format!("Unsupported signature algorithm: {}", self.signature_key_pair.signature_algorithm))
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(ValidatedAccountKeys {
|
||||||
|
private_key: self.public_key_encryption_key_pair.wrapped_private_key,
|
||||||
|
public_key: self.public_key_encryption_key_pair.public_key,
|
||||||
|
v2: Some(ValidatedV2AccountKeys {
|
||||||
|
signed_public_key,
|
||||||
|
signing_key: self.signature_key_pair.wrapped_signing_key,
|
||||||
|
verifying_key: self.signature_key_pair.verifying_key,
|
||||||
|
signature_algorithm,
|
||||||
|
security_state: self.security_state.security_state,
|
||||||
|
security_version: self.security_state.security_version,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<KeysData> for ValidatedAccountKeys {
|
impl From<KeysData> for ValidatedAccountKeys {
|
||||||
fn from(keys: KeysData) -> Self {
|
fn from(keys: KeysData) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -1023,16 +1054,18 @@ struct UpdateEmergencyAccessData {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct UpdateResetPasswordData {
|
struct UpdateResetPasswordData {
|
||||||
organization_id: OrganizationId,
|
organization_id: OrganizationId,
|
||||||
reset_password_key: String,
|
// Absent in a v1 -> v2 upgrade, which keeps the key the organization already holds
|
||||||
|
reset_password_key: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct KeyData {
|
struct KeyData {
|
||||||
account_unlock_data: RotateAccountUnlockData,
|
account_unlock_data: RotateAccountUnlockData,
|
||||||
account_keys: RotateAccountKeys,
|
account_keys: AccountKeysData,
|
||||||
account_data: RotateAccountData,
|
account_data: RotateAccountData,
|
||||||
old_master_key_authentication_hash: String,
|
old_master_key_authentication_hash: String,
|
||||||
|
new_user_key_id: Option<KeyId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -1041,6 +1074,8 @@ struct RotateAccountUnlockData {
|
|||||||
emergency_access_unlock_data: Vec<UpdateEmergencyAccessData>,
|
emergency_access_unlock_data: Vec<UpdateEmergencyAccessData>,
|
||||||
master_password_unlock_data: MasterPasswordUnlockData,
|
master_password_unlock_data: MasterPasswordUnlockData,
|
||||||
organization_account_recovery_unlock_data: Vec<UpdateResetPasswordData>,
|
organization_account_recovery_unlock_data: Vec<UpdateResetPasswordData>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
common: CommonUnlockData,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -1053,13 +1088,28 @@ struct MasterPasswordUnlockData {
|
|||||||
email: String,
|
email: String,
|
||||||
master_key_authentication_hash: String,
|
master_key_authentication_hash: String,
|
||||||
master_key_encrypted_user_key: String,
|
master_key_encrypted_user_key: String,
|
||||||
|
contained_key_id: Option<KeyId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
/// The unlock data both rotation endpoints share. Vaultwarden has neither trusted device encryption
|
||||||
|
/// nor passkey login, so `key-rotation-data` reports none of either and these must arrive empty.
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct RotateAccountKeys {
|
struct CommonUnlockData {
|
||||||
user_key_encrypted_account_private_key: String,
|
#[serde(default)]
|
||||||
account_public_key: String,
|
passkey_unlock_data: Vec<Value>,
|
||||||
|
#[serde(default)]
|
||||||
|
device_key_unlock_data: Vec<Value>,
|
||||||
|
v2_upgrade_token: Option<V2UpgradeTokenData>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lets clients that still hold the v1 user key derive the v2 one after another client upgraded the
|
||||||
|
/// account, so a v1 -> v2 upgrade doesn't have to log every other session out. Opaque to us.
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct V2UpgradeTokenData {
|
||||||
|
wrapped_user_key1: String,
|
||||||
|
wrapped_user_key2: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -1070,6 +1120,131 @@ struct RotateAccountData {
|
|||||||
sends: Vec<SendData>,
|
sends: Vec<SendData>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Body of `rotate-user-keys`, which rotates the keys without touching the master password.
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct RotateUserKeysData {
|
||||||
|
wrapped_account_cryptographic_state: WrappedAccountCryptographicState,
|
||||||
|
unlock_data: RotateUserKeysUnlockData,
|
||||||
|
account_data: RotateAccountData,
|
||||||
|
unlock_method_data: UnlockMethodData,
|
||||||
|
new_user_key_id: Option<KeyId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The v2-only account cryptographic state, where all three parts are mandatory.
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct WrappedAccountCryptographicState {
|
||||||
|
public_key_encryption_key_pair: PublicKeyEncryptionKeyPairData,
|
||||||
|
signature_key_pair: SignatureKeyPairData,
|
||||||
|
security_state: SecurityStateData,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct RotateUserKeysUnlockData {
|
||||||
|
emergency_access_unlock_data: Vec<UpdateEmergencyAccessData>,
|
||||||
|
organization_account_recovery_unlock_data: Vec<UpdateResetPasswordData>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
common: CommonUnlockData,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct UnlockMethodData {
|
||||||
|
unlock_method: i32,
|
||||||
|
master_password_unlock_data: Option<RotateMasterPasswordUnlockData>,
|
||||||
|
// `keyConnectorKeyWrappedUserKey` is deliberately not read: that unlock method is rejected.
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct RotateMasterPasswordUnlockData {
|
||||||
|
kdf: KDFData,
|
||||||
|
salt: String,
|
||||||
|
master_key_wrapped_user_key: String,
|
||||||
|
contained_key_id: Option<KeyId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user key wrapped in the master password unlock data has to be the new one.
|
||||||
|
///
|
||||||
|
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/Models/Data/MasterPasswordUnlockData.cs>
|
||||||
|
fn validate_contained_key_id(contained_key_id: Option<&KeyId>, new_user_key_id: Option<&KeyId>) -> EmptyResult {
|
||||||
|
match (contained_key_id, new_user_key_id) {
|
||||||
|
// Neither is sent by clients that predate key ids
|
||||||
|
(None, None) => Ok(()),
|
||||||
|
(Some(contained), Some(new)) if contained == new => Ok(()),
|
||||||
|
_ => err!("Invalid user key sent in master-password unlock data."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Api/KeyManagement/Enums/UnlockMethod.cs>
|
||||||
|
enum UnlockMethod {
|
||||||
|
Tde = 0,
|
||||||
|
MasterPassword = 1,
|
||||||
|
KeyConnector = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rotation-specific checks on the new account keys.
|
||||||
|
///
|
||||||
|
/// A rotation re-wraps the existing keys under a new user key; it must not swap the identity the
|
||||||
|
/// account presents to others. So the public key never changes, and for an account that is already
|
||||||
|
/// v2 the verifying key doesn't either — only the *wrapped* signing key does. A v1 account may gain
|
||||||
|
/// a signature key pair, which is the v1 -> v2 upgrade.
|
||||||
|
///
|
||||||
|
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/UserKey/Implementations/RotateUserAccountKeysCommand.cs>
|
||||||
|
async fn validate_rotation_account_keys(keys: &ValidatedAccountKeys, user: &User, conn: &DbConn) -> EmptyResult {
|
||||||
|
if user.public_key.as_ref() != Some(&keys.public_key) {
|
||||||
|
err!("Changing the asymmetric keypair is not possible during key rotation")
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(v2) = &keys.v2 else {
|
||||||
|
if user.is_v2() {
|
||||||
|
err!("Cannot downgrade an account from v2 to v1 encryption during key rotation")
|
||||||
|
}
|
||||||
|
// A v1 rotation: the private key stays wrapped by an AES-CBC-HMAC user key
|
||||||
|
if enc_string_type(&keys.private_key) != Some(ENC_TYPE_AES_CBC_256_HMAC_SHA256) {
|
||||||
|
err!("The provided account private key was not wrapped with AES-256-CBC-HMAC")
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
// Both a v2 rotation and the v1 -> v2 upgrade end up with a COSE user key wrapping the private keys
|
||||||
|
if enc_string_type(&v2.signing_key) != Some(ENC_TYPE_COSE_ENCRYPT0) {
|
||||||
|
err!("The provided signing key data is not wrapped with XChaCha20-Poly1305.")
|
||||||
|
}
|
||||||
|
if enc_string_type(&keys.private_key) != Some(ENC_TYPE_COSE_ENCRYPT0) {
|
||||||
|
err!("The provided private key encryption key is not wrapped with XChaCha20-Poly1305.")
|
||||||
|
}
|
||||||
|
if v2.verifying_key.is_empty() || v2.signed_public_key.is_empty() || v2.security_state.is_empty() {
|
||||||
|
err!("The v2 account keys are missing the verifying key, signed public key or security state")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !user.is_v2() {
|
||||||
|
// The v1 -> v2 upgrade, which is where the signature key pair comes from
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(key_pair) = UserSignatureKeyPair::find_active_by_user(&user.uuid, conn).await else {
|
||||||
|
err!("The account is missing its signature key pair")
|
||||||
|
};
|
||||||
|
if key_pair.verifying_key != v2.verifying_key {
|
||||||
|
err!("Changing the verifying key is not possible during key rotation")
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `AesCbc256_HmacSha256_B64`, the v1 user key
|
||||||
|
const ENC_TYPE_AES_CBC_256_HMAC_SHA256: &str = "2";
|
||||||
|
/// `CoseEncrypt0B64`, the v2 user key
|
||||||
|
const ENC_TYPE_COSE_ENCRYPT0: &str = "7";
|
||||||
|
|
||||||
|
/// The encryption type of an EncString, the number before the first `.`.
|
||||||
|
fn enc_string_type(enc_string: &str) -> Option<&str> {
|
||||||
|
enc_string.split_once('.').map(|(enc_type, _)| enc_type)
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_keydata(
|
fn validate_keydata(
|
||||||
data: &KeyData,
|
data: &KeyData,
|
||||||
existing_ciphers: &[Cipher],
|
existing_ciphers: &[Cipher],
|
||||||
@@ -1087,14 +1262,35 @@ fn validate_keydata(
|
|||||||
{
|
{
|
||||||
err!("Changing the kdf variant or email is not supported during key rotation");
|
err!("Changing the kdf variant or email is not supported during key rotation");
|
||||||
}
|
}
|
||||||
if user.public_key.as_ref() != Some(&data.account_keys.account_public_key) {
|
|
||||||
err!("Changing the asymmetric keypair is not possible during key rotation")
|
|
||||||
}
|
|
||||||
|
|
||||||
|
validate_rotation_data(
|
||||||
|
&data.account_data,
|
||||||
|
&data.account_unlock_data.emergency_access_unlock_data,
|
||||||
|
&data.account_unlock_data.organization_account_recovery_unlock_data,
|
||||||
|
existing_ciphers,
|
||||||
|
existing_folders,
|
||||||
|
existing_emergency_access,
|
||||||
|
existing_memberships,
|
||||||
|
existing_sends,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A rotation re-encrypts everything under the new user key, so anything left out would be
|
||||||
|
/// unreadable afterwards. Both rotation endpoints require the client to send the complete set.
|
||||||
|
#[expect(clippy::too_many_arguments, reason = "Every collection has to be cross-checked")]
|
||||||
|
fn validate_rotation_data(
|
||||||
|
account_data: &RotateAccountData,
|
||||||
|
emergency_access_unlock_data: &[UpdateEmergencyAccessData],
|
||||||
|
organization_account_recovery_unlock_data: &[UpdateResetPasswordData],
|
||||||
|
existing_ciphers: &[Cipher],
|
||||||
|
existing_folders: &[Folder],
|
||||||
|
existing_emergency_access: &[EmergencyAccess],
|
||||||
|
existing_memberships: &[Membership],
|
||||||
|
existing_sends: &[Send],
|
||||||
|
) -> EmptyResult {
|
||||||
// Check that we're correctly rotating all the user's ciphers
|
// Check that we're correctly rotating all the user's ciphers
|
||||||
let existing_cipher_ids = existing_ciphers.iter().map(|c| &c.uuid).collect::<HashSet<&CipherId>>();
|
let existing_cipher_ids = existing_ciphers.iter().map(|c| &c.uuid).collect::<HashSet<&CipherId>>();
|
||||||
let provided_cipher_ids = data
|
let provided_cipher_ids = account_data
|
||||||
.account_data
|
|
||||||
.ciphers
|
.ciphers
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|c| c.organization_id.is_none())
|
.filter(|c| c.organization_id.is_none())
|
||||||
@@ -1106,8 +1302,7 @@ fn validate_keydata(
|
|||||||
|
|
||||||
// Check that we're correctly rotating all the user's folders
|
// Check that we're correctly rotating all the user's folders
|
||||||
let existing_folder_ids = existing_folders.iter().map(|f| &f.uuid).collect::<HashSet<&FolderId>>();
|
let existing_folder_ids = existing_folders.iter().map(|f| &f.uuid).collect::<HashSet<&FolderId>>();
|
||||||
let provided_folder_ids =
|
let provided_folder_ids = account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>();
|
||||||
data.account_data.folders.iter().filter_map(|f| f.id.as_ref()).collect::<HashSet<&FolderId>>();
|
|
||||||
if !provided_folder_ids.is_superset(&existing_folder_ids) {
|
if !provided_folder_ids.is_superset(&existing_folder_ids) {
|
||||||
err!("All existing folders must be included in the rotation")
|
err!("All existing folders must be included in the rotation")
|
||||||
}
|
}
|
||||||
@@ -1115,12 +1310,8 @@ fn validate_keydata(
|
|||||||
// Check that we're correctly rotating all the user's emergency access keys
|
// Check that we're correctly rotating all the user's emergency access keys
|
||||||
let existing_emergency_access_ids =
|
let existing_emergency_access_ids =
|
||||||
existing_emergency_access.iter().map(|ea| &ea.uuid).collect::<HashSet<&EmergencyAccessId>>();
|
existing_emergency_access.iter().map(|ea| &ea.uuid).collect::<HashSet<&EmergencyAccessId>>();
|
||||||
let provided_emergency_access_ids = data
|
let provided_emergency_access_ids =
|
||||||
.account_unlock_data
|
emergency_access_unlock_data.iter().map(|ea| &ea.id).collect::<HashSet<&EmergencyAccessId>>();
|
||||||
.emergency_access_unlock_data
|
|
||||||
.iter()
|
|
||||||
.map(|ea| &ea.id)
|
|
||||||
.collect::<HashSet<&EmergencyAccessId>>();
|
|
||||||
if !provided_emergency_access_ids.is_superset(&existing_emergency_access_ids) {
|
if !provided_emergency_access_ids.is_superset(&existing_emergency_access_ids) {
|
||||||
err!("All existing emergency access keys must be included in the rotation")
|
err!("All existing emergency access keys must be included in the rotation")
|
||||||
}
|
}
|
||||||
@@ -1128,9 +1319,7 @@ fn validate_keydata(
|
|||||||
// Check that we're correctly rotating all the user's reset password keys
|
// Check that we're correctly rotating all the user's reset password keys
|
||||||
let existing_reset_password_ids =
|
let existing_reset_password_ids =
|
||||||
existing_memberships.iter().map(|m| &m.org_uuid).collect::<HashSet<&OrganizationId>>();
|
existing_memberships.iter().map(|m| &m.org_uuid).collect::<HashSet<&OrganizationId>>();
|
||||||
let provided_reset_password_ids = data
|
let provided_reset_password_ids = organization_account_recovery_unlock_data
|
||||||
.account_unlock_data
|
|
||||||
.organization_account_recovery_unlock_data
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|rp| &rp.organization_id)
|
.map(|rp| &rp.organization_id)
|
||||||
.collect::<HashSet<&OrganizationId>>();
|
.collect::<HashSet<&OrganizationId>>();
|
||||||
@@ -1140,7 +1329,7 @@ fn validate_keydata(
|
|||||||
|
|
||||||
// Check that we're correctly rotating all the user's sends
|
// Check that we're correctly rotating all the user's sends
|
||||||
let existing_send_ids = existing_sends.iter().map(|s| &s.uuid).collect::<HashSet<&SendId>>();
|
let existing_send_ids = existing_sends.iter().map(|s| &s.uuid).collect::<HashSet<&SendId>>();
|
||||||
let provided_send_ids = data.account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::<HashSet<&SendId>>();
|
let provided_send_ids = account_data.sends.iter().filter_map(|s| s.id.as_ref()).collect::<HashSet<&SendId>>();
|
||||||
if !provided_send_ids.is_superset(&existing_send_ids) {
|
if !provided_send_ids.is_superset(&existing_send_ids) {
|
||||||
err!("All existing sends must be included in the rotation")
|
err!("All existing sends must be included in the rotation")
|
||||||
}
|
}
|
||||||
@@ -1148,32 +1337,130 @@ fn validate_keydata(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The public keys and encrypted keysets that participate in a key rotation, so the client can
|
||||||
|
/// re-share the new user key without having to piece this together from several endpoints.
|
||||||
|
///
|
||||||
|
/// The four collections must always be present, even when empty: the SDK errors out if any of them
|
||||||
|
/// is missing. `trustedDeviceKeyData` and `passkeyKeyData` are always empty here, since vaultwarden
|
||||||
|
/// supports neither trusted device encryption nor passkey (PRF) login.
|
||||||
|
///
|
||||||
|
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/KeyManagement/UserKey/Queries/KeyRotationDataQuery.cs>
|
||||||
|
#[get("/accounts/key-management/key-rotation-data")]
|
||||||
|
async fn get_key_rotation_data(headers: Headers, conn: DbConn) -> JsonResult {
|
||||||
|
let user_id = &headers.user.uuid;
|
||||||
|
|
||||||
|
let mut organization_data = Vec::new();
|
||||||
|
for membership in Membership::find_by_user(user_id, &conn).await {
|
||||||
|
// Only memberships actually enrolled in account recovery take part in the rotation.
|
||||||
|
if membership.reset_password_key.is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(org) = Organization::find_by_uuid(&membership.org_uuid, &conn).await else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(public_key) = org.public_key else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
organization_data.push(json!({
|
||||||
|
"organizationId": org.uuid,
|
||||||
|
"organizationName": org.name,
|
||||||
|
"organizationPublicKey": public_key,
|
||||||
|
"object": "organizationPasswordResetKeyData",
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut emergency_access_data = Vec::new();
|
||||||
|
for emergency_access in EmergencyAccess::find_all_confirmed_by_grantor_uuid(user_id, &conn).await {
|
||||||
|
// Without a stored key there is nothing to re-share.
|
||||||
|
if emergency_access.key_encrypted.is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(grantee_id) = emergency_access.grantee_uuid.clone() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(grantee) = User::find_by_uuid(&grantee_id, &conn).await else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(public_key) = grantee.public_key.clone() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
emergency_access_data.push(json!({
|
||||||
|
"id": emergency_access.uuid,
|
||||||
|
"granteeId": grantee_id,
|
||||||
|
"granteeName": grantee.name,
|
||||||
|
"granteeEmail": grantee.email,
|
||||||
|
"publicKey": public_key,
|
||||||
|
"object": "emergencyAccessKeyData",
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Json(json!({
|
||||||
|
"organizationPasswordResetKeyData": organization_data,
|
||||||
|
"emergencyAccessKeyData": emergency_access_data,
|
||||||
|
"trustedDeviceKeyData": [],
|
||||||
|
"passkeyKeyData": [],
|
||||||
|
"object": "keyRotationData",
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the new user key gets wrapped, which is the one part the two rotation endpoints don't share.
|
||||||
|
enum UnlockRotation {
|
||||||
|
/// `rotate-user-account-keys`: the master password changes along with the keys.
|
||||||
|
PasswordChange {
|
||||||
|
authentication_hash: String,
|
||||||
|
wrapped_user_key: String,
|
||||||
|
},
|
||||||
|
/// `rotate-user-keys`: the password is untouched, only the wrapped user key is replaced.
|
||||||
|
WrappedUserKeyOnly {
|
||||||
|
wrapped_user_key: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything a rotation replaces, once each endpoint's wrapper has been peeled off.
|
||||||
|
struct RotateData {
|
||||||
|
account_keys: ValidatedAccountKeys,
|
||||||
|
account_data: RotateAccountData,
|
||||||
|
emergency_access_unlock_data: Vec<UpdateEmergencyAccessData>,
|
||||||
|
organization_account_recovery_unlock_data: Vec<UpdateResetPasswordData>,
|
||||||
|
v2_upgrade_token: Option<V2UpgradeTokenData>,
|
||||||
|
/// Only v2 (COSE) user keys have an id, so this is `None` for a v1 -> v1 rotation.
|
||||||
|
new_user_key_id: Option<KeyId>,
|
||||||
|
unlock: UnlockRotation,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CommonUnlockData {
|
||||||
|
/// We advertise no trusted devices or passkeys in `key-rotation-data`, so a client sending
|
||||||
|
/// either has produced keys for something that doesn't exist here. Silently dropping them would
|
||||||
|
/// leave the client believing an unlock method was rotated when it wasn't.
|
||||||
|
fn validate(&self) -> EmptyResult {
|
||||||
|
if !self.passkey_unlock_data.is_empty() {
|
||||||
|
err!("Passkey unlock is not supported")
|
||||||
|
}
|
||||||
|
if !self.device_key_unlock_data.is_empty() {
|
||||||
|
err!("Trusted device unlock is not supported")
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[post("/accounts/key-management/rotate-user-account-keys", data = "<data>")]
|
#[post("/accounts/key-management/rotate-user-account-keys", data = "<data>")]
|
||||||
async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult {
|
async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult {
|
||||||
// TODO: See if we can wrap everything within a SQL Transaction. If something fails it should revert everything.
|
|
||||||
let data: KeyData = data.into_inner();
|
let data: KeyData = data.into_inner();
|
||||||
|
|
||||||
if !headers.user.check_valid_password(&data.old_master_key_authentication_hash) {
|
if !headers.user.check_valid_password(&data.old_master_key_authentication_hash) {
|
||||||
err!("Invalid password")
|
err!("Invalid password")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate the import before continuing
|
data.account_unlock_data.common.validate()?;
|
||||||
// Bitwarden does not process the import if there is one item invalid.
|
|
||||||
// Since we check for the size of the encrypted note length, we need to do that here to pre-validate it.
|
|
||||||
// TODO: See if we can optimize the whole cipher adding/importing and prevent duplicate code and checks.
|
|
||||||
Cipher::validate_cipher_data(&data.account_data.ciphers)?;
|
|
||||||
|
|
||||||
let user_id = &headers.user.uuid;
|
let user_id = &headers.user.uuid;
|
||||||
|
let existing_ciphers = Cipher::find_owned_by_user(user_id, &conn).await;
|
||||||
// TODO: Ideally we'd do everything after this point in a single transaction.
|
let existing_folders = Folder::find_by_user(user_id, &conn).await;
|
||||||
|
let existing_emergency_access = EmergencyAccess::find_all_confirmed_by_grantor_uuid(user_id, &conn).await;
|
||||||
let mut existing_ciphers = Cipher::find_owned_by_user(user_id, &conn).await;
|
|
||||||
let mut existing_folders = Folder::find_by_user(user_id, &conn).await;
|
|
||||||
let mut existing_emergency_access = EmergencyAccess::find_all_confirmed_by_grantor_uuid(user_id, &conn).await;
|
|
||||||
let mut existing_memberships = Membership::find_by_user(user_id, &conn).await;
|
let mut existing_memberships = Membership::find_by_user(user_id, &conn).await;
|
||||||
// We only rotate the reset password key if it is set.
|
// We only rotate the reset password key if it is set.
|
||||||
existing_memberships.retain(|m| m.reset_password_key.is_some());
|
existing_memberships.retain(|m| m.reset_password_key.is_some());
|
||||||
let mut existing_sends = Send::find_by_user(user_id, &conn).await;
|
let existing_sends = Send::find_by_user(user_id, &conn).await;
|
||||||
|
|
||||||
validate_keydata(
|
validate_keydata(
|
||||||
&data,
|
&data,
|
||||||
@@ -1185,6 +1472,93 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
|
|||||||
&headers.user,
|
&headers.user,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
validate_contained_key_id(
|
||||||
|
data.account_unlock_data.master_password_unlock_data.contained_key_id.as_ref(),
|
||||||
|
data.new_user_key_id.as_ref(),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let unlock = UnlockRotation::PasswordChange {
|
||||||
|
authentication_hash: data.account_unlock_data.master_password_unlock_data.master_key_authentication_hash,
|
||||||
|
wrapped_user_key: data.account_unlock_data.master_password_unlock_data.master_key_encrypted_user_key,
|
||||||
|
};
|
||||||
|
|
||||||
|
rotate_account(
|
||||||
|
RotateData {
|
||||||
|
account_keys: data.account_keys.validate()?,
|
||||||
|
account_data: data.account_data,
|
||||||
|
emergency_access_unlock_data: data.account_unlock_data.emergency_access_unlock_data,
|
||||||
|
organization_account_recovery_unlock_data: data
|
||||||
|
.account_unlock_data
|
||||||
|
.organization_account_recovery_unlock_data,
|
||||||
|
// This endpoint always logs every session out, so an upgrade token is never kept here. That
|
||||||
|
// also clears one left over from an earlier upgrade. Ref: upstream's AccountsKeyManagementController
|
||||||
|
v2_upgrade_token: None,
|
||||||
|
new_user_key_id: data.new_user_key_id,
|
||||||
|
unlock,
|
||||||
|
},
|
||||||
|
(existing_ciphers, existing_folders, existing_emergency_access, existing_memberships, existing_sends),
|
||||||
|
headers,
|
||||||
|
conn,
|
||||||
|
nt,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
type ExistingRotationData = (Vec<Cipher>, Vec<Folder>, Vec<EmergencyAccess>, Vec<Membership>, Vec<Send>);
|
||||||
|
|
||||||
|
/// The body shared by both rotation endpoints: re-save every piece of data the client re-encrypted,
|
||||||
|
/// then swap the account keys and the wrapped user key.
|
||||||
|
async fn rotate_account(
|
||||||
|
data: RotateData,
|
||||||
|
existing: ExistingRotationData,
|
||||||
|
headers: Headers,
|
||||||
|
conn: DbConn,
|
||||||
|
nt: Notify<'_>,
|
||||||
|
) -> EmptyResult {
|
||||||
|
// TODO: See if we can wrap everything within a SQL Transaction. If something fails it should revert everything.
|
||||||
|
let (
|
||||||
|
mut existing_ciphers,
|
||||||
|
mut existing_folders,
|
||||||
|
mut existing_emergency_access,
|
||||||
|
mut existing_memberships,
|
||||||
|
mut existing_sends,
|
||||||
|
) = existing;
|
||||||
|
|
||||||
|
validate_rotation_account_keys(&data.account_keys, &headers.user, &conn).await?;
|
||||||
|
|
||||||
|
// The upgrade token only means anything for a v1 account moving to v2: it lets sessions still
|
||||||
|
// holding the v1 user key pick up the v2 one instead of being forced to re-authenticate. For an
|
||||||
|
// account that is already v2 it is meaningless, so it gets discarded and the security stamp is
|
||||||
|
// reset, as a rotation otherwise would. That ends the refresh tokens, while the access tokens in
|
||||||
|
// use run out on their own, as upstream.
|
||||||
|
let is_upgrade = data.v2_upgrade_token.is_some() && !headers.user.is_v2();
|
||||||
|
let upgrade_token = match &data.v2_upgrade_token {
|
||||||
|
Some(token) if is_upgrade => Some(serde_json::to_string(token)?),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
// An upgrade can't re-wrap the account recovery keys: that needs the organization's public key
|
||||||
|
// to be trusted, and an upgrade shows the user no prompt. So the stored keys are kept, and each
|
||||||
|
// organization gets the upgrade token instead, to unwrap the v2 user key with.
|
||||||
|
// Ref: upstream's OrganizationUserRotationValidator
|
||||||
|
for reset_password_data in &data.organization_account_recovery_unlock_data {
|
||||||
|
let has_key = reset_password_data.reset_password_key.as_deref().is_some_and(|k| !k.is_empty());
|
||||||
|
if is_upgrade && has_key {
|
||||||
|
err!("Account recovery keys cannot be rotated during a V1 to V2 upgrade rotation.")
|
||||||
|
}
|
||||||
|
if !is_upgrade && !has_key {
|
||||||
|
err!("Account recovery keys cannot be null or empty during rotation.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the import before continuing
|
||||||
|
// Bitwarden does not process the import if there is one item invalid.
|
||||||
|
// Since we check for the size of the encrypted note length, we need to do that here to pre-validate it.
|
||||||
|
// TODO: See if we can optimize the whole cipher adding/importing and prevent duplicate code and checks.
|
||||||
|
Cipher::validate_cipher_data(&data.account_data.ciphers)?;
|
||||||
|
|
||||||
|
// TODO: Ideally we'd do everything after this point in a single transaction.
|
||||||
|
|
||||||
// Update folder data
|
// Update folder data
|
||||||
for folder_data in data.account_data.folders {
|
for folder_data in data.account_data.folders {
|
||||||
// Skip `null` folder id entries.
|
// Skip `null` folder id entries.
|
||||||
@@ -1200,7 +1574,7 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update emergency access data
|
// Update emergency access data
|
||||||
for emergency_access_data in data.account_unlock_data.emergency_access_unlock_data {
|
for emergency_access_data in data.emergency_access_unlock_data {
|
||||||
let Some(saved_emergency_access) =
|
let Some(saved_emergency_access) =
|
||||||
existing_emergency_access.iter_mut().find(|ea| ea.uuid == emergency_access_data.id)
|
existing_emergency_access.iter_mut().find(|ea| ea.uuid == emergency_access_data.id)
|
||||||
else {
|
else {
|
||||||
@@ -1212,14 +1586,17 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update reset password data
|
// Update reset password data
|
||||||
for reset_password_data in data.account_unlock_data.organization_account_recovery_unlock_data {
|
for reset_password_data in data.organization_account_recovery_unlock_data {
|
||||||
let Some(membership) =
|
let Some(membership) =
|
||||||
existing_memberships.iter_mut().find(|m| m.org_uuid == reset_password_data.organization_id)
|
existing_memberships.iter_mut().find(|m| m.org_uuid == reset_password_data.organization_id)
|
||||||
else {
|
else {
|
||||||
err!("Reset password doesn't exist")
|
err!("Reset password doesn't exist")
|
||||||
};
|
};
|
||||||
|
|
||||||
membership.reset_password_key = Some(reset_password_data.reset_password_key);
|
if !is_upgrade {
|
||||||
|
membership.reset_password_key = reset_password_data.reset_password_key;
|
||||||
|
}
|
||||||
|
membership.v2_upgrade_token.clone_from(&upgrade_token);
|
||||||
membership.save(&conn).await?;
|
membership.save(&conn).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1249,25 +1626,126 @@ async fn post_rotatekey(data: Json<KeyData>, headers: Headers, conn: DbConn, nt:
|
|||||||
|
|
||||||
// Update user data
|
// Update user data
|
||||||
let mut user = headers.user;
|
let mut user = headers.user;
|
||||||
|
let keep_sessions_alive = is_upgrade;
|
||||||
|
user.v2_upgrade_token = upgrade_token;
|
||||||
|
|
||||||
user.private_key = Some(data.account_keys.user_key_encrypted_account_private_key);
|
data.account_keys.apply(&mut user)?;
|
||||||
user.set_password(
|
// The old id names a key that no longer exists, so it is replaced even when the new key has none.
|
||||||
&data.account_unlock_data.master_password_unlock_data.master_key_authentication_hash,
|
user.key_id = data.new_user_key_id;
|
||||||
Some(data.account_unlock_data.master_password_unlock_data.master_key_encrypted_user_key),
|
|
||||||
true,
|
|
||||||
None,
|
|
||||||
&conn,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let save_result = user.save(&conn).await;
|
match data.unlock {
|
||||||
|
UnlockRotation::PasswordChange {
|
||||||
|
authentication_hash,
|
||||||
|
wrapped_user_key,
|
||||||
|
} => {
|
||||||
|
user.set_password(&authentication_hash, Some(wrapped_user_key), false, None, &conn).await?;
|
||||||
|
}
|
||||||
|
UnlockRotation::WrappedUserKeyOnly {
|
||||||
|
wrapped_user_key,
|
||||||
|
} => {
|
||||||
|
user.akey = wrapped_user_key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !keep_sessions_alive {
|
||||||
|
user.reset_security_stamp_after_key_rotation(&conn).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The key pair goes first: if saving the user then fails during an upgrade, the account is still
|
||||||
|
// v1 and the key pair unused, instead of a v2 account without one, which no client could unlock.
|
||||||
|
// A failure between the two writes of a v2 rotation still needs a transaction to undo.
|
||||||
|
data.account_keys.save_signature_key_pair(&user.uuid, &conn).await?;
|
||||||
|
user.save(&conn).await?;
|
||||||
|
|
||||||
// Prevent logging out the client where the user requested this endpoint from.
|
// Prevent logging out the client where the user requested this endpoint from.
|
||||||
// If you do logout the user it will causes issues at the client side.
|
// If you do logout the user it will causes issues at the client side.
|
||||||
// Adding the device uuid will prevent this.
|
// Adding the device uuid will prevent this.
|
||||||
nt.send_logout(&user, Some(&headers.device), &conn).await;
|
// When the sessions were kept alive, the reason lets the other clients sync the new keys (through
|
||||||
|
// the upgrade token) instead of logging out, if they have `pm-31050-no-logout-key-upgrade-rotation`.
|
||||||
|
let reason = keep_sessions_alive.then_some(LogOutReason::KeyRotation);
|
||||||
|
nt.send_logout_with_reason(&user, Some(&headers.device), reason, &conn).await;
|
||||||
|
|
||||||
save_result
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rotates the account keys without changing the master password.
|
||||||
|
///
|
||||||
|
/// Unlike `rotate-user-account-keys` this carries no proof of the master password: the request is
|
||||||
|
/// authorized by the session alone, which is how upstream defines it, and the client has to be
|
||||||
|
/// unlocked to produce the payload in the first place.
|
||||||
|
///
|
||||||
|
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Api/KeyManagement/Controllers/AccountsKeyManagementController.cs>
|
||||||
|
#[post("/accounts/key-management/rotate-user-keys", data = "<data>")]
|
||||||
|
async fn post_rotate_user_keys(
|
||||||
|
data: Json<RotateUserKeysData>,
|
||||||
|
headers: Headers,
|
||||||
|
conn: DbConn,
|
||||||
|
nt: Notify<'_>,
|
||||||
|
) -> EmptyResult {
|
||||||
|
let data: RotateUserKeysData = data.into_inner();
|
||||||
|
|
||||||
|
data.unlock_data.common.validate()?;
|
||||||
|
|
||||||
|
let unlock = if data.unlock_method_data.unlock_method == UnlockMethod::MasterPassword as i32 {
|
||||||
|
let Some(unlock_data) = data.unlock_method_data.master_password_unlock_data else {
|
||||||
|
err!("Missing master password unlock data")
|
||||||
|
};
|
||||||
|
if headers.user.client_kdf_type != unlock_data.kdf.kdf
|
||||||
|
|| headers.user.client_kdf_iter != unlock_data.kdf.kdf_iterations
|
||||||
|
|| headers.user.client_kdf_memory != unlock_data.kdf.kdf_memory
|
||||||
|
|| headers.user.client_kdf_parallelism != unlock_data.kdf.kdf_parallelism
|
||||||
|
{
|
||||||
|
err!("Changing the kdf variant is not supported during key rotation")
|
||||||
|
}
|
||||||
|
if unlock_data.salt != headers.user.email {
|
||||||
|
err!("Invalid master password salt")
|
||||||
|
}
|
||||||
|
validate_contained_key_id(unlock_data.contained_key_id.as_ref(), data.new_user_key_id.as_ref())?;
|
||||||
|
UnlockRotation::WrappedUserKeyOnly {
|
||||||
|
wrapped_user_key: unlock_data.master_key_wrapped_user_key,
|
||||||
|
}
|
||||||
|
} else if data.unlock_method_data.unlock_method == UnlockMethod::Tde as i32 {
|
||||||
|
err!("Trusted device encryption is not supported")
|
||||||
|
} else if data.unlock_method_data.unlock_method == UnlockMethod::KeyConnector as i32 {
|
||||||
|
err!("Key connector is not supported")
|
||||||
|
} else {
|
||||||
|
err!("Unrecognized unlock method")
|
||||||
|
};
|
||||||
|
|
||||||
|
let user_id = &headers.user.uuid;
|
||||||
|
let existing_ciphers = Cipher::find_owned_by_user(user_id, &conn).await;
|
||||||
|
let existing_folders = Folder::find_by_user(user_id, &conn).await;
|
||||||
|
let existing_emergency_access = EmergencyAccess::find_all_confirmed_by_grantor_uuid(user_id, &conn).await;
|
||||||
|
let mut existing_memberships = Membership::find_by_user(user_id, &conn).await;
|
||||||
|
existing_memberships.retain(|m| m.reset_password_key.is_some());
|
||||||
|
let existing_sends = Send::find_by_user(user_id, &conn).await;
|
||||||
|
|
||||||
|
validate_rotation_data(
|
||||||
|
&data.account_data,
|
||||||
|
&data.unlock_data.emergency_access_unlock_data,
|
||||||
|
&data.unlock_data.organization_account_recovery_unlock_data,
|
||||||
|
&existing_ciphers,
|
||||||
|
&existing_folders,
|
||||||
|
&existing_emergency_access,
|
||||||
|
&existing_memberships,
|
||||||
|
&existing_sends,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
rotate_account(
|
||||||
|
RotateData {
|
||||||
|
account_keys: data.wrapped_account_cryptographic_state.validate()?,
|
||||||
|
account_data: data.account_data,
|
||||||
|
emergency_access_unlock_data: data.unlock_data.emergency_access_unlock_data,
|
||||||
|
organization_account_recovery_unlock_data: data.unlock_data.organization_account_recovery_unlock_data,
|
||||||
|
v2_upgrade_token: data.unlock_data.common.v2_upgrade_token,
|
||||||
|
new_user_key_id: data.new_user_key_id,
|
||||||
|
unlock,
|
||||||
|
},
|
||||||
|
(existing_ciphers, existing_folders, existing_emergency_access, existing_memberships, existing_sends),
|
||||||
|
headers,
|
||||||
|
conn,
|
||||||
|
nt,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
|
|||||||
+66
-13
@@ -24,6 +24,7 @@ use crate::{
|
|||||||
Archive, Attachment, AttachmentId, Cipher, CipherId, Collection, CollectionCipher, CollectionGroup,
|
Archive, Attachment, AttachmentId, Cipher, CipherId, Collection, CollectionCipher, CollectionGroup,
|
||||||
CollectionId, CollectionUser, EventType, Favorite, Folder, FolderCipher, FolderId, Group, KeyId,
|
CollectionId, CollectionUser, EventType, Favorite, Folder, FolderCipher, FolderId, Group, KeyId,
|
||||||
Membership, MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, Send, UserId,
|
Membership, MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, Send, UserId,
|
||||||
|
is_data_blob_encrypted,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
util::{NumberOrString, deser_opt_nonempty_str, save_temp_file},
|
util::{NumberOrString, deser_opt_nonempty_str, save_temp_file},
|
||||||
@@ -195,6 +196,15 @@ async fn sync(data: SyncData, headers: Headers, client_version: Option<ClientVer
|
|||||||
Value::Null
|
Value::Null
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Upstream omits these two when unset rather than sending null.
|
||||||
|
let mut user_decryption = json!({ "masterPasswordUnlock": master_password_unlock });
|
||||||
|
if let Some(key_id) = &headers.user.key_id {
|
||||||
|
user_decryption["userKeyId"] = json!(key_id);
|
||||||
|
}
|
||||||
|
if let Some(v2_upgrade_token) = headers.user.v2_upgrade_token_json() {
|
||||||
|
user_decryption["v2UpgradeToken"] = v2_upgrade_token;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(Json(json!({
|
Ok(Json(json!({
|
||||||
"profile": user_json,
|
"profile": user_json,
|
||||||
"folders": folders_json,
|
"folders": folders_json,
|
||||||
@@ -204,11 +214,7 @@ async fn sync(data: SyncData, headers: Headers, client_version: Option<ClientVer
|
|||||||
"ciphers": ciphers_json,
|
"ciphers": ciphers_json,
|
||||||
"domains": domains_json,
|
"domains": domains_json,
|
||||||
"sends": sends_json,
|
"sends": sends_json,
|
||||||
"userDecryption": {
|
"userDecryption": user_decryption,
|
||||||
"masterPasswordUnlock": master_password_unlock,
|
|
||||||
"userKeyId": headers.user.key_id,
|
|
||||||
"v2UpgradeToken": headers.user.v2_upgrade_token_json(),
|
|
||||||
},
|
|
||||||
"object": "sync"
|
"object": "sync"
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
@@ -285,7 +291,8 @@ pub struct CipherData {
|
|||||||
Passport = 8
|
Passport = 8
|
||||||
*/
|
*/
|
||||||
pub r#type: i32,
|
pub r#type: i32,
|
||||||
pub name: String,
|
// Absent on a blob-encrypted cipher, whose name is sealed inside `data`
|
||||||
|
pub name: Option<String>,
|
||||||
pub notes: Option<String>,
|
pub notes: Option<String>,
|
||||||
fields: Option<Value>,
|
fields: Option<Value>,
|
||||||
|
|
||||||
@@ -299,6 +306,9 @@ pub struct CipherData {
|
|||||||
drivers_license: Option<Value>,
|
drivers_license: Option<Value>,
|
||||||
passport: Option<Value>,
|
passport: Option<Value>,
|
||||||
|
|
||||||
|
// The sealed blob of a v2 account's cipher, which replaces all of the fields above
|
||||||
|
data: Option<String>,
|
||||||
|
|
||||||
favorite: Option<bool>,
|
favorite: Option<bool>,
|
||||||
reprompt: Option<i32>,
|
reprompt: Option<i32>,
|
||||||
|
|
||||||
@@ -320,6 +330,34 @@ pub struct CipherData {
|
|||||||
archived_date: Option<String>,
|
archived_date: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Upstream's `[StringLength(500000)]` on `CipherRequestModel.Data`
|
||||||
|
const MAX_CIPHER_DATA_LENGTH: usize = 500_000;
|
||||||
|
|
||||||
|
impl CipherData {
|
||||||
|
/// Checks the content the way upstream's model validation does, before anything is saved.
|
||||||
|
/// On failure, returns the offending field and the message for it.
|
||||||
|
///
|
||||||
|
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Api/Vault/Models/Request/CipherRequestModel.cs>
|
||||||
|
pub fn validate_content(&self) -> Result<(), (&'static str, String)> {
|
||||||
|
if let Some(data) = &self.data
|
||||||
|
&& data.len() > MAX_CIPHER_DATA_LENGTH
|
||||||
|
{
|
||||||
|
return Err((
|
||||||
|
"Data",
|
||||||
|
format!("The field Data must be a string with a maximum length of {MAX_CIPHER_DATA_LENGTH}."),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A blob carries the name inside it, so only the other formats need one
|
||||||
|
let is_blob = self.data.as_deref().is_some_and(is_data_blob_encrypted);
|
||||||
|
if !is_blob && self.name.as_deref().is_none_or(|n| n.trim().is_empty()) {
|
||||||
|
return Err(("Name", String::from("The Name field is required.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct PartialCipherData {
|
pub struct PartialCipherData {
|
||||||
@@ -362,7 +400,7 @@ async fn post_ciphers_create(
|
|||||||
// cipher.save() below.
|
// cipher.save() below.
|
||||||
enforce_personal_ownership_policy(Some(&data.cipher), &headers, &conn).await?;
|
enforce_personal_ownership_policy(Some(&data.cipher), &headers, &conn).await?;
|
||||||
|
|
||||||
let mut cipher = Cipher::new(data.cipher.r#type, data.cipher.name.clone());
|
let mut cipher = Cipher::new(data.cipher.r#type, data.cipher.name.clone().unwrap_or_default());
|
||||||
cipher.user_uuid = Some(headers.user.uuid.clone());
|
cipher.user_uuid = Some(headers.user.uuid.clone());
|
||||||
cipher.save(&conn).await?;
|
cipher.save(&conn).await?;
|
||||||
|
|
||||||
@@ -403,7 +441,7 @@ async fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn, nt
|
|||||||
// needed when creating a new cipher, so just ignore it unconditionally.
|
// needed when creating a new cipher, so just ignore it unconditionally.
|
||||||
data.last_known_revision_date = None;
|
data.last_known_revision_date = None;
|
||||||
|
|
||||||
let mut cipher = Cipher::new(data.r#type, data.name.clone());
|
let mut cipher = Cipher::new(data.r#type, data.name.clone().unwrap_or_default());
|
||||||
update_cipher_from_data(&mut cipher, data, &headers, None, &conn, &nt, UpdateType::SyncCipherCreate).await?;
|
update_cipher_from_data(&mut cipher, data, &headers, None, &conn, &nt, UpdateType::SyncCipherCreate).await?;
|
||||||
|
|
||||||
Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, None, CipherSyncType::User, &conn).await?))
|
Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, None, CipherSyncType::User, &conn).await?))
|
||||||
@@ -452,6 +490,10 @@ pub async fn update_cipher_from_data(
|
|||||||
|
|
||||||
enforce_personal_ownership_policy(Some(&data), headers, conn).await?;
|
enforce_personal_ownership_policy(Some(&data), headers, conn).await?;
|
||||||
|
|
||||||
|
if let Err((_, message)) = data.validate_content() {
|
||||||
|
err!(message)
|
||||||
|
}
|
||||||
|
|
||||||
// Check that the client isn't updating an existing cipher with stale data.
|
// Check that the client isn't updating an existing cipher with stale data.
|
||||||
// And only perform this check when not importing ciphers, else the date/time check will fail.
|
// And only perform this check when not importing ciphers, else the date/time check will fail.
|
||||||
if ut != UpdateType::None
|
if ut != UpdateType::None
|
||||||
@@ -539,6 +581,15 @@ pub async fn update_cipher_from_data(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A blob replaces every content field, so the per-type data below neither applies nor exists.
|
||||||
|
// `validate_content` made sure anything else has a name.
|
||||||
|
let blob = data.data.filter(|d| is_data_blob_encrypted(d));
|
||||||
|
let name = if blob.is_some() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
data.name.unwrap_or_default()
|
||||||
|
};
|
||||||
|
|
||||||
let type_data_opt = match data.r#type {
|
let type_data_opt = match data.r#type {
|
||||||
1 => data.login,
|
1 => data.login,
|
||||||
2 => data.secure_note,
|
2 => data.secure_note,
|
||||||
@@ -551,23 +602,25 @@ pub async fn update_cipher_from_data(
|
|||||||
_ => err!("Invalid type"),
|
_ => err!("Invalid type"),
|
||||||
};
|
};
|
||||||
|
|
||||||
let type_data = if let Some(mut data) = type_data_opt {
|
let stored_data = if let Some(blob) = blob {
|
||||||
|
blob
|
||||||
|
} else if let Some(mut data) = type_data_opt {
|
||||||
// Remove the 'Response' key from the base object.
|
// Remove the 'Response' key from the base object.
|
||||||
data.as_object_mut().unwrap().remove("response");
|
data.as_object_mut().unwrap().remove("response");
|
||||||
// Remove the 'Response' key from every Uri.
|
// Remove the 'Response' key from every Uri.
|
||||||
if data["uris"].is_array() {
|
if data["uris"].is_array() {
|
||||||
data["uris"] = clean_cipher_data(data["uris"].clone());
|
data["uris"] = clean_cipher_data(data["uris"].clone());
|
||||||
}
|
}
|
||||||
data
|
data.to_string()
|
||||||
} else {
|
} else {
|
||||||
err!("Data missing")
|
err!("Data missing")
|
||||||
};
|
};
|
||||||
|
|
||||||
cipher.key = data.key;
|
cipher.key = data.key;
|
||||||
cipher.name = data.name;
|
cipher.name = name;
|
||||||
cipher.notes = data.notes;
|
cipher.notes = data.notes;
|
||||||
cipher.fields = data.fields.map(|f| clean_cipher_data(f).to_string());
|
cipher.fields = data.fields.map(|f| clean_cipher_data(f).to_string());
|
||||||
cipher.data = type_data.to_string();
|
cipher.data = stored_data;
|
||||||
cipher.password_history = data.password_history.map(|f| f.to_string());
|
cipher.password_history = data.password_history.map(|f| f.to_string());
|
||||||
cipher.reprompt = data.reprompt.filter(|r| *r == RepromptType::None as i32 || *r == RepromptType::Password as i32);
|
cipher.reprompt = data.reprompt.filter(|r| *r == RepromptType::None as i32 || *r == RepromptType::Password as i32);
|
||||||
|
|
||||||
@@ -665,7 +718,7 @@ async fn post_ciphers_import(data: Json<ImportData>, headers: Headers, conn: DbC
|
|||||||
let folder_id = relations_map.get(&index).and_then(|i| folders.get(*i).cloned());
|
let folder_id = relations_map.get(&index).and_then(|i| folders.get(*i).cloned());
|
||||||
cipher_data.folder_id = folder_id;
|
cipher_data.folder_id = folder_id;
|
||||||
|
|
||||||
let mut cipher = Cipher::new(cipher_data.r#type, cipher_data.name.clone());
|
let mut cipher = Cipher::new(cipher_data.r#type, cipher_data.name.clone().unwrap_or_default());
|
||||||
update_cipher_from_data(&mut cipher, cipher_data, &headers, None, &conn, &nt, UpdateType::None).await?;
|
update_cipher_from_data(&mut cipher, cipher_data, &headers, None, &conn, &nt, UpdateType::None).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1885,7 +1885,7 @@ async fn post_org_import(
|
|||||||
cipher_data.folder_id = None;
|
cipher_data.folder_id = None;
|
||||||
// Replace the client-provided, unvalidated organizationId with the real target org
|
// Replace the client-provided, unvalidated organizationId with the real target org
|
||||||
cipher_data.organization_id = Some(org_id.clone());
|
cipher_data.organization_id = Some(org_id.clone());
|
||||||
let mut cipher = Cipher::new(cipher_data.r#type, cipher_data.name.clone());
|
let mut cipher = Cipher::new(cipher_data.r#type, cipher_data.name.clone().unwrap_or_default());
|
||||||
update_cipher_from_data(
|
update_cipher_from_data(
|
||||||
&mut cipher,
|
&mut cipher,
|
||||||
cipher_data,
|
cipher_data,
|
||||||
|
|||||||
+1
-1
@@ -23,7 +23,7 @@ pub use crate::api::{
|
|||||||
icons::routes as icons_routes,
|
icons::routes as icons_routes,
|
||||||
identity::routes as identity_routes,
|
identity::routes as identity_routes,
|
||||||
notifications::routes as notifications_routes,
|
notifications::routes as notifications_routes,
|
||||||
notifications::{AnonymousNotify, Notify, UpdateType, WS_ANONYMOUS_SUBSCRIPTIONS, WS_USERS},
|
notifications::{AnonymousNotify, LogOutReason, Notify, UpdateType, WS_ANONYMOUS_SUBSCRIPTIONS, WS_USERS},
|
||||||
push::{
|
push::{
|
||||||
push_cipher_update, push_folder_update, push_logout, push_send_update, push_user_update, register_push_device,
|
push_cipher_update, push_folder_update, push_logout, push_send_update, push_user_update, register_push_device,
|
||||||
unregister_push_device,
|
unregister_push_device,
|
||||||
|
|||||||
@@ -383,23 +383,36 @@ impl WebSocketUsers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_logout(&self, user: &User, acting_device: Option<&Device>, conn: &DbConn) {
|
pub async fn send_logout(&self, user: &User, acting_device: Option<&Device>, conn: &DbConn) {
|
||||||
|
self.send_logout_with_reason(user, acting_device, None, conn).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A logout that clients may handle differently depending on `reason`, e.g. syncing instead of
|
||||||
|
/// logging out after a key rotation that kept the sessions alive.
|
||||||
|
pub async fn send_logout_with_reason(
|
||||||
|
&self,
|
||||||
|
user: &User,
|
||||||
|
acting_device: Option<&Device>,
|
||||||
|
reason: Option<LogOutReason>,
|
||||||
|
conn: &DbConn,
|
||||||
|
) {
|
||||||
// Skip any processing if both WebSockets and Push are not active
|
// Skip any processing if both WebSockets and Push are not active
|
||||||
if *NOTIFICATIONS_DISABLED {
|
if *NOTIFICATIONS_DISABLED {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let acting_device_id = acting_device.map(|d| d.uuid.clone());
|
let acting_device_id = acting_device.map(|d| d.uuid.clone());
|
||||||
let data = create_update(
|
let mut payload =
|
||||||
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))],
|
vec![("UserId".into(), user.uuid.to_string().into()), ("Date".into(), serialize_date(user.updated_at))];
|
||||||
UpdateType::LogOut,
|
if let Some(reason) = reason {
|
||||||
acting_device_id,
|
payload.push(("Reason".into(), (reason as i32).into()));
|
||||||
);
|
}
|
||||||
|
let data = create_update(payload, UpdateType::LogOut, acting_device_id);
|
||||||
|
|
||||||
if CONFIG.enable_websocket() {
|
if CONFIG.enable_websocket() {
|
||||||
self.send_update(&user.uuid, &data).await;
|
self.send_update(&user.uuid, &data).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
if CONFIG.push_enabled() {
|
if CONFIG.push_enabled() {
|
||||||
push_logout(user, acting_device, conn).await;
|
push_logout(user, acting_device, reason, conn).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -667,6 +680,15 @@ fn create_ping() -> Vec<u8> {
|
|||||||
serialize(&Value::Array(vec![6.into()]))
|
serialize(&Value::Array(vec![6.into()]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Why a logout was pushed. Absent for a plain logout.
|
||||||
|
///
|
||||||
|
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/Enums/PushNotificationLogOutReason.cs>
|
||||||
|
/// (`KdfChange = 0` is not sent by vaultwarden yet.)
|
||||||
|
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||||
|
pub enum LogOutReason {
|
||||||
|
KeyRotation = 1,
|
||||||
|
}
|
||||||
|
|
||||||
// https://github.com/bitwarden/server/blob/375af7c43b10d9da03525d41452f95de3f921541/src/Core/Enums/PushType.cs
|
// https://github.com/bitwarden/server/blob/375af7c43b10d9da03525d41452f95de3f921541/src/Core/Enums/PushType.cs
|
||||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||||
pub enum UpdateType {
|
pub enum UpdateType {
|
||||||
|
|||||||
+4
-3
@@ -12,7 +12,7 @@ use tokio::sync::RwLock;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
CONFIG,
|
CONFIG,
|
||||||
api::{ApiResult, EmptyResult, UpdateType},
|
api::{ApiResult, EmptyResult, LogOutReason, UpdateType},
|
||||||
db::{
|
db::{
|
||||||
DbConn,
|
DbConn,
|
||||||
models::{AuthRequestId, Cipher, Device, Folder, PushId, Send, User, UserId},
|
models::{AuthRequestId, Cipher, Device, Folder, PushId, Send, User, UserId},
|
||||||
@@ -188,7 +188,7 @@ pub async fn push_cipher_update(ut: UpdateType, cipher: &Cipher, device: &Device
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn push_logout(user: &User, acting_device: Option<&Device>, conn: &DbConn) {
|
pub async fn push_logout(user: &User, acting_device: Option<&Device>, reason: Option<LogOutReason>, conn: &DbConn) {
|
||||||
if Device::check_user_has_push_device(&user.uuid, conn).await {
|
if Device::check_user_has_push_device(&user.uuid, conn).await {
|
||||||
tokio::task::spawn(send_to_push_relay(json!({
|
tokio::task::spawn(send_to_push_relay(json!({
|
||||||
"userId": user.uuid,
|
"userId": user.uuid,
|
||||||
@@ -198,7 +198,8 @@ pub async fn push_logout(user: &User, acting_device: Option<&Device>, conn: &DbC
|
|||||||
"type": UpdateType::LogOut as i32,
|
"type": UpdateType::LogOut as i32,
|
||||||
"payload": {
|
"payload": {
|
||||||
"userId": user.uuid,
|
"userId": user.uuid,
|
||||||
"date": format_date(&user.updated_at)
|
"date": format_date(&user.updated_at),
|
||||||
|
"reason": reason.map(|r| r as i32),
|
||||||
},
|
},
|
||||||
"clientType": null,
|
"clientType": null,
|
||||||
"installationId": null
|
"installationId": null
|
||||||
|
|||||||
+15
-26
@@ -30,7 +30,7 @@ use crate::{
|
|||||||
models::{
|
models::{
|
||||||
AttachmentId, CipherId, Collection, CollectionId, Device, DeviceId, DeviceType, EmergencyAccessId,
|
AttachmentId, CipherId, Collection, CollectionId, Device, DeviceId, DeviceType, EmergencyAccessId,
|
||||||
EventType, Membership, MembershipId, MembershipStatus, MembershipType, OrgApiKeyId, OrganizationId,
|
EventType, Membership, MembershipId, MembershipStatus, MembershipType, OrgApiKeyId, OrganizationId,
|
||||||
SendFileId, SendId, User, UserId, UserStampException,
|
SendFileId, SendId, User, UserId,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
error::Error,
|
error::Error,
|
||||||
@@ -662,36 +662,25 @@ impl<'r> FromRequest<'r> for Headers {
|
|||||||
err_handler!("Invalid device id")
|
err_handler!("Invalid device id")
|
||||||
};
|
};
|
||||||
|
|
||||||
let Some(user) = User::find_by_uuid(&user_id, &conn).await else {
|
let Some(mut user) = User::find_by_uuid(&user_id, &conn).await else {
|
||||||
err_handler!("Device has no user associated")
|
err_handler!("Device has no user associated")
|
||||||
};
|
};
|
||||||
|
|
||||||
if user.security_stamp != claims.sstamp {
|
if user.security_stamp != claims.sstamp {
|
||||||
if let Some(stamp_exception) =
|
let Some(current_route) = request.route().and_then(|r| r.name.as_deref()) else {
|
||||||
user.stamp_exception.as_deref().and_then(|s| serde_json::from_str::<UserStampException>(s).ok())
|
err_handler!("Error getting current route for stamp exception")
|
||||||
{
|
};
|
||||||
let Some(current_route) = request.route().and_then(|r| r.name.as_deref()) else {
|
|
||||||
err_handler!("Error getting current route for stamp exception")
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check if the stamp exception has expired first.
|
let allowed = user.stamp_exceptions().iter().any(|e| e.allows(&claims.sstamp, current_route));
|
||||||
// Then, check if the current route matches any of the allowed routes.
|
|
||||||
// After that check the stamp in exception matches the one in the claims.
|
// Drop the expired exceptions, so they aren't checked for every request from now on.
|
||||||
if Utc::now().timestamp() > stamp_exception.expire {
|
if user.retain_stamp_exceptions(|e| !e.is_expired())
|
||||||
// If the stamp exception has been expired remove it from the database.
|
&& let Err(e) = user.save_stamp_exceptions(&conn).await
|
||||||
// This prevents checking this stamp exception for new requests.
|
{
|
||||||
let mut user = user;
|
error!("Error updating user: {e:#?}");
|
||||||
user.reset_stamp_exception();
|
}
|
||||||
if let Err(e) = user.save(&conn).await {
|
|
||||||
error!("Error updating user: {e:#?}");
|
if !allowed {
|
||||||
}
|
|
||||||
err_handler!("Stamp exception is expired")
|
|
||||||
} else if !stamp_exception.routes.contains(¤t_route.to_owned()) {
|
|
||||||
err_handler!("Invalid security stamp: Current route and exception route do not match")
|
|
||||||
} else if stamp_exception.security_stamp != claims.sstamp {
|
|
||||||
err_handler!("Invalid security stamp for matched stamp exception")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
err_handler!("Invalid security stamp")
|
err_handler!("Invalid security stamp")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1434,6 +1434,9 @@ pub const SUPPORTED_FEATURE_FLAGS: &[&str] = &[
|
|||||||
"ssh-key-vault-item",
|
"ssh-key-vault-item",
|
||||||
"pm-25373-windows-biometrics-v2",
|
"pm-25373-windows-biometrics-v2",
|
||||||
"pm-26340-linux-biometrics-v2",
|
"pm-26340-linux-biometrics-v2",
|
||||||
|
"pm-31050-no-logout-key-upgrade-rotation",
|
||||||
|
"pm-27278-v2-password-registration",
|
||||||
|
"enable-account-encryption-v2-jit-password-registration",
|
||||||
// Mobile Team
|
// Mobile Team
|
||||||
"anon-addy-self-host-alias",
|
"anon-addy-self-host-alias",
|
||||||
"simple-login-self-host-alias",
|
"simple-login-self-host-alias",
|
||||||
|
|||||||
+148
-117
@@ -63,6 +63,17 @@ pub struct Cipher {
|
|||||||
pub reprompt: Option<i32>,
|
pub reprompt: Option<i32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether `data` is a sealed cipher blob rather than the legacy per-type JSON.
|
||||||
|
///
|
||||||
|
/// Ciphers of v2 accounts are encrypted as a single blob that carries everything, name included,
|
||||||
|
/// and is opaque to us. It is recognized the same way upstream does, by a top-level
|
||||||
|
/// `format_version` key that the legacy JSON never has.
|
||||||
|
///
|
||||||
|
/// Ref: <https://github.com/bitwarden/server/blob/main/src/Core/Vault/Entities/Cipher.cs>
|
||||||
|
pub fn is_data_blob_encrypted(data: &str) -> bool {
|
||||||
|
serde_json::from_str::<Value>(data).is_ok_and(|d| d.get("format_version").is_some())
|
||||||
|
}
|
||||||
|
|
||||||
pub enum RepromptType {
|
pub enum RepromptType {
|
||||||
None = 0,
|
None = 0,
|
||||||
Password = 1,
|
Password = 1,
|
||||||
@@ -110,6 +121,10 @@ impl Cipher {
|
|||||||
.insert(format!("Ciphers[{index}].Notes"), serde_json::to_value([&max_note_size_msg]).unwrap());
|
.insert(format!("Ciphers[{index}].Notes"), serde_json::to_value([&max_note_size_msg]).unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Err((field, message)) = cipher.validate_content() {
|
||||||
|
validation_errors.insert(format!("Ciphers[{index}].{field}"), serde_json::to_value([message]).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
// Validate the password history if it contains `null` values and if so, return a warning
|
// Validate the password history if it contains `null` values and if so, return a warning
|
||||||
if let Some(Value::Array(password_history)) = &cipher.password_history {
|
if let Some(Value::Array(password_history)) = &cipher.password_history {
|
||||||
for pwh in password_history {
|
for pwh in password_history {
|
||||||
@@ -154,6 +169,8 @@ impl Cipher {
|
|||||||
) -> Result<Value, crate::Error> {
|
) -> Result<Value, crate::Error> {
|
||||||
use crate::util::{format_date, validate_and_format_date};
|
use crate::util::{format_date, validate_and_format_date};
|
||||||
|
|
||||||
|
let is_blob_encrypted = is_data_blob_encrypted(&self.data);
|
||||||
|
|
||||||
let mut attachments_json: Value = Value::Null;
|
let mut attachments_json: Value = Value::Null;
|
||||||
if let Some(cipher_sync_data) = cipher_sync_data {
|
if let Some(cipher_sync_data) = cipher_sync_data {
|
||||||
if let Some(attachments) = cipher_sync_data.cipher_attachments.get(&self.uuid)
|
if let Some(attachments) = cipher_sync_data.cipher_attachments.get(&self.uuid)
|
||||||
@@ -189,124 +206,62 @@ impl Cipher {
|
|||||||
(false, false, false)
|
(false, false, false)
|
||||||
};
|
};
|
||||||
|
|
||||||
let fields_json: Vec<_> = self
|
// Like upstream, a cipher that was stored without fields or password history reports them as
|
||||||
.fields
|
// null rather than as an empty list; clients keep the two apart.
|
||||||
.as_ref()
|
let fields_json: Option<Vec<_>> = self.fields.as_ref().map(|s| {
|
||||||
.and_then(|s| {
|
serde_json::from_str::<Vec<LowerCase<Value>>>(s)
|
||||||
serde_json::from_str::<Vec<LowerCase<Value>>>(s)
|
.inspect_err(|e| warn!("Error parsing fields {e:?} for {}", self.uuid))
|
||||||
.inspect_err(|e| warn!("Error parsing fields {e:?} for {}", self.uuid))
|
.ok()
|
||||||
.ok()
|
.map(|d| {
|
||||||
})
|
d.into_iter()
|
||||||
.map(|d| {
|
.map(|mut f| {
|
||||||
d.into_iter()
|
// Check if the `type` key is a number, strings break some clients
|
||||||
.map(|mut f| {
|
// The fallback type is the hidden type `1`. this should prevent accidental data disclosure
|
||||||
// Check if the `type` key is a number, strings break some clients
|
// If not try to convert the string value to a number and fallback to `1`
|
||||||
// The fallback type is the hidden type `1`. this should prevent accidental data disclosure
|
// If it is both not a number and not a string, fallback to `1`
|
||||||
// If not try to convert the string value to a number and fallback to `1`
|
match f.data.get("type") {
|
||||||
// If it is both not a number and not a string, fallback to `1`
|
Some(t) if t.is_number() => {}
|
||||||
match f.data.get("type") {
|
Some(t) if t.is_string() => {
|
||||||
Some(t) if t.is_number() => {}
|
let type_num = &t.as_str().unwrap_or("1").parse::<u8>().unwrap_or(1);
|
||||||
Some(t) if t.is_string() => {
|
f.data["type"] = json!(type_num);
|
||||||
let type_num = &t.as_str().unwrap_or("1").parse::<u8>().unwrap_or(1);
|
}
|
||||||
f.data["type"] = json!(type_num);
|
_ => {
|
||||||
|
f.data["type"] = json!(1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => {
|
f.data
|
||||||
f.data["type"] = json!(1);
|
})
|
||||||
}
|
.collect()
|
||||||
}
|
})
|
||||||
f.data
|
.unwrap_or_default()
|
||||||
})
|
});
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let password_history_json: Vec<_> = self
|
let password_history_json: Option<Vec<_>> = self.password_history.as_ref().map(|s| {
|
||||||
.password_history
|
serde_json::from_str::<Vec<LowerCase<Value>>>(s)
|
||||||
.as_ref()
|
.inspect_err(|e| warn!("Error parsing password history {e:?} for {}", self.uuid))
|
||||||
.and_then(|s| {
|
.ok()
|
||||||
serde_json::from_str::<Vec<LowerCase<Value>>>(s)
|
.map(|d| {
|
||||||
.inspect_err(|e| warn!("Error parsing password history {e:?} for {}", self.uuid))
|
// Check every password history item if they are valid and return it.
|
||||||
.ok()
|
// If a password field has the type `null` skip it, it breaks newer Bitwarden clients
|
||||||
})
|
// A second check is done to verify the lastUsedDate exists and is a valid DateTime string, if not the epoch start time will be used
|
||||||
.map(|d| {
|
d.into_iter()
|
||||||
// Check every password history item if they are valid and return it.
|
.filter_map(|d| match d.data.get("password") {
|
||||||
// If a password field has the type `null` skip it, it breaks newer Bitwarden clients
|
Some(p) if p.is_string() => Some(d.data),
|
||||||
// A second check is done to verify the lastUsedDate exists and is a valid DateTime string, if not the epoch start time will be used
|
_ => None,
|
||||||
d.into_iter()
|
})
|
||||||
.filter_map(|d| match d.data.get("password") {
|
.map(|mut d| {
|
||||||
Some(p) if p.is_string() => Some(d.data),
|
let lud = if let Some(l) = d.get("lastUsedDate").and_then(|l| l.as_str()) {
|
||||||
_ => None,
|
validate_and_format_date(l)
|
||||||
})
|
} else {
|
||||||
.map(|mut d| {
|
"1970-01-01T00:00:00.000000Z".to_owned()
|
||||||
let lud = if let Some(l) = d.get("lastUsedDate").and_then(|l| l.as_str()) {
|
};
|
||||||
validate_and_format_date(l)
|
d["lastUsedDate"] = json!(lud);
|
||||||
} else {
|
d
|
||||||
"1970-01-01T00:00:00.000000Z".to_owned()
|
})
|
||||||
};
|
.collect()
|
||||||
d["lastUsedDate"] = json!(lud);
|
})
|
||||||
d
|
.unwrap_or_default()
|
||||||
})
|
});
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
// Get the type_data or a default to an empty json object '{}'.
|
|
||||||
// If not passing an empty object, mobile clients will crash.
|
|
||||||
let mut type_data_json = serde_json::from_str::<LowerCase<Value>>(&self.data)
|
|
||||||
.inspect_err(|_| warn!("Error parsing data field for {}", self.uuid))
|
|
||||||
.map_or_else(|_| Value::Object(serde_json::Map::new()), |d| d.data);
|
|
||||||
|
|
||||||
// NOTE: This was marked as *Backwards Compatibility Code*, but as of January 2021 this is still being used by upstream
|
|
||||||
// Set the first element of the Uris array as Uri, this is needed several (mobile) clients.
|
|
||||||
if self.atype == 1 {
|
|
||||||
// Upstream always has an `uri` key/value
|
|
||||||
type_data_json["uri"] = Value::Null;
|
|
||||||
if let Some(uris) = type_data_json["uris"].as_array_mut()
|
|
||||||
&& !uris.is_empty()
|
|
||||||
{
|
|
||||||
// Fix uri match values first, they are only allowed to be a number or null
|
|
||||||
// If it is a string, convert it to an int or null if that fails
|
|
||||||
for uri in &mut *uris {
|
|
||||||
if uri["match"].is_string() {
|
|
||||||
let match_value = match uri["match"].as_str().unwrap_or_default().parse::<u8>() {
|
|
||||||
Ok(n) => json!(n),
|
|
||||||
_ => Value::Null,
|
|
||||||
};
|
|
||||||
uri["match"] = match_value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
type_data_json["uri"] = uris[0]["uri"].clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if `passwordRevisionDate` is a valid date, else convert it
|
|
||||||
if let Some(pw_revision) = type_data_json["passwordRevisionDate"].as_str() {
|
|
||||||
type_data_json["passwordRevisionDate"] = json!(validate_and_format_date(pw_revision));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fix secure note issues when data is invalid
|
|
||||||
// This breaks at least the native mobile clients
|
|
||||||
if self.atype == 2 {
|
|
||||||
match type_data_json {
|
|
||||||
Value::Object(ref t) if t.get("type").is_some_and(Value::is_number) => {}
|
|
||||||
_ => {
|
|
||||||
type_data_json = json!({"type": 0});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fix invalid SSH Entries
|
|
||||||
// This breaks at least the native mobile client if invalid
|
|
||||||
// The only way to fix this is by setting type_data_json to `null`
|
|
||||||
// Opening this ssh-key in the mobile client will probably crash the client, but you can edit, save and afterwards delete it
|
|
||||||
if self.atype == 5
|
|
||||||
&& (type_data_json["keyFingerprint"].as_str().is_none_or(str::is_empty)
|
|
||||||
|| type_data_json["privateKey"].as_str().is_none_or(str::is_empty)
|
|
||||||
|| type_data_json["publicKey"].as_str().is_none_or(str::is_empty))
|
|
||||||
{
|
|
||||||
warn!("Error parsing ssh-key, mandatory fields are invalid for {}", self.uuid);
|
|
||||||
type_data_json = Value::Null;
|
|
||||||
}
|
|
||||||
|
|
||||||
let collection_ids = if let Some(cipher_sync_data) = cipher_sync_data {
|
let collection_ids = if let Some(cipher_sync_data) = cipher_sync_data {
|
||||||
if let Some(cipher_collections) = cipher_sync_data.cipher_collections.get(&self.uuid) {
|
if let Some(cipher_collections) = cipher_sync_data.cipher_collections.get(&self.uuid) {
|
||||||
@@ -403,10 +358,86 @@ impl Cipher {
|
|||||||
_ => err!(format!("Cipher {} has an invalid type {}", self.uuid, self.atype)),
|
_ => err!(format!("Cipher {} has an invalid type {}", self.uuid, self.atype)),
|
||||||
};
|
};
|
||||||
|
|
||||||
json_object[key] = type_data_json;
|
if is_blob_encrypted {
|
||||||
|
// The blob holds all of the content, so it is sent back as-is and the structured fields
|
||||||
|
// stay null, as upstream does.
|
||||||
|
json_object["data"] = json!(self.data);
|
||||||
|
json_object["name"] = Value::Null;
|
||||||
|
json_object["notes"] = Value::Null;
|
||||||
|
json_object["fields"] = Value::Null;
|
||||||
|
json_object["passwordHistory"] = Value::Null;
|
||||||
|
} else {
|
||||||
|
json_object[key] = self.legacy_type_data_json();
|
||||||
|
}
|
||||||
Ok(json_object)
|
Ok(json_object)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The per-type data (`login`, `card`, …) of a legacy cipher, with fixups for values that are
|
||||||
|
/// known to break clients.
|
||||||
|
fn legacy_type_data_json(&self) -> Value {
|
||||||
|
use crate::util::validate_and_format_date;
|
||||||
|
|
||||||
|
// Get the type_data or a default to an empty json object '{}'.
|
||||||
|
// If not passing an empty object, mobile clients will crash.
|
||||||
|
let mut type_data_json = serde_json::from_str::<LowerCase<Value>>(&self.data)
|
||||||
|
.inspect_err(|_| warn!("Error parsing data field for {}", self.uuid))
|
||||||
|
.map_or_else(|_| Value::Object(serde_json::Map::new()), |d| d.data);
|
||||||
|
|
||||||
|
// NOTE: This was marked as *Backwards Compatibility Code*, but as of January 2021 this is still being used by upstream
|
||||||
|
// Set the first element of the Uris array as Uri, this is needed several (mobile) clients.
|
||||||
|
if self.atype == 1 {
|
||||||
|
// Upstream always has an `uri` key/value
|
||||||
|
type_data_json["uri"] = Value::Null;
|
||||||
|
if let Some(uris) = type_data_json["uris"].as_array_mut()
|
||||||
|
&& !uris.is_empty()
|
||||||
|
{
|
||||||
|
// Fix uri match values first, they are only allowed to be a number or null
|
||||||
|
// If it is a string, convert it to an int or null if that fails
|
||||||
|
for uri in &mut *uris {
|
||||||
|
if uri["match"].is_string() {
|
||||||
|
let match_value = match uri["match"].as_str().unwrap_or_default().parse::<u8>() {
|
||||||
|
Ok(n) => json!(n),
|
||||||
|
_ => Value::Null,
|
||||||
|
};
|
||||||
|
uri["match"] = match_value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
type_data_json["uri"] = uris[0]["uri"].clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if `passwordRevisionDate` is a valid date, else convert it
|
||||||
|
if let Some(pw_revision) = type_data_json["passwordRevisionDate"].as_str() {
|
||||||
|
type_data_json["passwordRevisionDate"] = json!(validate_and_format_date(pw_revision));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fix secure note issues when data is invalid
|
||||||
|
// This breaks at least the native mobile clients
|
||||||
|
if self.atype == 2 {
|
||||||
|
match type_data_json {
|
||||||
|
Value::Object(ref t) if t.get("type").is_some_and(Value::is_number) => {}
|
||||||
|
_ => {
|
||||||
|
type_data_json = json!({"type": 0});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fix invalid SSH Entries
|
||||||
|
// This breaks at least the native mobile client if invalid
|
||||||
|
// The only way to fix this is by setting type_data_json to `null`
|
||||||
|
// Opening this ssh-key in the mobile client will probably crash the client, but you can edit, save and afterwards delete it
|
||||||
|
if self.atype == 5
|
||||||
|
&& (type_data_json["keyFingerprint"].as_str().is_none_or(str::is_empty)
|
||||||
|
|| type_data_json["privateKey"].as_str().is_none_or(str::is_empty)
|
||||||
|
|| type_data_json["publicKey"].as_str().is_none_or(str::is_empty))
|
||||||
|
{
|
||||||
|
warn!("Error parsing ssh-key, mandatory fields are invalid for {}", self.uuid);
|
||||||
|
type_data_json = Value::Null;
|
||||||
|
}
|
||||||
|
|
||||||
|
type_data_json
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn update_users_revision(&self, conn: &DbConn) -> Vec<UserId> {
|
pub async fn update_users_revision(&self, conn: &DbConn) -> Vec<UserId> {
|
||||||
let mut user_uuids = Vec::new();
|
let mut user_uuids = Vec::new();
|
||||||
match self.user_uuid {
|
match self.user_uuid {
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ mod user_signature_key_pair;
|
|||||||
pub use self::archive::Archive;
|
pub use self::archive::Archive;
|
||||||
pub use self::attachment::{Attachment, AttachmentId};
|
pub use self::attachment::{Attachment, AttachmentId};
|
||||||
pub use self::auth_request::{AuthRequest, AuthRequestId};
|
pub use self::auth_request::{AuthRequest, AuthRequestId};
|
||||||
pub use self::cipher::{Cipher, CipherId, RepromptType};
|
pub use self::cipher::{Cipher, CipherId, RepromptType, is_data_blob_encrypted};
|
||||||
pub use self::collection::{Collection, CollectionCipher, CollectionId, CollectionUser};
|
pub use self::collection::{Collection, CollectionCipher, CollectionId, CollectionUser};
|
||||||
pub use self::device::{Device, DeviceId, DeviceType, DeviceWithAuthRequest, PushId};
|
pub use self::device::{Device, DeviceId, DeviceType, DeviceWithAuthRequest, PushId};
|
||||||
pub use self::emergency_access::{EmergencyAccess, EmergencyAccessId, EmergencyAccessStatus, EmergencyAccessType};
|
pub use self::emergency_access::{EmergencyAccess, EmergencyAccessId, EmergencyAccessStatus, EmergencyAccessType};
|
||||||
@@ -40,5 +40,5 @@ pub use self::sso_auth::{OIDCAuthenticatedUser, OIDCCodeResponseError, SsoAuth};
|
|||||||
pub use self::two_factor::{TwoFactor, TwoFactorType};
|
pub use self::two_factor::{TwoFactor, TwoFactorType};
|
||||||
pub use self::two_factor_duo_context::TwoFactorDuoContext;
|
pub use self::two_factor_duo_context::TwoFactorDuoContext;
|
||||||
pub use self::two_factor_incomplete::TwoFactorIncomplete;
|
pub use self::two_factor_incomplete::TwoFactorIncomplete;
|
||||||
pub use self::user::{Invitation, KeyId, SsoUser, User, UserId, UserKdfType, UserStampException};
|
pub use self::user::{Invitation, KeyId, SsoUser, User, UserId, UserKdfType};
|
||||||
pub use self::user_signature_key_pair::{SignatureAlgorithm, UserSignatureKeyPair};
|
pub use self::user_signature_key_pair::{SignatureAlgorithm, UserSignatureKeyPair};
|
||||||
+93
-10
@@ -6,6 +6,7 @@ use serde_json::Value;
|
|||||||
use crate::{
|
use crate::{
|
||||||
CONFIG,
|
CONFIG,
|
||||||
api::EmptyResult,
|
api::EmptyResult,
|
||||||
|
auth::DEFAULT_ACCESS_VALIDITY,
|
||||||
crypto,
|
crypto,
|
||||||
db::{
|
db::{
|
||||||
DbConn,
|
DbConn,
|
||||||
@@ -109,13 +110,28 @@ enum UserStatus {
|
|||||||
_Disabled = 2,
|
_Disabled = 2,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A previous security stamp that is still accepted, until `expire`.
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct UserStampException {
|
pub struct UserStampException {
|
||||||
pub routes: Vec<String>,
|
/// The routes the stamp is still accepted on, or `None` for any route.
|
||||||
|
pub routes: Option<Vec<String>>,
|
||||||
pub security_stamp: String,
|
pub security_stamp: String,
|
||||||
pub expire: i64,
|
pub expire: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl UserStampException {
|
||||||
|
pub fn is_expired(&self) -> bool {
|
||||||
|
Utc::now().timestamp() > self.expire
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this exception lets a token carrying `security_stamp` through on `route`.
|
||||||
|
pub fn allows(&self, security_stamp: &str, route: &str) -> bool {
|
||||||
|
!self.is_expired()
|
||||||
|
&& self.security_stamp == security_stamp
|
||||||
|
&& self.routes.as_ref().is_none_or(|routes| routes.iter().any(|r| r == route))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Local methods
|
/// Local methods
|
||||||
impl User {
|
impl User {
|
||||||
pub const CLIENT_KDF_TYPE_DEFAULT: i32 = UserKdfType::Pbkdf2 as i32;
|
pub const CLIENT_KDF_TYPE_DEFAULT: i32 = UserKdfType::Pbkdf2 as i32;
|
||||||
@@ -239,10 +255,38 @@ impl User {
|
|||||||
|
|
||||||
pub async fn reset_security_stamp(&mut self, conn: &DbConn) -> EmptyResult {
|
pub async fn reset_security_stamp(&mut self, conn: &DbConn) -> EmptyResult {
|
||||||
self.security_stamp = get_uuid();
|
self.security_stamp = get_uuid();
|
||||||
|
// A reset is meant to end the other sessions, which a key rotation's grace would undo. The
|
||||||
|
// route exceptions stay, since they are set right before a reset, for the stamp it replaces.
|
||||||
|
self.retain_stamp_exceptions(|e| e.routes.is_some());
|
||||||
Device::rotate_refresh_tokens_by_user(&self.uuid, conn).await?;
|
Device::rotate_refresh_tokens_by_user(&self.uuid, conn).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resets the security stamp after a key rotation, while letting the access tokens already
|
||||||
|
/// issued keep working until they expire.
|
||||||
|
///
|
||||||
|
/// This is what upstream does: there the stamp is only checked when a token is refreshed, so a
|
||||||
|
/// rotation invalidates refresh tokens but not the access tokens in use. Clients rely on it to
|
||||||
|
/// keep a session going across a rotation. Chained rotations keep every earlier stamp that is
|
||||||
|
/// still within its window.
|
||||||
|
pub async fn reset_security_stamp_after_key_rotation(&mut self, conn: &DbConn) -> EmptyResult {
|
||||||
|
let previous_stamp = self.security_stamp.clone();
|
||||||
|
let mut grace: Vec<UserStampException> =
|
||||||
|
self.stamp_exceptions().into_iter().filter(|e| e.routes.is_none() && !e.is_expired()).collect();
|
||||||
|
|
||||||
|
self.reset_security_stamp(conn).await?;
|
||||||
|
|
||||||
|
grace.push(UserStampException {
|
||||||
|
routes: None,
|
||||||
|
security_stamp: previous_stamp,
|
||||||
|
expire: (Utc::now() + *DEFAULT_ACCESS_VALIDITY).timestamp(),
|
||||||
|
});
|
||||||
|
let mut exceptions = self.stamp_exceptions();
|
||||||
|
exceptions.extend(grace);
|
||||||
|
self.set_stamp_exceptions(&exceptions);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Set the stamp_exception to only allow a subsequent request matching a specific route using the current security-stamp.
|
/// Set the stamp_exception to only allow a subsequent request matching a specific route using the current security-stamp.
|
||||||
///
|
///
|
||||||
/// # Arguments
|
/// # Arguments
|
||||||
@@ -251,17 +295,56 @@ impl User {
|
|||||||
/// After these 2 minutes this stamp will expire.
|
/// After these 2 minutes this stamp will expire.
|
||||||
///
|
///
|
||||||
pub fn set_stamp_exception(&mut self, route_exception: Vec<String>) {
|
pub fn set_stamp_exception(&mut self, route_exception: Vec<String>) {
|
||||||
let stamp_exception = UserStampException {
|
self.set_stamp_exceptions(&[UserStampException {
|
||||||
routes: route_exception,
|
routes: Some(route_exception),
|
||||||
security_stamp: self.security_stamp.clone(),
|
security_stamp: self.security_stamp.clone(),
|
||||||
expire: (Utc::now() + TimeDelta::try_minutes(2).unwrap()).timestamp(),
|
expire: (Utc::now() + TimeDelta::try_minutes(2).unwrap()).timestamp(),
|
||||||
};
|
}]);
|
||||||
self.stamp_exception = Some(serde_json::to_string(&stamp_exception).unwrap_or_default());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resets the stamp_exception to prevent re-use of the previous security-stamp
|
/// The previous security stamps that are still accepted, expired ones included.
|
||||||
pub fn reset_stamp_exception(&mut self) {
|
pub fn stamp_exceptions(&self) -> Vec<UserStampException> {
|
||||||
self.stamp_exception = None;
|
let Some(stored) = self.stamp_exception.as_deref() else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
// Before key rotations kept sessions alive, only a single route exception was stored.
|
||||||
|
serde_json::from_str::<Vec<UserStampException>>(stored)
|
||||||
|
.or_else(|_| serde_json::from_str::<UserStampException>(stored).map(|e| vec![e]))
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_stamp_exceptions(&mut self, exceptions: &[UserStampException]) {
|
||||||
|
self.stamp_exception = if exceptions.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(serde_json::to_string(&exceptions).unwrap_or_default())
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persists only `stamp_exception`, for callers holding a user read earlier in the request.
|
||||||
|
///
|
||||||
|
/// A full `save` would write back every other column as it was read, undoing anything saved in
|
||||||
|
/// the meantime, such as the new keys of a key rotation made from another device.
|
||||||
|
pub async fn save_stamp_exceptions(&self, conn: &DbConn) -> EmptyResult {
|
||||||
|
let uuid = self.uuid.clone();
|
||||||
|
let stamp_exception = self.stamp_exception.clone();
|
||||||
|
conn.run(move |conn| {
|
||||||
|
diesel::update(users::table.filter(users::uuid.eq(uuid)))
|
||||||
|
.set(users::stamp_exception.eq(stamp_exception))
|
||||||
|
.execute(conn)
|
||||||
|
.map_res("Error updating user stamp exceptions")
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the stamp exceptions that don't match `keep`. Returns whether any were dropped.
|
||||||
|
pub fn retain_stamp_exceptions(&mut self, keep: impl Fn(&UserStampException) -> bool) -> bool {
|
||||||
|
let mut exceptions = self.stamp_exceptions();
|
||||||
|
let before = exceptions.len();
|
||||||
|
exceptions.retain(keep);
|
||||||
|
let changed = exceptions.len() != before;
|
||||||
|
self.set_stamp_exceptions(&exceptions);
|
||||||
|
changed
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn display_name(&self) -> &str {
|
pub fn display_name(&self) -> &str {
|
||||||
@@ -327,8 +410,8 @@ impl User {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn v2_upgrade_token_json(&self) -> Value {
|
pub fn v2_upgrade_token_json(&self) -> Option<Value> {
|
||||||
self.v2_upgrade_token.as_ref().and_then(|token| serde_json::from_str(token).ok()).unwrap_or(Value::Null)
|
self.v2_upgrade_token.as_ref().and_then(|token| serde_json::from_str(token).ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn to_json(&self, conn: &DbConn) -> Value {
|
pub async fn to_json(&self, conn: &DbConn) -> Value {
|
||||||
|
|||||||
Reference in new issue
Block a user