Keep deletes working when the principal doesn't answer, share the home-set lookup (#180)

This commit is contained in:
makiolaj committed 2026-11-25 15:37:54 +01:00
1 parent 91c6593ceb
commit 4201ef6abe
7 files changed
+68 -49

No files matched your search

@@ -208,10 +208,10 @@ class RemoteListRepository @Inject constructor(
?: return@withContext Outcome.NoAccount
if (CollectionHref.same(list.href, account.homeSetUrl)) return@withContext Outcome.AccountHome
val admin = adminFor(account) ?: return@withContext Outcome.NoAccount
// ⚠️ Asked again, not trusted from the row: only the first home set is
// stored, and deleting any of them takes the calendar's events too (#180).
val principal = account.principalUrl?.toHttpUrlOrNull() ?: return@withContext Outcome.NoAccount
val homeSets = admin.homeSets(principal) ?: return@withContext Outcome.Unreachable
// 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
}
@@ -7,22 +7,32 @@ object CollectionHref {
/** Whether [a] and [b] name the same collection: case, default port, escaping and a trailing slash aside. */
fun same(a: String?, b: String?): Boolean {
val left = a?.let(::key) ?: return false
return left == b?.let(::key)
if (a == null || b == null) return false
return key(a) == key(b)
}
private fun key(href: String): String? = runCatching {
val uri = URI(href)
val scheme = uri.scheme?.lowercase() ?: return null
private fun key(href: String): String = runCatching {
val uri = URI(URI(href).toASCIIString())
val scheme = uri.scheme.lowercase()
val host = (uri.host ?: uri.rawAuthority.substringAfterLast('@').substringBeforeLast(':')).lowercase()
val port = when {
uri.port != -1 -> uri.port
scheme == "https" -> HTTPS_PORT
scheme == "http" -> HTTP_PORT
else -> -1
}
"$scheme://${uri.host?.lowercase()}:$port${uri.path.orEmpty().trimEnd('/')}"
}.getOrNull()
"$scheme://$host:$port${normalizeEscapes(uri.rawPath.orEmpty()).trimEnd('/')}"
}.getOrElse { href.trimEnd('/') }
/** Decodes escaped ASCII but `%2F`, which is part of a segment, not a separator. */
private fun normalizeEscapes(path: String): String = ESCAPE.replace(path) { match ->
val code = match.groupValues[1].toInt(HEX)
if (code == '/'.code || code >= ASCII_END) match.value.uppercase() else code.toChar().toString()
}
private val ESCAPE = Regex("%([0-9A-Fa-f]{2})")
private const val HEX = 16
private const val ASCII_END = 0x80
private const val HTTPS_PORT = 443
private const val HTTP_PORT = 80
}
@@ -112,7 +112,7 @@ fun ListEditorSheet(
?: destinations.firstOrNull()
val readOnly = initial?.isReadOnly == true
val deletable = onDelete != null && initial?.isAccountHome != true
val deleteAction = onDelete?.takeIf { initial?.isAccountHome != true }
val valid = name.isNotBlank() && !readOnly
val commit = {
if (valid) {
@@ -183,7 +183,7 @@ fun ListEditorSheet(
)
}
if (deletable) {
if (deleteAction != null) {
Spacer(Modifier.height(24.dp))
DeleteRow(onClick = { confirmDelete = true })
} else if (initial?.isAccountHome == true && !readOnly) {
@@ -207,7 +207,7 @@ fun ListEditorSheet(
)
}
if (confirmDelete && deletable && onDelete != null) {
if (confirmDelete && deleteAction != null) {
DeleteListDialog(
listName = initial?.name.orEmpty(),
// A synced list is deleted on the server too, and that reaches every
@@ -216,7 +216,7 @@ fun ListEditorSheet(
synced = initial?.accountId != null,
onConfirm = {
confirmDelete = false
onDelete()
deleteAction()
onDismiss()
},
onDismiss = { confirmDelete = false },
@@ -428,7 +428,8 @@ fun TaskListScreen(
// ⚠️ Absent for a read-only share, whose removal belongs to whoever
// owns it — and which the server would refuse anyway. Present for
// the account's own collections, where it now deletes on the server
// as well as here.
// as well as here; the sheet itself withholds it from the account's
// home set (#180).
onDelete = if (list.isReadOnly) {
null
} else {
@@ -12,6 +12,15 @@ class CollectionHrefTest {
assertThat(CollectionHref.same(home, "https://DAV.example.com:443/calendars/user%40example.com/1/")).isTrue()
}
@Test
fun `odd hosts and characters still compare`() {
assertThat(CollectionHref.same("https://my_server.lan/cal/1/", "https://my_server.lan/cal/1")).isTrue()
assertThat(CollectionHref.same("https://my_server.lan/cal/1/", "https://other_server.lan/cal/1/")).isFalse()
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()
}
@Test
fun `a different path, port or a missing side is not the same`() {
val home = "https://dav.example.com/calendars/user/1/"
@@ -272,30 +272,11 @@ class CalDavDiscovery(
}
internal fun fromPrincipal(principal: HttpUrl, movedTo: HttpUrl? = null): Outcome {
val homeSets = mutableListOf<HttpUrl>()
val principalResource = DavResource(httpClient, principal)
val homeSetResult = runCatching {
principalResource.propfind(0, CalendarHomeSet.NAME) { response, _ ->
// ⚠️ Iterate ALL hrefs. Multiple home sets are normative (RFC 4791
// §6.2.1's own example) and iCloud depends on it: the principal is
// on caldav.icloud.com and the home set on pNN-caldav.icloud.com.
// ⚠️ Against where the PROPFIND *landed*, not where it was
// aimed. `followRedirects` rewrites `location` in place, and the
// probe above already reads it back for exactly this reason. A
// principal that has permanently moved answers a relative
// `<href>calendars/alice/</href>`, which resolved against the
// pre-redirect URL names a path on the old host — the home-set
// PROPFIND 404s and a perfectly good account reports that it
// holds no calendars.
response[CalendarHomeSet::class.java]?.hrefs?.forEach { raw ->
principalResource.location.resolve(raw)?.let(homeSets::add)
}
}
}
homeSetResult.exceptionOrNull()?.let { error ->
val listing = runCatching { calendarHomeSets(httpClient, principal) }.getOrElse { error ->
if (isUnauthorized(error)) return Outcome.NeedsAuthentication(listOf(principal.host))
return failure(error)
}
val homeSets = listing.urls
if (homeSets.isEmpty()) {
return Outcome.Failed(Outcome.Cause.NO_CALENDARS, "principal has no calendar-home-set")
@@ -304,7 +285,7 @@ class CalDavDiscovery(
// Cross-host is legal and required, but never over plain HTTP: the
// credentials follow the home set, and a downgrade would send them in the
// clear. The caller surfaces the host change to the user.
val crossHost = homeSets.filter { it.host != principalResource.location.host }
val crossHost = homeSets.filter { it.host != listing.landedAt.host }
val insecure = homeSets.filter { principal.isHttps && !it.isHttps }
if (insecure.isNotEmpty()) {
return Outcome.Failed(
@@ -398,3 +379,30 @@ class CalDavDiscovery(
private const val NOT_IMPLEMENTED = 501
}
}
/**
* Every `calendar-home-set` href [principal] reports, resolved, and where the
* PROPFIND landed. Throws what the PROPFIND throws.
*/
internal fun calendarHomeSets(httpClient: OkHttpClient, principal: HttpUrl): HomeSetListing {
val homeSets = mutableListOf<HttpUrl>()
val resource = DavResource(httpClient, principal)
resource.propfind(0, CalendarHomeSet.NAME) { response, _ ->
// ⚠️ Iterate ALL hrefs. Multiple home sets are normative (RFC 4791
// §6.2.1's own example) and iCloud depends on it: the principal is
// on caldav.icloud.com and the home set on pNN-caldav.icloud.com.
// ⚠️ Against where the PROPFIND *landed*, not where it was
// aimed. `followRedirects` rewrites `location` in place. A
// principal that has permanently moved answers a relative
// `<href>calendars/alice/</href>`, which resolved against the
// pre-redirect URL names a path on the old host — the home-set
// PROPFIND 404s and a perfectly good account reports that it
// holds no calendars.
response[CalendarHomeSet::class.java]?.hrefs?.forEach { raw ->
resource.location.resolve(raw)?.let(homeSets::add)
}
}
return HomeSetListing(landedAt = resource.location, urls = homeSets)
}
internal data class HomeSetListing(val landedAt: HttpUrl, val urls: List<HttpUrl>)
@@ -5,7 +5,6 @@ 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.property.CalendarHomeSet
import at.bitfire.dav4jvm.property.ResourceType
import okhttp3.HttpUrl
import okhttp3.MediaType.Companion.toMediaType
@@ -139,16 +138,8 @@ class DavCollectionAdmin(
CollectionSupport.NONE
}
override fun homeSets(principal: HttpUrl): List<HttpUrl>? {
val resource = DavResource(httpClient, principal)
val hrefs = mutableListOf<String>()
runCatching {
resource.propfind(0, CalendarHomeSet.NAME) { response, _ ->
response[CalendarHomeSet::class.java]?.hrefs?.let(hrefs::addAll)
}
}.onFailure { return null }
return hrefs.mapNotNull { resource.location.resolve(it) }
}
override fun homeSets(principal: HttpUrl): List<HttpUrl>? =
runCatching { calendarHomeSets(httpClient, principal).urls }.getOrNull()
/**
* A home set that is itself a calendar, as on all-inkl.com (#180), cannot