V2 Encryption followups (#7963)

* Add the account recovery V2 upgrade routes

GET /organizations/{orgId}/users/keys/pending-v2-upgrades lists, a page at a
time, the memberships whose account recovery key still wraps the member's V1
user key after an upgrade to V2 encryption, with the upgrade token the admin
re-wraps it from. POST .../v2-upgrades stores the re-wrapped keys in one
transaction, or unenrolls the members whose token holds no usable key. Only
Owners and Admins, an Admin never for Owners, and a membership that changed
since the read is skipped. GET /organizations/{orgId}/private-key gives the
organization's private key these need, to everyone with Manage users as
upstream. The SDK's encrypted migrator calls all three.

Enrolling in or withdrawing from account recovery drops a leftover upgrade
token, which would otherwise get a member who re-enrolled after the upgrade
unenrolled.

* Check membership for the organization public key in the handler

The public key routes serve the placeholder SSO organization's key to users
without an organization, so they couldn't require the member guard, but it
still ran for every request: it logged a membership error for each legitimate
v2 JIT password setup and authenticated the request twice. The routes now
authenticate once, return the placeholder key first, and check the membership
themselves, with the same rule as the guard.

* List attachments in sync with a stable URL

Sync and the cipher responses list each attachment with an unsigned URL of
upstream's form, which no longer changes on every sync nor costs a presign per
attachment on S3, and which isn't served without a token. The attachment routes
sign it: the cipher route and its admin variant, and the emergency access view's
route the web vault downloads through, which is added. The admin variant also
signs it for a member who can open the item themselves, because the web vault's
fallback to the listed URL no longer works.

* Seed the SDK live tests' vectors with their attachments

Sync now lists attachments with a stable URL, so the rotation test's before and after comparison holds with them.
Only the legacy attachments without a key of their own stay out: the SDK refuses to rotate a vault holding one.
This commit is contained in:
Daniel García authored and GitHub committed 2026-11-15 00:46:59 +01:00
1 parent 81ec0966cb
commit bd7beab76e
9 files changed
+400 -45

No files matched your search

+21 -4
View File
@@ -65,16 +65,33 @@ impl Attachment {
}
}
pub async fn to_json(&self, host: &str) -> Result<Value, crate::Error> {
Ok(json!({
/// The attachment as sync and the cipher responses list it. Its `url` is a leftover from the old download flow.
/// Clients get a signed URL from the attachment routes (`to_json_for_download`) instead, only the web vault and the
/// CLI read this one, as a fallback when those routes answer 404.
///
/// Ref: <https://github.com/bitwarden/server/blob/341acc9d3d8988cec8fe05debfa6d557cf5ab749/src/Api/Vault/Models/Response/AttachmentResponseModel.cs#L24-L29>
pub fn to_json(&self, host: &str) -> Value {
self.json_with_url(&format!("{host}/attachments/{}/{}", self.cipher_uuid, self.id))
}
/// The attachment with a `url` the client can download it from for a short while, for the attachment routes
/// (`GET /ciphers/{id}/attachment/{attachmentId}`, its admin variant, the emergency access one).
///
/// Ref: <https://github.com/bitwarden/server/blob/341acc9d3d8988cec8fe05debfa6d557cf5ab749/src/Api/Vault/Controllers/CiphersController.cs#L1699-L1717>
pub async fn to_json_for_download(&self, host: &str) -> Result<Value, crate::Error> {
Ok(self.json_with_url(&self.get_url(host).await?))
}
fn json_with_url(&self, url: &str) -> Value {
json!({
"id": self.id,
"url": self.get_url(host).await?,
"url": url,
"fileName": self.file_name,
"size": self.file_size.to_string(),
"sizeName": crate::util::get_display_size(self.file_size),
"key": self.akey,
"object": "attachment"
}))
})
}
}
+2 -2
View File
@@ -270,7 +270,7 @@ impl Cipher {
{
let mut attachments_json_vec = vec![];
for attachment in attachments {
attachments_json_vec.push(attachment.to_json(host).await?);
attachments_json_vec.push(attachment.to_json(host));
}
attachments_json = Value::Array(attachments_json_vec);
}
@@ -279,7 +279,7 @@ impl Cipher {
if !attachments.is_empty() {
let mut attachments_json_vec = vec![];
for attachment in attachments {
attachments_json_vec.push(attachment.to_json(host).await?);
attachments_json_vec.push(attachment.to_json(host));
}
attachments_json = Value::Array(attachments_json_vec);
}
+100 -4
View File
@@ -19,15 +19,27 @@ use crate::{
organizations, users, users_collections, users_organizations,
},
},
error::MapResult,
error::{Error, MapResult},
};
use macros::UuidFromParam;
use super::{
Cipher, CipherId, Collection, CollectionId, CollectionUser, Group, GroupId, GroupUser, OrgPolicy, OrgPolicyType,
TwoFactor, User, UserId,
Cipher, CipherId, Collection, CollectionId, CollectionUser, Group, GroupId, GroupUser, KeyId, OrgPolicy,
OrgPolicyType, TwoFactor, User, UserId,
};
/// A membership whose account recovery key still wraps the member's V1 user key: an upgrade to V2 encryption can't
/// re-wrap it (that needs the member to trust the organization's key), so it left the token the admin re-wraps it from.
#[derive(Queryable)]
pub struct PendingV2Upgrade {
pub member_id: MembershipId,
/// The member's current user key id, which the re-wrapped key must be sent back with
pub user_key_id: KeyId,
/// The V1 user key, wrapped with the organization's public key
pub account_recovery_key: String,
pub v2_upgrade_token: String,
}
#[derive(Identifiable, Queryable, Insertable, AsChangeset)]
#[diesel(table_name = organizations)]
#[diesel(treat_none_as_null = true)]
@@ -293,7 +305,7 @@ impl CustomPermission {
/// replaces the member's permissions, so a malformed value must not silently remove one. Granting a
/// permission this version does not enforce is rejected as well. The clients also send permissions
/// Vaultwarden does not know at all, like `manageSso`, those are ignored.
pub fn requested(permissions: &HashMap<String, Value>) -> Result<HashSet<CustomPermission>, crate::Error> {
pub fn requested(permissions: &HashMap<String, Value>) -> Result<HashSet<CustomPermission>, Error> {
let mut granted = HashSet::new();
for permission in CustomPermission::ALL {
match permissions.get(permission.json_key()) {
@@ -1258,6 +1270,90 @@ impl Membership {
.await
}
/// The most account recovery V2 upgrades one request reads or writes, like upstream's
/// `OrganizationUserV2UpgradesRequestModel.MaxUpgrades`.
pub const MAX_V2_UPGRADES: i64 = 100;
/// The next page of memberships of this organization whose account recovery key the admin still has to re-wrap
/// with the member's V2 user key: enrolled, carrying an upgrade token, of a user with a key id (the re-wrapped key
/// is checked against it), and Owners only for an Owner. Ordered by id, after `after`, at most `MAX_V2_UPGRADES`.
pub async fn find_pending_v2_upgrades(
org_uuid: &OrganizationId,
include_owners: bool,
after: Option<&MembershipId>,
conn: &DbConn,
) -> Vec<PendingV2Upgrade> {
conn.run(move |conn| {
let mut query = users_organizations::table
.inner_join(users::table)
.filter(users_organizations::org_uuid.eq(org_uuid))
.filter(users_organizations::v2_upgrade_token.is_not_null())
.filter(users_organizations::reset_password_key.is_not_null())
.filter(users::key_id.is_not_null())
.into_boxed();
if !include_owners {
query = query.filter(users_organizations::atype.ne(MembershipType::Owner as i32));
}
if let Some(after) = after {
query = query.filter(users_organizations::uuid.gt(after));
}
query
.order(users_organizations::uuid)
.limit(Self::MAX_V2_UPGRADES)
// The filters above make sure these are set
.select((
users_organizations::uuid,
users::key_id.assume_not_null(),
users_organizations::reset_password_key.assume_not_null(),
users_organizations::v2_upgrade_token.assume_not_null(),
))
.load(conn)
.unwrap_or_default()
})
.await
}
/// Replaces the account recovery key of a member who upgraded to V2 encryption with `account_recovery_key`, or
/// unenrolls them when it is `None`, and consumes the upgrade token, so it can't be replayed. Only while the
/// membership is still enrolled, carrying the token, not an Owner unless `include_owners`, and its user's key id is
/// still `user_key_id` (the key the new recovery key wraps). Returns whether it applied, otherwise the membership
/// stays pending. It runs inside a transaction, so it leaves the user's revision to the caller.
pub async fn apply_v2_upgrade(
&self,
include_owners: bool,
user_key_id: &KeyId,
account_recovery_key: Option<&str>,
conn: &DbConn,
) -> Result<bool, Error> {
// An empty list excludes no one
let excluded = if include_owners {
vec![]
} else {
vec![MembershipType::Owner as i32]
};
let rows: usize = conn
.run(move |conn| {
diesel::update(
users_organizations::table
.filter(users_organizations::uuid.eq(&self.uuid))
.filter(users_organizations::v2_upgrade_token.is_not_null())
.filter(users_organizations::reset_password_key.is_not_null())
.filter(users_organizations::atype.ne_all(excluded))
.filter(diesel::dsl::exists(
users::table.filter(users::uuid.eq(&self.user_uuid)).filter(users::key_id.eq(user_key_id)),
)),
)
.set((
users_organizations::reset_password_key.eq(account_recovery_key),
users_organizations::v2_upgrade_token.eq(None::<String>),
))
.execute(conn)
.map_res("Error saving membership")
})
.await?;
Ok(rows > 0)
}
pub async fn count_confirmed_by_org_and_type(
org_uuid: &OrganizationId,
atype: MembershipType,