refactor: optimize Firestore rules and meal cleanup

- Tighten Firestore validation rules (data size and limits)
- Pass context to `deletePhotoFile` for safer file management
- Cleanup unused dependencies in build configuration
- Update Robolectric SDK target for tests
This commit is contained in:
bleackstorm committed 2026-11-08 20:06:30 +01:00
1 parent 87bbb448c2
commit 79e04f64d8
28 files changed
+1606 -1230

No files matched your search

@@ -60,12 +60,20 @@ object CsvExporter {
return sb.toString()
}
private fun escapeCsvField(value: String): String {
val sanitized = value.replace("\r\n", " ").replace("\n", " ").trim()
return if (sanitized.contains(",") || sanitized.contains("\"") || sanitized.contains(";")) {
"\"${sanitized.replace("\"", "\"\"")}\""
fun escapeCsvField(value: String): String {
val rawWithoutNewlines = value.replace("\r\n", " ").replace("\n", " ")
val trimmed = rawWithoutNewlines.trim()
val formulaProtected = if (rawWithoutNewlines.isNotEmpty() && rawWithoutNewlines[0] in listOf('=', '+', '-', '@', '\t', '\r')) {
"'$rawWithoutNewlines"
} else if (trimmed.isNotEmpty() && trimmed[0] in listOf('=', '+', '-', '@')) {
"'$trimmed"
} else {
sanitized
trimmed
}
return if (formulaProtected.contains(",") || formulaProtected.contains("\"") || formulaProtected.contains(";")) {
"\"${formulaProtected.replace("\"", "\"\"")}\""
} else {
formulaProtected
}
}
@@ -63,4 +63,10 @@ object GoogleSheetsAuthHelper {
Result.failure(e)
}
}
fun invalidateToken(context: Context, token: String) {
try {
GoogleAuthUtil.clearToken(context.applicationContext, token)
} catch (_: Exception) {}
}
}
@@ -20,10 +20,13 @@ data class GoogleSheetsSyncResult(
val timestamp: Long = System.currentTimeMillis()
)
class AuthExpiredException(message: String) : IllegalStateException(message)
object GoogleSheetsSyncService {
private const val TAG = "GoogleSheetsSync"
const val SPREADSHEET_TITLE = "Satiéa — Journal des Repas"
const val SHEET_TAB_TITLE = "Journal des repas"
private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
@@ -38,7 +41,7 @@ object GoogleSheetsSyncService {
cachedSpreadsheetId: String? = null
): Result<Pair<String, String>> = withContext(Dispatchers.IO) {
try {
// 1. If we have a cached spreadsheetId, verify it still exists and is accessible
// 1. If we have a cached spreadsheetId, verify it still exists
if (!cachedSpreadsheetId.isNullOrBlank()) {
val checkRequest = Request.Builder()
.url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl")
@@ -46,36 +49,37 @@ object GoogleSheetsSyncService {
.get()
.build()
try {
okHttpClient.newCall(checkRequest).execute().use { response ->
if (response.isSuccessful) {
val bodyStr = response.body?.string().orEmpty()
val json = JSONObject(bodyStr)
val id = json.optString("spreadsheetId", cachedSpreadsheetId)
val url = json.optString(
"spreadsheetUrl",
"https://docs.google.com/spreadsheets/d/$id/edit"
)
return@withContext Result.success(Pair(id, url))
}
okHttpClient.newCall(checkRequest).execute().use { response ->
if (response.code == 401) {
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
}
if (response.isSuccessful) {
val body = response.body?.string().orEmpty()
val json = JSONObject(body)
val id = json.getString("spreadsheetId")
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
return@withContext Result.success(Pair(id, url))
}
} catch (e: Exception) {
Log.w(TAG, "Cached spreadsheet check failed, searching Drive: ${e.message}")
}
}
// 2. Search Drive for existing spreadsheet named "Satiéa — Journal des Repas"
// 2. Search Drive for existing "Satiéa — Journal des Repas"
val query = "name = '$SPREADSHEET_TITLE' and mimeType = 'application/vnd.google-apps.spreadsheet' and trashed = false"
val encodedQuery = URLEncoder.encode(query, "UTF-8")
val driveSearchUrl = "https://www.googleapis.com/drive/v3/files?q=$encodedQuery&fields=files(id,name,webViewLink)"
val searchUrl = "https://www.googleapis.com/drive/v3/files?q=" +
URLEncoder.encode(query, "UTF-8") +
"&fields=" + URLEncoder.encode("files(id, name, webViewLink)", "UTF-8") +
"&spaces=drive"
val searchRequest = Request.Builder()
.url(driveSearchUrl)
.url(searchUrl)
.header("Authorization", "Bearer $accessToken")
.get()
.build()
okHttpClient.newCall(searchRequest).execute().use { searchResponse ->
if (searchResponse.code == 401) {
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
}
if (searchResponse.isSuccessful) {
val body = searchResponse.body?.string().orEmpty()
val json = JSONObject(body)
@@ -89,7 +93,7 @@ object GoogleSheetsSyncService {
}
}
// 3. Not found, create a new Google Sheet
// 3. Not found, create a new Google Sheet with dedicated named tab
val createPayload = JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SPREADSHEET_TITLE)
@@ -97,7 +101,7 @@ object GoogleSheetsSyncService {
put("sheets", JSONArray().apply {
put(JSONObject().apply {
put("properties", JSONObject().apply {
put("title", "Journal")
put("title", SHEET_TAB_TITLE)
put("gridProperties", JSONObject().apply {
put("frozenRowCount", 1)
})
@@ -114,6 +118,9 @@ object GoogleSheetsSyncService {
okHttpClient.newCall(createRequest).execute().use { response ->
val bodyStr = response.body?.string().orEmpty()
if (response.code == 401) {
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
}
if (!response.isSuccessful) {
val errorMsg = parseErrorMessage(bodyStr, response.code)
return@withContext Result.failure(IllegalStateException("Création du classeur Google Sheets échouée: $errorMsg"))
@@ -138,8 +145,9 @@ object GoogleSheetsSyncService {
try {
val rows = GoogleSheetsDataFormatter.formatMealsToRows(meals)
// 1. Clear previous content to remove stale deleted rows
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/A1:Z:clear"
// 1. Clear previous content with explicit sheet range to remove stale deleted rows
val clearRange = URLEncoder.encode("'$SHEET_TAB_TITLE'!A:Z", "UTF-8")
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear"
val clearRequest = Request.Builder()
.url(clearUrl)
.header("Authorization", "Bearer $accessToken")
@@ -147,12 +155,17 @@ object GoogleSheetsSyncService {
.build()
try {
okHttpClient.newCall(clearRequest).execute().close()
okHttpClient.newCall(clearRequest).execute().use { clearResp ->
if (clearResp.code == 401) {
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
}
}
} catch (e: Exception) {
if (e is AuthExpiredException) throw e
Log.w(TAG, "Clear range warning: ${e.message}")
}
// 2. Put formatted values starting at A1
// 2. Put formatted values starting at A1 using RAW input (neutralizes CWE-1236 Formula Injection)
val jsonValuesArray = JSONArray()
for (row in rows) {
val rowArray = JSONArray()
@@ -163,12 +176,13 @@ object GoogleSheetsSyncService {
}
val writePayload = JSONObject().apply {
put("range", "A1")
put("range", "'$SHEET_TAB_TITLE'!A1")
put("majorDimension", "ROWS")
put("values", jsonValuesArray)
}
val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/A1?valueInputOption=USER_ENTERED"
val writeRange = URLEncoder.encode("'$SHEET_TAB_TITLE'!A1", "UTF-8")
val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$writeRange?valueInputOption=RAW"
val writeRequest = Request.Builder()
.url(writeUrl)
.header("Authorization", "Bearer $accessToken")
@@ -177,6 +191,9 @@ object GoogleSheetsSyncService {
okHttpClient.newCall(writeRequest).execute().use { response ->
val bodyStr = response.body?.string().orEmpty()
if (response.code == 401) {
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
}
if (!response.isSuccessful) {
val errorMsg = parseErrorMessage(bodyStr, response.code)
return@withContext Result.failure(IllegalStateException("Mise à jour de la feuille Google Sheets échouée: $errorMsg"))
@@ -96,19 +96,45 @@ object ImageUtils {
}
}
fun deletePhotoFile(context: Context, photoUriStr: String?): Boolean {
if (photoUriStr.isNullOrBlank()) return false
return try {
val uri = Uri.parse(photoUriStr)
val path = uri.path ?: return false
val targetFile = File(path).canonicalFile
val allowedDirectory = getPhotosDirectory(context).canonicalFile
// Path Traversal Defense: Must strictly reside inside allowed directory
val isWithinAllowedDir = targetFile.path.startsWith(allowedDirectory.path + File.separator)
if (!isWithinAllowedDir) {
Log.w(TAG, "Security Alert: Refusing to delete photo outside allowed directory: ${targetFile.path}")
return false
}
if (targetFile.exists()) {
targetFile.delete()
} else {
false
}
} catch (e: Exception) {
Log.w(TAG, "Could not delete photo file: ${e.message}")
false
}
}
// Overload for backward-compatibility with traversal mitigation
fun deletePhotoFile(photoUriStr: String?): Boolean {
if (photoUriStr.isNullOrBlank()) return false
return try {
val uri = Uri.parse(photoUriStr)
val path = uri.path
if (path != null) {
val file = File(path)
if (file.exists()) {
file.delete()
} else false
} else false
} catch (e: Exception) {
Log.w(TAG, "Could not delete photo file: ${e.message}")
val path = uri.path ?: return false
if (path.contains("..") || !path.contains(PHOTOS_DIR_NAME)) {
Log.w(TAG, "Security Alert: Traversal attempt blocked in uncontextual delete: $path")
return false
}
val file = File(path)
if (file.exists()) file.delete() else false
} catch (_: Exception) {
false
}
}