Skip to content

Commit e3ee7e6

Browse files
fix(albums): sanitize image_ids and secure IN clause (#629)
* fix(albums): sanitize image_ids and secure IN clause to prevent SQL injection * Fix: optimize db_add_images_to_album for UUID support and single IN query * Remove redundant if Check --------- Co-authored-by: ROHAN PANDEY <95585299+rohan-pandeyy@users.noreply.github.com>
1 parent c3ee2fb commit e3ee7e6

1 file changed

Lines changed: 30 additions & 10 deletions

File tree

backend/app/database/albums.py

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -169,23 +169,43 @@ def db_get_album_images(album_id: str):
169169

170170

171171
def db_add_images_to_album(album_id: str, image_ids: list[str]):
172+
"""
173+
Safely adds images to an album using parameterized queries.
174+
Maintains UUID support and uses efficient single queries.
175+
"""
176+
# Validate input type
177+
if not isinstance(image_ids, list):
178+
raise ValueError("image_ids must be a list of IDs")
179+
180+
# Remove integer conversion - keep IDs as strings for UUID support
181+
sanitized_ids = []
182+
for img_id in image_ids:
183+
# Basic validation - ensure it's a non-empty string
184+
if isinstance(img_id, str) and img_id.strip():
185+
sanitized_ids.append(img_id.strip())
186+
187+
if not sanitized_ids:
188+
raise ValueError("No valid image IDs provided")
189+
172190
with get_db_connection() as conn:
173191
cursor = conn.cursor()
174192

175-
query = (
176-
f"SELECT id FROM images WHERE id IN ({','.join('?' for _ in image_ids)})"
177-
)
178-
cursor.execute(query, image_ids)
193+
# Generate placeholders safely based on list length
194+
placeholders = ",".join(["?"] * len(sanitized_ids))
195+
query = f"SELECT id FROM images WHERE id IN ({placeholders})"
196+
cursor.execute(query, sanitized_ids) # Pass string IDs directly
179197
valid_images = [row[0] for row in cursor.fetchall()]
180198

181-
if valid_images:
182-
cursor.executemany(
183-
"INSERT OR IGNORE INTO album_images (album_id, image_id) VALUES (?, ?)",
184-
[(album_id, img_id) for img_id in valid_images],
185-
)
186-
else:
199+
if not valid_images:
187200
raise ValueError("None of the provided image IDs exist in the database.")
188201

202+
# Insert into album_images using executemany
203+
cursor.executemany(
204+
"INSERT OR IGNORE INTO album_images (album_id, image_id) VALUES (?, ?)",
205+
[(album_id, img_id) for img_id in valid_images],
206+
)
207+
conn.commit()
208+
189209

190210
def db_remove_image_from_album(album_id: str, image_id: str):
191211
with get_db_connection() as conn:

0 commit comments

Comments
 (0)