π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix Photos export recovery and storage lifetime
Manav Rathi90206dba6b50
diff --git a/rust/apps/cli-next/src/export/mod.rs b/rust/apps/cli-next/src/export/mod.rsindex 4c3c767941..b38dd62f0b 100644--- a/rust/apps/cli-next/src/export/mod.rs+++ b/rust/apps/cli-next/src/export/mod.rs@@ -40,6 +40,8 @@ async fn run_locked(args: ExportArgs, selected: Option<&str>, as_json: bool) ->let index = state.resolve(selected)?;let account = state.accounts.swap_remove(index);let session = api::session(&account, Product::Photos)?;+ // Declare first so export's stores drop before this lock.+ let _storage_use;let mut export = Export::open(&args.destination,&session.master_key,@@ -58,6 +60,7 @@ async fn run_locked(args: ExportArgs, selected: Option<&str>, as_json: bool) ->.context("account was removed while waiting for access")?;let session = api::session(&account, Product::Photos)?;export.verify_source(&session.master_key)?;+ _storage_use = account_home.storage_use()?;home::create(&account_home.path)?;let db_path = store_path(&account_home.path, export.destination())?;ensure!(diff --git a/rust/apps/cli-next/src/home.rs b/rust/apps/cli-next/src/home.rsindex b2815f9256..3c267dcf5a 100644--- a/rust/apps/cli-next/src/home.rs+++ b/rust/apps/cli-next/src/home.rs@@ -5,7 +5,7 @@ use std::{path::{Path, PathBuf},};-use anyhow::{Context, Result, ensure};+use anyhow::{Context, Result, bail, ensure};use uuid::Uuid;pub struct AccountHome {@@ -13,6 +13,11 @@ pub struct AccountHome {_lock: File,}+pub struct RemovalGuard {+ _lock: File,+ home: AccountHome,+}+pub fn application_home() -> Result<PathBuf> {if let Some(home) = env::var_os("ENTE_CLI_HOME") {ensure!(!home.is_empty(), "ENTE_CLI_HOME cannot be empty");@@ -38,6 +43,18 @@ pub fn create(path: &Path) -> io::Result<()> {}pub fn lock_account(id: Uuid, create: bool) -> Result<AccountHome> {+ let home = account_home(id, create)?;+ home._lock.lock().context("cannot lock the account home")?;+ Ok(home)+}++pub fn try_lock_account(id: Uuid) -> Result<AccountHome> {+ let home = account_home(id, true)?;+ try_lock(&home._lock)?;+ Ok(home)+}++fn account_home(id: Uuid, create: bool) -> Result<AccountHome> {let accounts = application_home()?.join("accounts");let path = accounts.join(id.to_string());let lock_path = accounts.join(format!("{id}.lock"));@@ -46,33 +63,65 @@ pub fn lock_account(id: Uuid, create: bool) -> Result<AccountHome> {} else {ensure!(path.is_dir(), "no local data; run the command online first");}- let mut options = OpenOptions::new();- options.read(true).write(true).create(true);- #[cfg(unix)]- {- use std::os::unix::fs::OpenOptionsExt;- options.mode(0o600);- }- let lock = options- .open(lock_path)- .context("cannot open the account lock")?;- lock.lock().context("cannot lock the account home")?;+ let lock = open_lock(&lock_path).context("cannot open the account lock")?;Ok(AccountHome { path, _lock: lock })}impl AccountHome {+ pub fn storage_use(&self) -> Result<File> {+ let lock = open_lock(&self.path.with_extension("use.lock"))+ .context("cannot open the account use lock")?;+ lock.lock_shared().context("cannot lock account storage")?;+ Ok(lock)+ }++ pub fn for_removal(self) -> Result<RemovalGuard> {+ let lock = open_lock(&self.path.with_extension("use.lock"))+ .context("cannot open the account use lock")?;+ try_lock(&lock)?;+ Ok(RemovalGuard {+ _lock: lock,+ home: self,+ })+ }+}++impl RemovalGuard {pub fn remove(self) -> Result<()> {- if let Err(error) = fs::remove_dir_all(&self.path)+ if let Err(error) = fs::remove_dir_all(&self.home.path)&& error.kind() != io::ErrorKind::NotFound{return Err(error.into());}// The vault must exclude this account before its lock is unlinked.- if let Err(error) = fs::remove_file(self.path.with_extension("lock"))- && error.kind() != io::ErrorKind::NotFound- {- return Err(error.into());+ for extension in ["use.lock", "lock"] {+ if let Err(error) = fs::remove_file(self.home.path.with_extension(extension))+ && error.kind() != io::ErrorKind::NotFound+ {+ return Err(error.into());+ }}Ok(())}}++fn try_lock(lock: &File) -> Result<()> {+ match lock.try_lock() {+ Ok(()) => Ok(()),+ Err(fs::TryLockError::WouldBlock) => {+ bail!("account is in use; finish or cancel active commands before logging out")+ }+ Err(fs::TryLockError::Error(error)) => Err(error).context("cannot lock the account"),+ }+}++fn open_lock(path: &Path) -> io::Result<File> {+ let mut options = OpenOptions::new();+ options.read(true).write(true).create(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options.mode(0o600);+ }+ options.open(path)+}diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rsindex e6df40e49b..e333942cc0 100644--- a/rust/apps/cli-next/src/main.rs+++ b/rust/apps/cli-next/src/main.rs@@ -118,8 +118,14 @@ async fn session(SessionCommand::Logout => {let mut vault = Vault::open()?;let index = vault.state.resolve(selected)?;- let home = home::lock_account(vault.state.accounts[index].storage_id, true)?;+ let home = home::try_lock_account(vault.state.accounts[index].storage_id)?;let name = vault.state.accounts[index].name.clone();+ let sessions = &vault.state.accounts[index].sessions;+ let removal = if sessions.len() == 1 && sessions.contains_key(&product) {+ Some(home.for_removal()?)+ } else {+ None+ };api::logout(&vault.state.accounts[index], product).await?;vault.state.accounts[index].sessions.remove(&product);let removed = vault.state.accounts[index].sessions.is_empty();@@ -127,8 +133,8 @@ async fn session(remove_account(&mut vault.state, index);}vault.save()?;- if removed {- home.remove()?;+ if let Some(removal) = removal {+ removal.remove()?;}drop(vault);output::action(@@ -193,7 +199,8 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<();let mut vault = Vault::open()?;let index = vault.state.named(&name)?;- let home = home::lock_account(vault.state.accounts[index].storage_id, true)?;+ let home =+ home::try_lock_account(vault.state.accounts[index].storage_id)?.for_removal()?;let products = vault.state.accounts[index].sessions.keys()diff --git a/rust/apps/cli-next/src/photos.rs b/rust/apps/cli-next/src/photos.rsindex 201e9fbaad..30c20407c7 100644--- a/rust/apps/cli-next/src/photos.rs+++ b/rust/apps/cli-next/src/photos.rs@@ -41,6 +41,7 @@ pub async fn run(let mut replica = Replica::new(&mut db, session.user_id);if !options.offline {replica.sync_collections(&session).await?;+ replica.retry_failed_albums(&session)?;} else {ensure!(replica.collections_cursor()?.is_some(),@@ -58,25 +59,37 @@ pub async fn run(fn album(command: AlbumCommand, replica: &Replica<'_>, options: &Options) -> Result<()> {match command {- AlbumCommand::List(args) => replica.collections(- None,- args.limit().map(|limit| i64::from(limit) + 1),- |rows| {- output::albums(- rows.map(|album| AlbumView::try_from(album?)),- &args,- options.json,- )- },- ),+ AlbumCommand::List(args) => replica.collections(None, None, |rows| {+ let mut incomplete = false;+ let albums = rows.filter_map(|row| {+ let entry = match row {+ Ok(entry) => entry,+ Err(error) => return Some(Err(error.into())),+ };+ match entry.value.and_then(AlbumView::try_from) {+ Ok(album) => Some(Ok(album)),+ Err(error) => {+ eprintln!("album {}: {error:#}", entry.id);+ incomplete = true;+ None+ }+ }+ });+ output::albums(albums, &args, options.json)?;+ ensure!(!incomplete, "album list is incomplete");+ Ok(())+ }),AlbumCommand::View { album } => {let album =replica.collections(Some(&album), Some((MAX_CANDIDATES + 1) as i64), |rows| {select(rows.map(|album| Ok(album?)), &album, "album", |a| {- (a.id, &a.name)+ (a.id, a.name.as_deref().unwrap_or("unavailable"))})})?;- let album = AlbumView::try_from(album)?;+ let album = album+ .value+ .and_then(AlbumView::try_from)+ .with_context(|| format!("album {}", album.id))?;if options.json {output::json(&album)} else {@@ -93,17 +106,29 @@ async fn file(replica: &mut Replica<'_>,options: &Options,) -> Result<()> {+ let mut incomplete = false;let albums =replica.collections(album, album.map(|_| (MAX_CANDIDATES + 1) as i64), |rows| {if let Some(selector) = album {- Ok(vec![select(- rows.map(|album| Ok(album?)),- selector,- "album",- |a| (a.id, &a.name),- )?])+ let entry = select(rows.map(|album| Ok(album?)), selector, "album", |a| {+ (a.id, a.name.as_deref().unwrap_or("unavailable"))+ })?;+ Ok(vec![+ entry.value.with_context(|| format!("album {}", entry.id))?,+ ])} else {- rows.map(|album| Ok(album?)).collect::<Result<Vec<_>>>()+ let mut albums = Vec::new();+ for row in rows {+ let entry = row?;+ match entry.value {+ Ok(album) => albums.push(album),+ Err(error) => {+ eprintln!("album {}: {error:#}", entry.id);+ incomplete = true;+ }+ }+ }+ Ok(albums)}})?;if options.offline {@@ -119,36 +144,44 @@ async fn file(}let album_id = album.map(|_| albums[0].id);let find = |selector: &str| {- replica.files(+ let entry = replica.files(album_id,Some(selector),Some((MAX_CANDIDATES + 1) as i64),|rows| {select(rows.map(|entry| Ok(entry?)), selector, "file", |e| {- (e.file.id, &e.file.name)+ (e.id, e.name.as_deref().unwrap_or("unavailable"))})},- )+ )?;+ let file = entry.file.with_context(|| format!("file {}", entry.id))?;+ Ok::<_, anyhow::Error>((file, entry.album_ids))};match command {- FileCommand::List(args) => replica.files(- album_id,- None,- args.limit().map(|limit| i64::from(limit) + 1),- |rows| {- output::files(- rows.map(|entry| {- let entry = entry?;- FileView::new(entry.file, &entry.album_ids)- }),- &args,- options.json,- )- },- ),+ FileCommand::List(args) => replica.files(album_id, None, None, |rows| {+ let files = rows.filter_map(|row| {+ let entry = match row {+ Ok(entry) => entry,+ Err(error) => return Some(Err(error.into())),+ };+ match entry+ .file+ .and_then(|file| FileView::new(file, &entry.album_ids))+ {+ Ok(file) => Some(Ok(file)),+ Err(error) => {+ eprintln!("file {}: {error:#}", entry.id);+ incomplete = true;+ None+ }+ }+ });+ output::files(files, &args, options.json)+ }),FileCommand::View { file } => {- let entry = find(&file)?;- let view = FileView::new(entry.file, &entry.album_ids)?;+ let (file, album_ids) = find(&file)?;+ let id = file.id;+ let view = FileView::new(file, &album_ids).with_context(|| format!("file {id}"))?;if options.json {output::json(&view)} else {@@ -156,24 +189,22 @@ async fn file(}}FileCommand::Download { file, output } => {- let entry = find(&file)?;+ ensure!(+ !incomplete,+ "album lookup is incomplete; select an available album with --album before downloading"+ );+ let (file, _) = find(&file)?;let parent = output.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));let mut temporary = tempfile::NamedTempFile::new_in(parent)?;- files::download(- session,- entry.file.id,- &entry.file.key,- &entry.file.header,- || {- let file = temporary.as_file_mut();- file.set_len(0)?;- file.rewind()?;- file.try_clone()- },- )+ files::download(session, file.id, &file.key, &file.header, || {+ let file = temporary.as_file_mut();+ file.set_len(0)?;+ file.rewind()?;+ file.try_clone()+ }).await?;temporary.as_file().sync_all()?;let bytes = temporary.as_file().metadata()?.len();@@ -183,11 +214,13 @@ async fn file(.with_context(|| format!("cannot save download to {}", output.display()))?;output::action(options.json,- &json!({ "id": entry.file.id.to_string(), "output": output, "bytes": bytes }),- &format!("Downloaded {:?} to {}.", entry.file.name, output.display()),+ &json!({ "id": file.id.to_string(), "output": output.to_string_lossy(), "bytes": bytes }),+ &format!("Downloaded {:?} to {}.", file.name, output.display()),)}- }+ }?;+ ensure!(!incomplete, "file results are incomplete");+ Ok(())}fn open_account(selected: Option<&str>, create: bool) -> Result<(Account, home::AccountHome)> {@@ -199,7 +232,7 @@ fn open_account(selected: Option<&str>, create: bool) -> Result<(Account, home::.into_iter().find(|account| account.storage_id == id)else {- home.remove()?;+ home.for_removal()?.remove()?;bail!("account was removed while waiting for access");};if create {diff --git a/rust/apps/cli-next/src/replica.rs b/rust/apps/cli-next/src/replica.rsindex 49705e857e..2d2540a8c7 100644--- a/rust/apps/cli-next/src/replica.rs+++ b/rust/apps/cli-next/src/replica.rs@@ -27,7 +27,7 @@ pub const SCHEMA: &str = "CREATE TABLE photos_files (collection_id INTEGER NOT NULL REFERENCES photos_collections(id) ON DELETE CASCADE,id INTEGER NOT NULL, name TEXT, updated_at INTEGER NOT NULL,- record TEXT NOT NULL, decrypt_failed INTEGER NOT NULL,+ record TEXT NOT NULL, failed INTEGER NOT NULL,PRIMARY KEY(collection_id,id));CREATE INDEX photos_files_id ON photos_files(id,updated_at DESC);@@ -190,8 +190,16 @@ impl FileRecord {}}+pub struct AlbumEntry {+ pub id: i64,+ pub name: Option<String>,+ pub value: Result<Collection>,+}+pub struct Entry {- pub file: File,+ pub id: i64,+ pub name: Option<String>,+ pub file: Result<File>,pub album_ids: Vec<i64>,}@@ -249,11 +257,28 @@ impl<'a> Replica<'a> {Ok(())}+ pub fn retry_failed_albums(&mut self, session: &Session) -> Result<()> {+ let mut after = 0;+ loop {+ let ids: Vec<i64> = self.db.read(|db| {+ let mut query = db.prepare("SELECT id FROM photos_collections WHERE id>?1 AND json_extract(record,'$.failure') IS NOT NULL ORDER BY id LIMIT 128")?;+ Ok(query.query_map([after], |row| row.get(0))?.collect::<SqliteResult<_>>()?)+ })?;+ if ids.is_empty() {+ return Ok(());+ }+ for id in ids {+ after = id;+ self.retry_album(session, id)?;+ }+ }+ }+pub fn retry_album(&mut self, session: &Session, id: i64) -> Result<()> {let Some(previous) = self.album_record(id)? else {return Ok(());};- if previous.documents.is_some() {+ if previous.documents.is_some() && previous.failure.is_none() {return Ok(());}let parent_key = if previous.remote.owner.id == session.user_id {@@ -337,7 +362,7 @@ impl<'a> Replica<'a> {let mut after = 0;loop {let records: Vec<FileRecord> = self.db.read(|db| {- let mut query = db.prepare("SELECT record FROM photos_files WHERE collection_id=?1 AND decrypt_failed=1 AND id>?2 ORDER BY id LIMIT 128")?;+ let mut query = db.prepare("SELECT record FROM photos_files WHERE collection_id=?1 AND failed=1 AND id>?2 ORDER BY id LIMIT 128")?;Ok(query.query_map(params![album.id,after], |r| read_json(r,0))?.collect::<SqliteResult<_>>()?)})?;if records.is_empty() {@@ -387,9 +412,9 @@ impl<'a> Replica<'a> {&self,selector: Option<&str>,limit: Option<i64>,- read: impl FnOnce(&mut dyn Iterator<Item = SqliteResult<Collection>>) -> Result<T>,+ read: impl FnOnce(&mut dyn Iterator<Item = SqliteResult<AlbumEntry>>) -> Result<T>,) -> Result<T> {- let mut sql = "SELECT record FROM photos_collections".to_owned();+ let mut sql = "SELECT record,name FROM photos_collections".to_owned();let mut parameters = Vec::new();if let Some(selector) = selector {sql.push_str(" WHERE id=? OR name=?");@@ -404,7 +429,11 @@ impl<'a> Replica<'a> {let mut statement = db.prepare(&sql)?;let mut rows = statement.query_map(params_from_iter(parameters), |row| {let record: AlbumRecord = read_json(row, 0)?;- record.album(self.user_id).map_err(conversion)+ Ok(AlbumEntry {+ id: record.remote.id,+ name: row.get(1)?,+ value: record.album(self.user_id),+ })})?;Ok(read(&mut rows))})?@@ -417,22 +446,23 @@ impl<'a> Replica<'a> {limit: Option<i64>,read: impl FnOnce(&mut dyn Iterator<Item = SqliteResult<Entry>>) -> Result<T>,) -> Result<T> {- let mut conditions = Vec::new();+ let mut sql = "SELECT record,(SELECT json_group_array(collection_id ORDER BY collection_id) FROM photos_files m WHERE m.id=f.id".to_owned();let mut parameters = Vec::new();if let Some(album) = album {- conditions.push("collection_id=?");+ sql.push_str(" AND m.collection_id=?1");parameters.push(Value::Integer(album));}+ sql.push_str("),name FROM photos_files f WHERE ");+ if album.is_some() {+ sql.push_str("collection_id=?1");+ } else {+ sql.push_str("NOT EXISTS (SELECT 1 FROM photos_files newer WHERE newer.id=f.id AND (newer.updated_at>f.updated_at OR (newer.updated_at=f.updated_at AND newer.collection_id<f.collection_id)))");+ }if let Some(selector) = selector {- conditions.push("(id=? OR name=?)");+ sql.push_str(" AND (id=? OR name=?)");parameters.extend([canonical_id(selector), Value::Text(selector.into())]);}- let mut sql = "WITH matched AS (SELECT * FROM photos_files".to_owned();- if !conditions.is_empty() {- sql.push_str(" WHERE ");- sql.push_str(&conditions.join(" AND "));- }- sql.push_str(") SELECT record,(SELECT json_group_array(collection_id ORDER BY collection_id) FROM matched m WHERE m.id=f.id) FROM (SELECT *,row_number() OVER(PARTITION BY id ORDER BY updated_at DESC,collection_id) AS rank FROM matched) f WHERE rank=1 ORDER BY id");+ sql.push_str(" ORDER BY id");if let Some(limit) = limit {sql.push_str(" LIMIT ?");parameters.push(Value::Integer(limit));@@ -442,7 +472,9 @@ impl<'a> Replica<'a> {let mut rows = statement.query_map(params_from_iter(parameters), |row| {let record: FileRecord = read_json(row, 0)?;Ok(Entry {- file: record.file(self.user_id).map_err(conversion)?,+ id: record.remote.id,+ name: row.get(2)?,+ file: record.file(self.user_id),album_ids: read_json(row, 1)?,})})?;@@ -488,7 +520,7 @@ fn save_album(};let json = encode(&record)?;tx.execute(- "INSERT INTO photos_collections(id,name,updated_at,record) VALUES(?1,?2,?3,?4) ON CONFLICT(id) DO UPDATE SET name=coalesce(excluded.name,photos_collections.name),updated_at=excluded.updated_at,record=excluded.record",+ "INSERT INTO photos_collections(id,name,updated_at,record) VALUES(?1,?2,?3,?4) ON CONFLICT(id) DO UPDATE SET name=coalesce(excluded.name,photos_collections.name),updated_at=excluded.updated_at,record=excluded.record WHERE excluded.record!=photos_collections.record OR coalesce(excluded.name,photos_collections.name) IS NOT photos_collections.name",params![record.remote.id, name, record.remote.updation_time, json],)?;Ok(())@@ -512,14 +544,14 @@ fn save_file(};let json = encode(&record)?;tx.execute(- "INSERT INTO photos_files VALUES(?1,?2,?3,?4,?5,?6) ON CONFLICT(collection_id,id) DO UPDATE SET name=coalesce(excluded.name,photos_files.name),updated_at=excluded.updated_at,record=excluded.record,decrypt_failed=excluded.decrypt_failed WHERE excluded.updated_at>=photos_files.updated_at",+ "INSERT INTO photos_files VALUES(?1,?2,?3,?4,?5,?6) ON CONFLICT(collection_id,id) DO UPDATE SET name=coalesce(excluded.name,photos_files.name),updated_at=excluded.updated_at,record=excluded.record,failed=excluded.failed WHERE excluded.updated_at>=photos_files.updated_at AND (excluded.record!=photos_files.record OR coalesce(excluded.name,photos_files.name) IS NOT photos_files.name OR excluded.failed!=photos_files.failed)",params![album,record.remote.id,name,record.remote.updation_time,json,- record.documents.is_none()+ record.failure.is_some()],)?;Ok(())@@ -535,10 +567,6 @@ pub fn read_json<T: DeserializeOwned>(row: &Row<'_>, column: usize) -> SqliteRes.map_err(|e| SqliteError::FromSqlConversionFailure(column, Type::Text, Box::new(e)))}-fn conversion(error: anyhow::Error) -> SqliteError {- SqliteError::FromSqlConversionFailure(0, Type::Text, error.into_boxed_dyn_error())-}-pub fn canonical_id(selector: &str) -> Value {selector.parse::<i64>()diff --git a/rust/apps/cli-next/tests/support/export.rs b/rust/apps/cli-next/tests/support/export.rsindex b85d1db778..f5264ddb83 100644--- a/rust/apps/cli-next/tests/support/export.rs+++ b/rust/apps/cli-next/tests/support/export.rs@@ -1103,13 +1103,26 @@ fn export_rejects_invalid_live_archives_and_component_hashes() -> TestResult {}archives.push(zip.finish()?.into_inner());}+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));+ for name in ["image.jpg", "video.mov"] {+ zip.start_file(+ name,+ zip::write::SimpleFileOptions::default()+ .compression_method(zip::CompressionMethod::Deflated),+ )?;+ std::io::copy(+ &mut std::io::Read::take(std::io::repeat(0), 9 * 1024 * 1024),+ &mut zip,+ )?;+ }+ archives.push(zip.finish()?.into_inner());for (index, archive) in archives.iter().enumerate() {let mut data = metadata(&format!("Invalid-{index}.jpg"), archive);data["fileType"] = json!(2);data["hash"] = json!(format!("{}:{}",digest(b"component"),- digest(if index + 1 == archives.len() {+ digest(if index == 5 {b"wrong video"} else {b"component"@@ -1129,13 +1142,17 @@ fn export_rejects_invalid_live_archives_and_component_hashes() -> TestResult {let destination = tempfile::tempdir()?;let root = destination.path().join("export");let output = home.run(&["photos", "export", root.to_str().unwrap(), "--json"]);- failure(&output);+ let error = failure(&output);+ assert!(+ error.contains("Live Photo archive expands beyond limit"),+ "{error}"+ );let result: Value = serde_json::from_slice(&output.stdout)?;assert_eq!(result["copies"],- json!({"expected":7,"completed":1,"pending":6})+ json!({"expected":8,"completed":1,"pending":7}));- assert_eq!(result["failures"], 6);+ assert_eq!(result["failures"], 7);assert_eq!(fs::read(root.join("Album/Good.jpg"))?, b"independent");assert_eq!(fs::read_dir(root.join("Album/metadata"))?.count(), 1);for index in 0..archives.len() {diff --git a/rust/apps/cli-next/tests/support/export_maintenance.rs b/rust/apps/cli-next/tests/support/export_maintenance.rsindex b818ee1c73..2a7f25c6ee 100644--- a/rust/apps/cli-next/tests/support/export_maintenance.rs+++ b/rust/apps/cli-next/tests/support/export_maintenance.rs@@ -46,6 +46,239 @@ fn count(db: &rusqlite::Connection, sql: &str) -> i64 {db.query_row(sql, [], |r| r.get(0)).unwrap()}+#[test]+#[cfg(target_os = "linux")]+fn export_and_download_preserve_non_utf8_paths() {+ use std::os::unix::ffi::OsStringExt;++ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let key = Key::generate();+ listing(&mut server, json!([collection(1, "First", &key)]));+ let (file, bytes) = source(10, &key, b"original", "Photo.jpg");+ page(&mut server, 1, 0, json!([file]), false).create();+ let fetched = download(&mut server, 10, &bytes, 2);+ let directory = tempfile::tempdir().unwrap();+ let root = directory+ .path()+ .join(std::ffi::OsString::from_vec(b"photos-\xff".to_vec()));+ for exported in [1, 0] {+ let output = success(+ home.command(&["photos", "export", "--json"])+ .arg(&root)+ .output()+ .unwrap(),+ );+ let result: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(result["complete"], true);+ assert_eq!(result["changes"]["exported"], exported);+ assert_eq!(+ result["destination"],+ fs::canonicalize(&root).unwrap().to_string_lossy().as_ref()+ );+ assert_component(&root, "First", "Photo.jpg", b"original");+ }+ let path = root.join("download.jpg");+ let output = success(+ home.command(&["photos", "file", "download", "10", "--json", "--output"])+ .arg(&path)+ .output()+ .unwrap(),+ );+ let result: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(result["output"], path.to_string_lossy().as_ref());+ assert_eq!(fs::read(path).unwrap(), b"original");+ fetched.assert();+}++#[test]+fn file_name_lookup_uses_latest_scoped_metadata_and_all_memberships() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let key = Key::generate();+ let albums = listing(+ &mut server,+ json!([collection(1, "First", &key), collection(2, "Second", &key)]),+ );+ let (old, _) = source(10, &key, b"original", "Old.jpg");+ for album in [1, 2] {+ page(&mut server, album, 0, json!([old]), false).create();+ }+ assert_eq!(+ home.json(&["photos", "file", "list"])[0]["albumIds"],+ json!(["1", "2"])+ );+ albums.remove();+ listing(+ &mut server,+ json!([+ revision(collection(1, "First", &key), 40),+ revision(collection(2, "Second", &key), 40)+ ]),+ );+ let (new, _) = source(10, &key, b"original", "New.jpg");+ let changed = page(&mut server, 1, 10, json!([revision(new, 30)]), false)+ .expect(1)+ .create();+ let failed = page(&mut server, 2, 10, json!([]), false)+ .with_status(400)+ .expect(1)+ .create();+ failure(&home.run(&["photos", "file", "list"]));+ let by_id = home.json(&["photos", "file", "view", "10", "--offline"]);+ assert_eq!(by_id["name"], "New.jpg");+ assert_eq!(by_id["albumIds"], json!(["1", "2"]));+ assert_eq!(+ home.json(&["photos", "file", "view", "New.jpg", "--offline"]),+ by_id+ );+ assert!(+ failure(&home.run(&["photos", "file", "view", "Old.jpg", "--offline"]))+ .contains("no file matches")+ );+ for (album, name, id) in [("First", "New.jpg", "1"), ("Second", "Old.jpg", "2")] {+ let scoped = home.json(&[+ "photos",+ "file",+ "view",+ name,+ "--album",+ album,+ "--offline",+ ]);+ assert_eq!(scoped["name"], name);+ assert_eq!(scoped["albumIds"], json!([id]));+ }+ changed.assert();+ failed.assert();+ failed.remove();+ let (numeric, _) = source(11, &key, b"other", "10");+ page(+ &mut server,+ 2,+ 10,+ json!([revision(old, 30), revision(numeric, 30)]),+ false,+ )+ .create();+ assert_eq!(home.json(&["photos", "file", "view", "New.jpg"]), by_id);+ assert!(+ failure(&home.run(&["photos", "file", "view", "Old.jpg", "--offline"]))+ .contains("no file matches")+ );+ let error = failure(&home.run(&["photos", "file", "view", "10", "--offline"]));+ assert!(error.contains("is ambiguous"));+ assert!(error.contains("10 \"New.jpg\""));+ assert!(error.contains("11 \"10\""));+}++#[test]+fn failed_catalog_records_do_not_hide_healthy_results() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let key = Key::generate();+ let mut album = collection(1, "Unavailable", &key);+ album["encryptedKey"] = json!("invalid");+ listing(+ &mut server,+ json!([+ album,+ collection(2, "Healthy", &key),+ collection(3, "Other", &key)+ ]),+ );+ let (old, _) = source(10, &key, b"old", "Old.jpg");+ let bad = public(old.clone(), &key, json!({"editedName": 42}), 20);+ let (good, bytes) = source(11, &key, b"good", "Good.jpg");+ page(&mut server, 2, 0, json!([bad, good]), false)+ .expect(1)+ .create();+ page(&mut server, 3, 0, json!([old]), false)+ .expect(1)+ .create();+ let output = home.run(&["photos", "file", "list", "--limit", "1", "--json"]);+ let error = failure(&output);+ assert!(error.contains("album 1:"), "{error}");+ assert!(+ error.contains("file 10: invalid public file metadata"),+ "{error}"+ );+ let rows: Vec<Value> = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0]["id"], "11");+ let db = database(&home);+ assert_eq!(+ count(+ &db,+ "SELECT count(*) FROM photos_files WHERE collection_id=2 AND id=10 AND failed=1"+ ),+ 1+ );+ db.execute_batch("CREATE TRIGGER no_file_rewrite AFTER UPDATE ON photos_files BEGIN SELECT RAISE(ABORT,'file rewritten'); END; CREATE TRIGGER no_album_rewrite AFTER UPDATE OF record,name ON photos_collections BEGIN SELECT RAISE(ABORT,'album rewritten'); END;").unwrap();+ let output = home.run(&["photos", "album", "list", "--limit", "1", "--json"]);+ assert!(failure(&output).contains("album 1:"));+ let rows: Vec<Value> = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0]["id"], "2");+ let output = home.run(&["photos", "file", "list", "--all", "--offline", "--json"]);+ assert!(failure(&output).contains("file 10:"));+ assert_eq!(+ serde_json::from_slice::<Vec<Value>>(&output.stdout)+ .unwrap()+ .len(),+ 1+ );+ assert!(+ failure(&home.run(&["photos", "album", "view", "1", "--offline"])).contains("album 1:")+ );+ assert!(+ failure(&home.run(&["photos", "file", "view", "10", "--offline"])).contains("file 10:")+ );+ assert!(+ failure(&home.run(&["photos", "file", "view", "Old.jpg", "--offline"]))+ .contains("no file matches")+ );+ let output = success(home.run(&["photos", "file", "view", "11", "--album", "2", "--json"]));+ assert!(output.stderr.is_empty());+ assert_eq!(+ serde_json::from_slice::<Value>(&output.stdout).unwrap()["id"],+ "11"+ );+ let path = home.dir.path().join("download.jpg");+ let downloaded = download(&mut server, 11, &bytes, 1);+ assert!(+ failure(&home.run(&[+ "photos",+ "file",+ "download",+ "11",+ "--output",+ path.to_str().unwrap()+ ]))+ .contains("album lookup is incomplete")+ );+ assert!(!path.exists());+ success(home.run(&[+ "photos",+ "file",+ "download",+ "11",+ "--album",+ "2",+ "--output",+ path.to_str().unwrap(),+ ]));+ assert_eq!(fs::read(path).unwrap(), b"good");+ downloaded.assert();+ db.execute_batch("DROP TRIGGER no_file_rewrite; UPDATE photos_files SET record='{' WHERE collection_id=2 AND id=10;").unwrap();+ let error = failure(&home.run(&["photos", "file", "list", "--offline", "--all", "--json"]));+ assert!(error.contains("EOF while parsing"), "{error}");+ assert!(!error.contains("file results are incomplete"));+}+#[test]fn export_retries_transient_collection_and_file_refresh_failures() {for route in ["/collections/v2", "/collections/v2/diff"] {@@ -2049,19 +2282,34 @@ fn export_automatically_retries_saved_selected_album_and_file_failures() {"saved failure");db.execute(- "INSERT INTO photos_files SELECT 1,id,name,updated_at,record,decrypt_failed FROM photos_files WHERE collection_id=3 AND id=10",+ "INSERT INTO photos_files SELECT 1,id,name,updated_at,record,failed FROM photos_files WHERE collection_id=3 AND id=10",[],).unwrap();db.execute(- "UPDATE photos_files SET record=json_set(record,'$.documents',NULL,'$.key',NULL,'$.failure','saved failure'),decrypt_failed=1 WHERE id=10",+ "UPDATE photos_files SET record=json_set(record,'$.documents',NULL,'$.key',NULL,'$.failure','saved failure'),failed=1 WHERE id=10",[],).unwrap();run(&home, &root, &["--album", "1", "--album", "3"], true);for album in [1, 3] {assert!(record(&db, album, 10)["documents"].is_object());+ assert!(record(&db, album, 10)["failure"].is_null());}+ assert_eq!(+ count(+ &db,+ "SELECT count(*) FROM photos_files WHERE id=10 AND name='Photo.jpg' AND failed=0"+ ),+ 2+ );+ assert_eq!(+ count(+ &db,+ "SELECT count(*) FROM photos_collections WHERE id=1 AND name='First' AND json_extract(record,'$.failure') IS NULL"+ ),+ 1+ );assert_component(&root, "First", "Photo.jpg", b"original");assert!(!home@@ -2197,28 +2445,33 @@ fn export_recovers_empty_initial_directories_without_claiming_unrelated_contents}#[test]-fn export_reports_completion_progress_before_the_command_finishes() {+fn export_reports_progress_and_keeps_account_storage_while_workers_run() {use std::sync::{Mutex, mpsc};use std::time::{Duration, Instant};let mut server = mockito::Server::new();+ let mut media = mockito::Server::new();let home = TestHome::new();home.seed(&server.url());let key = Key::generate();- listing(&mut server, json!([collection(1, "Album", &key)]));+ listing(+ &mut server,+ json!([collection(1, "Album", &key), collection(2, "Empty", &key)]),+ );+ page(&mut server, 2, 0, json!([]), false).create();let (first, first_bytes) = source(10, &key, b"first", "First.jpg");let (second, second_bytes) = source(11, &key, b"second", "Second.jpg");page(&mut server, 1, 0, json!([first, second]), false).create();let fetched = download(&mut server, 10, &first_bytes, 1);let url = server.mock("GET", "/files/download/v3/11")- .with_body(json!({"url":format!("{}/slow",server.url())}).to_string())+ .with_body(json!({"url":format!("{}/slow",media.url())}).to_string()).expect(1).create();let (started, reading) = mpsc::channel();let (release, receiver) = mpsc::channel::<()>();let receiver = Mutex::new(receiver);- let slow = server+ let slow = media.mock("GET", "/slow").with_body_from_request(move |_| {let _ = started.send(());@@ -2261,6 +2514,59 @@ fn export_reports_completion_progress_before_the_command_finishes() {std::thread::sleep(Duration::from_millis(10));}assert!(child.try_wait().unwrap().is_none());+ let state = home.read_vault();+ let account = home+ .dir+ .path()+ .join("accounts")+ .join(state["accounts"][0]["storage_id"].as_str().unwrap());+ let revoke = server.mock("POST", "/users/logout").expect(0).create();+ for args in [+ vec!["account", "logout", "fixture", "--local"],+ vec!["account", "logout", "fixture"],+ vec!["photos", "logout"],+ ] {+ let output = ExportChild::spawn(&mut home.command(&args))+ .unwrap()+ .wait_with_output()+ .unwrap();+ assert!(failure(&output).contains("account is in use"));+ assert_eq!(home.read_vault(), state);+ assert!(account.join("exports").is_dir());+ }+ revoke.assert();+ revoke.remove();+ success(+ ExportChild::spawn(&mut home.command(&["photos", "album", "list", "--offline"]))+ .unwrap()+ .wait_with_output()+ .unwrap(),+ );+ let other = destination.path().join("other");+ success(+ ExportChild::spawn(&mut home.command(&[+ "photos",+ "export",+ other.to_str().unwrap(),+ "--album",+ "2",+ ]))+ .unwrap()+ .wait_with_output()+ .unwrap(),+ );+ let mut with_locker = state;+ with_locker["accounts"][0]["sessions"]["locker"] = json!({"token": [1]});+ home.write_vault(&with_locker);+ let revoke = server.mock("POST", "/users/logout").expect(1).create();+ success(+ ExportChild::spawn(&mut home.command(&["photos", "logout"]))+ .unwrap()+ .wait_with_output()+ .unwrap(),+ );+ assert!(account.is_dir());+ revoke.assert();drop(release);let output = child.wait_with_output().unwrap();assert!(output.status.success());@@ -2271,6 +2577,28 @@ fn export_reports_completion_progress_before_the_command_finishes() {fetched.assert();url.assert();slow.assert();+ let lock = fs::File::options()+ .read(true)+ .write(true)+ .open(account.with_extension("lock"))+ .unwrap();+ lock.lock().unwrap();+ let output =+ ExportChild::spawn(&mut home.command(&["account", "logout", "fixture", "--local"]))+ .unwrap()+ .wait_with_output()+ .unwrap();+ assert!(failure(&output).contains("account is in use"));+ assert!(home.read_vault()["accounts"][0]["sessions"]["locker"].is_object());+ drop(lock);+ success(home.run(&["account", "logout", "fixture", "--local"]));+ assert!(!account.exists());+ assert_eq!(+ fs::read_dir(home.dir.path().join("accounts"))+ .unwrap()+ .count(),+ 0+ );}#[test]diff --git a/rust/apps/cli-next/tests/support/export_sources.rs b/rust/apps/cli-next/tests/support/export_sources.rsindex 8515b41a04..9a772a3ee4 100644--- a/rust/apps/cli-next/tests/support/export_sources.rs+++ b/rust/apps/cli-next/tests/support/export_sources.rs@@ -197,7 +197,7 @@ fn export_reevaluates_saved_metadata_without_an_upstream_change() {let home = TestHome::new();home.seed(&server.url());let key = Key::generate();- server+ let albums = server.mock("GET", "/collections/v2").match_query(mockito::Matcher::Any).with_body(json!({"collections":[collection(1,"First",&key)]}).to_string())@@ -231,6 +231,88 @@ fn export_reevaluates_saved_metadata_without_an_upstream_change() {"reevaluated stored caption");+ albums.remove();+ server+ .mock("GET", "/collections/v2")+ .match_query(mockito::Matcher::UrlEncoded(+ "sinceTime".into(),+ "20".into(),+ ))+ .with_body(json!({"collections":[]}).to_string())+ .create();+ docs["editedName"] = json!("Recovered.jpg");+ db.execute(+ "UPDATE photos_collections SET record=json_set(record,'$.documents.original',?1,'$.failure','saved interpretation failure') WHERE id=1",+ [b64::encode(b"Recovered")],+ ).unwrap();+ db.execute(+ "UPDATE photos_files SET record=json_set(record,'$.documents.public',?1,'$.failure','saved interpretation failure'),failed=1 WHERE id=10",+ [b64::encode(&serde_json::to_vec(&docs).unwrap())],+ ).unwrap();+ let saved = record(&db, 1, 10);+ assert!(+ failure(&home.run(&[+ "photos",+ "file",+ "view",+ "Recovered.jpg",+ "--album",+ "1",+ "--offline"+ ]))+ .contains("no file matches")+ );+ assert_eq!(record(&db, 1, 10), saved);+ assert_eq!(+ home.json(&[+ "photos",+ "file",+ "view",+ "Recovered.jpg",+ "--album",+ "Recovered"+ ])["id"],+ "10"+ );+ assert!(record(&db, 1, 10)["failure"].is_null());+ assert_eq!(+ db.query_row("SELECT failed FROM photos_files WHERE id=10", [], |r| r+ .get::<_, i64>(0))+ .unwrap(),+ 0+ );+ assert_eq!(+ read_json(&root.join("First/metadata.json"))["title"],+ "First"+ );+ assert!(root.join("First/metadata/Good.jpg.json").exists());++ db.execute_batch("UPDATE photos_collections SET name='First',record=json_set(record,'$.failure','saved interpretation failure') WHERE id=1; UPDATE photos_files SET name='Good.jpg',record=json_set(record,'$.failure','saved interpretation failure'),failed=1 WHERE id=10;").unwrap();+ run(&home, &root, &["--album", "1"], true);+ assert_eq!(+ read_json(&root.join("Recovered/metadata.json"))["title"],+ "Recovered"+ );+ assert_eq!(+ read_json(&root.join("Recovered/metadata/Recovered.jpg.json"))["description"],+ "reevaluated stored caption"+ );+ assert_eq!(+ fs::read(root.join("Recovered/Recovered.jpg")).unwrap(),+ b"original"+ );+ assert!(record(&db, 1, 10)["failure"].is_null());+ assert_eq!(db.query_row("SELECT count(*) FROM photos_collections WHERE name='Recovered' AND json_extract(record,'$.failure') IS NULL", [], |r| r.get::<_, i64>(0)).unwrap(), 1);+ assert_eq!(+ db.query_row(+ "SELECT count(*) FROM photos_files WHERE name='Recovered.jpg' AND failed=0",+ [],+ |r| r.get::<_, i64>(0)+ )+ .unwrap(),+ 1+ );+page.assert();downloaded.assert();}diff --git a/rust/apps/cli-next/tests/support/museum.rs b/rust/apps/cli-next/tests/support/museum.rsindex 5d13ac9e12..1177c4a7d9 100644--- a/rust/apps/cli-next/tests/support/museum.rs+++ b/rust/apps/cli-next/tests/support/museum.rs@@ -280,7 +280,6 @@ async fn exercise(origin: String) -> TestResult {]));assert_eq!(fs::read(output_path).unwrap(), original);- // Two origins with the same server user ID are still different accounts.let alias_origin = origin.replace("127.0.0.1", "localhost");assert_ne!(alias_origin, origin);let before = fs::read(home.dir.path().join("vault.json")).unwrap();diff --git a/rust/crates/photos-export/src/lib.rs b/rust/crates/photos-export/src/lib.rsindex bc9427eb7c..275330c99e 100644--- a/rust/crates/photos-export/src/lib.rs+++ b/rust/crates/photos-export/src/lib.rs@@ -678,7 +678,7 @@ fn fatal_cause(cause: &(dyn std::error::Error + 'static)) -> bool {match error {crate::live_photo::Error::Io(error) => return fatal_cause(error),crate::live_photo::Error::Zip(error) => return fatal_cause(error),- crate::live_photo::Error::Components => {}+ crate::live_photo::Error::Components | crate::live_photo::Error::ExpansionLimit => {}}}cause.source().is_some_and(fatal_cause)@@ -709,7 +709,7 @@ fn summary(store: &Store, destination: &Path, prepared: bool) -> Result<Summary>|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),)?;let complete = !unknown && failures == 0 && completed == expected;- let result = json!({"destination":destination,"complete":complete,"files":if unknown {None}else{Some(files)},"copies":if unknown {None}else{Some(json!({"expected":expected,"completed":completed,"pending":expected-completed}))},"changes":{"exported":exported,"metadataUpdated":metadata_updated,"renamed":renamed,"retained":retained},"failures":failures,"conflicts":conflicts});+ let result = json!({"destination":destination.to_string_lossy(),"complete":complete,"files":if unknown {None}else{Some(files)},"copies":if unknown {None}else{Some(json!({"expected":expected,"completed":completed,"pending":expected-completed}))},"changes":{"exported":exported,"metadataUpdated":metadata_updated,"renamed":renamed,"retained":retained},"failures":failures,"conflicts":conflicts});Ok(Summary {json: result,complete,diff --git a/rust/crates/photos-export/src/live_photo.rs b/rust/crates/photos-export/src/live_photo.rsindex daa9832822..401369dacf 100644--- a/rust/crates/photos-export/src/live_photo.rs+++ b/rust/crates/photos-export/src/live_photo.rs@@ -1,4 +1,4 @@-use std::io::{Read, Seek, Write};+use std::io::{Read, Seek, SeekFrom, Write};use crate::metadata::Role;@@ -10,15 +10,22 @@ pub enum Error {Io(#[from] std::io::Error),#[error("Live Photo must contain one image and one video")]Components,+ #[error("Live Photo archive expands beyond limit")]+ ExpansionLimit,}pub fn extract<R: Read + Seek, W: Write>(- reader: R,+ mut reader: R,mut output: impl FnMut(Role, &str) -> std::io::Result<W>,) -> Result<Vec<(Role, String, W)>, Error> {+ let limit = reader+ .seek(SeekFrom::End(0))?+ .saturating_mul(20)+ .saturating_add(16 * 1024 * 1024);let mut archive = zip::ZipArchive::new(reader)?;let mut image = None;let mut video = None;+ let mut declared_remaining = limit;for index in 0..archive.len() {let entry = archive.by_index(index)?;if entry.is_dir() {@@ -45,16 +52,102 @@ pub fn extract<R: Read + Seek, W: Write>(if slot.replace((index, extension.to_owned())).is_some() {return Err(Error::Components);}+ declared_remaining = declared_remaining+ .checked_sub(entry.size())+ .ok_or(Error::ExpansionLimit)?;}let (Some(image), Some(video)) = (image, video) else {return Err(Error::Components);};let mut results = Vec::with_capacity(2);+ let mut remaining = limit;for (role, (index, extension)) in [(Role::Image, image), (Role::Video, video)] {let mut writer = output(role.clone(), &extension)?;- std::io::copy(&mut archive.by_index(index)?, &mut writer)?;+ let mut entry = archive.by_index(index)?;+ remaining -= std::io::copy(&mut entry.by_ref().take(remaining), &mut writer)?;+ if entry.read(&mut [0])? != 0 {+ return Err(Error::ExpansionLimit);+ }writer.flush()?;results.push((role, extension, writer));}Ok(results)}++#[cfg(test)]+mod tests {+ use super::*;+ use std::{cell::Cell, io::Cursor};++ struct Count<'a>(&'a Cell<u64>);++ impl Write for Count<'_> {+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {+ self.0.set(self.0.get() + bytes.len() as u64);+ Ok(bytes.len())+ }++ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+ }++ fn archive(sizes: [u64; 2], method: zip::CompressionMethod) -> Vec<u8> {+ let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));+ for (name, size) in ["image.heic", "video.mov"].into_iter().zip(sizes) {+ zip.start_file(+ name,+ zip::write::SimpleFileOptions::default().compression_method(method),+ )+ .unwrap();+ std::io::copy(&mut std::io::repeat(0).take(size), &mut zip).unwrap();+ }+ zip.finish().unwrap().into_inner()+ }++ #[test]+ fn accepts_stored_large_components_and_deflated_pairs() {+ for (method, sizes) in [+ (zip::CompressionMethod::Stored, [21 * 1024 * 1024, 1]),+ (zip::CompressionMethod::Deflated, [7 * 1024 * 1024; 2]),+ ] {+ let written = Cell::new(0);+ let parts = extract(Cursor::new(archive(sizes, method)), |_, _| {+ Ok(Count(&written))+ })+ .unwrap();+ assert_eq!(written.get(), sizes.into_iter().sum::<u64>());+ assert_eq!(parts.len(), 2);+ }+ }++ #[test]+ fn limits_declared_and_actual_combined_expansion() {+ let mut bytes = archive([9 * 1024 * 1024; 2], zip::CompressionMethod::Deflated);+ let written = Cell::new(0);+ let mut opened = 0;+ let result = extract(Cursor::new(&bytes), |_, _| {+ opened += 1;+ Ok(Count(&written))+ });+ assert!(matches!(result, Err(Error::ExpansionLimit)));+ assert_eq!(opened, 0);+ let headers: Vec<_> = bytes+ .windows(4)+ .enumerate()+ .filter_map(|(i, bytes)| (bytes == b"PK\x01\x02").then_some(i))+ .collect();+ assert_eq!(headers.len(), 2);+ for offset in headers {+ bytes[offset + 24..offset + 28].copy_from_slice(&1u32.to_le_bytes());+ }+ let limit = bytes.len() as u64 * 20 + 16 * 1024 * 1024;+ let result = extract(Cursor::new(&bytes), |_, _| {+ opened += 1;+ Ok(Count(&written))+ });+ assert!(matches!(result, Err(Error::ExpansionLimit)));+ assert_eq!(opened, 2);+ assert_eq!(written.get(), limit);+ }+}