-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Add WebP format support for admin panel image uploads #60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
- Updated client-side file input validation to accept image/webp - Enhanced server-side upload_emoji function to detect and handle WebP format - Added file type detection based on content-type header and file signatures - Updated documentation to reflect WebP support Co-authored-by: nate nowack <zzstoatzz@users.noreply.github.com>
Code Review for PR #60: WebP Support for Admin Panel Image UploadsThank you for implementing WebP support! Here's my comprehensive review: ✅ Strengths
🔍 Code Quality & Best Practices
|
|
@claude numerous formatting issues, you need to run formatting and stuff dude |
|
Claude finished @zzstoatzz's task —— View job ✅ Formatting issues fixedI've applied formatting fixes to Changes made:
Todo List:
The formatting has been successfully applied and pushed to the branch. |
- Alphabetize imports - Break long lines for better readability - Format error handling blocks consistently - Improve WebP detection condition formatting Co-authored-by: nate nowack <zzstoatzz@users.noreply.github.com>
Code Review for PR #60: WebP Support for Admin Panel Image Uploads✅ Strengths
🔍 Issues & Recommendations1. Security Concerns 🔴
Suggested fix for // Add proper admin check
let admin_did = app_config.admin_did.clone();
let session_did = session.get::<String>("did").unwrap_or(None);
if session_did.is_none() || session_did.unwrap() != admin_did {
return Ok(HttpResponse::Unauthorized().body("Admin access required"));
}2. Code Duplication 🟡The file signature detection logic is duplicated (lines 75-88 and 93-106). Consider extracting this into a helper function: fn detect_image_format(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
Some("png")
} else if bytes.starts_with(&[0x47, 0x49, 0x46]) {
Some("gif")
} else if bytes.starts_with(b"RIFF") && bytes.len() > 12 && &bytes[8..12] == b"WEBP" {
Some("webp")
} else {
None
}
}3. Input Validation 🟡
Suggested additions: // Add after line 65
if file_bytes.len() > 5 * 1024 * 1024 {
return Err(AppError::ValidationError("File too large. Maximum size is 5MB.".into()));
}
// Sanitize filename (after line 111)
let filename = name
.filter(|s| !s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_'))
.unwrap_or_else(|| format!("emoji_{}", chrono::Utc::now().timestamp()));4. Performance Consideration 🟡Loading entire file into memory could be problematic for large files. While 5MB isn't huge, consider streaming to disk for better memory efficiency in high-traffic scenarios. 5. Missing Tests 🔴No test coverage for the new WebP functionality. Consider adding tests for:
📋 SummaryThe PR successfully adds WebP support but has critical security issues that must be addressed before merging:
The WebP implementation itself is correct, but the security gaps need immediate attention. Please address these issues and I'll be happy to re-review! |
- Reorder imports alphabetically - Fix line breaks for better readability - Apply consistent formatting to json responses
Code Review for PR #60: WebP Format Support✅ Strengths
🔍 Issues & Recommendations1. Security: File Size Validation MissingThe code removed "Basic validation omitted for brevity" comment but doesn't implement actual file size validation. The README mentions "max 5MB" but this isn't enforced in Recommendation: Add validation before processing: const MAX_FILE_SIZE: usize = 5 * 1024 * 1024; // 5MB
if file_bytes.len() > MAX_FILE_SIZE {
return Err(AppError::ValidationError("File exceeds 5MB limit".into()));
}2. Code Duplication: File Type DetectionThe file signature detection logic is duplicated (lines 68-87 and 91-105 in status_write.rs). Recommendation: Extract to a helper function: fn detect_image_format(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
Some("png")
} else if bytes.starts_with(&[0x47, 0x49, 0x46]) {
Some("gif")
} else if bytes.starts_with(b"RIFF") && bytes.len() > 12 && &bytes[8..12] == b"WEBP" {
Some("webp")
} else {
None
}
}3. Error Handling: Incomplete WebP ValidationThe WebP detection checks for "RIFF" header and "WEBP" fourCC, but doesn't validate the actual WebP format (VP8/VP8L/VP8X chunks). Recommendation: Consider using a proper image validation library like 4. Performance: Unnecessary String AllocationLine 112 creates a new string for the response when Minor optimization: Ok(HttpResponse::Ok()
.json(serde_json::json!({"ok": true, "name": format!("{}.{}", filename, extension)})))Could use: 5. Missing TestsNo tests were added for the new WebP functionality. Critical paths to test:
📋 Additional Considerations
✅ SummaryThe implementation is solid and follows the existing patterns well. The main concerns are around security (file size validation) and code maintainability (duplication). With the suggested improvements, this will be a valuable addition for reducing bandwidth and storage costs. Verdict: Approve with minor changes recommended |
- Add webp extension check when listing available emojis - Implement proper priority ordering: PNG > WebP > GIF for duplicates - Fixes issue where uploaded WebP emojis weren't appearing in the list
Code Review for PR #60: WebP Format Support✅ Strengths
🔍 Issues & Recommendations1. Security Concern: File Size Validation MissingThe PR removes the comment about "Basic validation omitted for brevity" but doesn't add actual file size validation. The README mentions "max 5MB" but this isn't enforced in code. Recommendation: Add file size validation: const MAX_FILE_SIZE: usize = 5 * 1024 * 1024; // 5MB
if file_bytes.len() > MAX_FILE_SIZE {
return Err(AppError::ValidationError(
format!("File too large. Maximum size is 5MB, got {}MB",
file_bytes.len() / (1024 * 1024)).into()
));
}2. Code Duplication: File Signature DetectionThe file signature detection logic is duplicated in the content-type match arm's fallback and the else branch. Recommendation: Extract to a helper function: fn detect_image_format(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
Some("png")
} else if bytes.starts_with(&[0x47, 0x49, 0x46]) {
Some("gif")
} else if bytes.starts_with(b"RIFF")
&& bytes.len() > 12
&& &bytes[8..12] == b"WEBP" {
Some("webp")
} else {
None
}
}3. Missing Input ValidationThe filename sanitization only checks for empty strings but doesn't validate for path traversal or invalid characters. Recommendation: Add proper filename validation: fn validate_filename(name: &str) -> Result<String, AppError> {
let re = regex::Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap();
if !re.is_match(name) {
return Err(AppError::ValidationError(
"Invalid filename. Only letters, numbers, hyphens, and underscores allowed".into()
));
}
Ok(name.to_string())
}4. Performance ConsiderationThe priority logic in let priority = |ext: &str| match ext {
"png" => 3,
"webp" => 2,
"gif" => 1,
_ => 0,
};5. Missing TestsNo tests were added for the new WebP functionality. Consider adding:
🚨 Critical Issues
📊 Overall AssessmentThe implementation is functional and follows the existing codebase patterns well. However, it needs security improvements before merging, particularly around file size limits and input validation. The code duplication should also be addressed for maintainability. Verdict: Changes Requested - Please address the security concerns and consider the code quality improvements before merging. 🤖 Generated with Claude Code |
- Add 'image/webp' to client-side MIME type validation - Update error message to include WebP format - Fixes frontend rejection of valid WebP files
Code Review for PR #60: WebP Format SupportThank you for adding WebP support to the admin panel image uploads! Here's my comprehensive review: ✅ Strengths
🔍 Code Quality Observations1. File Type Detection Logic (src/api/status_write.rs:67-105)The dual approach (content-type + file signature) is robust, but there's code duplication between the two branches. Consider extracting the detection logic: fn detect_image_format(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
Some("png")
} else if bytes.starts_with(&[0x47, 0x49, 0x46]) {
Some("gif")
} else if bytes.starts_with(b"RIFF") && bytes.len() > 12 && &bytes[8..12] == b"WEBP" {
Some("webp")
} else {
None
}
}2. Security Considerations
3. Performance
|
…load failures - Return JSON error responses instead of plain text from AppError handler - Add comprehensive console logging on client-side for debugging - Add server-side logging for all upload failure scenarios - Add file size validation (5MB limit) with clear error messages - Improve error messages to show specific failure reasons - Check for existing files to prevent overwrites - Ensure emoji directory exists before writing files
Code Review for PR #60: WebP Format Support✅ Strengths
🔍 Areas for Improvement1. Security Considerations
2. Performance Optimizations
let extension = match &file_bytes[..] {
bytes if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) => "png",
bytes if bytes.starts_with(&[0x47, 0x49, 0x46]) => "gif",
bytes if bytes.len() > 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" => "webp",
_ => return Err(AppError::ValidationError("Unsupported format".into()))
};3. Code Quality Issues
4. Potential Bugs
5. Test Coverage
📝 Recommendations
✨ Overall AssessmentThe implementation is functional and adds valuable WebP support. However, it needs security hardening, test coverage, and some refactoring to reduce code duplication. The error handling improvements are excellent and the logging additions will help with debugging. Recommendation: Address the security concerns and add basic test coverage before merging. |
Closes #59
Summary
Adds support for uploading WebP format images in the admin panel's image upload functionality.
Changes
Benefits
Generated with Claude Code