Browse Source

Add archiving

pull/6916/head
Matt Aaron 3 days ago
committed by user
parent
commit
27c8a77ed7
  1. 1
      migrations/mysql/2026-03-09-005927-0000_2026-03-08-200000_add_archives/down.sql
  2. 8
      migrations/mysql/2026-03-09-005927-0000_2026-03-08-200000_add_archives/up.sql
  3. 1
      migrations/postgresql/2026-03-09-005927-0000_2026-03-08-200000_add_archives/down.sql
  4. 10
      migrations/postgresql/2026-03-09-005927-0000_2026-03-08-200000_add_archives/up.sql
  5. 1
      migrations/sqlite/2026-03-09-005927-0000_2026-03-08-200000_add_archives/down.sql
  6. 8
      migrations/sqlite/2026-03-09-005927-0000_2026-03-08-200000_add_archives/up.sql
  7. 107
      src/api/core/ciphers.rs
  8. 2
      src/config.rs
  9. 81
      src/db/models/archive.rs
  10. 17
      src/db/models/cipher.rs
  11. 2
      src/db/models/mod.rs
  12. 8
      src/db/schema.rs

1
migrations/mysql/2026-03-09-005927-0000_2026-03-08-200000_add_archives/down.sql

@ -0,0 +1 @@
DROP TABLE archives;

8
migrations/mysql/2026-03-09-005927-0000_2026-03-08-200000_add_archives/up.sql

@ -0,0 +1,8 @@
DROP TABLE IF EXISTS archives;
CREATE TABLE archives (
user_uuid CHAR(36) NOT NULL REFERENCES users (uuid) ON DELETE CASCADE,
cipher_uuid CHAR(36) NOT NULL REFERENCES ciphers (uuid) ON DELETE CASCADE,
archived_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_uuid, cipher_uuid)
);

1
migrations/postgresql/2026-03-09-005927-0000_2026-03-08-200000_add_archives/down.sql

@ -0,0 +1 @@
DROP TABLE archives;

10
migrations/postgresql/2026-03-09-005927-0000_2026-03-08-200000_add_archives/up.sql

@ -0,0 +1,10 @@
DROP TABLE IF EXISTS archives;
CREATE TABLE archives (
user_uuid CHAR(36) NOT NULL,
cipher_uuid CHAR(36) NOT NULL,
archived_at TIMESTAMP NOT NULL DEFAULT now(),
PRIMARY KEY (user_uuid, cipher_uuid),
FOREIGN KEY(user_uuid) REFERENCES users(uuid) ON DELETE CASCADE,
FOREIGN KEY(cipher_uuid) REFERENCES ciphers(uuid) ON DELETE CASCADE
);

1
migrations/sqlite/2026-03-09-005927-0000_2026-03-08-200000_add_archives/down.sql

@ -0,0 +1 @@
DROP TABLE archives;

8
migrations/sqlite/2026-03-09-005927-0000_2026-03-08-200000_add_archives/up.sql

@ -0,0 +1,8 @@
DROP TABLE IF EXISTS archives;
CREATE TABLE archives (
user_uuid CHAR(36) NOT NULL REFERENCES users (uuid) ON DELETE CASCADE,
cipher_uuid CHAR(36) NOT NULL REFERENCES ciphers (uuid) ON DELETE CASCADE,
archived_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_uuid, cipher_uuid)
);

107
src/api/core/ciphers.rs

@ -19,9 +19,9 @@ use crate::{
crypto,
db::{
models::{
Attachment, AttachmentId, Cipher, CipherId, Collection, CollectionCipher, CollectionGroup, CollectionId,
CollectionUser, EventType, Favorite, Folder, FolderCipher, FolderId, Group, Membership, MembershipType,
OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, Send, UserId,
Archive, Attachment, AttachmentId, Cipher, CipherId, Collection, CollectionCipher, CollectionGroup,
CollectionId, CollectionUser, EventType, Favorite, Folder, FolderCipher, FolderId, Group, Membership,
MembershipType, OrgPolicy, OrgPolicyType, OrganizationId, RepromptType, Send, UserId,
},
DbConn, DbPool,
},
@ -95,6 +95,10 @@ pub fn routes() -> Vec<Route> {
post_collections_update,
post_collections_admin,
put_collections_admin,
archive_cipher_put,
archive_cipher_selected,
unarchive_cipher_put,
unarchive_cipher_selected,
]
}
@ -1703,6 +1707,36 @@ async fn delete_all(
}
}
#[put("/ciphers/<cipher_id>/archive")]
async fn archive_cipher_put(cipher_id: CipherId, headers: Headers, conn: DbConn, nt: Notify<'_>) -> JsonResult {
_set_archived_cipher_by_uuid(&cipher_id, &headers, true, false, &conn, &nt).await
}
#[put("/ciphers/archive", data = "<data>")]
async fn archive_cipher_selected(
data: Json<CipherIdsData>,
headers: Headers,
conn: DbConn,
nt: Notify<'_>,
) -> JsonResult {
_set_archived_multiple_ciphers(data, &headers, true, &conn, &nt).await
}
#[put("/ciphers/<cipher_id>/unarchive")]
async fn unarchive_cipher_put(cipher_id: CipherId, headers: Headers, conn: DbConn, nt: Notify<'_>) -> JsonResult {
_set_archived_cipher_by_uuid(&cipher_id, &headers, false, false, &conn, &nt).await
}
#[put("/ciphers/unarchive", data = "<data>")]
async fn unarchive_cipher_selected(
data: Json<CipherIdsData>,
headers: Headers,
conn: DbConn,
nt: Notify<'_>,
) -> JsonResult {
_set_archived_multiple_ciphers(data, &headers, false, &conn, &nt).await
}
#[derive(PartialEq)]
pub enum CipherDeleteOptions {
SoftSingle,
@ -1921,6 +1955,66 @@ async fn _delete_cipher_attachment_by_id(
Ok(Json(json!({"cipher":cipher_json})))
}
async fn _set_archived_cipher_by_uuid(
cipher_id: &CipherId,
headers: &Headers,
archived: bool,
multi_archive: bool,
conn: &DbConn,
nt: &Notify<'_>,
) -> JsonResult {
let Some(cipher) = Cipher::find_by_uuid(cipher_id, conn).await else {
err!("Cipher doesn't exist")
};
if !cipher.is_write_accessible_to_user(&headers.user.uuid, conn).await {
err!("Cipher can't be archived by user")
}
cipher.set_archived(archived, &headers.user.uuid, conn).await?;
if !multi_archive {
nt.send_cipher_update(
UpdateType::SyncCipherUpdate,
&cipher,
&cipher.update_users_revision(conn).await,
&headers.device,
None,
conn,
)
.await;
}
Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, None, CipherSyncType::User, conn).await?))
}
async fn _set_archived_multiple_ciphers(
data: Json<CipherIdsData>,
headers: &Headers,
archived: bool,
conn: &DbConn,
nt: &Notify<'_>,
) -> JsonResult {
let data = data.into_inner();
let mut ciphers: Vec<Value> = Vec::new();
for cipher_id in data.ids {
match _set_archived_cipher_by_uuid(&cipher_id, headers, archived, true, conn, nt).await {
Ok(json) => ciphers.push(json.into_inner()),
err => return err,
}
}
// Multi archive actions do not send out a push for each cipher, we need to send a general sync here
nt.send_user_update(UpdateType::SyncCiphers, &headers.user, &headers.device.push_uuid, conn).await;
Ok(Json(json!({
"data": ciphers,
"object": "list",
"continuationToken": null
})))
}
/// This will hold all the necessary data to improve a full sync of all the ciphers
/// It can be used during the `Cipher::to_json()` call.
/// It will prevent the so called N+1 SQL issue by running just a few queries which will hold all the data needed.
@ -1930,6 +2024,7 @@ pub struct CipherSyncData {
pub cipher_folders: HashMap<CipherId, FolderId>,
pub cipher_favorites: HashSet<CipherId>,
pub cipher_collections: HashMap<CipherId, Vec<CollectionId>>,
pub cipher_archives: HashMap<CipherId, NaiveDateTime>,
pub members: HashMap<OrganizationId, Membership>,
pub user_collections: HashMap<CollectionId, CollectionUser>,
pub user_collections_groups: HashMap<CollectionId, CollectionGroup>,
@ -1946,6 +2041,7 @@ impl CipherSyncData {
pub async fn new(user_id: &UserId, sync_type: CipherSyncType, conn: &DbConn) -> Self {
let cipher_folders: HashMap<CipherId, FolderId>;
let cipher_favorites: HashSet<CipherId>;
let cipher_archives: HashMap<CipherId, NaiveDateTime>;
match sync_type {
// User Sync supports Folders and Favorites
CipherSyncType::User => {
@ -1954,12 +2050,16 @@ impl CipherSyncData {
// Generate a HashSet of all the Cipher UUID's which are marked as favorite
cipher_favorites = Favorite::get_all_cipher_uuid_by_user(user_id, conn).await.into_iter().collect();
// Generate a HashMap with the Cipher UUID as key and the archived date time as value
cipher_archives = Archive::find_by_user(user_id, conn).await.into_iter().collect();
}
// Organization Sync does not support Folders and Favorites.
// If these are set, it will cause issues in the web-vault.
CipherSyncType::Organization => {
cipher_folders = HashMap::with_capacity(0);
cipher_favorites = HashSet::with_capacity(0);
cipher_archives = HashMap::with_capacity(0);
}
}
@ -2019,6 +2119,7 @@ impl CipherSyncData {
};
Self {
cipher_archives,
cipher_attachments,
cipher_folders,
cipher_favorites,

2
src/config.rs

@ -1052,6 +1052,8 @@ fn validate_config(cfg: &ConfigItems) -> Result<(), Error> {
"cxp-export-mobile",
// Webauthn Related Origins
"pm-30529-webauthn-related-origins",
// Innovation Team
"pm-19148-innovation-archive"
];
let configured_flags = parse_experimental_client_feature_flags(&cfg.experimental_client_feature_flags);
let invalid_flags: Vec<_> = configured_flags.keys().filter(|flag| !KNOWN_FLAGS.contains(&flag.as_str())).collect();

81
src/db/models/archive.rs

@ -0,0 +1,81 @@
use chrono::{NaiveDateTime, Utc};
use diesel::prelude::*;
use super::{CipherId, User, UserId};
use crate::api::EmptyResult;
use crate::db::schema::archives;
use crate::db::DbConn;
use crate::error::MapResult;
#[derive(Identifiable, Queryable, Insertable)]
#[diesel(table_name = archives)]
#[diesel(primary_key(user_uuid, cipher_uuid))]
pub struct Archive {
pub user_uuid: UserId,
pub cipher_uuid: CipherId,
pub archived_at: NaiveDateTime,
}
impl Archive {
// Returns the date the specified cipher was archived
pub async fn get_archived_date(cipher_uuid: &CipherId, user_uuid: &UserId, conn: &DbConn) -> Option<NaiveDateTime> {
db_run! { conn: {
archives::table
.filter(archives::cipher_uuid.eq(cipher_uuid))
.filter(archives::user_uuid.eq(user_uuid))
.select(archives::archived_at)
.first::<NaiveDateTime>(conn).ok()
}}
}
// Sets the specified cipher to be archived or unarchived
pub async fn set_archived(
archived: bool,
cipher_uuid: &CipherId,
user_uuid: &UserId,
conn: &DbConn,
) -> EmptyResult {
let (old, new) = (Self::get_archived_date(cipher_uuid, user_uuid, conn).await.is_some(), archived);
match (old, new) {
(false, true) => {
User::update_uuid_revision(user_uuid, conn).await;
db_run! { conn: {
diesel::insert_into(archives::table)
.values((
archives::user_uuid.eq(user_uuid),
archives::cipher_uuid.eq(cipher_uuid),
archives::archived_at.eq(Utc::now().naive_utc()),
))
.execute(conn)
.map_res("Error archiving")
}}
}
(true, false) => {
User::update_uuid_revision(user_uuid, conn).await;
db_run! { conn: {
diesel::delete(
archives::table
.filter(archives::user_uuid.eq(user_uuid))
.filter(archives::cipher_uuid.eq(cipher_uuid))
)
.execute(conn)
.map_res("Error unarchiving")
}}
}
// Otherwise, the archived status is already what it should be
_ => Ok(()),
}
}
/// Return a vec with (cipher_uuid, archived_at)
/// This is used during a full sync so we only need one query for all folder matches
pub async fn find_by_user(user_uuid: &UserId, conn: &DbConn) -> Vec<(CipherId, NaiveDateTime)> {
db_run! { conn: {
archives::table
.filter(archives::user_uuid.eq(user_uuid))
.select((archives::cipher_uuid, archives::archived_at))
.load::<(CipherId, NaiveDateTime)>(conn)
.unwrap_or_default()
}}
}
}

17
src/db/models/cipher.rs

@ -10,8 +10,8 @@ use diesel::prelude::*;
use serde_json::Value;
use super::{
Attachment, CollectionCipher, CollectionId, Favorite, FolderCipher, FolderId, Group, Membership, MembershipStatus,
MembershipType, OrganizationId, User, UserId,
Archive, Attachment, CollectionCipher, CollectionId, Favorite, FolderCipher, FolderId, Group, Membership,
MembershipStatus, MembershipType, OrganizationId, User, UserId,
};
use crate::api::core::{CipherData, CipherSyncData, CipherSyncType};
use macros::UuidFromParam;
@ -380,6 +380,11 @@ impl Cipher {
} else {
self.is_favorite(user_uuid, conn).await
});
json_object["archivedDate"] = json!(if let Some(cipher_sync_data) = cipher_sync_data {
cipher_sync_data.cipher_archives.get(&self.uuid).map_or(Value::Null, |d| Value::String(format_date(&d)))
} else {
self.get_archived_date(user_uuid, conn).await.map_or(Value::Null, |d| Value::String(format_date(&d)))
});
// These values are true by default, but can be false if the
// cipher belongs to a collection or group where the org owner has enabled
// the "Read Only" or "Hide Passwords" restrictions for the user.
@ -737,6 +742,14 @@ impl Cipher {
}
}
pub async fn get_archived_date(&self, user_uuid: &UserId, conn: &DbConn) -> Option<NaiveDateTime> {
Archive::get_archived_date(&self.uuid, user_uuid, conn).await
}
pub async fn set_archived(&self, archived: bool, user_uuid: &UserId, conn: &DbConn) -> EmptyResult {
Archive::set_archived(archived, &self.uuid, user_uuid, conn).await
}
pub async fn get_folder_uuid(&self, user_uuid: &UserId, conn: &DbConn) -> Option<FolderId> {
db_run! { conn: {
folders_ciphers::table

2
src/db/models/mod.rs

@ -1,3 +1,4 @@
mod archive;
mod attachment;
mod auth_request;
mod cipher;
@ -17,6 +18,7 @@ mod two_factor_duo_context;
mod two_factor_incomplete;
mod user;
pub use self::archive::Archive;
pub use self::attachment::{Attachment, AttachmentId};
pub use self::auth_request::{AuthRequest, AuthRequestId};
pub use self::cipher::{Cipher, CipherId, RepromptType};

8
src/db/schema.rs

@ -341,6 +341,14 @@ table! {
}
}
table! {
archives (user_uuid, cipher_uuid) {
user_uuid -> Text,
cipher_uuid -> Text,
archived_at -> Timestamp,
}
}
joinable!(attachments -> ciphers (cipher_uuid));
joinable!(ciphers -> organizations (organization_uuid));
joinable!(ciphers -> users (user_uuid));

Loading…
Cancel
Save