Modern Apps git

← Modern-Apps.git

backup: add SAF and WebDAV storage backends with encrypted repository

Commit
9645cfe00904fc184d6c660a476495b2d1e1833c
Author
Vayun Mathur <[email protected]>
When
2026-08-12 19:08 UTC (3 months ago)
Parents
46a4f6c

Diff

backup/src/main/java/com/vayunmathur/backup/backend/BackendFactory.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/backend/BackendFactory.kt b/backup/src/main/java/com/vayunmathur/backup/backend/BackendFactory.ktnew file mode 100644index 0000000000..802fff7a37--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/backend/BackendFactory.kt@@ -0,0 +1,22 @@+package com.vayunmathur.backup.backend++import android.content.Context+import android.net.Uri+import com.vayunmathur.backup.data.BackendType+import com.vayunmathur.backup.data.BackupSettings++/** Builds the active [BackupBackend] from persisted [BackupSettings]. */+object BackendFactory {+    fun create(context: Context, settings: BackupSettings): BackupBackend? =+        when (settings.backendType) {+            BackendType.NONE -> null+            BackendType.SAF -> settings.safTreeUri+                ?.takeIf { it.isNotBlank() }+                ?.let { SafBackend(context.applicationContext, Uri.parse(it)) }+            BackendType.WEBDAV -> settings.webdavUrl+                .takeIf { it.isNotBlank() }+                ?.let {+                    WebDavBackend(it, settings.webdavUser, settings.webdavPassword)+                }+        }+}
backup/src/main/java/com/vayunmathur/backup/backend/BackupBackend.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/backend/BackupBackend.kt b/backup/src/main/java/com/vayunmathur/backup/backend/BackupBackend.ktnew file mode 100644index 0000000000..bfd389e2d3--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/backend/BackupBackend.kt@@ -0,0 +1,53 @@+package com.vayunmathur.backup.backend++import java.io.ByteArrayInputStream+import java.io.OutputStream++/**+ * A destination for encrypted backup blobs, addressed by POSIX-style relative+ * paths (e.g. `metadata.json`, `kv/<pkg>/<key>`, `full/<pkg>`, `files/<id>`). Blob+ * contents are opaque ciphertext; the backend never sees plaintext. Concrete+ * backends are a user-chosen SAF folder tree ([SafBackend]) or a WebDAV/Nextcloud+ * remote ([WebDavBackend]).+ *+ * Reads and writes are scoped so the backend controls stream lifetime: pass a+ * [writer]/[reader] that consumes the stream; it is closed when the lambda returns.+ * All methods are safe to call from any dispatcher (implementations move I/O off the+ * calling thread themselves).+ */+interface BackupBackend {+    /** Human-readable destination description for the UI (e.g. the folder name or host). */+    val displayName: String++    /** Creates [path] as a directory (and any missing parents). No-op if it exists. */+    suspend fun ensureDir(path: String)++    /** Writes the blob at [path], creating parent directories, overwriting any existing blob. */+    suspend fun write(path: String, writer: suspend (OutputStream) -> Unit)++    /** Reads the blob at [path]; throws if it does not exist. */+    suspend fun <T> read(path: String, reader: suspend (java.io.InputStream) -> T): T++    /** Names (leaf, not full paths) of the blobs directly under directory [dir]. */+    suspend fun list(dir: String): List<String>++    /** Deletes the blob or directory at [path]. No-op if it does not exist. */+    suspend fun delete(path: String)++    /** Whether a blob or directory exists at [path]. */+    suspend fun exists(path: String): Boolean++    suspend fun save(path: String, bytes: ByteArray) = write(path) { it.write(bytes); it.flush() }++    suspend fun load(path: String): ByteArray = read(path) { it.readBytes() }++    suspend fun loadOrNull(path: String): ByteArray? =+        if (exists(path)) load(path) else null++    companion object {+        fun bytesWriter(bytes: ByteArray): suspend (OutputStream) -> Unit =+            { it.write(bytes); it.flush() }++        fun emptyStream() = ByteArrayInputStream(ByteArray(0))+    }+}
backup/src/main/java/com/vayunmathur/backup/backend/BackupRepository.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/backend/BackupRepository.kt b/backup/src/main/java/com/vayunmathur/backup/backend/BackupRepository.ktnew file mode 100644index 0000000000..83543f7eeb--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/backend/BackupRepository.kt@@ -0,0 +1,56 @@+package com.vayunmathur.backup.backend++import com.vayunmathur.backup.crypto.Crypto+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.InputStream+import java.io.OutputStream++/**+ * The on-backend layout of an encrypted backup, and the bridge between [Crypto] and a+ * [BackupBackend]: every blob written here is [Crypto]-encrypted first and decrypted+ * on read, so the backend only ever stores ciphertext.+ *+ * Layout (all relative to the backend root):+ * ```+ * metadata.json           – encrypted backup manifest (version, device, timestamp)+ * kv/<pkg>/<keyId>        – key/value backup entities, one blob per record key+ * full/<pkg>              – full-data (tar) app backup blob+ * files/<fileId>         – standalone file/media backup blobs+ * ```+ * Ported concept (Seedvault repository layout) — see backup/LICENSE-Seedvault.+ */+class BackupRepository(+    val backend: BackupBackend,+    private val crypto: Crypto,+) {+    suspend fun writeEncrypted(path: String, input: InputStream) =+        backend.write(path) { out -> crypto.encrypt(input, out) }++    suspend fun writeEncrypted(path: String, bytes: ByteArray) =+        writeEncrypted(path, ByteArrayInputStream(bytes))++    suspend fun readEncryptedTo(path: String, out: OutputStream) =+        backend.read(path) { input -> crypto.decrypt(input, out) }++    suspend fun readEncrypted(path: String): ByteArray =+        ByteArrayOutputStream().also { readEncryptedTo(path, it) }.toByteArray()++    suspend fun exists(path: String) = backend.exists(path)++    suspend fun delete(path: String) = backend.delete(path)++    suspend fun list(dir: String) = backend.list(dir)++    companion object {+        const val METADATA = "metadata.json"+        const val KV_DIR = "kv"+        const val FULL_DIR = "full"+        const val FILES_DIR = "files"++        fun kvPath(packageName: String, keyId: String) = "$KV_DIR/$packageName/$keyId"+        fun kvPackageDir(packageName: String) = "$KV_DIR/$packageName"+        fun fullPath(packageName: String) = "$FULL_DIR/$packageName"+        fun filePath(fileId: String) = "$FILES_DIR/$fileId"+    }+}
backup/src/main/java/com/vayunmathur/backup/backend/SafBackend.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/backend/SafBackend.kt b/backup/src/main/java/com/vayunmathur/backup/backend/SafBackend.ktnew file mode 100644index 0000000000..d097eb2a34--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/backend/SafBackend.kt@@ -0,0 +1,153 @@+package com.vayunmathur.backup.backend++import android.content.Context+import android.net.Uri+import android.provider.DocumentsContract+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.io.FileNotFoundException+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream++/**+ * [BackupBackend] over a Storage Access Framework document tree — a user-chosen+ * folder on internal storage, a USB drive, or an SD card, picked via+ * `ACTION_OPEN_DOCUMENT_TREE` and persisted with a takePersistableUriPermission+ * grant. Paths map to a directory/file hierarchy under the tree, addressed through+ * [DocumentsContract] (no androidx.documentfile dependency).+ */+class SafBackend(+    private val context: Context,+    private val treeUri: Uri,+) : BackupBackend {++    private val resolver get() = context.contentResolver+    private val rootDocId get() = DocumentsContract.getTreeDocumentId(treeUri)++    override val displayName: String+        get() = treeUri.lastPathSegment?.substringAfterLast(':')?.ifEmpty { "SAF folder" } ?: "SAF folder"++    override suspend fun ensureDir(path: String) = withContext(Dispatchers.IO) {+        resolveDir(segments(path), create = true) ?: throw IOException("cannot create dir: $path")+        Unit+    }++    override suspend fun write(path: String, writer: suspend (OutputStream) -> Unit) =+        withContext(Dispatchers.IO) {+            val segments = segments(path)+            val name = segments.last()+            val parent = resolveDir(segments.dropLast(1), create = true)+                ?: throw IOException("cannot create parent of: $path")+            val existing = findChild(parent, name)+            val fileUri = if (existing != null) {+                docUri(existing.docId)+            } else {+                DocumentsContract.createDocument(resolver, docUri(parent), MIME_OCTET, name)+                    ?: throw IOException("cannot create file: $path")+            }+            val out = openOutput(fileUri) ?: throw IOException("cannot open for write: $path")+            out.use { writer(it) }+        }++    override suspend fun <T> read(path: String, reader: suspend (InputStream) -> T): T =+        withContext(Dispatchers.IO) {+            val docId = resolveFile(path) ?: throw FileNotFoundException(path)+            val input = resolver.openInputStream(docUri(docId))+                ?: throw IOException("cannot open for read: $path")+            input.use { reader(it) }+        }++    override suspend fun list(dir: String): List<String> = withContext(Dispatchers.IO) {+        val parent = resolveDir(segments(dir), create = false) ?: return@withContext emptyList()+        buildList {+            resolver.query(+                childrenUri(parent),+                arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME),+                null, null, null,+            )?.use { c -> while (c.moveToNext()) add(c.getString(0)) }+        }+    }++    override suspend fun delete(path: String) = withContext(Dispatchers.IO) {+        val segments = segments(path)+        val parent = resolveDir(segments.dropLast(1), create = false) ?: return@withContext+        val child = findChild(parent, segments.last()) ?: return@withContext+        DocumentsContract.deleteDocument(resolver, docUri(child.docId))+        Unit+    }++    override suspend fun exists(path: String): Boolean = withContext(Dispatchers.IO) {+        val segments = segments(path)+        if (segments.isEmpty()) return@withContext true+        val parent = resolveDir(segments.dropLast(1), create = false) ?: return@withContext false+        findChild(parent, segments.last()) != null+    }++    // --- DocumentsContract helpers ---++    private data class Child(val docId: String, val isDir: Boolean)++    private fun docUri(docId: String): Uri =+        DocumentsContract.buildDocumentUriUsingTree(treeUri, docId)++    private fun childrenUri(parentDocId: String): Uri =+        DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocId)++    private fun openOutput(uri: Uri): OutputStream? =+        runCatching { resolver.openOutputStream(uri, "wt") }.getOrNull()+            ?: runCatching { resolver.openOutputStream(uri, "w") }.getOrNull()++    private fun findChild(parentDocId: String, name: String): Child? {+        resolver.query(+            childrenUri(parentDocId),+            arrayOf(+                DocumentsContract.Document.COLUMN_DOCUMENT_ID,+                DocumentsContract.Document.COLUMN_DISPLAY_NAME,+                DocumentsContract.Document.COLUMN_MIME_TYPE,+            ),+            null, null, null,+        )?.use { c ->+            while (c.moveToNext()) {+                if (c.getString(1) == name) {+                    return Child(c.getString(0), c.getString(2) == DocumentsContract.Document.MIME_TYPE_DIR)+                }+            }+        }+        return null+    }++    /** Walks (optionally creating) directory [segments]; returns the deepest doc id. */+    private fun resolveDir(segments: List<String>, create: Boolean): String? {+        var parent = rootDocId+        for (seg in segments) {+            val existing = findChild(parent, seg)+            parent = when {+                existing != null && existing.isDir -> existing.docId+                existing != null -> return null // a file blocks this path+                create -> {+                    val uri = DocumentsContract.createDocument(+                        resolver, docUri(parent), DocumentsContract.Document.MIME_TYPE_DIR, seg,+                    ) ?: return null+                    DocumentsContract.getDocumentId(uri)+                }+                else -> return null+            }+        }+        return parent+    }++    /** Resolves a file path to its doc id, or null if any segment is missing. */+    private fun resolveFile(path: String): String? {+        val segments = segments(path)+        val parent = resolveDir(segments.dropLast(1), create = false) ?: return null+        return findChild(parent, segments.last())?.docId+    }++    private fun segments(path: String): List<String> =+        path.split('/').filter { it.isNotEmpty() }++    companion object {+        private const val MIME_OCTET = "application/octet-stream"+    }+}
backup/src/main/java/com/vayunmathur/backup/backend/WebDavBackend.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/backend/WebDavBackend.kt b/backup/src/main/java/com/vayunmathur/backup/backend/WebDavBackend.ktnew file mode 100644index 0000000000..18822fc05a--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/backend/WebDavBackend.kt@@ -0,0 +1,120 @@+package com.vayunmathur.backup.backend++import android.net.Uri+import android.util.Base64+import com.vayunmathur.library.network.NetworkClient+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.FileNotFoundException+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream++/**+ * [BackupBackend] over a WebDAV/Nextcloud remote, using the platform HTTP stack+ * ([NetworkClient], HttpURLConnection — including the reflection-based support for+ * the WebDAV verbs MKCOL/PROPFIND). Blobs are files under [baseUrl]; directories are+ * WebDAV collections. Authentication is HTTP Basic.+ *+ * Note: PUT/GET buffer a blob fully in memory (HttpURLConnection needs a known+ * content length), so very large full-data app blobs are best sent to a [SafBackend].+ */+class WebDavBackend(+    baseUrl: String,+    username: String,+    password: String,+    displayName: String? = null,+) : BackupBackend {++    private val base = baseUrl.trimEnd('/')+    private val authHeader =+        "Basic " + Base64.encodeToString("$username:$password".toByteArray(), Base64.NO_WRAP)++    override val displayName: String = displayName ?: (Uri.parse(base).host ?: "WebDAV")++    private fun url(path: String): String {+        val encoded = path.split('/').filter { it.isNotEmpty() }.joinToString("/") { Uri.encode(it) }+        return if (encoded.isEmpty()) base else "$base/$encoded"+    }++    private fun headers(vararg extra: Pair<String, String>) =+        mapOf("Authorization" to authHeader, *extra)++    override suspend fun ensureDir(path: String) {+        // MKCOL creates a single collection; create each ancestor progressively.+        val segments = path.split('/').filter { it.isNotEmpty() }+        var current = ""+        for (seg in segments) {+            current = if (current.isEmpty()) seg else "$current/$seg"+            val resp = NetworkClient.execute(url(current), method = "MKCOL", headers = headers())+            // 201 created; 405/301/409-after-parent are tolerated as "already exists".+            if (resp.status !in intArrayOf(201, 405, 301, 200)) {+                if (resp.status == 409) continue // parent race; keep going+            }+        }+    }++    override suspend fun write(path: String, writer: suspend (OutputStream) -> Unit) {+        val buffer = ByteArrayOutputStream()+        writer(buffer)+        val parent = path.substringBeforeLast('/', "")+        if (parent.isNotEmpty()) ensureDir(parent)+        val resp = NetworkClient.execute(+            url(path),+            method = "PUT",+            headers = headers("Content-Type" to "application/octet-stream"),+            body = buffer.toByteArray(),+        )+        if (!resp.isSuccess) throw IOException("WebDAV PUT $path failed: ${resp.status}")+    }++    override suspend fun <T> read(path: String, reader: suspend (InputStream) -> T): T {+        val resp = NetworkClient.execute(url(path), method = "GET", headers = headers())+        if (resp.status == 404) throw FileNotFoundException(path)+        if (!resp.isSuccess) throw IOException("WebDAV GET $path failed: ${resp.status}")+        return ByteArrayInputStream(resp.bytes).use { reader(it) }+    }++    override suspend fun list(dir: String): List<String> {+        val resp = NetworkClient.execute(+            url(dir),+            method = "PROPFIND",+            headers = headers("Depth" to "1", "Content-Type" to "application/xml"),+            body = PROPFIND_BODY,+        )+        if (resp.status == 404) return emptyList()+        if (!resp.isSuccess && resp.status != 207) {+            throw IOException("WebDAV PROPFIND $dir failed: ${resp.status}")+        }+        val selfPath = Uri.parse(url(dir)).path?.trimEnd('/') ?: ""+        return HREF_REGEX.findAll(resp.text)+            .map { Uri.decode(it.groupValues[1]).trimEnd('/') }+            .filter { it.isNotEmpty() && it != selfPath }+            .map { it.substringAfterLast('/') }+            .filter { it.isNotEmpty() }+            .distinct()+            .toList()+    }++    override suspend fun delete(path: String) {+        val resp = NetworkClient.execute(url(path), method = "DELETE", headers = headers())+        if (!resp.isSuccess && resp.status != 404) {+            throw IOException("WebDAV DELETE $path failed: ${resp.status}")+        }+    }++    override suspend fun exists(path: String): Boolean {+        val resp = NetworkClient.execute(+            url(path),+            method = "PROPFIND",+            headers = headers("Depth" to "0"),+        )+        return resp.status == 207 || resp.isSuccess+    }++    companion object {+        private val PROPFIND_BODY =+            """<?xml version="1.0" encoding="utf-8"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/></d:prop></d:propfind>"""+        private val HREF_REGEX = Regex("<[^>]*href[^>]*>([^<]+)</[^>]*href>", RegexOption.IGNORE_CASE)+    }+}
backup/src/main/java/com/vayunmathur/backup/data/BackupConfig.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/data/BackupConfig.kt b/backup/src/main/java/com/vayunmathur/backup/data/BackupConfig.ktnew file mode 100644index 0000000000..feb5fc2db7--- /dev/null+++ b/backup/src/main/java/com/vayunmathur/backup/data/BackupConfig.kt@@ -0,0 +1,97 @@+package com.vayunmathur.backup.data++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++/** Which storage destination a backup is written to. */+enum class BackendType { NONE, SAF, WEBDAV }++/**+ * An immutable snapshot of the backup configuration. Credentials for a WebDAV remote+ * are held here for simplicity; on a real deployment these should be wrapped by the+ * AndroidKeyStore (see [com.vayunmathur.backup.crypto.KeyManager]).+ */+data class BackupSettings(+    val backendType: BackendType = BackendType.NONE,+    val safTreeUri: String? = null,+    val webdavUrl: String = "",+    val webdavUser: String = "",+    val webdavPassword: String = "",+    val appBackupEnabled: Boolean = false,+    val fileBackupEnabled: Boolean = false,+    val lastRun: Long = 0L,+) {+    val isConfigured: Boolean+        get() = when (backendType) {+            BackendType.NONE -> false+            BackendType.SAF -> !safTreeUri.isNullOrBlank()+            BackendType.WEBDAV -> webdavUrl.isNotBlank()+        }+}++private val Context.backupDataStore by preferencesDataStore(name = "backup_config")++/** DataStore-backed persistence for [BackupSettings]. */+class BackupConfig(private val context: Context) {+    val settings: Flow<BackupSettings> = context.backupDataStore.data.map { p ->+        BackupSettings(+            backendType = p[KEY_BACKEND]?.let { runCatching { BackendType.valueOf(it) }.getOrNull() }+                ?: BackendType.NONE,+            safTreeUri = p[KEY_SAF_URI],+            webdavUrl = p[KEY_WEBDAV_URL] ?: "",+            webdavUser = p[KEY_WEBDAV_USER] ?: "",+            webdavPassword = p[KEY_WEBDAV_PASS] ?: "",+            appBackupEnabled = (p[KEY_APP_ENABLED] ?: 0L) == 1L,+            fileBackupEnabled = (p[KEY_FILE_ENABLED] ?: 0L) == 1L,+            lastRun = p[KEY_LAST_RUN] ?: 0L,+        )+    }++    suspend fun setSafBackend(treeUri: String) {+        context.backupDataStore.edit {+            it[KEY_BACKEND] = BackendType.SAF.name+            it[KEY_SAF_URI] = treeUri+        }+    }++    suspend fun setWebDavBackend(url: String, user: String, password: String) {+        context.backupDataStore.edit {+            it[KEY_BACKEND] = BackendType.WEBDAV.name+            it[KEY_WEBDAV_URL] = url+            it[KEY_WEBDAV_USER] = user+            it[KEY_WEBDAV_PASS] = password+        }+    }++    suspend fun setAppBackupEnabled(enabled: Boolean) {+        context.backupDataStore.edit { it[KEY_APP_ENABLED] = if (enabled) 1L else 0L }+    }++    suspend fun setFileBackupEnabled(enabled: Boolean) {+        context.backupDataStore.edit { it[KEY_FILE_ENABLED] = if (enabled) 1L else 0L }+    }++    suspend fun setLastRun(epochMillis: Long) {+        context.backupDataStore.edit { it[KEY_LAST_RUN] = epochMillis }+    }++    suspend fun clear() {+        context.backupDataStore.edit { it.clear() }+    }++    companion object {+        private val KEY_BACKEND = stringPreferencesKey("backend_type")+        private val KEY_SAF_URI = stringPreferencesKey("saf_tree_uri")+        private val KEY_WEBDAV_URL = stringPreferencesKey("webdav_url")+        private val KEY_WEBDAV_USER = stringPreferencesKey("webdav_user")+        private val KEY_WEBDAV_PASS = stringPreferencesKey("webdav_password")+        private val KEY_APP_ENABLED = longPreferencesKey("app_backup_enabled")+        private val KEY_FILE_ENABLED = longPreferencesKey("file_backup_enabled")+        private val KEY_LAST_RUN = longPreferencesKey("last_run")+    }+}