Short refusal snack, stop a delete on a refused principal, sturdier URL comparison (#180)

This commit is contained in:
makiolaj committed 2026-11-25 15:43:12 +01:00
1 parent 4201ef6abe
commit f6c7e3a385
7 files changed
+75 -16

No files matched your search

@@ -14,6 +14,7 @@ import de.jeanlucmakiola.caldav.CollectionAdmin
import de.jeanlucmakiola.caldav.CollectionOutcome
import de.jeanlucmakiola.caldav.CollectionSupport
import de.jeanlucmakiola.caldav.DavCollectionAdmin
import de.jeanlucmakiola.caldav.HomeSets
import de.jeanlucmakiola.caldav.ResourceNames
import de.jeanlucmakiola.caldav.ServerTrust
import kotlinx.coroutines.CoroutineDispatcher
@@ -211,9 +212,12 @@ class RemoteListRepository @Inject constructor(
// Only the first home set is stored, so the others are asked for. A
// principal that does not answer leaves the stored check above as the
// guard, rather than blocking every delete on this account (#180).
val homeSets = account.principalUrl?.toHttpUrlOrNull()?.let(admin::homeSets).orEmpty()
if (homeSets.any { CollectionHref.same(it.toString(), list.href) }) {
return@withContext Outcome.AccountHome
when (val homeSets = account.principalUrl?.toHttpUrlOrNull()?.let(admin::homeSets)) {
is HomeSets.Listed -> if (homeSets.urls.any { CollectionHref.same(it.toString(), list.href) }) {
return@withContext Outcome.AccountHome
}
is HomeSets.Refused -> return@withContext Outcome.Refused(homeSets.code)
HomeSets.Unknown, null -> Unit
}
when (val outcome = admin.delete(url)) {
@@ -1,6 +1,7 @@
package de.jeanlucmakiola.agendula.data
import java.net.URI
import java.util.concurrent.ConcurrentHashMap
/** Compares collection URLs the way a server means them, not the way it spells them. */
object CollectionHref {
@@ -11,18 +12,37 @@ object CollectionHref {
return key(a) == key(b)
}
private fun key(href: String): String = runCatching {
val uri = URI(URI(href).toASCIIString())
/** Memoised: the lists flow maps every row on every sync, and hrefs rarely change. */
private fun key(href: String): String {
keys[href]?.let { return it }
if (keys.size > MAX_CACHED) keys.clear()
return parse(href).also { keys[href] = it }
}
private fun parse(href: String): String = runCatching {
val uri = URI(URI(escapePath(href)).toASCIIString())
val scheme = uri.scheme.lowercase()
val host = (uri.host ?: uri.rawAuthority.substringAfterLast('@').substringBeforeLast(':')).lowercase()
val authority = uri.rawAuthority.substringAfterLast('@')
val host = (uri.host ?: authority.substringBeforeLast(':')).lowercase()
val explicitPort = if (uri.host != null) uri.port else authority.substringAfterLast(':', "").toIntOrNull() ?: -1
val port = when {
uri.port != -1 -> uri.port
explicitPort != -1 -> explicitPort
scheme == "https" -> HTTPS_PORT
scheme == "http" -> HTTP_PORT
else -> -1
}
"$scheme://$host:$port${normalizeEscapes(uri.rawPath.orEmpty()).trimEnd('/')}"
}.getOrElse { href.trimEnd('/') }
}.getOrElse { href.lowercase().trimEnd('/') }
/** Escapes what servers leave raw in paths but [URI] refuses, such as `[` and a space. */
private fun escapePath(href: String): String {
val pathStart = href.indexOf('/', href.indexOf("://").let { if (it < 0) 0 else it + SCHEME_SEPARATOR })
if (pathStart < 0) return href
val path = href.substring(pathStart).map { c ->
if (c in UNSAFE) "%" + c.code.toString(HEX).uppercase().padStart(2, '0') else c.toString()
}
return href.substring(0, pathStart) + path.joinToString("")
}
/** Decodes escaped ASCII but `%2F`, which is part of a segment, not a separator. */
private fun normalizeEscapes(path: String): String = ESCAPE.replace(path) { match ->
@@ -30,7 +50,11 @@ object CollectionHref {
if (code == '/'.code || code >= ASCII_END) match.value.uppercase() else code.toChar().toString()
}
private val keys = ConcurrentHashMap<String, String>()
private val ESCAPE = Regex("%([0-9A-Fa-f]{2})")
private const val UNSAFE = " \"<>[]\\^`{|}"
private const val SCHEME_SEPARATOR = 3
private const val MAX_CACHED = 512
private const val HEX = 16
private const val ASCII_END = 0x80
private const val HTTPS_PORT = 443
@@ -260,7 +260,7 @@ internal fun listWriteFailureMessage(failure: ListWriteFailure): Int = when (fai
ListWriteFailure.OFFLINE -> R.string.list_save_failed_offline
ListWriteFailure.READ_ONLY -> R.string.list_save_failed_read_only
ListWriteFailure.UNSUPPORTED -> R.string.list_save_failed_unsupported
ListWriteFailure.ACCOUNT_HOME -> R.string.list_delete_account_home
ListWriteFailure.ACCOUNT_HOME -> R.string.list_delete_failed_account_home
}
@Composable
+1
View File
@@ -325,6 +325,7 @@
<string name="list_delete">Delete list</string>
<string name="list_save_failed">Could not save the list.</string>
<string name="list_delete_failed">Could not delete the list.</string>
<string name="list_delete_failed_account_home">That list is the account\u2019s calendar itself.</string>
<string name="list_delete_account_home">This list is the account’s calendar itself, so it can’t be deleted here. Deleting it would also delete the calendar’s events.</string>
<string name="list_delete_confirm_title">Delete list?</string>
<string name="list_where">Where</string>
@@ -19,6 +19,8 @@ class CollectionHrefTest {
assertThat(CollectionHref.same("https://h.example/kalender/gr%C3%BCn/", "https://h.example/kalender/grün")).isTrue()
assertThat(CollectionHref.same("https://h.example/cal/[1]/", "https://h.example/cal/[1]")).isTrue()
assertThat(CollectionHref.same("https://h.example/cal/a%2Fb/", "https://h.example/cal/a/b/")).isFalse()
assertThat(CollectionHref.same("https://my_server.lan:8443/cal/1/", "https://my_server.lan/cal/1/")).isFalse()
assertThat(CollectionHref.same("https://h.example/cal/[1]/", "https://H.example/cal/%5B1%5D")).isTrue()
}
@Test
@@ -5,6 +5,7 @@ import at.bitfire.dav4jvm.Property
import at.bitfire.dav4jvm.Response
import at.bitfire.dav4jvm.XmlUtils
import at.bitfire.dav4jvm.XmlUtils.insertTag
import at.bitfire.dav4jvm.exception.HttpException
import at.bitfire.dav4jvm.property.ResourceType
import okhttp3.HttpUrl
import okhttp3.MediaType.Companion.toMediaType
@@ -96,8 +97,19 @@ interface CollectionAdmin {
/** DELETE. The tasks go with it, on the server and everywhere else. */
fun delete(url: HttpUrl): CollectionOutcome
/** The `calendar-home-set` hrefs [principal] reports now, or null when it did not answer. */
fun homeSets(principal: HttpUrl): List<HttpUrl>?
/** The `calendar-home-set` hrefs [principal] reports now. */
fun homeSets(principal: HttpUrl): HomeSets
}
/** What a principal said about its home sets. */
sealed interface HomeSets {
data class Listed(val urls: List<HttpUrl>) : HomeSets
/** Rejected credentials or throttling: another request would only add to it. */
data class Refused(val code: Int) : HomeSets
/** Any other failure; the caller decides what not knowing means. */
data object Unknown : HomeSets
}
class DavCollectionAdmin(
@@ -138,8 +150,14 @@ class DavCollectionAdmin(
CollectionSupport.NONE
}
override fun homeSets(principal: HttpUrl): List<HttpUrl>? =
runCatching { calendarHomeSets(httpClient, principal).urls }.getOrNull()
override fun homeSets(principal: HttpUrl): HomeSets =
runCatching { calendarHomeSets(httpClient, principal).urls }.fold(
onSuccess = { HomeSets.Listed(it) },
onFailure = { error ->
val code = (error as? HttpException)?.code ?: -1
if (code == UNAUTHORIZED || code == TOO_MANY_REQUESTS) HomeSets.Refused(code) else HomeSets.Unknown
},
)
/**
* A home set that is itself a calendar, as on all-inkl.com (#180), cannot
@@ -336,6 +354,8 @@ class DavCollectionAdmin(
const val COMPONENT = "VTODO"
const val NOT_FOUND = 404
const val GONE = 410
const val UNAUTHORIZED = 401
const val TOO_MANY_REQUESTS = 429
val MIME_XML = "application/xml; charset=utf-8".toMediaType()
val MKCALENDAR = Property.Name(XmlUtils.NS_CALDAV, "mkcalendar")
@@ -95,15 +95,23 @@ class CollectionAdminTest {
),
)
assertThat(admin.homeSets(server.url("/principals/me/")))
.containsExactly(server.url("/calendars/me/1/"), server.url("/calendars/me/2/"))
assertThat(admin.homeSets(server.url("/principals/me/"))).isEqualTo(
HomeSets.Listed(listOf(server.url("/calendars/me/1/"), server.url("/calendars/me/2/"))),
)
}
@Test
fun `a principal that does not answer has no known home sets`() {
server.enqueue(MockResponse().setResponseCode(500))
assertThat(admin.homeSets(server.url("/principals/me/"))).isNull()
assertThat(admin.homeSets(server.url("/principals/me/"))).isEqualTo(HomeSets.Unknown)
}
@Test
fun `rejected credentials on the principal are reported, not shrugged off`() {
server.enqueue(MockResponse().setResponseCode(401))
assertThat(admin.homeSets(server.url("/principals/me/"))).isEqualTo(HomeSets.Refused(401))
}
private fun resourceType(types: String) = MockResponse()