π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix pet pipeline safety: parameterize SQL, prevent overflow, and validate inputs
Amrithesh Kakkoth Ented4766ebaa3a2
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dartindex fbd993c30d..62923316c5 100644--- a/mobile/apps/photos/lib/db/ml/db.dart+++ b/mobile/apps/photos/lib/db/ml/db.dart@@ -306,10 +306,11 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {List<DBPetFace> dbPetFaces,List<PetFaceResult> petFaces,) async {- assert(- dbPetFaces.length == petFaces.length,- 'dbPetFaces.length (${dbPetFaces.length}) != petFaces.length (${petFaces.length})',- );+ if (dbPetFaces.length != petFaces.length) {+ throw StateError(+ 'dbPetFaces.length (${dbPetFaces.length}) != petFaces.length (${petFaces.length})',+ );+ }try {final db = await asyncDB;// Group by species@@ -371,10 +372,11 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {List<DBPetBody> dbPetBodies,List<PetBodyResult> petBodies,) async {- assert(- dbPetBodies.length == petBodies.length,- 'dbPetBodies.length (${dbPetBodies.length}) != petBodies.length (${petBodies.length})',- );+ if (dbPetBodies.length != petBodies.length) {+ throw StateError(+ 'dbPetBodies.length (${dbPetBodies.length}) != petBodies.length (${petBodies.length})',+ );+ }try {final db = await asyncDB;// Group by species (0 = dog, 1 = cat)@@ -772,7 +774,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final db = await asyncDB;const String query = '''SELECT * FROM $petBodiesTable- WHERE $fileIDColumn = ?+ WHERE $fileIDColumn = ? AND $speciesColumn != -1''';final List<Map<String, dynamic>> maps = await db.getAll(query,@@ -2359,12 +2361,13 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {int minimumMlVersion = petMlVersion,}) async {final db = await asyncDB;- final String query = '''+ const String query = '''SELECT DISTINCT $fileIDColumn, $mlVersionColumnFROM $petFacesTable- WHERE $mlVersionColumn >= $minimumMlVersion+ WHERE $mlVersionColumn >= ?''';- final List<Map<String, dynamic>> maps = await db.getAll(query);+ final List<Map<String, dynamic>> maps =+ await db.getAll(query, [minimumMlVersion]);final Map<int, int> result = {};for (final map in maps) {result[map[fileIDColumn] as int] = map[mlVersionColumn] as int;@@ -2377,9 +2380,10 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {int minimumMlVersion = petMlVersion,}) async {final db = await asyncDB;- final String query =- 'SELECT COUNT(DISTINCT $fileIDColumn) as count FROM $petFacesTable WHERE $mlVersionColumn >= $minimumMlVersion';- final List<Map<String, dynamic>> maps = await db.getAll(query);+ const String query =+ 'SELECT COUNT(DISTINCT $fileIDColumn) as count FROM $petFacesTable WHERE $mlVersionColumn >= ?';+ final List<Map<String, dynamic>> maps =+ await db.getAll(query, [minimumMlVersion]);return maps.first['count'] as int;}diff --git a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dartindex ffcb4ff674..7d96923177 100644--- a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart+++ b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart@@ -35,6 +35,7 @@ class DBPetFace {faceDetectionColumn: detection,faceVectorIdColumn: faceVectorId,speciesColumn: species,+ // Use string literals for keys that collide with instance member names.'score': faceScore,'height': imageHeight,'width': imageWidth,@@ -106,6 +107,7 @@ class DBPetBody {detectionColumn: detection,bodyVectorIdColumn: bodyVectorId,speciesColumn: species,+ // Use string literals for keys that collide with instance member names.'score': score,'height': imageHeight,'width': imageWidth,diff --git a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart b/mobile/apps/photos/lib/db/ml/pet_vector_db.dartindex c346968d2b..c48aa54571 100644--- a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart+++ b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart@@ -106,6 +106,10 @@ class PetVectorDB {required bool isFace,bool offline = false,}) {+ assert(+ species == 0 || species == 1,+ 'Invalid pet species: $species (expected 0=dog or 1=cat)',+ );if (offline) {if (species == 0) {return isFace ? offlineDogFace : offlineDogBody;diff --git a/mobile/apps/photos/rust/src/ml/pet/align.rs b/mobile/apps/photos/rust/src/ml/pet/align.rsindex 1d8f08e672..41685b3d0f 100644--- a/mobile/apps/photos/rust/src/ml/pet/align.rs+++ b/mobile/apps/photos/rust/src/ml/pet/align.rs@@ -59,8 +59,10 @@ pub fn run_pet_face_alignment(}// Absolute bounding box (clamped to image bounds on both sides)- let box_x1 = (detection.box_xyxy[0] * img_wf).clamp(0.0, img_wf) as i32;- let box_y1 = (detection.box_xyxy[1] * img_hf).clamp(0.0, img_hf) as i32;+ let max_xf = (img_w as f32 - 1.0).max(0.0);+ let max_yf = (img_h as f32 - 1.0).max(0.0);+ let box_x1 = (detection.box_xyxy[0] * img_wf).clamp(0.0, max_xf) as i32;+ let box_y1 = (detection.box_xyxy[1] * img_hf).clamp(0.0, max_yf) as i32;let box_x2 = (detection.box_xyxy[2] * img_wf).clamp(0.0, img_wf) as i32;let box_y2 = (detection.box_xyxy[3] * img_hf).clamp(0.0, img_hf) as i32;@@ -89,8 +91,8 @@ pub fn run_pet_face_alignment(let region_y1 = (box_y1 - pad).max(0) as u32;let region_x2 = ((box_x2 + pad) as u32).min(img_w);let region_y2 = ((box_y2 + pad) as u32).min(img_h);- let region_w = region_x2 - region_x1;- let region_h = region_y2 - region_y1;+ let region_w = region_x2.saturating_sub(region_x1);+ let region_h = region_y2.saturating_sub(region_y1);if region_w == 0 || region_h == 0 {continue;}@@ -221,15 +223,24 @@ fn crop_and_resize_rgb() -> MlResult<RgbImage> {// Extract crop byteslet src_w = source.width();- let mut crop_bytes = Vec::with_capacity((w * h * 3) as usize);- for row in y..(y + h) {- for col in x..(x + w) {- let px = source.get_pixel(col.min(src_w - 1), row.min(source.height() - 1)).0;+ let src_h = source.height();+ // Clamp crop region to source bounds to avoid edge-replication artifacts.+ let clamped_w = w.min(src_w.saturating_sub(x));+ let clamped_h = h.min(src_h.saturating_sub(y));+ if clamped_w == 0 || clamped_h == 0 {+ return Err(MlError::Preprocess(+ "crop_and_resize_rgb: crop region extends beyond source image".to_string(),+ ));+ }+ let mut crop_bytes = Vec::with_capacity((clamped_w as usize) * (clamped_h as usize) * 3);+ for row in y..(y + clamped_h) {+ for col in x..(x + clamped_w) {+ let px = source.get_pixel(col, row).0;crop_bytes.extend_from_slice(&px);}}- let src_img = FirImage::from_vec_u8(w, h, crop_bytes, PixelType::U8x3)+ let src_img = FirImage::from_vec_u8(clamped_w, clamped_h, crop_bytes, PixelType::U8x3).map_err(|e| MlError::Preprocess(format!("FIR source: {e}")))?;let mut dst_img = FirImage::new(PET_FACE_CROP_SIZE, PET_FACE_CROP_SIZE, PixelType::U8x3);@@ -253,11 +264,11 @@ fn extract_rgb_region(w: u32,h: u32,) -> MlResult<RgbImage> {- let img_w = decoded.dimensions.width;- let mut buf = Vec::with_capacity((w * h * 3) as usize);+ let img_w = decoded.dimensions.width as usize;+ let mut buf = Vec::with_capacity((w as usize) * (h as usize) * 3);for row in y..(y + h) {- let start = ((row * img_w + x) * 3) as usize;- let end = start + (w * 3) as usize;+ let start = ((row as usize) * img_w + (x as usize)) * 3;+ let end = start + (w as usize) * 3;if end > decoded.rgb.len() {return Err(MlError::Preprocess(format!("region row {row} out of bounds (end={end}, len={})", decoded.rgb.len()@@ -278,11 +289,11 @@ fn crop_and_resize_decoded(w: u32,h: u32,) -> MlResult<RgbImage> {- let img_w = decoded.dimensions.width;- let mut crop_bytes = Vec::with_capacity((w * h * 3) as usize);+ let img_w = decoded.dimensions.width as usize;+ let mut crop_bytes = Vec::with_capacity((w as usize) * (h as usize) * 3);for row in y..(y + h) {- let start = ((row * img_w + x) * 3) as usize;- let end = start + (w * 3) as usize;+ let start = ((row as usize) * img_w + (x as usize)) * 3;+ let end = start + (w as usize) * 3;if end > decoded.rgb.len() {return Err(MlError::Preprocess(format!("crop row {row} out of bounds (end={end}, len={})", decoded.rgb.len()@@ -320,14 +331,12 @@ fn aligned_face_to_tensor(face_image: &RgbImage) -> Vec<f32> {let g_off = pixel_count;let b_off = 2 * pixel_count;- for y in 0..h {- for x in 0..w {- let px = face_image.get_pixel(x as u32, y as u32).0;- let idx = y * w + x;- output[r_off + idx] = (px[0] as f32 / 255.0 - MEAN[0]) / STD[0];- output[g_off + idx] = (px[1] as f32 / 255.0 - MEAN[1]) / STD[1];- output[b_off + idx] = (px[2] as f32 / 255.0 - MEAN[2]) / STD[2];- }+ let raw = face_image.as_raw();+ for i in 0..pixel_count {+ let src_idx = i * 3;+ output[r_off + i] = (raw[src_idx] as f32 / 255.0 - MEAN[0]) / STD[0];+ output[g_off + i] = (raw[src_idx + 1] as f32 / 255.0 - MEAN[1]) / STD[1];+ output[b_off + i] = (raw[src_idx + 2] as f32 / 255.0 - MEAN[2]) / STD[2];}outputdiff --git a/mobile/apps/photos/rust/src/ml/pet/detect.rs b/mobile/apps/photos/rust/src/ml/pet/detect.rsindex 894ef7760a..967aad1911 100644--- a/mobile/apps/photos/rust/src/ml/pet/detect.rs+++ b/mobile/apps/photos/rust/src/ml/pet/detect.rs@@ -16,10 +16,15 @@ const PET_FACE_MIN_SCORE: f32 = 0.3;const BODY_IOU_THRESHOLD: f32 = 0.5;const BODY_MIN_SCORE: f32 = 0.3;-// COCO class IDs+// COCO class IDs (used by body detection)const COCO_CAT: u8 = 15;const COCO_DOG: u8 = 16;+// Species IDs used across both Rust and Dart:+// 0 = dog (face detection class_id=0, COCO_DOG=16)+// 1 = cat (face detection class_id=1, COCO_CAT=15)+// Dart maps COCO β species via: cocoClass == 15 ? 1 : 0+/// Run pet face detection using YOLOv5-face model with 3 keypoints.////// Output format per row: [x, y, w, h, obj_conf, lx, ly, rx, ry, nx, ny, ...]@@ -47,18 +52,27 @@ pub fn run_pet_face_detection(*output_shape.last().unwrap() as usize} else if output_shape.len() == 1 {// Flat output: total_elements, must infer row_len.- // Prefer the smallest valid row length to avoid false matches- // (e.g. 143 is divisible by both 11 and 13).+ // Prefer 13 (2-class model) as the expected format, then fall back.let total = output_data.len();- if total % 11 == 0 { 11 }+ let inferred = if total % 13 == 0 { 13 }else if total % 12 == 0 { 12 }- else if total % 13 == 0 { 13 }+ else if total % 11 == 0 { 11 }else {return Err(MlError::Postprocess(format!("unexpected pet face detector output size: {} (shape: {:?})",total, output_shape)));+ };+ // Warn if the total is ambiguously divisible by multiple candidates.+ let candidates = [11usize, 12, 13];+ let valid_count = candidates.iter().filter(|&&c| total % c == 0).count();+ if valid_count > 1 {+ eprintln!(+ "[ml][pet] WARNING: flat output len={total} is divisible by {valid_count} row-length candidates; using {inferred}. \+ Prefer a model with 2D output shape for reliability."+ );}+ inferred} else {return Err(MlError::Postprocess("pet face detector output shape is empty".to_string(),diff --git a/mobile/apps/photos/rust/src/ml/pet/embed.rs b/mobile/apps/photos/rust/src/ml/pet/embed.rsindex dc2f22c0cf..95f23a5b41 100644--- a/mobile/apps/photos/rust/src/ml/pet/embed.rs+++ b/mobile/apps/photos/rust/src/ml/pet/embed.rs@@ -229,7 +229,7 @@ fn normalize_embedding(embedding: &mut [f32]) {norm += value * value;}let norm = norm.sqrt();- if norm <= f32::EPSILON {+ if norm <= 1e-12 {return;}for value in embedding.iter_mut() {diff --git a/mobile/apps/photos/rust/src/ml/pet/preprocess.rs b/mobile/apps/photos/rust/src/ml/pet/preprocess.rsindex d42a0eb3d3..c42e6abdd4 100644--- a/mobile/apps/photos/rust/src/ml/pet/preprocess.rs+++ b/mobile/apps/photos/rust/src/ml/pet/preprocess.rs@@ -89,8 +89,10 @@ pub fn extract_crop(let img_w = decoded.dimensions.width;let img_h = decoded.dimensions.height;- let x1 = (box_xyxy[0] * img_w as f32).round().clamp(0.0, img_w as f32) as u32;- let y1 = (box_xyxy[1] * img_h as f32).round().clamp(0.0, img_h as f32) as u32;+ let max_x = if img_w > 0 { img_w - 1 } else { 0 };+ let max_y = if img_h > 0 { img_h - 1 } else { 0 };+ let x1 = (box_xyxy[0] * img_w as f32).round().clamp(0.0, max_x as f32) as u32;+ let y1 = (box_xyxy[1] * img_h as f32).round().clamp(0.0, max_y as f32) as u32;let x2 = (box_xyxy[2] * img_w as f32).round().clamp(0.0, img_w as f32) as u32;let y2 = (box_xyxy[3] * img_h as f32).round().clamp(0.0, img_h as f32) as u32;@@ -103,10 +105,12 @@ pub fn extract_crop());}- let mut crop = Vec::with_capacity((crop_w * crop_h * 3) as usize);+ let mut crop = Vec::with_capacity((crop_w as usize) * (crop_h as usize) * 3);for row in y1..y2 {- let row_start = ((row * img_w + x1) * 3) as usize;- let row_end = ((row * img_w + x2) * 3) as usize;+ let row_start = (row as usize) * (img_w as usize) + (x1 as usize);+ let row_end = (row as usize) * (img_w as usize) + (x2 as usize);+ let row_start = row_start * 3;+ let row_end = row_end * 3;if row_end > decoded.rgb.len() || row_start > decoded.rgb.len() {return Err(MlError::Preprocess(format!("crop row {} out of bounds: start={}, end={}, buffer_len={}",diff --git a/mobile/apps/photos/rust/src/ml/runtime.rs b/mobile/apps/photos/rust/src/ml/runtime.rsindex 5544586439..ab625fd702 100644--- a/mobile/apps/photos/rust/src/ml/runtime.rs+++ b/mobile/apps/photos/rust/src/ml/runtime.rs@@ -178,6 +178,8 @@ fn create_runtime(config: &MlRuntimeConfig) -> MlRuntime {let p = &config.provider_policy;// Pet models use CPU-only to avoid NNAPI/CoreML driver issues with// FP16 models on some devices.+ // TODO: Make pet EP policy configurable so hardware acceleration can be+ // re-enabled once driver issues are resolved.let pet_policy = ExecutionProviderPolicy {prefer_coreml: false,prefer_nnapi: false,