From a333942bb94b95e6ba4d775a5ce3432a2bca7183 Mon Sep 17 00:00:00 2001 From: Brandon McAnsh Date: Wed, 30 Sep 2026 21:58:57 -0400 Subject: [PATCH] fix: make email ingress fail loudly and stop blocking on slow dependencies Worker: a non-2xx or thrown fetch to the API was logged and the email dropped while the sender saw success. The worker now times the fetch out at 25s and calls setReject on any failure. The Workers types document setReject as a permanent SMTP error only, so 5xx/429/timeouts bounce with "Temporary failure, please retry" rather than being retried by the sender's MTA. API: - Ingress body limit is 16 MB for POST /v1/inboxes/{address}/emails with a valid worker secret (attachments are base64-encoded into one JSON body, so 10 MB of raw mail always 413'd); other routes stay at 10 MB. Chunked ingress bodies get 411. Test asserts the handler does not run after a 413. - SseManager drops the oldest event instead of suspending, so a stalled SSE client can no longer block ingest. SSE streams send a keepalive comment every 25s and close when the session has expired. - TursoClient retries network errors, timeouts, 5xx and 429 (3 attempts, 200ms/600ms backoff), never 4xx; request timeout 30s -> 10s; empty responses raise a clear error instead of NoSuchElementException. - /health is SELECT 1 only and returns {status}; the unauthenticated COUNT(*) stats are removed (nothing in web/ or cli/ reads them). /livez returns 200 without touching the DB. - Attachments are decoded and validated before the email row is inserted, so bad base64 no longer leaves an orphan row. - Decrypt failures log at ERROR and return a placeholder body (or fail the attachment download) instead of returning ciphertext. --- .../dev/bmcreations/blip/server/CoreModule.kt | 39 +++++++- .../bmcreations/blip/server/db/TursoClient.kt | 55 ++++++++--- .../blip/server/routes/HealthRoutes.kt | 86 +++--------------- .../blip/server/routes/SseRoutes.kt | 49 +++++++++- .../blip/server/services/EmailService.kt | 91 +++++++++++++------ .../bmcreations/blip/server/sse/SseManager.kt | 12 ++- .../bmcreations/blip/server/BodyLimitTest.kt | 50 ++++++++++ .../blip/server/db/TursoClientRetryTest.kt | 58 ++++++++++++ .../blip/server/routes/HealthRoutesTest.kt | 22 ++++- .../blip/server/services/EmailServiceTest.kt | 13 +++ .../blip/server/sse/SseManagerTest.kt | 14 +++ workers/email-ingress/src/index.ts | 49 +++++++--- 12 files changed, 392 insertions(+), 146 deletions(-) create mode 100644 server/core/src/test/kotlin/dev/bmcreations/blip/server/BodyLimitTest.kt create mode 100644 server/core/src/test/kotlin/dev/bmcreations/blip/server/db/TursoClientRetryTest.kt diff --git a/server/core/src/main/kotlin/dev/bmcreations/blip/server/CoreModule.kt b/server/core/src/main/kotlin/dev/bmcreations/blip/server/CoreModule.kt index 309baad..ad7f215 100644 --- a/server/core/src/main/kotlin/dev/bmcreations/blip/server/CoreModule.kt +++ b/server/core/src/main/kotlin/dev/bmcreations/blip/server/CoreModule.kt @@ -48,11 +48,40 @@ data class CoreServices( val cleanupService: CleanupService, ) -private val RequestBodyLimit = createApplicationPlugin("RequestBodyLimit") { +private const val DEFAULT_BODY_LIMIT = 10L * 1024 * 1024 + +// The email worker base64-encodes attachments into one JSON body (~4/3 growth), +// and PRO allows 10 MB attachments, so the ingress route needs a larger cap. +private const val INGRESS_BODY_LIMIT = 16L * 1024 * 1024 + +private val IngressPath = Regex("^/v1/inboxes/[^/]+/emails/?$") + +private fun isIngressRequest(call: ApplicationCall, workerSecret: String): Boolean { + if (call.request.httpMethod != HttpMethod.Post) return false + if (!IngressPath.matches(call.request.path())) return false + val provided = call.request.headers["X-Worker-Secret"] ?: return false + return java.security.MessageDigest.isEqual(provided.toByteArray(), workerSecret.toByteArray()) +} + +internal class RequestBodyLimitConfig { + var workerSecret: String = "" +} + +internal val RequestBodyLimit = createApplicationPlugin("RequestBodyLimit", ::RequestBodyLimitConfig) { + val workerSecret = pluginConfig.workerSecret onCall { call -> + val ingress = isIngressRequest(call, workerSecret) + val limit = if (ingress) INGRESS_BODY_LIMIT else DEFAULT_BODY_LIMIT val contentLength = call.request.header(HttpHeaders.ContentLength)?.toLongOrNull() - if (contentLength != null && contentLength > 10 * 1024 * 1024) { - call.respond(HttpStatusCode.PayloadTooLarge, ErrorResponse("payload_too_large", "Request body too large")) + val chunked = call.request.header(HttpHeaders.TransferEncoding) + ?.contains("chunked", ignoreCase = true) == true + when { + contentLength != null && contentLength > limit -> + call.respond(HttpStatusCode.PayloadTooLarge, ErrorResponse("payload_too_large", "Request body too large")) + // A chunked body has no declared size, so the limit can't be enforced up front. + // Only the ingress route is stricter; other routes keep accepting small chunked bodies. + ingress && contentLength == null && chunked -> + call.respond(HttpStatusCode.LengthRequired, ErrorResponse("length_required", "Content-Length required")) } } } @@ -80,7 +109,9 @@ fun Application.coreModule(config: CoreConfig): CoreServices { val webhookService = WebhookService(turso, encryptionService = encryptionService, inboxService = inboxService) val cleanupService = CleanupService(turso, webhookService, sseManager, config.cleanupContributors) - install(RequestBodyLimit) + install(RequestBodyLimit) { + workerSecret = config.workerSecret + } install(ContentNegotiation) { json(json) diff --git a/server/core/src/main/kotlin/dev/bmcreations/blip/server/db/TursoClient.kt b/server/core/src/main/kotlin/dev/bmcreations/blip/server/db/TursoClient.kt index 70dd725..efddf34 100644 --- a/server/core/src/main/kotlin/dev/bmcreations/blip/server/db/TursoClient.kt +++ b/server/core/src/main/kotlin/dev/bmcreations/blip/server/db/TursoClient.kt @@ -8,7 +8,10 @@ import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.serialization.kotlinx.json.* +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay import kotlinx.serialization.Serializable +import java.io.IOException import kotlinx.serialization.json.* class TursoClient( @@ -21,16 +24,19 @@ class TursoClient( json(json) } install(HttpTimeout) { - requestTimeoutMillis = 30_000 + requestTimeoutMillis = 10_000 connectTimeoutMillis = 10_000 } } + private val logger = org.slf4j.LoggerFactory.getLogger(TursoClient::class.java) + private val pipelineUrl = "$baseUrl/v2/pipeline" suspend fun execute(sql: String, args: List = emptyList()): TursoResult { val results = executeBatch(listOf(Statement(sql, args))) - return results.first() + return results.firstOrNull() + ?: throw RuntimeException("Turso returned no result for statement") } suspend fun executeBatch(statements: List): List { @@ -59,20 +65,9 @@ class TursoClient( } } - val response = client.post(pipelineUrl) { - contentType(ContentType.Application.Json) - if (authToken.isNotBlank()) { - header("Authorization", "Bearer $authToken") - } - setBody(body.toString()) - } - - if (response.status != HttpStatusCode.OK) { - val text = response.bodyAsText() - throw RuntimeException("Turso error ${response.status}: $text") - } + val responseText = postWithRetry(body.toString()) - val responseJson = json.parseToJsonElement(response.bodyAsText()).jsonObject + val responseJson = json.parseToJsonElement(responseText).jsonObject val results = responseJson["results"]?.jsonArray ?: return emptyList() return results.mapNotNull { result -> @@ -93,6 +88,34 @@ class TursoClient( } } + /** Retries network errors, timeouts, 5xx and 429; any other status fails immediately. */ + private suspend fun postWithRetry(body: String): String { + var lastError: Exception? = null + for (attempt in 0 until RETRY_DELAYS_MS.size + 1) { + if (attempt > 0) delay(RETRY_DELAYS_MS[attempt - 1]) + try { + val response = client.post(pipelineUrl) { + contentType(ContentType.Application.Json) + if (authToken.isNotBlank()) { + header("Authorization", "Bearer $authToken") + } + setBody(body) + } + if (response.status == HttpStatusCode.OK) return response.bodyAsText() + val error = RuntimeException("Turso error ${response.status}: ${response.bodyAsText()}") + val retryable = response.status.value >= 500 || response.status == HttpStatusCode.TooManyRequests + if (!retryable) throw error + lastError = error + } catch (e: CancellationException) { + throw e + } catch (e: IOException) { // includes Ktor request/connect/socket timeouts + lastError = e + } + logger.warn("Turso request failed (attempt {}/{}): {}", attempt + 1, RETRY_DELAYS_MS.size + 1, lastError?.message) + } + throw lastError!! + } + private fun parseResult(result: JsonObject?): TursoResult { if (result == null) return TursoResult(emptyList(), emptyList(), 0, 0) @@ -125,6 +148,8 @@ class TursoClient( } } +private val RETRY_DELAYS_MS = listOf(200L, 600L) + data class Statement(val sql: String, val args: List = emptyList()) data class TursoResult( diff --git a/server/core/src/main/kotlin/dev/bmcreations/blip/server/routes/HealthRoutes.kt b/server/core/src/main/kotlin/dev/bmcreations/blip/server/routes/HealthRoutes.kt index b249a5a..0da321e 100644 --- a/server/core/src/main/kotlin/dev/bmcreations/blip/server/routes/HealthRoutes.kt +++ b/server/core/src/main/kotlin/dev/bmcreations/blip/server/routes/HealthRoutes.kt @@ -5,90 +5,28 @@ import io.ktor.http.* import io.ktor.server.response.* import io.ktor.server.routing.* import kotlinx.serialization.Serializable -import java.lang.management.ManagementFactory @Serializable -data class HealthResponse( - val status: String, - val uptime: String, - val db: DbHealth, - val stats: Stats? = null, -) - -@Serializable -data class DbHealth( - val connected: Boolean, - val latencyMs: Long, -) - -@Serializable -data class Stats( - val activeSessions: Long, - val activeInboxes: Long, - val emailsLast24h: Long, -) +data class HealthResponse(val status: String) fun Route.healthRoutes(turso: TursoClient) { - get("/health") { - val uptime = ManagementFactory.getRuntimeMXBean().uptime - val uptimeStr = formatUptime(uptime) + // Liveness: no dependencies, so a database outage doesn't get the process restarted. + get("/livez") { + call.respond(HttpStatusCode.OK, HealthResponse("ok")) + } - // Check DB connectivity and latency - val dbStart = System.currentTimeMillis() + // Readiness: one trivial query. Public, so it returns no counts or timings. + get("/health") { val dbConnected = try { turso.execute("SELECT 1", emptyList()) true } catch (_: Exception) { false } - val dbLatency = System.currentTimeMillis() - dbStart - - val stats = if (dbConnected) { - try { - val now = java.time.Instant.now().toString() - val dayAgo = java.time.Instant.now().minus(java.time.Duration.ofHours(24)).toString() - - val sessions = turso.execute( - "SELECT COUNT(*) as cnt FROM sessions WHERE expires_at > ?", - listOf(dev.bmcreations.blip.server.db.TursoValue.Text(now)) - ).firstOrNull()?.get("cnt")?.toLongOrNull() ?: 0 - - val inboxes = turso.execute( - "SELECT COUNT(*) as cnt FROM inboxes WHERE expires_at > ?", - listOf(dev.bmcreations.blip.server.db.TursoValue.Text(now)) - ).firstOrNull()?.get("cnt")?.toLongOrNull() ?: 0 - - val emails = turso.execute( - "SELECT COUNT(*) as cnt FROM emails WHERE received_at > ?", - listOf(dev.bmcreations.blip.server.db.TursoValue.Text(dayAgo)) - ).firstOrNull()?.get("cnt")?.toLongOrNull() ?: 0 - - Stats(activeSessions = sessions, activeInboxes = inboxes, emailsLast24h = emails) - } catch (_: Exception) { - null - } - } else null - - val status = if (dbConnected) "ok" else "degraded" - val httpStatus = if (dbConnected) HttpStatusCode.OK else HttpStatusCode.ServiceUnavailable - - call.respond(httpStatus, HealthResponse( - status = status, - uptime = uptimeStr, - db = DbHealth(connected = dbConnected, latencyMs = dbLatency), - stats = stats, - )) - } -} - -private fun formatUptime(millis: Long): String { - val seconds = millis / 1000 - val days = seconds / 86400 - val hours = (seconds % 86400) / 3600 - val minutes = (seconds % 3600) / 60 - return when { - days > 0 -> "${days}d ${hours}h ${minutes}m" - hours > 0 -> "${hours}h ${minutes}m" - else -> "${minutes}m" + if (dbConnected) { + call.respond(HttpStatusCode.OK, HealthResponse("ok")) + } else { + call.respond(HttpStatusCode.ServiceUnavailable, HealthResponse("degraded")) + } } } diff --git a/server/core/src/main/kotlin/dev/bmcreations/blip/server/routes/SseRoutes.kt b/server/core/src/main/kotlin/dev/bmcreations/blip/server/routes/SseRoutes.kt index d2ced7e..1a19666 100644 --- a/server/core/src/main/kotlin/dev/bmcreations/blip/server/routes/SseRoutes.kt +++ b/server/core/src/main/kotlin/dev/bmcreations/blip/server/routes/SseRoutes.kt @@ -1,5 +1,7 @@ package dev.bmcreations.blip.server.routes +import dev.bmcreations.blip.models.EmailSummary +import dev.bmcreations.blip.server.UnauthorizedException import dev.bmcreations.blip.server.services.InboxService import dev.bmcreations.blip.server.services.SessionService import dev.bmcreations.blip.server.sse.SseManager @@ -7,13 +9,26 @@ import io.ktor.http.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.utils.io.* +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.merge import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json +const val SSE_HEARTBEAT_MILLIS = 25_000L + +private sealed interface SseEvent { + data class Email(val summary: EmailSummary) : SseEvent + data object Heartbeat : SseEvent +} + fun Route.sseRoutes( sseManager: SseManager, sessionService: SessionService, inboxService: InboxService, + heartbeatMillis: Long = SSE_HEARTBEAT_MILLIS, ) { get("/v1/inboxes/{id}/sse") { // Support token via query param for EventSource (can't set headers) @@ -30,9 +45,37 @@ fun Route.sseRoutes( writeStringUtf8("event: connected\ndata: {}\n\n") flush() - sseManager.subscribe(inboxId).collect { email -> - val data = Json.encodeToString(email) - writeStringUtf8("event: email\ndata: $data\n\n") + val events = sseManager.subscribe(inboxId).map { SseEvent.Email(it) } + val heartbeats = flow { + while (true) { + delay(heartbeatMillis) + emit(SseEvent.Heartbeat) + } + } + + // A single collector writes both streams, so writes never interleave. + merge(events, heartbeats).collect { event -> + when (event) { + is SseEvent.Email -> { + val data = Json.encodeToString(event.summary) + writeStringUtf8("event: email\ndata: $data\n\n") + } + SseEvent.Heartbeat -> { + // Re-check expiry so an expired session doesn't keep a stream open. + // Failures other than an auth rejection (e.g. a transient DB error) keep the stream. + val stillValid = try { + sessionService.getSessionByToken(token ?: "") + true + } catch (_: UnauthorizedException) { + false + } catch (_: Exception) { + true + } + if (!stillValid) throw CancellationException("Session expired") + // Comment line keeps idle connections open through proxies. + writeStringUtf8(": keepalive\n\n") + } + } flush() } } diff --git a/server/core/src/main/kotlin/dev/bmcreations/blip/server/services/EmailService.kt b/server/core/src/main/kotlin/dev/bmcreations/blip/server/services/EmailService.kt index 66e1a36..8cb9e59 100644 --- a/server/core/src/main/kotlin/dev/bmcreations/blip/server/services/EmailService.kt +++ b/server/core/src/main/kotlin/dev/bmcreations/blip/server/services/EmailService.kt @@ -10,6 +10,13 @@ import kotlinx.serialization.json.Json import java.time.Instant import java.util.UUID +private class DecodedAttachment( + val name: String, + val contentType: String, + val base64: String, + val bytes: ByteArray, +) + class EmailService( private val turso: TursoClient, private val sseManager: SseManager, @@ -47,6 +54,23 @@ class EmailService( encryptionService.encrypt(htmlBody, encryptionKey) } else htmlBody + // Decode and validate attachments before touching the database, so bad base64 + // fails the request without leaving an orphan email row behind. + val attachments = if (stripAttachments) emptyList() else request.attachments.mapNotNull { att -> + val decoded = try { + java.util.Base64.getDecoder().decode(att.contentBase64) + } catch (e: IllegalArgumentException) { + throw IllegalArgumentException("Attachment '${att.name}' is not valid base64") + } + if (maxAttachmentBytes > 0 && decoded.size > maxAttachmentBytes) { + logger.warn( + "Skipping oversized attachment '{}' ({} bytes, limit {} bytes) on email {}", + att.name, decoded.size, maxAttachmentBytes, emailId + ) + null + } else DecodedAttachment(att.name, att.contentType, att.contentBase64, decoded) + } + turso.execute( """ INSERT INTO emails (id, inbox_id, from_addr, to_addr, subject, text_body, html_body, headers, received_at, preview) @@ -67,34 +91,24 @@ class EmailService( ) // Store attachments (unless stripped for FREE tier) - if (!stripAttachments) { - for (att in request.attachments) { - val attId = UUID.randomUUID().toString() - val decoded = java.util.Base64.getDecoder().decode(att.contentBase64) - if (maxAttachmentBytes > 0 && decoded.size > maxAttachmentBytes) { - logger.warn( - "Skipping oversized attachment '{}' ({} bytes, limit {} bytes) on email {}", - att.name, decoded.size, maxAttachmentBytes, emailId - ) - continue - } - val storedData = if (encryptionKey != null) { - java.util.Base64.getEncoder().encodeToString( - encryptionService.encryptBytes(decoded, encryptionKey) - ) - } else att.contentBase64 - turso.execute( - "INSERT INTO attachments (id, email_id, name, content_type, size, data) VALUES (?, ?, ?, ?, ?, ?)", - listOf( - TursoValue.Text(attId), - TursoValue.Text(emailId), - TursoValue.Text(att.name), - TursoValue.Text(att.contentType), - TursoValue.Integer(decoded.size.toLong()), - TursoValue.Blob(storedData), - ) + for (att in attachments) { + val attId = UUID.randomUUID().toString() + val storedData = if (encryptionKey != null) { + java.util.Base64.getEncoder().encodeToString( + encryptionService.encryptBytes(att.bytes, encryptionKey) ) - } + } else att.base64 + turso.execute( + "INSERT INTO attachments (id, email_id, name, content_type, size, data) VALUES (?, ?, ?, ?, ?, ?)", + listOf( + TursoValue.Text(attId), + TursoValue.Text(emailId), + TursoValue.Text(att.name), + TursoValue.Text(att.contentType), + TursoValue.Integer(att.bytes.size.toLong()), + TursoValue.Blob(storedData), + ) + ) } val summary = EmailSummary( @@ -111,6 +125,14 @@ class EmailService( return summary } + private fun decryptOrPlaceholder(raw: String, key: String, emailId: String, part: String): String = + try { + encryptionService.decrypt(raw, key) + } catch (e: Exception) { + logger.error("Failed to decrypt {} body of email {}", part, emailId, e) + DECRYPT_FAILED_PLACEHOLDER + } + suspend fun getEmail(emailId: String): EmailDetail { val row = turso.execute( "SELECT * FROM emails WHERE id = ?", @@ -140,12 +162,12 @@ class EmailService( val encryptionKey = inboxService?.getEncryptionKey(row["inbox_id"]!!) val textBody = row["text_body"]?.let { raw -> if (encryptionKey != null) { - try { encryptionService.decrypt(raw, encryptionKey) } catch (_: Exception) { raw } + decryptOrPlaceholder(raw, encryptionKey, emailId, "text") } else raw } val htmlBody = row["html_body"]?.let { raw -> if (encryptionKey != null) { - try { encryptionService.decrypt(raw, encryptionKey) } catch (_: Exception) { raw } + decryptOrPlaceholder(raw, encryptionKey, emailId, "html") } else raw } @@ -190,7 +212,12 @@ class EmailService( // Decrypt if encryption key is available val encryptionKey = inboxId?.let { inboxService?.getEncryptionKey(it) } val decrypted = if (encryptionKey != null) { - try { encryptionService.decryptBytes(bytes, encryptionKey) } catch (_: Exception) { bytes } + try { + encryptionService.decryptBytes(bytes, encryptionKey) + } catch (e: Exception) { + logger.error("Failed to decrypt attachment '{}' on email {}", name, emailId, e) + throw IllegalStateException("Attachment could not be decrypted") + } } else bytes return contentType to decrypted @@ -212,4 +239,8 @@ class EmailService( ).firstOrNull() ?: throw NotFoundException("Email not found") return row["inbox_id"]!! } + + private companion object { + const val DECRYPT_FAILED_PLACEHOLDER = "[This message could not be decrypted]" + } } diff --git a/server/core/src/main/kotlin/dev/bmcreations/blip/server/sse/SseManager.kt b/server/core/src/main/kotlin/dev/bmcreations/blip/server/sse/SseManager.kt index b102bb6..50b6f1d 100644 --- a/server/core/src/main/kotlin/dev/bmcreations/blip/server/sse/SseManager.kt +++ b/server/core/src/main/kotlin/dev/bmcreations/blip/server/sse/SseManager.kt @@ -1,6 +1,7 @@ package dev.bmcreations.blip.server.sse import dev.bmcreations.blip.models.EmailSummary +import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.* import java.util.concurrent.ConcurrentHashMap @@ -11,13 +12,18 @@ class SseManager { return getOrCreateFlow(inboxId).asSharedFlow() } - suspend fun publish(inboxId: String, email: EmailSummary) { - getOrCreateFlow(inboxId).emit(email) + /** Never suspends: a slow subscriber loses its oldest events instead of blocking ingest. */ + fun publish(inboxId: String, email: EmailSummary) { + getOrCreateFlow(inboxId).tryEmit(email) } private fun getOrCreateFlow(inboxId: String): MutableSharedFlow { return flows.getOrPut(inboxId) { - MutableSharedFlow(replay = 0, extraBufferCapacity = 64) + MutableSharedFlow( + replay = 0, + extraBufferCapacity = 64, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) } } diff --git a/server/core/src/test/kotlin/dev/bmcreations/blip/server/BodyLimitTest.kt b/server/core/src/test/kotlin/dev/bmcreations/blip/server/BodyLimitTest.kt new file mode 100644 index 0000000..1de01b4 --- /dev/null +++ b/server/core/src/test/kotlin/dev/bmcreations/blip/server/BodyLimitTest.kt @@ -0,0 +1,50 @@ +package dev.bmcreations.blip.server + +import io.ktor.client.request.* +import io.ktor.client.statement.* +import io.ktor.http.* +import io.ktor.serialization.kotlinx.json.* +import io.ktor.server.application.* +import io.ktor.server.response.* +import io.ktor.server.routing.* +import io.ktor.server.testing.* +import kotlin.test.* + +class BodyLimitTest { + + private val secret = "s3cret" + private var handlerCalls = 0 + + private fun ApplicationTestBuilder.setup() { + application { + install(io.ktor.server.plugins.contentnegotiation.ContentNegotiation) { json() } + install(RequestBodyLimit) { workerSecret = secret } + routing { + post("/v1/inboxes/{address}/emails") { handlerCalls++; call.respond(HttpStatusCode.OK) } + post("/other") { handlerCalls++; call.respond(HttpStatusCode.OK) } + } + } + } + + private fun HttpRequestBuilder.sized(bytes: Long, withSecret: Boolean) { + if (withSecret) header("X-Worker-Secret", secret) + setBody(ByteArray(bytes.toInt())) + } + + @Test + fun `ingress route with worker secret accepts up to 16 MB`() = testApplication { + setup() + val ok = client.post("/v1/inboxes/a@b.c/emails") { sized(12L shl 20, true) } + assertEquals(HttpStatusCode.OK, ok.status) + val tooBig = client.post("/v1/inboxes/a@b.c/emails") { sized(17L shl 20, true) } + assertEquals(HttpStatusCode.PayloadTooLarge, tooBig.status) + } + + @Test + fun `other routes and ingress without secret stay at 10 MB and handler is not run`() = testApplication { + setup() + assertEquals(HttpStatusCode.PayloadTooLarge, client.post("/other") { sized(12L shl 20, true) }.status) + assertEquals(HttpStatusCode.PayloadTooLarge, client.post("/v1/inboxes/a@b.c/emails") { sized(12L shl 20, false) }.status) + assertEquals(0, handlerCalls, "handler must not run after the limit response") + } +} diff --git a/server/core/src/test/kotlin/dev/bmcreations/blip/server/db/TursoClientRetryTest.kt b/server/core/src/test/kotlin/dev/bmcreations/blip/server/db/TursoClientRetryTest.kt new file mode 100644 index 0000000..42839e2 --- /dev/null +++ b/server/core/src/test/kotlin/dev/bmcreations/blip/server/db/TursoClientRetryTest.kt @@ -0,0 +1,58 @@ +package dev.bmcreations.blip.server.db + +import com.sun.net.httpserver.HttpServer +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import java.net.InetSocketAddress +import java.util.concurrent.atomic.AtomicInteger +import kotlin.test.* + +class TursoClientRetryTest { + + private val okBody = + """{"results":[{"type":"ok","response":{"type":"execute","result":{"cols":[{"name":"x"}],"rows":[[{"type":"integer","value":"1"}]],"affected_row_count":0,"last_insert_rowid":null}}}]}""" + + private fun server(statuses: List, hits: AtomicInteger): HttpServer = + HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/v2/pipeline") { ex -> + val status = statuses[minOf(hits.getAndIncrement(), statuses.size - 1)] + val bytes = (if (status == 200) okBody else "err").toByteArray() + ex.sendResponseHeaders(status, bytes.size.toLong()) + ex.responseBody.use { it.write(bytes) } + } + start() + } + + private fun client(s: HttpServer) = + TursoClient("http://127.0.0.1:${s.address.port}", "", Json { ignoreUnknownKeys = true }) + + @Test + fun `retries 5xx and 429 then succeeds`() = runTest { + val hits = AtomicInteger() + val s = server(listOf(503, 429, 200), hits) + try { + assertEquals("1", client(s).execute("SELECT 1").firstOrNull()?.get("x")) + assertEquals(3, hits.get()) + } finally { s.stop(0) } + } + + @Test + fun `does not retry 4xx`() = runTest { + val hits = AtomicInteger() + val s = server(listOf(400), hits) + try { + assertFailsWith { client(s).execute("SELECT 1") } + assertEquals(1, hits.get()) + } finally { s.stop(0) } + } + + @Test + fun `gives up after three attempts on persistent 5xx`() = runTest { + val hits = AtomicInteger() + val s = server(listOf(500), hits) + try { + assertFailsWith { client(s).execute("SELECT 1") } + assertEquals(3, hits.get()) + } finally { s.stop(0) } + } +} diff --git a/server/core/src/test/kotlin/dev/bmcreations/blip/server/routes/HealthRoutesTest.kt b/server/core/src/test/kotlin/dev/bmcreations/blip/server/routes/HealthRoutesTest.kt index 76319e7..929a8d7 100644 --- a/server/core/src/test/kotlin/dev/bmcreations/blip/server/routes/HealthRoutesTest.kt +++ b/server/core/src/test/kotlin/dev/bmcreations/blip/server/routes/HealthRoutesTest.kt @@ -33,9 +33,25 @@ class HealthRoutesTest { assertEquals(HttpStatusCode.OK, response.status) val body = response.bodyAsText() assertTrue(body.contains("\"ok\""), "Should report ok status") - assertTrue(body.contains("\"uptime\""), "Should include uptime") - assertTrue(body.contains("\"db\""), "Should include db health") - assertTrue(body.contains("\"stats\""), "Should include stats") + assertFalse(body.contains("stats"), "Public health must not expose counts") + coVerify(exactly = 1) { turso.execute("SELECT 1", emptyList()) } + } + + @Test + fun `GET livez returns 200 without touching the db`() = testApplication { + val turso = mockk() + + install(ContentNegotiation) { + json(Json { ignoreUnknownKeys = true; encodeDefaults = true }) + } + routing { + healthRoutes(turso) + } + + val response = client.get("/livez") + + assertEquals(HttpStatusCode.OK, response.status) + confirmVerified(turso) } @Test diff --git a/server/core/src/test/kotlin/dev/bmcreations/blip/server/services/EmailServiceTest.kt b/server/core/src/test/kotlin/dev/bmcreations/blip/server/services/EmailServiceTest.kt index 7309a12..2a65df5 100644 --- a/server/core/src/test/kotlin/dev/bmcreations/blip/server/services/EmailServiceTest.kt +++ b/server/core/src/test/kotlin/dev/bmcreations/blip/server/services/EmailServiceTest.kt @@ -110,6 +110,19 @@ class EmailServiceTest { } } + @Test + fun `ingestEmail rejects invalid base64 before inserting the email row`() = runTest { + stubInsertEmail() + stubSsePublish() + + val request = simpleEmailRequest( + attachments = listOf(IngressAttachment(name = "bad.bin", contentType = "application/octet-stream", contentBase64 = "!!not base64!!")) + ) + + assertFailsWith { service.ingestEmail(inboxId, request) } + coVerify(exactly = 0) { turso.execute(match { it.contains("INSERT INTO emails") }, any()) } + } + @Test fun `ingestEmail stores attachments`() = runTest { stubInsertEmail() diff --git a/server/core/src/test/kotlin/dev/bmcreations/blip/server/sse/SseManagerTest.kt b/server/core/src/test/kotlin/dev/bmcreations/blip/server/sse/SseManagerTest.kt index 07f389b..a79053b 100644 --- a/server/core/src/test/kotlin/dev/bmcreations/blip/server/sse/SseManagerTest.kt +++ b/server/core/src/test/kotlin/dev/bmcreations/blip/server/sse/SseManagerTest.kt @@ -81,4 +81,18 @@ class SseManagerTest { assertEquals(1, received1.size) assertEquals(1, received2.size) } + + @Test + fun `publish does not suspend when a subscriber is stalled`() = runTest { + val gate = CompletableDeferred() + val received = mutableListOf() + val job = launch(UnconfinedTestDispatcher()) { + sseManager.subscribe("inbox-1").collect { gate.await(); received += it.id } + } + yield() + // Far more than the 64-slot buffer; a SUSPEND policy would hang here. + repeat(500) { sseManager.publish("inbox-1", email("e$it")) } + gate.complete(Unit) + job.cancel() + } } diff --git a/workers/email-ingress/src/index.ts b/workers/email-ingress/src/index.ts index 7573bbf..27f777c 100644 --- a/workers/email-ingress/src/index.ts +++ b/workers/email-ingress/src/index.ts @@ -5,6 +5,8 @@ interface Env { WORKER_SECRET: string; } +const FETCH_TIMEOUT_MS = 25_000; + export default { async email(message: ForwardableEmailMessage, env: Env): Promise { const rawEmail = await new Response(message.raw).arrayBuffer(); @@ -18,7 +20,10 @@ export default { const address = to.toLowerCase(); const attachments = (parsed.attachments || []).map((att) => { - const bytes = new Uint8Array(att.content); + const bytes = + typeof att.content === 'string' + ? new TextEncoder().encode(att.content) + : new Uint8Array(att.content); let binary = ''; for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]); @@ -49,20 +54,36 @@ export default { const apiUrl = `${env.API_BASE_URL}/v1/inboxes/${encodeURIComponent(address)}/emails`; - const response = await fetch(apiUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Worker-Secret': env.WORKER_SECRET, - }, - body: JSON.stringify(payload), - }); + let response: Response; + try { + response = await fetch(apiUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Worker-Secret': env.WORKER_SECRET, + }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + } catch (err) { + // Timeout or network failure: the API may or may not have stored the email. + console.error(`API request failed for ${address}: ${err}`); + message.setReject('Temporary failure, please retry'); + return; + } + + if (response.ok) return; + + const body = await response.text().catch(() => ''); + console.error(`API error ${response.status} for ${address}: ${body}`); - if (!response.ok) { - const body = await response.text(); - console.error(`API error ${response.status}: ${body}`); - // Don't throw - we don't want Cloudflare to retry and create duplicates - // The email is simply dropped if the inbox doesn't exist + // setReject() always produces a permanent (5xx) SMTP rejection; the Workers + // API has no temporary-failure variant. Rejecting still beats the previous + // behaviour of accepting and silently dropping the message. + if (response.status >= 500 || response.status === 429) { + message.setReject('Temporary failure, please retry'); + } else { + message.setReject(`Message rejected: ${response.status}`); } }, } satisfies ExportedHandler;