Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Fix login validation and export recovery

Manav Rathi54e9a0906b1a
diff --git a/rust/apps/cli-next/tests/cli/export_adoption.rs b/rust/apps/cli-next/tests/cli/export_adoption.rs
index 83e922f739..f173b19362 100644
--- a/rust/apps/cli-next/tests/cli/export_adoption.rs
+++ b/rust/apps/cli-next/tests/cli/export_adoption.rs
@@ -537,6 +537,18 @@ fn adoption_history_resumes_after_media_move_and_keeps_the_full_scope() {
downloaded.assert();
assert!(!root.join("export_status.json").exists());
assert_eq!(count(&engine.db(), "SELECT bound FROM export"), 1);
+ engine.catalog.files.remove(&(FAMILY, PHOTO));
+ assert!(engine.run(false, &[]).unwrap().complete);
+ assert_eq!(
+ fs::read(root.join("Trash/Family/Pair.jpg")).unwrap(),
+ b"existing trash"
+ );
+ assert!(root.join("Trash/Family-1/Photo.jpg").is_file());
+ assert!(
+ root.join("Trash/Family-1/metadata/Photo.jpg.json")
+ .is_file()
+ );
+ assert!(engine.run(false, &[]).unwrap().complete);
}
#[test]
diff --git a/rust/apps/cli-next/tests/cli/export_maintenance.rs b/rust/apps/cli-next/tests/cli/export_maintenance.rs
index ea17263510..f2c879f179 100644
--- a/rust/apps/cli-next/tests/cli/export_maintenance.rs
+++ b/rust/apps/cli-next/tests/cli/export_maintenance.rs
@@ -1063,8 +1063,7 @@ fn export_cancels_pending_retention_when_selected_membership_returns() {
let root = destination.path().join("photos");
run(&home, &root, &[], true);
let db = export_database(&home);
- fs::create_dir_all(root.join("Trash/First")).unwrap();
- fs::write(root.join("Trash/First/notes"), b"unrelated album").unwrap();
+ db.execute_batch("CREATE TRIGGER stop_retention BEFORE UPDATE ON pending WHEN new.retained=1 AND json_type(new.action,'$.Directory') IS NOT NULL BEGIN SELECT RAISE(ABORT,'stop before retention directory'); END;").unwrap();
let mut version = 10;
for (step, remove, complete) in [
(0, true, false),
@@ -1074,9 +1073,8 @@ fn export_cancels_pending_retention_when_selected_membership_returns() {
(4, true, false),
(5, false, true),
] {
- if step == 2 {
- fs::remove_file(root.join("Trash/First/notes")).unwrap();
- fs::remove_dir(root.join("Trash/First")).unwrap();
+ if step == 1 {
+ db.execute_batch("DROP TRIGGER stop_retention;").unwrap();
}
if step == 4 {
fs::write(root.join("Trash/First/Original-1.jpg"), b"unrelated file").unwrap();
@@ -1436,7 +1434,7 @@ fn export_adoption_ignores_unrelated_non_utf8_entries_but_rejects_claimed_paths(
}
#[test]
-fn export_missing_move_endpoints_require_active_repair_or_retained_recovery() {
+fn export_missing_move_endpoints_restore_active_media_and_finish_removal() {
for retaining in [false, true] {
let mut server = mockito::Server::new();
let home = TestHome::new();
@@ -1476,11 +1474,10 @@ fn export_missing_move_endpoints_require_active_repair_or_retained_recovery() {
assert!(!root.join("First/Photo.jpg").exists());
db.execute_batch("DROP TRIGGER stop_move;").unwrap();
if retaining {
- run(&home, &root, &[], false);
+ run(&home, &root, &[], true);
+ assert!(!root.join("First/metadata/Photo.jpg.json").exists());
assert!(!root.join("Trash/First/metadata/Photo.jpg.json").exists());
- fs::write(root.join(moved), b"original").unwrap();
run(&home, &root, &[], true);
- assert_component(&root, "Trash/First", "Photo.jpg", b"original");
} else {
run(&home, &root, &[], true);
assert_component(&root, "First", "Renamed.jpg", b"original");
diff --git a/rust/apps/cli-next/tests/cli/export_media.rs b/rust/apps/cli-next/tests/cli/export_media.rs
index e859983f5d..8cb0a0c6c8 100644
--- a/rust/apps/cli-next/tests/cli/export_media.rs
+++ b/rust/apps/cli-next/tests/cli/export_media.rs
@@ -263,7 +263,7 @@ fn engine_preserves_native_dates_and_metadata_overrides() {
}
let encrypted = blob::encrypt_json(&uploaded, &file_key(&file, &key)).unwrap();
file["metadata"] = json!({"encryptedData":b64::encode(&encrypted.encrypted_data),"decryptionHeader":b64::encode(encrypted.decryption_header.as_bytes())});
- let fetched = download(&mut server, 10, &bytes, 1);
+ let fetched = download(&mut server, 10, &bytes, 4);
let mut engine = new_engine(&server, key, file.clone());
for (index, (edits, description, location, seconds)) in [
(json!({"editedTime":null,"caption":null,"lat":0}), None, (12.0,34.0), "1700000000"),
@@ -383,6 +383,75 @@ fn engine_preserves_local_media_and_restores_missing_copies() {
fetched.assert();
}
+#[test]
+fn engine_forgets_removed_photos_when_all_local_components_are_missing() {
+ for (live, interrupted) in [(false, false), (true, false), (true, true)] {
+ let mut server = mockito::Server::new();
+ let key = Key::generate();
+ let (file, bytes) = original_fixture(&key, b"original", live, true, 10);
+ let fetched = download(&mut server, 10, &bytes, 1);
+ let mut engine = new_engine(&server, key, file);
+ run(&mut engine, true);
+ let root = engine.root();
+ let db = engine.db();
+ engine.catalog.files.remove(&(1, 10));
+ if interrupted {
+ db.execute_batch("CREATE TRIGGER stop_retention BEFORE UPDATE ON pending WHEN old.album=1 AND old.retained=1 AND json_type(old.action,'$.Move') IS NOT NULL AND new.action='null' BEGIN SELECT RAISE(ABORT,'stop after retention move'); END;").unwrap();
+ run(&mut engine, false);
+ db.execute_batch("DROP TRIGGER stop_retention;").unwrap();
+ }
+ let folder = if interrupted { "Trash/First" } else { "First" };
+ let name = if live { "Motion.heic" } else { "Photo.jpg" };
+ fs::remove_file(root.join(folder).join(name)).unwrap();
+ if live {
+ run(&mut engine, false);
+ assert_eq!(
+ fs::read(root.join("First/Motion.mov")).unwrap(),
+ b"original"
+ );
+ fs::remove_file(root.join("First/Motion.mov")).unwrap();
+ }
+ for _ in 0..2 {
+ run(&mut engine, true);
+ for folder in ["First", "Trash/First"] {
+ for name in ["Photo.jpg", "Motion.heic", "Motion.mov"] {
+ assert!(
+ !root
+ .join(folder)
+ .join("metadata")
+ .join(format!("{name}.json"))
+ .exists()
+ );
+ }
+ }
+ assert_component(&root, "Second", name, b"original");
+ }
+ fetched.assert();
+ }
+}
+
+#[test]
+fn engine_refetches_hashless_originals_after_database_loss() {
+ let mut server = mockito::Server::new();
+ let key = Key::generate();
+ let (old, bytes) = original_fixture(&key, b"old", false, false, 10);
+ let fetched = download(&mut server, 10, &bytes, 1);
+ let mut engine = new_engine(&server, key, old);
+ run(&mut engine, true);
+ fetched.assert();
+ fetched.remove();
+ let (new, bytes) = original_fixture(&engine.catalog.key, b"new", false, false, 30);
+ engine.catalog.files = BTreeMap::from([((1, 10), new.clone()), ((2, 10), new)]);
+ engine.database = "recovered.db".into();
+ let fetched = download(&mut server, 10, &bytes, 1);
+ assert!(engine.run(true, &[]).unwrap().complete);
+ run(&mut engine, true);
+ for folder in ["First", "Second"] {
+ assert_component(&engine.root(), folder, "Photo.jpg", b"new");
+ }
+ fetched.assert();
+}
+
#[test]
fn engine_checks_previous_bytes_before_source_and_layout_replacement() {
for (before_live, after_live, hashed) in [
diff --git a/rust/apps/cli-next/tests/cli/export_sources.rs b/rust/apps/cli-next/tests/cli/export_sources.rs
index 59621e0f10..7ef54408a9 100644
--- a/rust/apps/cli-next/tests/cli/export_sources.rs
+++ b/rust/apps/cli-next/tests/cli/export_sources.rs
@@ -586,39 +586,19 @@ fn export_clears_deleted_adopted_album_rename_reservations() {
fs::create_dir_all(root.join("Trash/First")).unwrap();
let retained_blocker = root.join("Trash/First/notes.txt");
fs::write(&retained_blocker, b"unrelated retention target").unwrap();
- run(&fresh, &root, &["--album", "1"], false);
- let retained = || {
- db.query_row(
- "SELECT name1 FROM pending WHERE owner='retained:1'",
- [],
- |r| r.get::<_, String>(0),
- )
- .unwrap()
- };
- let pending_retention = retained();
- assert!(root.join("First/metadata.json").exists());
- assert_eq!(pending_retention, "First");
- run(&fresh, &root, &["--album", "1"], false);
- assert_eq!(retained(), pending_retention);
- assert!(!root.join("Trash/First-1").exists());
- assert_eq!(
- fs::read(root.join("First/Original.jpg")).unwrap(),
- b"original"
- );
+ run(&fresh, &root, &["--album", "1"], true);
assert_eq!(
fs::read(&retained_blocker).unwrap(),
b"unrelated retention target"
);
assert_eq!(fs::read(&unrelated).unwrap(), b"unrelated rename target");
- fs::remove_file(retained_blocker).unwrap();
- fs::remove_dir(root.join("Trash/First")).unwrap();
run(&fresh, &root, &["--album", "1"], true);
assert_eq!(
- fs::read(root.join("Trash/First/Original.jpg")).unwrap(),
+ fs::read(root.join("Trash/First-1/Original.jpg")).unwrap(),
b"original"
);
assert_eq!(
- read_json(&root.join("Trash/First/metadata/Original.jpg.json"))["ente"]["fileID"],
+ read_json(&root.join("Trash/First-1/metadata/Original.jpg.json"))["ente"]["fileID"],
"10"
);
deletion.remove();
diff --git a/rust/crates/accounts/src/auth/srp.rs b/rust/crates/accounts/src/auth/srp.rs
index abb5429c77..23a9394c0b 100644
--- a/rust/crates/accounts/src/auth/srp.rs
+++ b/rust/crates/accounts/src/auth/srp.rs
@@ -67,6 +67,9 @@ impl SrpSession {
}
pub fn compute_m1(&mut self, server_b: &[u8]) -> Result<Vec<u8>> {
+ if server_b.len() > SRP_N_BYTES {
+ return Err(Error::Srp("Server SRP value is too large".into()));
+ }
let verifier = self
.inner
.process_reply(
@@ -203,6 +206,10 @@ mod tests {
k: None,
};
+ assert!(matches!(
+ session.compute_m1(&[1; SRP_N_BYTES + 1]),
+ Err(Error::Srp(_))
+ ));
let m1 = session.compute_m1(&b_pub).unwrap();
let verifier_client = ClientG4096::<Sha256>::new();
diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rs
index b9928e972b..ca7e6e6974 100644
--- a/rust/crates/accounts/src/client.rs
+++ b/rust/crates/accounts/src/client.rs
@@ -213,7 +213,7 @@ impl AccountsClient {
.error_for_code()
.await
.map_err(|error| match error.status_code() {
- Some(400 | 401) => Error::IncorrectEmailVerificationCode,
+ Some(401) => Error::IncorrectEmailVerificationCode,
Some(410) => Error::EmailVerificationCodeExpired,
Some(429) => Error::EmailVerificationRateLimited,
_ => error.into(),
@@ -417,7 +417,7 @@ impl AccountsClient {
.error_for_code()
.await
.map_err(|error| match error.status_code() {
- Some(400 | 401) => Error::IncorrectTotp,
+ Some(401) => Error::IncorrectTotp,
Some(404 | 410) => Error::SecondFactorSessionExpired,
Some(429) => Error::TotpRateLimited,
_ => error.into(),
diff --git a/rust/crates/accounts/src/login.rs b/rust/crates/accounts/src/login.rs
index bf2671ff34..76e559ebfd 100644
--- a/rust/crates/accounts/src/login.rs
+++ b/rust/crates/accounts/src/login.rs
@@ -64,11 +64,15 @@ impl LoginFlow {
return Err(Error::InvalidInput("Password is not expected".into()));
};
if let Some(response) = response {
+ let attributes = response
+ .key_attributes
+ .as_ref()
+ .ok_or(Error::MissingKeyAttributes)?;
let kek = derive_kek(
password,
- &self.attributes.kek_salt,
- self.attributes.mem_limit,
- self.attributes.ops_limit,
+ &attributes.kek_salt,
+ attributes.mem_limit,
+ attributes.ops_limit,
)?;
let account = build_authenticated_account(response, &kek)?;
self.state = State::Complete;
diff --git a/rust/crates/accounts/src/login/tests.rs b/rust/crates/accounts/src/login/tests.rs
index de98f0ad2c..d0a307887b 100644
--- a/rust/crates/accounts/src/login/tests.rs
+++ b/rust/crates/accounts/src/login/tests.rs
@@ -55,11 +55,13 @@ async fn email_login_retries_password_and_accepts_plain_token_without_recovery_k
let mut attributes = generated.key_attributes;
attributes.recovery_key_encrypted_with_master_key = None;
attributes.recovery_key_decryption_nonce = None;
+ let mut initial_attributes = attributes.clone();
+ initial_attributes.kek_salt = b64::encode(&[1; 16]);
let token = [255; 32];
let mut server = Server::new_async().await;
let (client, mut flow) = start_email_login(
&mut server,
- &attributes,
+ &initial_attributes,
json!({"id": 77, "keyAttributes": attributes, "token": b64::encode_url_safe(&token)}),
)
.await;
@@ -208,6 +210,12 @@ async fn login_retries_email_and_totp() {
let incorrect_email = server
.mock("POST", "/users/verify-email")
.match_body(Matcher::PartialJson(serde_json::json!({"ott": "wrong"})))
+ .with_status(401)
+ .create_async()
+ .await;
+ let invalid_email = server
+ .mock("POST", "/users/verify-email")
+ .match_body(Matcher::PartialJson(json!({"ott": "invalid"})))
.with_status(400)
.create_async()
.await;
@@ -230,7 +238,7 @@ async fn login_retries_email_and_totp() {
let incorrect_totp = server
.mock("POST", "/users/two-factor/verify")
.match_body(Matcher::PartialJson(serde_json::json!({"code": "wrong"})))
- .with_status(400)
+ .with_status(401)
.create_async()
.await;
let verify_totp = server
@@ -259,6 +267,10 @@ async fn login_retries_email_and_totp() {
Err(Error::EmailVerificationCodeExpired)
));
flow.resend_code(&client).await.unwrap();
+ assert!(matches!(
+ flow.submit_code(&client, "invalid").await,
+ Err(Error::Http(error)) if error.status_code() == Some(400)
+ ));
assert!(matches!(
flow.submit_code(&client, "wrong").await,
Err(Error::IncorrectEmailVerificationCode)
@@ -290,6 +302,7 @@ async fn login_retries_email_and_totp() {
ott.assert_async().await;
expired_email.assert_async().await;
incorrect_email.assert_async().await;
+ invalid_email.assert_async().await;
incorrect_totp.assert_async().await;
verify_email.assert_async().await;
verify_totp.assert_async().await;
@@ -301,7 +314,7 @@ async fn totp_errors_are_preserved() {
auth::generate_keys_with_strength("password", KeyDerivationStrength::Interactive)
.unwrap()
.key_attributes;
- for status in [404, 429] {
+ for status in [400, 404, 429] {
let mut server = Server::new_async().await;
let (client, mut flow) = start_email_login(
&mut server,
@@ -319,10 +332,11 @@ async fn totp_errors_are_preserved() {
.create_async()
.await;
let error = flow.submit_code(&client, "654321").await.err().unwrap();
- assert!(matches!(
- (status, error),
- (404, Error::SecondFactorSessionExpired) | (429, Error::TotpRateLimited)
- ));
+ assert!(match (status, error) {
+ (400, Error::Http(error)) => error.status_code() == Some(400),
+ (404, Error::SecondFactorSessionExpired) | (429, Error::TotpRateLimited) => true,
+ _ => false,
+ });
verify.assert_async().await;
}
}
diff --git a/rust/crates/photos-export/src/reconcile.rs b/rust/crates/photos-export/src/reconcile.rs
index 16d2c52877..cb72fac776 100644
--- a/rust/crates/photos-export/src/reconcile.rs
+++ b/rust/crates/photos-export/src/reconcile.rs
@@ -1,4 +1,5 @@
use std::{
+ collections::HashSet,
fs as disk,
fs::{File, OpenOptions},
io::Write,
@@ -464,10 +465,6 @@ impl Run<'_> {
super::Conflict(format!("at {}: moved bytes differ", to.display()))
);
} else {
- ensure!(
- !target.retained || current_media,
- "retained original is missing at both move endpoints"
- );
return self.clear_action(target);
}
let store = store::lock(self.store)?;
@@ -791,13 +788,24 @@ impl Run<'_> {
fn album_target(&self, album: i64, name: &str, retained: bool) -> Result<Pending> {
let store = store::lock(self.store)?;
let existing = store.album(album, retained)?;
+ let mut occupied = HashSet::new();
+ if retained && existing.is_none() {
+ let trash = names::check(self.root, "Trash")?;
+ if directory_exists(&trash)? {
+ for entry in disk::read_dir(trash)? {
+ occupied.insert(names::folded(&entry?.file_name().to_string_lossy()));
+ }
+ }
+ }
let owner = existing
.as_ref()
.map(|album| album.key.clone())
.unwrap_or_else(|| format!("{}:{album}", if retained { "retained" } else { "active" }));
if let Some(pending) = store.pending(&owner)? {
ensure!(pending.action.is_none(), "album has unfinished action");
- if pending.name == name || retained {
+ if (pending.name == name || retained)
+ && !occupied.contains(&names::folded(&pending.names[0]))
+ {
return Ok(pending);
}
}
@@ -810,6 +818,17 @@ impl Run<'_> {
&& names::available(&store, parent, &[name.to_owned()], &owner, "album")?
{
vec![name.to_owned()]
+ } else if !occupied.is_empty() {
+ let mut suffix = 0;
+ loop {
+ if let Some(candidates) = names::candidates(name, true, None, suffix)?
+ && !occupied.contains(&names::folded(&candidates[0]))
+ && names::available(&store, parent, &candidates, &owner, "album")?
+ {
+ break candidates;
+ }
+ suffix += 1;
+ }
} else {
names::allocate(&store, parent, name, "album", None, &owner)?
};
@@ -1481,6 +1500,45 @@ impl Run<'_> {
|r| r.get(0),
)?;
let components = store::lock(self.store)?.components(&target.owner)?;
+ if !restoring {
+ let mut present = false;
+ for component in &components {
+ present |= Properties::optional(&self.path(&component.location)?)?.is_some();
+ }
+ if !present {
+ for component in &components {
+ let record = store::lock(self.store)?
+ .json_record(&target.owner, Some(&component.role))?;
+ if let Some(record) = record
+ && let Some(location) = record.location
+ {
+ self.start(
+ target,
+ Action::Remove {
+ location,
+ role: Some(component.role.clone()),
+ },
+ &[],
+ )?;
+ self.finish_action(target, false, None)?;
+ }
+ }
+ let store = store::lock(self.store)?;
+ let transaction = store.db.unchecked_transaction()?;
+ store
+ .db
+ .execute("DELETE FROM components WHERE placement=?1", [&target.owner])?;
+ store
+ .db
+ .execute("DELETE FROM json_records WHERE owner=?1", [&target.owner])?;
+ store
+ .db
+ .execute("DELETE FROM placements WHERE id=?1", [&target.owner])?;
+ store.clear_pending(&target.owner)?;
+ transaction.commit()?;
+ return Ok(());
+ }
+ }
for component in &components {
let name = target_component(target, &component.role)?;
let location = Location {
diff --git a/rust/crates/photos-export/src/transfer.rs b/rust/crates/photos-export/src/transfer.rs
index fba537d72b..e0f0c36f94 100644
--- a/rust/crates/photos-export/src/transfer.rs
+++ b/rust/crates/photos-export/src/transfer.rs
@@ -85,7 +85,7 @@ fn source_changed(component: &Component, file: &FileSnapshot, signature: &str) -
&& component
.signature
.as_ref()
- .is_some_and(|original| original != signature))
+ .is_none_or(|original| original != signature))
}
fn verify(
@@ -208,14 +208,8 @@ pub async fn prepare(run: &Run<'_>, session: &Session, file: &FileSnapshot) -> R
before = rowid;
let components = store::lock(run.store)?.components(&id)?;
for component in components {
- if !roles.contains(&component.role)
+ if source_changed(&component, file, &signature)
|| reusable.iter().any(|source| source.role == component.role)
- || expected_hash(file, &component.role).is_some_and(|hash| hash != component.hash)
- || (expected_hash(file, &component.role).is_none()
- && component
- .signature
- .as_ref()
- .is_some_and(|original| original != &signature))
{
continue;
}