diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e00992d4..55301351 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +- Writable storage confined to declared roots (#460, ADR-002 3.0, ADR-020 step 4). `fs::Storage` is the contract of a + writable storage: stable paginated listing (`list(dir, after, limit)`, at most 1000 entries a page), `status`, + `openRead`, `beginWrite(path, createNew | replace)` whose `commit()` renames a temporary file atomically (an uncommitted + writer removes it), `createDirectory`, `remove` and `rename` (never replacing). Failures are `fs::StorageError`, a + `BridgeError` with a `storage.*` code (`notFound`, `linkRefused`, `unsafeDirectory`, `rootMoved`, + `confinementViolated`…) whose message never names the root's host location. `fs::NativeStorage` resolves every path + from the opened root, one component at a time, without following links (`openat(O_NOFOLLOW)` on POSIX, `NtCreateFile` + relative to the parent handle with reparse points refused on Windows; `LinkPolicy::followInside` follows a relative + link that stays inside, POSIX only), checks on every operation that the declared location still designates the root + (`rootMoved`), refuses on POSIX a root, a directory or an ancestor another user could move, by its mode or, on macOS, + its extended ACL (`unsafeDirectory`; `/tmp` + accepted; `RootOptions::shared` lifts the check as a weakened confinement), holds the root and the traversed + directories without `FILE_SHARE_DELETE` on Windows, and detects a directory or a root moved by the same user before a + commit and after every operation (`confinementViolated`). On POSIX a move by the same user or the superuser after the + last check is not prevented. Names starting with `.wf-tmp-`, in any letter case, are reserved to temporary files. A replacing write creates its temporary file private (0600, in a private 0700 directory, without inherited ACL) and its commit gives the new file the group, permission bits and ACL of the file it then replaces (none if it has none), or refuses the replacement; running out of descriptors is not taken for a moved root. `fs::MemoryStorage` is the simulated storage of the tests. `fs::File` reads a + `fs::ByteSource`, the extension point for native handles. `safeRelativePath` now also refuses, on every platform, the + device names Windows reserves (`CON`, `NUL`, `COM1`…, with any extension) and names ending with a dot or a space. - The bridge supports long strings, homogeneous lists of strings, tuples, typed arrays and bitsets, and typed errors with application codes. A `cppFunction` callback can return a `webfront::ResultTask` or another sender and answer when it completes; disconnecting the browser requests cancellation and drops late answers (#456–#459). diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 30302311..a7fff850 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -97,6 +97,12 @@ are retained for investigation; diagnostics alone do not establish a correction. Manifest permissions bound only the scripts' `context` API. Only browser packages install; installation scripts and native add-ons do not run. The [content policy](CONTENT_POLICY.md) restricts browser origins and navigation but provides neither TLS nor client authentication. +- `fs::NativeStorage` confines writable storage to a declared root while resolving each path, but + on POSIX it cannot prevent the effective user or the superuser from moving a directory out of the + root during an operation: it detects such a move before a commit and after each operation, at + best. Windows prevents those moves while an operation holds its directories; links are always + refused there. A `shared` root lifts the POSIX ownership checks. No service uses the storage yet + (ADR-020). See [ADR-002](adr/ADR-002-systemes-de-fichiers-composables.md). - A synchronous infinite loop in a spec blocks the page hosting `wf test`; the native test driver's watchdog terminates stalled runs with failure. Windows file reads beyond 260 characters remain unsupported (#349). diff --git a/docs/adr/ADR-002-systemes-de-fichiers-composables.md b/docs/adr/ADR-002-systemes-de-fichiers-composables.md index 1dcdf967..5e8d1347 100644 --- a/docs/adr/ADR-002-systemes-de-fichiers-composables.md +++ b/docs/adr/ADR-002-systemes-de-fichiers-composables.md @@ -16,11 +16,12 @@ | 2.4 | 2026-10-14 | Acceptée | Ambroise Leclerc | Fournisseur PackageFS et stockage transactionnel des outils installés. | [4bcfc28](https://github.com/ambroise-leclerc/WebFront/commit/4bcfc28c7b78672603a2114a72d9decf25d36387) | | 2.5 | 2026-11-03 | Acceptée | Ambroise Leclerc | `fs::File::knownSize()` : taille connue avant lecture (données embarquées, fichier natif sur flux positionnable), pour annoncer `Content-Length` et envoyer le fichier en flux (#454). Les routes dynamiques passent après le `WebFront.js` protégé et ne peuvent pas le masquer. | Branche `454-dynamic-routes` | | 2.6 | 2026-11-04 | Acceptée | Ambroise Leclerc | `fs::File::seek`, `entityTag()` et `setEntityTag()` : positionnement dans un fichier de taille connue et validateur fort fourni par le fournisseur (jamais déduit d'un chemin, d'une taille ou d'une date), pour les requêtes `Range` et `If-Range` (#455). Le serveur traite les plages ; `fs::Provider` ne voit toujours pas la requête. | Branche `455-range-requests` | +| 3.0 | 2026-11-05 | Acceptée | Ambroise Leclerc | Stockage modifiable sous des racines déclarées (#460, ADR-020) : concept `fs::Storage` (listage paginé stable, métadonnées, lecture, écriture par fichier temporaire validée par renommage atomique, création de dossier, suppression, renommage sans remplacement), erreurs typées `fs::StorageError` (`storage.*`), `fs::NativeStorage` confiné pendant la résolution par descripteurs (POSIX) ou handles (Windows), contrôle des propriétaires des répertoires et des ancêtres, `rootMoved` et `confinementViolated`, `fs::MemoryStorage` simulé ; `fs::ByteSource`, point d'extension de `fs::File` pour les handles natifs ; `SafePath` refuse les noms réservés de Windows. Les fournisseurs restent en lecture seule. | [509de1a](https://github.com/ambroise-leclerc/WebFront/commit/509de1a), branche `460-writable-storage` (PR #500) | ## État et chronologie **Acceptée.** Décision initiale : **2023-03-16** (version 1.0). -Dernière révision : **2026-11-03** (version 2.5). +Dernière révision : **2026-11-05** (version 3.0). Le présent texte expose la décision en vigueur ; le tableau retrace ses états antérieurs. ## Contexte @@ -40,6 +41,12 @@ Les fichiers modifiables ne sont qu’un usage de cette abstraction. Il faut en script du pont demeure conforme au codec C++, même si une racine locale contient un autre `WebFront.js`. +Jusqu’à la version 2.6, cette décision ne définissait que la lecture (`open → fs::File`). Les services du +système (ADR-020) doivent aussi lister, écrire, créer, renommer et supprimer des fichiers de l’hôte, sous des +racines que l’application déclare, sans qu’un script de la page ni un processus local sans droit sur ces racines +puisse les faire agir à l’extérieur. Une vérification du chemin suivie d’une ouverture par nom ne suffit pas : +entre les deux, un processus local peut remplacer un composant par un lien vers l’extérieur. + ## Décision Dissocier les ressources web du système de fichiers physique. Le serveur @@ -60,6 +67,11 @@ un handle natif mobile ou un stockage spécialisé devra adapter ses octets à c faire évoluer explicitement `File` avec ses tests. Le `span` des données statiques emprunte leur stockage, qui doit survivre à la lecture. +`fs::File` lit aussi les octets d’un `fs::ByteSource`, que fournit un stockage ou un provider lisant par son propre +handle : un descripteur ouvert relativement à une racine (`fs::NativeStorage`), plus tard une URI `content://` +d’Android ou une URL « security-scoped » de macOS, que WebFront n’a pas à connaître. Ces handles natifs ne sont +pas implémentés ; `ByteSource` est leur point d’extension. + Le filesystem par défaut consulte, dans cet ordre : le `WebFront.js` embarqué protégé, la racine de développement optionnelle, puis la page de repli embarquée d’`IndexFS`. `fs::DefaultFSWith` place les providers supplémentaires entre le bridge protégé @@ -70,6 +82,93 @@ ressources réutilisables des pages applicatives ; `PackageFS` et les composants sont retirés (ADR-010 v1.7), l'environnement développeur sert les siennes sous `webfront/developer/`. Les fichiers natifs de développement et `NativeDebugFS` ne constituent pas un sandbox de production. +### Stockage modifiable sous des racines déclarées + +Un fournisseur sert des ressources en lecture ; un **stockage** (`fs::Storage`, `Storage.hpp`) est modifiable et +confiné à une racine. Ce sont deux contrats distincts : le serveur HTTP ne consomme que des fournisseurs, et un +stockage n’est servi que par une route à jeton de l’ADR-020. + +- **Contrat.** Chemins relatifs séparés par `/`, vérifiés par `SafePath` (le chemin vide désigne la racine) ; + `list(dir, after, limit)` rend une page triée par nom, au plus `maxStoragePageSize` (1000) entrées, et un curseur : + une entrée présente pendant tout le listage y figure exactement une fois, quoi qu’on ajoute ou retire entre deux + pages ; `status` (un lien n’est pas suivi), `openRead`, `beginWrite(path, createNew | replace)` qui écrit dans un + fichier temporaire rendu visible par un renommage atomique à `commit()` et supprimé si l’écrivain est détruit avant, + `createDirectory`, `remove` (fichier, lien ou dossier vide), `rename` (jamais de remplacement). Les noms commençant + par `.wf-tmp-` (`fs::temporaryPrefix`), quelle que soit la casse de ses lettres (un volume insensible à la casse + désigne le même fichier par `.WF-TMP-`), sont réservés aux temporaires : refusés (`invalidPath`) et omis des listages, + de sorte qu’un listage ne masque jamais un fichier validé. Le concept ne fait + aucune hypothèse POSIX : un stockage sans `std::filesystem` (FatFs, LittleFS) peut le satisfaire. +- **Erreurs typées.** `fs::StorageError` est une `BridgeError` (ADR-004) de code `storage.` : `notFound`, + `alreadyExists`, `notDirectory`, `isDirectory`, `notEmpty`, `accessDenied`, `invalidPath`, `linkRefused`, + `unsafeDirectory`, `rootMoved`, `confinementViolated`, `busy`, `ioError`. Son message nomme le chemin relatif, + jamais l’emplacement de la racine sur l’hôte. Les droits rapportés par `status` et le listage sont indicatifs (bits + de mode POSIX, attribut lecture seule de Windows ; les ACL n’y sont pas examinées). +- **Syntaxe.** `SafePath` refuse en outre, sur toutes les plateformes, les noms de périphériques réservés de Windows + (`CON`, `PRN`, `AUX`, `NUL`, `COM1` à `COM9`, `LPT1` à `LPT9`, `CONIN$`, `CONOUT$`, quelle que soit l’extension), + et les noms terminés par un point ou une espace, que Windows modifie. Un nom qu’il + refuse n’est pas listé, puisqu’aucune opération ne pourrait le désigner. La syntaxe ne confine pas : elle suffit + seulement aux stockages sans liens. +- **`fs::NativeStorage`.** La racine est la forme canonique de l’emplacement déclaré (ses liens sont résolus une fois, + à la déclaration). Chaque opération repart de la racine ouverte et ouvre chaque composant relativement au précédent, + sans suivre de lien (POSIX : `openat(O_NOFOLLOW | O_DIRECTORY)`, `O_PATH` sous Linux, `O_SEARCH` sous macOS ; + Windows : `NtCreateFile` relatif au handle parent, `FILE_OPEN_REPARSE_POINT`, points de réanalyse refusés) ; le + dernier composant est traité par `openat(O_CREAT | O_EXCL | O_NOFOLLOW)`, `fstatat(AT_SYMLINK_NOFOLLOW)`, + `mkdirat`, `unlinkat`, `renameat`, renommage sans remplacement par `renameat2(RENAME_NOREPLACE)` (Linux) ou + `renameatx_np(RENAME_EXCL)` (macOS) ; sur un système de fichiers Linux sans `renameat2`, un fichier est lié puis + délié (`link` ne remplace jamais) et un dossier est refusé, faute de primitive atomique. Sous Windows, le renommage + passe par `NtSetInformationFile` relatif au handle du dossier (`SetFileInformationByHandle` convertit le nom en + chemin absolu, que ce renommage refuse), la suppression par disposition. Aucun descripteur ne survit à l’opération. `openat2(RESOLVE_BENEATH)` n’est + pas utilisé : chaque répertoire traversé doit de toute façon être ouvert pour contrôler son propriétaire. + Les liens sont refusés par défaut (`linkRefused`) ; `LinkPolicy::followInside` suit sous POSIX un lien relatif dont + la résolution, faite par la même descente, reste dans la racine (au plus 32 liens) ; un lien absolu ou qui sort est + refusé. Sous Windows, tout point de réanalyse est refusé. +- **Emplacement déclaré.** Chaque opération vérifie d’abord que l’emplacement déclaré, ouvert composant par composant + sans suivre de lien, désigne encore l’identité de la racine (`st_dev`/`st_ino`, `FILE_ID_INFO`) ; sinon `rootMoved`, + pour cette opération et les suivantes, jusqu’à une nouvelle déclaration. Seuls un composant absent, qui n’est pas un + répertoire ou qui est un lien, et une identité différente, valent déplacement ; une autre erreur (descripteurs + épuisés, mémoire, droits) est signalée comme telle et ne verrouille pas la racine. +- **Propriétaires (POSIX).** Chaque répertoire traversé et la racine appartiennent à l’utilisateur effectif ou au + superutilisateur et ne sont modifiables ni par le groupe ni par les autres ; chaque ancêtre appartient à l’un d’eux + et, s’il est modifiable par le groupe ou les autres, porte le bit collant et l’élément suivant appartient aussi à + l’un d’eux (cas de `/tmp`). Sous macOS, une ACL étendue qui accorde à un autre que ces deux utilisateurs le droit + d’ajouter, de retirer ou de renommer des entrées, de supprimer le répertoire ou de changer son ACL ou son + propriétaire rend aussi le répertoire ou l’ancêtre inadmissible (une ACL illisible compte comme telle ; une entrée + `only_inherit`, qui ne vaut que pour les descendants, est ignorée pour ce répertoire et contrôlée sur le + sous-répertoire qui en hérite) ; sous Linux, + une entrée nommée d’ACL POSIX qui accorde l’écriture positionne le bit d’écriture du groupe (masque) et tombe sous la + règle des bits. Contrôle à la déclaration et à chaque opération, avant tout effet ; sinon `unsafeDirectory`. Les dossiers créés le sont en mode 0755, les fichiers en 0644 (masqués par l’umask), pour rester + utilisables. `RootOptions::shared` lève ces contrôles : confinement affaibli, pour un dossier partagé ou un support + monté sans permissions. +- **Windows (volumes).** L’emplacement est ouvert depuis son volume : lettre de lecteur, partage UNC (le partage fait + partie du volume) ou `\\?\Volume{…}` ; un chemin `\\?\GLOBALROOT` (volume sans nom DOS) est refusé (`invalidPath`). +- **Windows.** La racine est tenue sans `FILE_SHARE_DELETE` pendant toute la déclaration, chaque répertoire traversé + pendant toute l’opération (écriture du temporaire et renommage compris), puis relâché une fois la validation + vérifiée : leur renommage ou leur suppression échoue pendant l’opération, plus après. NTFS refuse aussi le renommage + d’un ancêtre sous lequel un handle est ouvert ; le test le vérifie. Coût accepté : la racine ne peut pas être + renommée tant qu’elle est déclarée. +- **Remplacement.** Sous POSIX, le temporaire d’une écriture `replace` est créé en 0600 dans un répertoire privé (0700) + ouvert pour lui, dont l’ACL héritée est retirée avant qu’il existe : il n’hérite d’aucune entrée et personne d’autre + ne peut l’ouvrir dès sa création, même si le fichier à remplacer n’apparaît qu’après `beginWrite()`. À la validation, + sous le verrou du stockage, il prend le groupe (refus si l’utilisateur effectif n’en est pas membre), les bits de + permission (sans setuid, setgid ni bit collant) et l’ACL (ACL étendue de macOS, ACL d’accès POSIX de Linux) du fichier + qu’il remplace à ce moment, et aucune ACL si ce fichier n’en a pas ; sans fichier à remplacer, le nouveau fichier + reste privé (0600). Si l’ACL ne peut être lue ou recopiée (sous macOS, un fichier que l’utilisateur effectif ne peut + pas lire), le remplacement est refusé (`accessDenied`). Le propriétaire devient l’utilisateur effectif. Sous Windows, + le fichier remplacé reçoit l’ACL héritée du dossier, pas celle de l’ancien fichier (limite connue). Un lien suivi dans + la racine ne peut pas désigner un temporaire (`linkRefused`). +- **Détection.** Avant de valider une écriture et après toute opération, le stockage vérifie que le répertoire où il + a agi est encore sous la racine (remontée par `..` jusqu’à l’identité de la racine sous POSIX, chemin final du + handle sous Windows) et que la racine est à son emplacement ; sinon `confinementViolated`, la validation n’a pas lieu + et le temporaire est supprimé. Les renommages, validations, suppressions et créations d’un stockage sont sérialisés. +- **Garantie.** Windows : empêchement pendant toute l’opération. POSIX : empêchement face à tout autre utilisateur que + l’utilisateur effectif et le superutilisateur ; face à eux, détection au mieux : un déplacement entre la dernière + vérification et le renommage, ou pendant l’écriture du temporaire après la vérification, peut laisser un fichier à + l’extérieur. +- **`fs::MemoryStorage`** est le stockage simulé des tests (arbre en mémoire, droits simulés par `setAccess`), et le + modèle d’un stockage sans liens. `fs::StorageHooks` est réservé aux tests : points d’injection entre deux étapes + de résolution, avant l’effet, après la création du temporaire et avant la validation, et substitution de + l’utilisateur effectif ou du propriétaire d’un répertoire. + ## Orientation embarquée, Yocto et mobile | Déclinaison visée | Conséquence de la séparation | Travail d’intégration restant | @@ -120,11 +219,21 @@ un store restent optionnels et demandent un emplacement adapté à la cible. - Respecter le traitement URI de la couche HTTP : ne pas utiliser query ou fragment comme nom de fichier. Ne pas introduire une seconde convention de résolution dans un composant. - Conserver métadonnées MIME/encodage et taille servie cohérentes ; voir ADR-009 pour gzip. +- Ne jamais confiner une écriture ou une lecture de l’hôte par une vérification de chemin suivie d’une ouverture par + nom : passer par un `fs::Storage`, dont chaque opération résout son chemin relativement à la racine ouverte. +- Ne pas présenter `RootOptions::shared` ni un stockage sans liens comme un confinement complet ; documenter la + garantie POSIX (aucun empêchement face au même utilisateur ou au superutilisateur). +- Un nouveau stockage satisfait `fs::Storage`, lève `fs::StorageError` et se teste comme `MemoryStorage` ; un + stockage natif ajoute les tests de liens, de remplacement et de déplacement concurrents par `StorageHooks`. ## Sources et vérification - [DefaultFS](../../include/webfront/system/DefaultFS.hpp), [FileSystem](../../include/webfront/system/FileSystem.hpp), - [NativeFS](../../include/webfront/system/NativeFS.hpp). + [NativeFS](../../include/webfront/system/NativeFS.hpp), [Storage](../../include/webfront/system/Storage.hpp), + [NativeStorage](../../include/webfront/system/NativeStorage.hpp), [MemoryStorage](../../include/webfront/system/MemoryStorage.hpp), + [SafePath](../../include/webfront/system/SafePath.hpp). - Tests : [FileSystemTests](../../test/unit/FileSystemTests.cpp), [DefaultFSTests](../../test/unit/DefaultFSTests.cpp), - [ModuleHTTPServerTests](../../test/unit/ModuleHTTPServerTests.cpp). + [ModuleHTTPServerTests](../../test/unit/ModuleHTTPServerTests.cpp), [StorageTests](../../test/unit/StorageTests.cpp), + [NativeStorageTests](../../test/unit/NativeStorageTests.cpp), [SafePathTests](../../test/unit/SafePathTests.cpp). +- Décision qui motive le stockage modifiable : [ADR-020](ADR-020-services-systeme.md), règles 2 à 4 et prescriptions. - Voir [ADR-009](ADR-009-modules-et-assets-reproductibles.md) et [ADR-010](ADR-010-composants-et-outils-optionnels.md). diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 9a2ca6f9..74c58537 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -11,6 +11,7 @@ | 1.4 | 2026-11-04 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #455 (étape 2) : requêtes partielles `Range` (206, 416, `Accept-Ranges`) pour les fichiers non encodés de taille connue et pour les routes dynamiques (`http::fileReply`, `http::range::select`), `If-Range` sur un `ETag` fort fourni par le fournisseur, plages multiples servies en entier. La liaison à la connexion (#469) reste à faire. | [61a9726](https://github.com/ambroise-leclerc/WebFront/commit/61a9726037edb24cc07601ddc68bcf24b3064d04) | | 1.5 | 2026-11-04 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #469 (étape 2) : `addReadRoute`, `UI::grantRead`, cookie de liaison `wf-client--` échangé contre un secret à usage unique reçu par le pont, mode transférable borné à 15 minutes, en-têtes de neutralisation, jeton masqué des journaux, transport déclaré (`remoteFileTransport`, `loopbackAttested` vérifié à la configuration). Les tests navigateur passent sous WKWebView ; la qualification sous CEF, WebView2, WebKitGTK et les navigateurs système reste à exécuter. | [ecf17ba](https://github.com/ambroise-leclerc/WebFront/commit/ecf17ba124969037fcdaf4ce4175b9b5f53fe661) | | 1.6 | 2026-11-05 | Proposée, partiellement livrée | Ambroise Leclerc | Étape 3 (#448) : chaînes longues, listes, erreurs typées et réponses différées du pont ; les services eux-mêmes restent à livrer. | [a51449b](https://github.com/ambroise-leclerc/WebFront/commit/a51449b7bf7796c2e23bddacf11af5ce891335a0), [c817501](https://github.com/ambroise-leclerc/WebFront/commit/c81750191ff0d1e1e1e8f4b42ee5ef49d0d69d64) | +| 1.7 | 2026-11-05 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #460 (étape 4) : stockage modifiable sous des racines déclarées (ADR-002 3.0), `fs::Storage`, `fs::NativeStorage` confiné pendant la résolution, contrôle des propriétaires POSIX, handles tenus sans partage de suppression sous Windows, `rootMoved` et `confinementViolated`, `fs::MemoryStorage` simulé. Écarts aux prescriptions : descente composant par composant sous Linux plutôt que `openat2`, points de réanalyse jamais suivis sous Windows (refusés à la traversée et à la lecture, signalés par `status`, supprimés eux-mêmes par `remove`), vérification d'appartenance par le chemin final du handle et renommage par `NtSetInformationFile` sous Windows. #461 reste à faire. | [509de1a](https://github.com/ambroise-leclerc/WebFront/commit/509de1a), branche `460-writable-storage` (PR #500) | ## État et chronologie @@ -375,6 +376,8 @@ limites par moteur. #452 est livré dans la version 1.2 (`beforeunload` n'est pa #469 est livré dans la version 1.5 : `app.addReadRoute(préfixe, gestionnaire)` (sous `/webfront/services/`, hors `bind/`) et `ui.grantRead(route, chemin, ReadOptions)` appliquent les règles ci-dessus. Le jeton est `.` placé après le préfixe ; la requête est acceptée si le jeton est connu, non expiré, si la connexion propriétaire est ouverte et si l'un des cookies présentés désigne son client (sauf mode transférable : durée obligatoire de 15 minutes au plus). Un jeton est refusé de la même façon dans tous les cas (`403`, mêmes en-têtes). `WebFront.js` échange le secret reçu par `wfBind.exchange` contre le cookie (`GET /webfront/services/bind/`, puis `check`) et `webFront.bound` rejette avec une erreur explicite si le navigateur refuse le cookie. Le cookie est `Secure` si l'application déclare `httpsByDeployment` (le navigateur utilise `https://`) ; un tunnel chiffré sous `http://` (`encryptedByDeployment`) n'en reçoit pas, car le navigateur refuserait un cookie `Secure` reçu en HTTP. Un transport non local sans déclaration est refusé à l'émission du jeton et à chaque requête. +#460 est livré dans la version 1.7 (révision 3.0 de l'ADR-002, qui en donne le détail) : `fs::NativeStorage` applique les mesures de la section « Prescriptions » à toute opération (listage paginé, métadonnées, lecture, écriture par temporaire et renommage, création, suppression, renommage), avec les erreurs typées `storage.rootMoved`, `storage.confinementViolated`, `storage.unsafeDirectory`, `storage.linkRefused`… (`fs::StorageError`, une `BridgeError`). Quatre écarts aux prescriptions, sans affaiblir la garantie : sous Linux, la descente composant par composant est toujours employée plutôt qu'`openat2`, puisque chaque répertoire traversé doit être ouvert pour contrôler son propriétaire ; sous Windows, un point de réanalyse n'est jamais suivi (`LinkPolicy::followInside` ne vaut que sous POSIX) : une opération qui le traverserait ou le lirait échoue avec `linkRefused`, tandis que `status` le signale comme lien et que `remove` supprime le point lui-même, sans atteindre sa cible ; sous Windows, l'appartenance du répertoire à la racine se vérifie par le chemin final de son handle, les handles tenus empêchant déjà le déplacement ; sous Windows encore, le renommage passe par `NtSetInformationFile`, car `SetFileInformationByHandle` convertit un nom relatif en chemin absolu, que refuse un renommage relatif au handle d'un dossier (`STATUS_INVALID_PARAMETER`). Les tests Catch2 couvrent le stockage simulé, les sorties par liens (jonctions sous Windows), le remplacement concurrent d'un composant ou du fichier final par des points d'injection, une course répétée (POSIX), les déplacements d'un répertoire ou de la racine pendant la résolution, l'écriture du temporaire et avant la validation, et les propriétaires refusés ou admis (simulés, et `/tmp` réel). Les droits refusés par le système réel ne sont simulés que par `fs::MemoryStorage` : un test qui retire des droits sur disque échoue sous le superutilisateur. Le paquet `@webfront/services` (#461) reste à faire. + Après l'étape 4, le premier service (sélecteur HTML, poignées, import et export côté client) fera l'objet de sa propre épique ; les dialogues natifs suivront l'étape 5. `PUT`/`POST` ne sont pas des préalables : les écritures passent par des tableaux typés en morceaux ; leur ajout au serveur, utile aux très gros envois en flux et aux formulaires sans @@ -528,7 +531,8 @@ autorisations explicites, backend par connexion). ouvert, puis `renameat`, `unlinkat`, `mkdirat` relatifs à ce même descripteur. macOS : même descente avec `O_NOFOLLOW` (ou `O_NOFOLLOW_ANY`), `renameatx_np`. Windows : ouvertures relatives au handle du répertoire (`NtCreateFile` avec `RootDirectory`), points de réanalyse refusés par composant (`FILE_FLAG_OPEN_REPARSE_POINT`), - renommage par `SetFileInformationByHandle` sur le handle ouvert. Un lien interne à la racine est suivi seulement si la + renommage par `NtSetInformationFile` (`FileRenameInformation`) sur le handle ouvert, relatif au handle du dossier de + destination (`SetFileInformationByHandle` convertit le nom en chemin absolu et ce renommage échoue). Un lien interne à la racine est suivi seulement si la résolution le confine ; par défaut, les liens sont refusés. Les stockages sans liens (FatFs, LittleFS) se contentent du contrôle syntaxique. - **Déplacement d'un répertoire déjà ouvert.** La résolution par descripteur empêche la substitution d'un composant diff --git a/docs/adr/README.md b/docs/adr/README.md index eaefaa78..7e0fc09c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -42,7 +42,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | ADR | Decision | Status | Initial creation | Current version | | --- | --- | --- | --- | --- | | [ADR-001](ADR-001-coeur-cpp23-header-only.md) | A header-only C++23 core embedded in the application | Accepted | 2020-04-19 | 1.5 — 2026-10-13 | -| [ADR-002](ADR-002-systemes-de-fichiers-composables.md) | An abstract, composable filesystem as the foundation for portability | Accepted | 2023-03-16 | 2.6 — 2026-11-04 | +| [ADR-002](ADR-002-systemes-de-fichiers-composables.md) | An abstract, composable filesystem as the foundation for portability | Accepted | 2023-03-16 | 3.0 — 2026-11-05 | | [ADR-003](ADR-003-protocole-binaire-et-bornes.md) | A shared, typed and bounded binary protocol | Accepted | 2022-02-06 | 1.19 — 2026-11-05 | | [ADR-004](ADR-004-appels-asynchrones-et-erreurs.md) | Asynchronous calls with deliberately asymmetric contracts | Accepted | 2022-02-06 | 2.6 — 2026-11-05 | | [ADR-005](ADR-005-evolution-reseau-asio-stdnet.md) | From standalone ASIO to stdnet: anticipating standard networking without blocking progress | Accepted through 3.1; 3.2 proposed | 2022-01-21 | 3.2 — 2026-10-26 | @@ -60,7 +60,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-017](ADR-017-acces-direct-aux-frontends.md) | Direct access to embedded frontends, with HTML kept normative | Proposed | 2026-10-24 | 1.1 — 2026-10-25 | | [ADR-018](ADR-018-acces-au-dom.md) | DOM access from C++ through a bounded mutation stream, without contesting the DOM of UI libraries | Proposed, partially superseded, partially delivered | 2026-10-26 | 1.5 — 2026-10-30 | | [ADR-019](ADR-019-developpement-automatisable-et-agents.md) | Automating the developer environment through shared operations and an optional local MCP adapter | Accepted | 2026-10-28 | 1.2 — 2026-10-29 | -| [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.6 — 2026-11-05 | +| [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.7 — 2026-11-05 | | [ADR-021](ADR-021-publication-de-l-environnement-developpeur.md) | Simplifying the publication of the developer environment: automate the release, keep pinned hashes, no dedicated server | Accepted (domain delivered; phase 1 to implement) | 2026-11-02 | 1.0 — 2026-11-02 | Numbering follows the reading topics; milestones and individual file histories provide diff --git a/include/webfront/system/FileSystem.hpp b/include/webfront/system/FileSystem.hpp index 6eea3bd5..9e36b8f2 100644 --- a/include/webfront/system/FileSystem.hpp +++ b/include/webfront/system/FileSystem.hpp @@ -12,8 +12,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -34,14 +36,32 @@ concept EncodedData = IsData && HasEncoding; template concept RawData = IsData; +/// @brief The bytes of a file a provider or a storage reads through its own handle: a descriptor opened relative to a +/// storage root (fs::NativeStorage), and later the handles a platform grants instead of a path (an Android +/// `content://` URI, a macOS security-scoped URL), which a provider wraps without WebFront knowing them. +class ByteSource { +public: + virtual ~ByteSource() = default; + /// Reads up to `buffer.size()` bytes; fewer only at the end of the content. + virtual std::size_t read(std::span buffer) = 0; + /// The number of bytes left from the position the source had when the File was built, when known. + [[nodiscard]] virtual std::optional size() const = 0; + /// Positions the next read at `offset` bytes from that original position; false when the source cannot seek. + [[nodiscard]] virtual bool seek(std::uint64_t offset) = 0; +}; + class File { - enum class FileType { nativeFStream, staticData }; + enum class FileType { nativeFStream, staticData, byteSource }; public: File(EncodedData auto t) : File(decltype(t)::data, decltype(t)::dataSize, decltype(t)::encoding) {} File(RawData auto t) : File(decltype(t)::data, decltype(t)::dataSize) {} File(std::span input, size_t fileSize, std::string_view contentEncoding = "") : fileType{FileType::staticData}, data(input), size(fileSize), eofBit(fileSize==0), encoding(contentEncoding) {} File(std::ifstream ifstream) : fileType{FileType::nativeFStream}, fstream{std::move(ifstream)} { measureStream(); } + /// A file read through a provider's own handle (see ByteSource). + explicit File(std::unique_ptr byteSource) : fileType{FileType::byteSource}, source{std::move(byteSource)} { + if (!source) throw std::invalid_argument("A File needs a byte source"); + } [[nodiscard]] bool isEncoded() const { return !encoding.empty(); } [[nodiscard]] std::string_view getEncoding() const { return encoding; } @@ -49,7 +69,10 @@ class File { /// The number of bytes this file yields, when known before reading it (always for embedded data, and for a /// native file whose stream can seek). A server uses it to announce a length and stream the file in chunks. - [[nodiscard]] std::optional knownSize() const { return fileType == FileType::staticData ? std::optional{size} : streamSize; } + [[nodiscard]] std::optional knownSize() const { + if (fileType == FileType::byteSource) return source->size(); + return fileType == FileType::staticData ? std::optional{size} : streamSize; + } /// A strong entity tag (RFC 9110 §8.8.3) for the bytes this file yields, when its provider can guarantee one. /// WebFront derives none from a pathname, a size or a modification time: those can describe another version than @@ -70,6 +93,10 @@ class File { eofBit = readIndex == size; return true; } + if (fileType == FileType::byteSource) { + eofBit = false; + return source->seek(offset); + } if (!streamSize || !fstream.is_open()) return false; const auto target = std::min(offset, *streamSize); fstream.clear(); @@ -83,7 +110,8 @@ class File { // @return bytes read size_t read(std::span buffer) { if (fileType == FileType::staticData) return readData(buffer); - else return readFStream(buffer); + if (fileType == FileType::byteSource) return readSource(buffer); + return readFStream(buffer); } private: @@ -96,6 +124,13 @@ class File { bool eofBit{false}; const std::string encoding{}; std::ifstream fstream; + std::unique_ptr source; + + size_t readSource(std::span buffer) { + const auto count = source->read(buffer); + if (count < buffer.size()) eofBit = true; + return count; + } // The generated headers pack the bytes into big-endian 64-bit words. Each byte is taken from // its word by position, so a read may stop in the middle of a word. diff --git a/include/webfront/system/MemoryStorage.hpp b/include/webfront/system/MemoryStorage.hpp new file mode 100644 index 00000000..e4c31f0a --- /dev/null +++ b/include/webfront/system/MemoryStorage.hpp @@ -0,0 +1,239 @@ +/// @brief A simulated storage held in memory: the backend of the Catch2 tests of the services, and the model of a storage +/// without links (FatFs, LittleFS), where the syntax of SafePath is the whole confinement. +#pragma once + +#include "Storage.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::fs { + +/** + * @brief A storage whose entries live in memory, thread-safe and without links. + * + * Its content is lost with the last copy of the storage (copies share it) and with the writers still open on it. + * setAccess() simulates the rights a system would refuse. + */ +class MemoryStorage { + struct Node { + EntryType type{EntryType::directory}; + std::shared_ptr content; + std::map> children; + std::chrono::system_clock::time_point modified{std::chrono::system_clock::now()}; + bool readable{true}; + bool writable{true}; + }; + + struct State { + std::mutex mutex; + Node root; + }; + + // The bytes a File reads: shared with the node, so a later replacement does not change an opened file. + class Content : public ByteSource { + public: + explicit Content(std::shared_ptr shared) : bytes(std::move(shared)) { } + std::size_t read(std::span buffer) override { + const auto count = std::min(buffer.size(), bytes->size() - position); + std::copy_n(bytes->data() + position, count, buffer.data()); + position += count; + return count; + } + [[nodiscard]] std::optional size() const override { + return bytes->size(); + } + [[nodiscard]] bool seek(std::uint64_t offset) override { + position = static_cast(std::min(offset, bytes->size())); + return true; + } + + private: + std::shared_ptr bytes; + std::size_t position{}; + }; + +public: + MemoryStorage() : state(std::make_shared()) { } + + /// A write in progress, buffered in memory until commit(). + class Writer { + public: + void write(std::span bytes) { + if (done) + throw std::logic_error("The write is already committed"); + buffer.append(bytes.data(), bytes.size()); + } + + void commit() { + if (done) + throw std::logic_error("The write is already committed"); + std::scoped_lock lock(state->mutex); + auto& parent = directory(state->root, components, components.size() - 1, true); + const auto& name = components.back(); + if (auto existing = parent.children.find(name); existing != parent.children.end()) { + if (mode == WriteMode::createNew) + throw StorageError(StorageErrc::alreadyExists, "'" + detail::joinComponents(components) + "' already exists"); + if (existing->second.type == EntryType::directory) + throw StorageError(StorageErrc::isDirectory, "'" + detail::joinComponents(components) + "' is a directory"); + if (!existing->second.writable) + throw StorageError(StorageErrc::accessDenied, "'" + detail::joinComponents(components) + "' is read-only"); + } + Node file; + file.type = EntryType::file; + file.content = std::make_shared(std::move(buffer)); + parent.children.insert_or_assign(name, std::move(file)); + done = true; + } + + private: + friend class MemoryStorage; + Writer(std::shared_ptr storageState, std::vector path, WriteMode writeMode) + : state(std::move(storageState)), components(std::move(path)), mode(writeMode) { } + + std::shared_ptr state; + std::vector components; + WriteMode mode; + std::string buffer; + bool done{false}; + }; + + DirectoryPage list(std::string_view path, std::string_view after = {}, std::size_t limit = maxStoragePageSize) { + const auto components = detail::storageComponents(path); + std::vector entries; + { + std::scoped_lock lock(state->mutex); + const auto& node = directory(state->root, components, components.size(), false); + if (!node.readable) + throw StorageError(StorageErrc::accessDenied, "Cannot list '" + std::string(path) + "'"); + for (const auto& [name, child] : node.children) + entries.push_back(info(name, child)); + } + return detail::pageOf(std::move(entries), after, limit); + } + + EntryInfo status(std::string_view path) { + const auto components = detail::storageComponents(path); + std::scoped_lock lock(state->mutex); + if (components.empty()) + return info({}, state->root); + return info(components.back(), entry(components)); + } + + File openRead(std::string_view path) { + const auto components = detail::entryComponents(path); + std::scoped_lock lock(state->mutex); + const auto& node = entry(components); + if (node.type == EntryType::directory) + throw StorageError(StorageErrc::isDirectory, "'" + std::string(path) + "' is a directory"); + if (!node.readable) + throw StorageError(StorageErrc::accessDenied, "Cannot read '" + std::string(path) + "'"); + return File{std::make_unique(node.content)}; + } + + Writer beginWrite(std::string_view path, WriteMode mode) { + auto components = detail::entryComponents(path); + std::scoped_lock lock(state->mutex); + directory(state->root, components, components.size() - 1, true); + return Writer{state, std::move(components), mode}; + } + + void createDirectory(std::string_view path) { + const auto components = detail::entryComponents(path); + std::scoped_lock lock(state->mutex); + auto& parent = directory(state->root, components, components.size() - 1, true); + if (parent.children.contains(components.back())) + throw StorageError(StorageErrc::alreadyExists, "'" + std::string(path) + "' already exists"); + parent.children.emplace(components.back(), Node{}); + } + + void remove(std::string_view path) { + const auto components = detail::entryComponents(path); + std::scoped_lock lock(state->mutex); + auto& parent = directory(state->root, components, components.size() - 1, true); + const auto found = parent.children.find(components.back()); + if (found == parent.children.end()) + throw StorageError(StorageErrc::notFound, "'" + std::string(path) + "' does not exist"); + if (found->second.type == EntryType::directory && !found->second.children.empty()) + throw StorageError(StorageErrc::notEmpty, "'" + std::string(path) + "' is not empty"); + parent.children.erase(found); + } + + void rename(std::string_view from, std::string_view to) { + const auto source = detail::entryComponents(from); + const auto target = detail::entryComponents(to); + std::scoped_lock lock(state->mutex); + auto& sourceParent = directory(state->root, source, source.size() - 1, true); + const auto found = sourceParent.children.find(source.back()); + if (found == sourceParent.children.end()) + throw StorageError(StorageErrc::notFound, "'" + std::string(from) + "' does not exist"); + if (found->second.type == EntryType::directory && std::ranges::equal(source, target | std::views::take(source.size()))) + throw StorageError(StorageErrc::invalidPath, "Cannot move '" + std::string(from) + "' into itself"); + auto& targetParent = directory(state->root, target, target.size() - 1, true); + if (targetParent.children.contains(target.back())) + throw StorageError(StorageErrc::alreadyExists, "'" + std::string(to) + "' already exists"); + auto node = std::move(found->second); + sourceParent.children.erase(found); + targetParent.children.emplace(target.back(), std::move(node)); + } + + /// Simulates the rights the system grants on an entry: an unreadable directory cannot be listed nor traversed, an + /// unwritable directory refuses entries to be created, removed or renamed in it, an unwritable file refuses to be + /// replaced, an unreadable file to be opened. + void setAccess(std::string_view path, bool readable, bool writable) { + const auto components = detail::storageComponents(path); + std::scoped_lock lock(state->mutex); + auto& node = components.empty() ? state->root : entry(components); + node.readable = readable; + node.writable = writable; + } + +private: + std::shared_ptr state; + + static EntryInfo info(std::string name, const Node& node) { + return {std::move(name), node.type, node.content ? node.content->size() : 0, node.modified, node.readable, node.writable}; + } + + // The directory made of the first `count` components, traversable, and writable when `forChange` is set. + static Node& directory(Node& root, const std::vector& components, std::size_t count, bool forChange) { + Node* node = &root; + for (std::size_t index = 0; index < count; ++index) { + if (!node->readable) + throw StorageError(StorageErrc::accessDenied, "Cannot traverse '" + prefix(components, index) + "'"); + const auto found = node->children.find(components[index]); + if (found == node->children.end()) + throw StorageError(StorageErrc::notFound, "'" + prefix(components, index + 1) + "' does not exist"); + if (found->second.type != EntryType::directory) + throw StorageError(StorageErrc::notDirectory, "'" + prefix(components, index + 1) + "' is not a directory"); + node = &found->second; + } + if (!node->readable || (forChange && !node->writable)) + throw StorageError(StorageErrc::accessDenied, "Access to '" + prefix(components, count) + "' is denied"); + return *node; + } + + Node& entry(const std::vector& components) { + auto& parent = directory(state->root, components, components.size() - 1, false); + const auto found = parent.children.find(components.back()); + if (found == parent.children.end()) + throw StorageError(StorageErrc::notFound, "'" + detail::joinComponents(components) + "' does not exist"); + return found->second; + } + + static std::string prefix(const std::vector& components, std::size_t count) { + return detail::joinComponents({components.begin(), components.begin() + static_cast(count)}); + } +}; + +static_assert(Storage); + +} // namespace webfront::fs diff --git a/include/webfront/system/NativeStorage.hpp b/include/webfront/system/NativeStorage.hpp new file mode 100644 index 00000000..98a42e85 --- /dev/null +++ b/include/webfront/system/NativeStorage.hpp @@ -0,0 +1,1888 @@ +/// @brief Writable storage on the host's file system, confined to a declared root while resolving every path (ADR-002, +/// ADR-020): operations are relative to directories already opened, never a check of a path followed by an open by name. +#pragma once + +#include "Storage.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + #include "WindowsCompat.hpp" + + #include + #include + #include + #include + #include + + #include +#else + #include + + #include + #include + #include + #include + #if defined(__APPLE__) + #include + #include + #include + #include + #elif defined(__linux__) + #include + #include + #endif +#endif + +namespace webfront::fs { + +/// What resolving a path does with a symbolic link (or, on Windows, any reparse point: links and junctions). +enum class LinkPolicy { + refuse, ///< any link on the path fails with linkRefused (the default) + followInside ///< a relative link is followed when its resolution stays inside the root (POSIX; refused on Windows) +}; + +/// How a root is declared. +struct RootOptions { + /// Lifts the POSIX ownership checks of the root's directories and ancestors, for a shared folder or a removable + /// medium mounted without permissions. The confinement is weakened: another user who can write in one of those + /// directories can move it, and the storage's later operations with it, out of the root. + bool shared{false}; + LinkPolicy links{LinkPolicy::refuse}; +}; + +/// The points of an operation where StorageHooks::at is called, so that a test injects a concurrent change exactly there. +enum class StoragePoint { + componentOpened, ///< a directory of the path was opened (argument: its name); the next one is not opened yet + resolved, ///< the path is resolved, the operation has no effect yet (argument: the final name) + temporaryCreated, ///< a write created its temporary file, before writing to it (argument: the final name) + beforeCommit ///< a commit is about to check the confinement, then rename (argument: the final name) +}; + +/// The POSIX owner and mode of a directory, as the ownership checks see them. +struct DirectoryFacts { + std::uint32_t owner{}; + std::uint32_t mode{}; + /// An extended ACL (macOS) lets someone else than the effective user and the superuser add, remove or rename + /// entries of the directory, delete it, or change its ACL or owner. Linux POSIX ACLs need no such flag: a named + /// entry that grants writing also sets the group write bit of the mode (the ACL mask). + bool othersMayChange{}; +}; + +/** + * @brief Injection points for the tests of a NativeStorage. Production code passes none. + * + * `at` runs on the thread of the operation, at the points StoragePoint lists. `effectiveUser` replaces the effective + * user the POSIX checks admit, and `facts` may rewrite what fstat() reported of a directory (its absolute path is + * given), so that a test simulates a directory owned by another user without being the superuser. + */ +struct StorageHooks { + std::function at; + std::optional effectiveUser; + std::function facts; +}; + +namespace detail { + + +inline std::string temporaryName() { + thread_local std::mt19937_64 random{std::random_device{}()}; + static constexpr char digits[] = "0123456789abcdef"; + std::string name(temporaryPrefix); + auto bits = random(); + for (int index = 0; index < 16; ++index, bits >>= 4) + name += digits[bits & 0xF]; + return name; +} + +inline std::string quoted(const std::vector& components) { + return "'" + joinComponents(components) + "'"; +} + +} // namespace detail + +/** + * @brief A writable storage under a root directory of the host, which satisfies fs::Storage. + * + * The root is the canonical form of the location given at construction (links in it are resolved once, at the + * declaration). Every operation then: + * - checks that this location, resolved component by component without following links, still designates the + * directory opened at declaration; otherwise it fails with rootMoved, and every later operation too; + * - resolves its path from the root's descriptor (POSIX) or handle (Windows), one component at a time, refusing links + * unless RootOptions::links follows them inside the root; no descriptor outlives the operation; + * - POSIX: checks that each directory traversed, the root and its ancestors cannot be moved by another user: each must + * belong to the effective user or the superuser and be writable by neither the group nor the others, except an + * ancestor with the sticky bit whose next element belongs to one of them (the case of `/tmp`); otherwise + * unsafeDirectory, before any effect (RootOptions::shared lifts these checks); + * - Windows: holds the root and every directory traversed without sharing their deletion, so that nobody can rename or + * remove them during the operation (and the root during the whole declaration); + * - before committing a write and after every operation, checks that the directory it acted in is still under the root + * (up through `..` on POSIX) and that the root is still at its location; otherwise confinementViolated (the + * temporary file of a write is removed and the write not committed). + * + * Guarantee: on Windows, these directories cannot move during an operation. On POSIX, no other user than the effective + * one and the superuser can move them; those two can, and the last check only detects a move it sees: a move between + * that check and the rename, or during the write of the temporary file, can leave a file outside the root. + * + * Renames, commits, removals and directory creations of a storage are serialized. Entries whose name SafePath would + * reject, and the temporary files of writes in progress, are not listed. + */ +class NativeStorage { + struct State; + +public: + /// Declares a root. + /// @throws StorageError notFound or notDirectory when the location is not an existing directory, unsafeDirectory + /// when a POSIX check refuses it, linkRefused when it is a Windows reparse point. + explicit NativeStorage(const std::filesystem::path& location, RootOptions options = {}, std::shared_ptr hooks = {}); + + /// The canonical location of the root, for the application. Never send it to JavaScript unless it should know it. + [[nodiscard]] const std::filesystem::path& location() const; + + class Writer; + + DirectoryPage list(std::string_view path, std::string_view after = {}, std::size_t limit = maxStoragePageSize); + EntryInfo status(std::string_view path); + File openRead(std::string_view path); + Writer beginWrite(std::string_view path, WriteMode mode); + void createDirectory(std::string_view path); + void remove(std::string_view path); + void rename(std::string_view from, std::string_view to); + +private: + std::shared_ptr state; +}; + +#ifndef _WIN32 + +namespace detail::posix { + + #if defined(__linux__) && defined(O_PATH) +inline constexpr int searchFlags = O_PATH | O_DIRECTORY; + #elif defined(O_SEARCH) +inline constexpr int searchFlags = O_SEARCH; + #else +inline constexpr int searchFlags = O_RDONLY | O_DIRECTORY; + #endif + +class Fd { +public: + Fd() = default; + explicit Fd(int value) : descriptor(value) { } + Fd(Fd&& other) noexcept : descriptor(std::exchange(other.descriptor, -1)) { } + Fd& operator=(Fd&& other) noexcept { + if (this != &other) { + reset(); + descriptor = std::exchange(other.descriptor, -1); + } + return *this; + } + Fd(const Fd&) = delete; + Fd& operator=(const Fd&) = delete; + ~Fd() { + reset(); + } + + [[nodiscard]] int get() const noexcept { + return descriptor; + } + [[nodiscard]] explicit operator bool() const noexcept { + return descriptor >= 0; + } + int release() noexcept { + return std::exchange(descriptor, -1); + } + void reset() noexcept { + if (descriptor >= 0) + ::close(descriptor); + descriptor = -1; + } + +private: + int descriptor{-1}; +}; + +struct Identity { + dev_t device{}; + ino_t inode{}; + bool operator==(const Identity&) const = default; +}; + +inline Identity identityOf(const struct stat& status) { + return {status.st_dev, status.st_ino}; +} + +inline StorageErrc errcOf(int error) { + switch (error) { + case ENOENT: + return StorageErrc::notFound; + case EEXIST: + return StorageErrc::alreadyExists; + case ENOTDIR: + return StorageErrc::notDirectory; + case EISDIR: + return StorageErrc::isDirectory; + case ENOTEMPTY: + return StorageErrc::notEmpty; + case EACCES: + case EPERM: + case EROFS: + return StorageErrc::accessDenied; + case ELOOP: + return StorageErrc::linkRefused; + case EBUSY: + case ETXTBSY: + return StorageErrc::busy; + case EINVAL: + case ENAMETOOLONG: + return StorageErrc::invalidPath; + default: + return StorageErrc::ioError; + } +} + +[[noreturn]] inline void fail(int error, const std::string& what) { + throw StorageError(errcOf(error), what + ": " + std::generic_category().message(error)); +} + +inline Fd openAt(int directory, const char* name, int flags, mode_t mode = 0) { + int descriptor; + do + descriptor = ::openat(directory, name, flags | O_CLOEXEC, mode); + while (descriptor < 0 && errno == EINTR); + return Fd{descriptor}; +} + +inline struct stat statOf(int descriptor, const std::string& what) { + struct stat status{}; + if (::fstat(descriptor, &status) != 0) + fail(errno, what); + return status; +} + +inline std::chrono::system_clock::time_point modifiedOf(const struct stat& status) { + #if defined(__APPLE__) + const auto& time = status.st_mtimespec; + #else + const auto& time = status.st_mtim; + #endif + return std::chrono::system_clock::time_point{ + std::chrono::duration_cast(std::chrono::seconds{time.tv_sec} + std::chrono::nanoseconds{time.tv_nsec})}; +} + +inline bool inGroup(gid_t group) { + if (group == ::getegid()) + return true; + const int count = ::getgroups(0, nullptr); + if (count <= 0) + return false; + std::vector groups(static_cast(count)); + const int found = ::getgroups(count, groups.data()); + return found > 0 && std::ranges::find(groups.begin(), groups.begin() + found, group) != groups.begin() + found; +} + +inline EntryInfo infoOf(std::string name, const struct stat& status) { + EntryInfo info{.name = std::move(name), .modified = modifiedOf(status)}; + if (S_ISREG(status.st_mode)) { + info.type = EntryType::file; + info.size = static_cast(status.st_size); + } else if (S_ISDIR(status.st_mode)) + info.type = EntryType::directory; + else if (S_ISLNK(status.st_mode)) + info.type = EntryType::link; + const auto user = ::geteuid(); + if (user == 0) { + info.readable = info.writable = true; + return info; + } + const mode_t shift = status.st_uid == user ? 6 : inGroup(status.st_gid) ? 3 : 0; + info.readable = (status.st_mode >> shift) & 04; + info.writable = (status.st_mode >> shift) & 02; + return info; +} + +// The rename that refuses to replace: renameat2(RENAME_NOREPLACE) on Linux, renameatx_np(RENAME_EXCL) on macOS. On a +// Linux file system without it, a file is linked then unlinked (link() never replaces); a directory, which no atomic +// primitive can then move without risking to replace an empty directory created meanwhile, is refused (ENOTSUP). +inline int renameNoReplace(int fromDirectory, const char* from, int toDirectory, const char* to) { + #if defined(__APPLE__) + return ::renameatx_np(fromDirectory, from, toDirectory, to, RENAME_EXCL); + #else + #if defined(SYS_renameat2) + constexpr unsigned noReplace = 1; // RENAME_NOREPLACE + if (::syscall(SYS_renameat2, fromDirectory, from, toDirectory, to, noReplace) == 0) + return 0; + if (errno != ENOSYS && errno != EINVAL) + return -1; + #endif + struct stat status{}; + if (::fstatat(fromDirectory, from, &status, AT_SYMLINK_NOFOLLOW) != 0) + return -1; + if (!S_ISDIR(status.st_mode)) { + if (::linkat(fromDirectory, from, toDirectory, to, 0) != 0) + return -1; + return ::unlinkat(fromDirectory, from, 0); + } + errno = ENOTSUP; + return -1; + #endif +} + +// The file system has no ACL or extended attribute. ENOTSUP and EOPNOTSUPP are the same value on Linux, not on macOS. +inline bool unsupported(int error) noexcept { + #if ENOTSUP == EOPNOTSUPP + return error == ENOTSUP; + #else + return error == ENOTSUP || error == EOPNOTSUPP; + #endif +} + +// True when an extended ACL of the directory grants someone else than `user` and the superuser a right to change its +// entries, delete it, or change its ACL or owner. Fails closed: an ACL that cannot be read counts as granting. +inline bool othersMayChange(int directory, std::uint32_t user) { + #if defined(__APPLE__) + acl_t acl = ::acl_get_fd_np(directory, ACL_TYPE_EXTENDED); + if (!acl) + return errno != ENOENT && !unsupported(errno); + uuid_t admitted[2]{}; + if (::mbr_uid_to_uuid(static_cast(user), admitted[0]) != 0 || ::mbr_uid_to_uuid(0, admitted[1]) != 0) { + ::acl_free(acl); + return true; + } + bool granting = false; + acl_entry_t entry{}; + for (int which = ACL_FIRST_ENTRY; !granting && ::acl_get_entry(acl, which, &entry) == 0; which = ACL_NEXT_ENTRY) { + acl_tag_t tag{}; + acl_permset_t permissions{}; + if (::acl_get_tag_type(entry, &tag) != 0 || ::acl_get_permset(entry, &permissions) != 0) { + granting = true; + break; + } + if (tag != ACL_EXTENDED_ALLOW) + continue; + // An entry marked only_inherit applies to the descendants it is passed on to, not to this directory: a + // subdirectory that inherits it is checked in its turn when an operation traverses it. + acl_flagset_t flags{}; + if (::acl_get_flagset_np(entry, &flags) != 0) { + granting = true; + break; + } + if (::acl_get_flag_np(flags, ACL_ENTRY_ONLY_INHERIT) == 1) + continue; + bool changes = false; + for (const auto permission : {ACL_ADD_FILE, ACL_ADD_SUBDIRECTORY, ACL_DELETE_CHILD, ACL_DELETE, ACL_WRITE_SECURITY, ACL_CHANGE_OWNER}) + changes = changes || ::acl_get_perm_np(permissions, permission) == 1; + if (!changes) + continue; + auto* qualifier = static_cast(::acl_get_qualifier(entry)); + granting = !qualifier || (::uuid_compare(qualifier, admitted[0]) != 0 && ::uuid_compare(qualifier, admitted[1]) != 0); + if (qualifier) + ::acl_free(qualifier); + } + ::acl_free(acl); + return granting; + #else + (void)directory; + (void)user; + return false; + #endif +} + +// Gives the temporary file of a replacing write the access control list of the file it replaces (macOS extended ACL, +// Linux POSIX access ACL). Throws accessDenied when an existing ACL cannot be read or copied: the replacement is then +// refused rather than publishing the new content with looser rights. On macOS, reading the ACL through a descriptor +// needs the right to read the file: a file the effective user may not read cannot be replaced. +inline void copyAccessControl(int directory, const std::string& name, int temporary, const std::string& what) { + #if defined(__APPLE__) + const Fd existing = openAt(directory, name.c_str(), O_EVTONLY | O_NOFOLLOW); + if (!existing) { + if (errno == ENOENT) + return; + throw StorageError(StorageErrc::accessDenied, "Cannot read the access control list of " + what); + } + acl_t acl = ::acl_get_fd_np(existing.get(), ACL_TYPE_EXTENDED); + if (!acl) { + if (unsupported(errno)) + return; + if (errno != ENOENT) + throw StorageError(StorageErrc::accessDenied, "Cannot read the access control list of " + what); + // No ACL on the replaced file: the temporary file must not keep entries it inherited from its directory. + acl = ::acl_init(0); + if (!acl) + throw StorageError(StorageErrc::accessDenied, "Cannot keep the access control list of " + what); + } + const int copied = ::acl_set_fd_np(temporary, acl, ACL_TYPE_EXTENDED); + ::acl_free(acl); + if (copied != 0) + throw StorageError(StorageErrc::accessDenied, "Cannot keep the access control list of " + what); + #elif defined(__linux__) + const Fd existing = openAt(directory, name.c_str(), O_PATH | O_NOFOLLOW); + if (!existing) { + if (errno == ENOENT) + return; + fail(errno, "Cannot read the access control list of " + what); + } + // An O_PATH descriptor has no fgetxattr(): its /proc link reads the attribute of that very file. + const auto link = "/proc/self/fd/" + std::to_string(existing.get()); + const char* key = "system.posix_acl_access"; + auto size = ::getxattr(link.c_str(), key, nullptr, 0); + if (size < 0) { + if (unsupported(errno)) + return; + if (errno != ENODATA) + throw StorageError(StorageErrc::accessDenied, "Cannot read the access control list of " + what); + // No ACL on the replaced file: the temporary file must not keep the one a default ACL of its directory gave it. + if (::fremovexattr(temporary, key) != 0 && errno != ENODATA) + throw StorageError(StorageErrc::accessDenied, "Cannot keep the access control list of " + what); + return; + } + std::vector acl(static_cast(size)); + size = ::getxattr(link.c_str(), key, acl.data(), acl.size()); + if (size < 0 || ::fsetxattr(temporary, key, acl.data(), static_cast(size), 0) != 0) + throw StorageError(StorageErrc::accessDenied, "Cannot keep the access control list of " + what); + #else + (void)directory; + (void)name; + (void)temporary; + (void)what; + #endif +} + +// Removes from a new file the access control list its directory passed on to it, so that its mode alone decides who may +// read it: a macOS ACL inherited with file_inherit is not limited by the mode. On Linux a default ACL is limited by the +// mode the file was created with, and is removed too. +inline void clearAccessControl(int file, const std::string& what) { + #if defined(__APPLE__) + acl_t empty = ::acl_init(0); + if (!empty) + throw StorageError(StorageErrc::accessDenied, "Cannot make " + what + " private"); + const int cleared = ::acl_set_fd_np(file, empty, ACL_TYPE_EXTENDED); + const int error = errno; + ::acl_free(empty); + if (cleared != 0 && !unsupported(error)) + throw StorageError(StorageErrc::accessDenied, "Cannot make " + what + " private"); + #elif defined(__linux__) + if (::fremovexattr(file, "system.posix_acl_access") != 0 && errno != ENODATA && !unsupported(errno)) + throw StorageError(StorageErrc::accessDenied, "Cannot make " + what + " private"); + #else + (void)file; + (void)what; + #endif +} + +// The content of a file opened relative to a directory of the root. +class FdSource : public ByteSource { +public: + FdSource(Fd opened, std::uint64_t length) : file(std::move(opened)), total(length) { } + + std::size_t read(std::span buffer) override { + std::size_t count = 0; + while (count < buffer.size()) { + const auto got = ::read(file.get(), buffer.data() + count, buffer.size() - count); + if (got < 0 && errno == EINTR) + continue; + if (got < 0) + fail(errno, "Cannot read the file"); + if (got == 0) + break; + count += static_cast(got); + } + return count; + } + [[nodiscard]] std::optional size() const override { + return total; + } + [[nodiscard]] bool seek(std::uint64_t offset) override { + return ::lseek(file.get(), static_cast(std::min(offset, total)), SEEK_SET) >= 0; + } + +private: + Fd file; + std::uint64_t total; +}; + +} // namespace detail::posix + +struct NativeStorage::State { + using Fd = detail::posix::Fd; + using Identity = detail::posix::Identity; + + std::filesystem::path location; + std::vector locationComponents; + RootOptions options; + std::shared_ptr hooks; + Fd root; + Identity rootIdentity; + std::uint32_t effectiveUser{}; + std::mutex structure; + std::atomic moved{false}; + + // The directories an operation holds, from the root down to the one it acts in. + struct Walk { + std::vector directories; + std::vector names; + int links{}; + + [[nodiscard]] int top() const { + return directories.back().get(); + } + }; + + void notify(StoragePoint point, std::string_view name) const { + if (hooks && hooks->at) + hooks->at(point, name); + } + + [[nodiscard]] bool admissible(std::uint32_t owner) const { + return owner == effectiveUser || owner == 0; + } + + DirectoryFacts factsOf(int directory, const std::filesystem::path& path) const { + const auto status = detail::posix::statOf(directory, "Cannot inspect a directory of the root or an ancestor"); + DirectoryFacts facts{static_cast(status.st_uid), + static_cast(status.st_mode), + !options.shared && detail::posix::othersMayChange(directory, effectiveUser)}; + if (hooks && hooks->facts) + hooks->facts(path, facts); + return facts; + } + + // A directory of the root, the root included: only an admissible owner may move its entries out. + void checkTraversed(const DirectoryFacts& facts, const std::string& what) const { + if (options.shared) + return; + if (!admissible(facts.owner) || (facts.mode & (S_IWGRP | S_IWOTH)) != 0 || facts.othersMayChange) + throw StorageError(StorageErrc::unsafeDirectory, what + " can be moved by another user"); + } + + // An ancestor of the root, and the element of the location that follows it. + void checkAncestor(const DirectoryFacts& ancestor, const DirectoryFacts& next) const { + if (options.shared) + return; + const bool othersWrite = (ancestor.mode & (S_IWGRP | S_IWOTH)) != 0; + const bool sticky = (ancestor.mode & S_ISVTX) != 0; + if (!admissible(ancestor.owner) || ancestor.othersMayChange || (othersWrite && !(sticky && admissible(next.owner)))) + throw StorageError(StorageErrc::unsafeDirectory, "An ancestor of the root can be moved by another user"); + } + + // Opens the declared location from `/` without following links, checking every ancestor. `onMove` is the error a + // location that no longer leads to a directory reports. + Fd openLocation(StorageErrc onMove) const { + Fd current = detail::posix::openAt(AT_FDCWD, "/", detail::posix::searchFlags); + if (!current) + detail::posix::fail(errno, "Cannot open the file system root"); + std::filesystem::path path = "/"; + auto facts = factsOf(current.get(), path); + for (const auto& component : locationComponents) { + Fd next = detail::posix::openAt(current.get(), component.c_str(), detail::posix::searchFlags | O_NOFOLLOW); + if (!next) { + // Only a missing component, a non-directory or a link shows that the location changed; any other + // failure (EMFILE, ENOMEM, EACCES, EIO...) is reported as such and does not mark the root as moved. + const int error = errno; + if (error != ENOENT && error != ENOTDIR && error != ELOOP && error != EMLINK) + detail::posix::fail(error, "Cannot reach the root"); + throw StorageError(onMove, "The root is no longer at its declared location"); + } + path /= component; + const auto nextFacts = factsOf(next.get(), path); + checkAncestor(facts, nextFacts); + facts = nextFacts; + current = std::move(next); + } + checkTraversed(facts, "The root"); + return current; + } + + // Fails with rootMoved, now and for every later operation, when the declared location designates another directory. + void verifyLocation() { + if (moved) + throw StorageError(StorageErrc::rootMoved, "The root is no longer at its declared location"); + try { + const auto found = openLocation(StorageErrc::rootMoved); + if (detail::posix::identityOf(detail::posix::statOf(found.get(), "Cannot inspect the root")) != rootIdentity) + throw StorageError(StorageErrc::rootMoved, "The root is no longer at its declared location"); + } catch (const StorageError& error) { + if (error.errc() == StorageErrc::rootMoved) + moved = true; + throw; + } + } + + // True when `directory` is the root or below it, walking up through "..". + bool isUnderRoot(int directory) const { + auto current = detail::posix::openAt(directory, ".", detail::posix::searchFlags); + for (int depth = 0; current && depth < 4096; ++depth) { + struct stat status{}; + if (::fstat(current.get(), &status) != 0) + return false; + const auto identity = detail::posix::identityOf(status); + if (identity == rootIdentity) + return true; + auto parent = detail::posix::openAt(current.get(), "..", detail::posix::searchFlags); + struct stat parentStatus{}; + if (!parent || ::fstat(parent.get(), &parentStatus) != 0 || detail::posix::identityOf(parentStatus) == identity) + return false; + current = std::move(parent); + } + return false; + } + + // The check that follows an operation and precedes a commit: confinementViolated when a directory left the root. + void confirm(std::initializer_list directories) { + for (const int directory : directories) + if (!isUnderRoot(directory)) + throw StorageError(StorageErrc::confinementViolated, "A directory left the root during the operation"); + try { + verifyLocation(); + } catch (const StorageError& error) { + if (error.errc() != StorageErrc::rootMoved) + throw; + throw StorageError(StorageErrc::confinementViolated, "The root moved during the operation"); + } + } + + Walk start() { + verifyLocation(); + Walk walk; + auto top = detail::posix::openAt(root.get(), ".", detail::posix::searchFlags); + if (!top) + detail::posix::fail(errno, "Cannot open the root"); + walk.directories.push_back(std::move(top)); + return walk; + } + + // Replaces the link `name` of the top directory by its target in `pending`, when the policy follows it. + void spliceLink(Walk& walk, const std::string& name, std::deque& pending) const { + auto named = walk.names; + named.push_back(name); + const auto where = detail::quoted(named); + if (options.links != LinkPolicy::followInside) + throw StorageError(StorageErrc::linkRefused, where + " is a link"); + if (++walk.links > 32) + throw StorageError(StorageErrc::linkRefused, "Too many links resolving " + where); + // readlinkat() truncates silently: a target that fills the buffer may be longer, and is refused rather than + // resolved as another path. + std::string target(4097, '\0'); + const auto length = ::readlinkat(walk.top(), name.c_str(), target.data(), target.size()); + if (length < 0) + detail::posix::fail(errno, "Cannot read the link " + where); + if (static_cast(length) >= target.size()) + throw StorageError(StorageErrc::linkRefused, "The target of the link " + where + " is too long"); + target.resize(static_cast(length)); + if (target.empty() || target.front() == '/') + throw StorageError(StorageErrc::linkRefused, "The link " + where + " is absolute"); + std::vector parts; + for (const auto part : std::views::split(std::string_view(target), '/')) + if (!part.empty()) + parts.emplace_back(part.begin(), part.end()); + // A link must not reach what a path may not name: the temporary file of a write in progress. + if (std::ranges::any_of(parts, [](const std::string& part) { + return isTemporaryName(part); + })) + throw StorageError(StorageErrc::linkRefused, "The link " + where + " names a temporary file"); + pending.insert(pending.begin(), parts.begin(), parts.end()); + } + + // Opens the directories of `pending` from the top of the walk until `keep` components remain. + void descend(Walk& walk, std::deque& pending, std::size_t keep) { + while (pending.size() > keep) { + auto name = std::move(pending.front()); + pending.pop_front(); + if (name == ".") + continue; + if (name == "..") { + if (walk.names.empty()) + throw StorageError(StorageErrc::linkRefused, "A link leads out of the root"); + walk.directories.pop_back(); + walk.names.pop_back(); + continue; + } + auto next = detail::posix::openAt(walk.top(), name.c_str(), detail::posix::searchFlags | O_NOFOLLOW); + if (!next) { + const int error = errno; + struct stat status{}; + if (::fstatat(walk.top(), name.c_str(), &status, AT_SYMLINK_NOFOLLOW) == 0) { + if (S_ISLNK(status.st_mode)) { + spliceLink(walk, name, pending); + continue; + } + if (!S_ISDIR(status.st_mode)) + throw StorageError(StorageErrc::notDirectory, "'" + name + "' is not a directory"); + } + detail::posix::fail(error, "Cannot open '" + name + "'"); + } + walk.names.push_back(name); + auto path = location; + for (const auto& component : walk.names) + path /= component; + checkTraversed(factsOf(next.get(), path), detail::quoted(walk.names)); + walk.directories.push_back(std::move(next)); + notify(StoragePoint::componentOpened, walk.names.back()); + } + } + + // The parent directory of a path and its final name. + std::pair resolveParent(const std::vector& components) { + auto walk = start(); + std::deque pending(components.begin(), components.end()); + descend(walk, pending, 1); + return {std::move(walk), std::move(pending.front())}; + } + + // Opens the final name of a resolution, following links inside the root when the policy allows. + Fd openFinal(Walk& walk, std::string& name, int flags) { + while (true) { + auto file = detail::posix::openAt(walk.top(), name.c_str(), flags | O_NOFOLLOW); + if (file) + return file; + const int error = errno; + struct stat status{}; + if ((error == ELOOP || error == EMLINK || error == ENOTDIR) && ::fstatat(walk.top(), name.c_str(), &status, AT_SYMLINK_NOFOLLOW) == 0 + && S_ISLNK(status.st_mode)) { + std::deque pending; + spliceLink(walk, name, pending); + if (pending.empty()) + throw StorageError(StorageErrc::linkRefused, "The link '" + name + "' names a directory"); + descend(walk, pending, 1); + name = std::move(pending.front()); + if (name == "." || name == "..") + throw StorageError(StorageErrc::linkRefused, "A link names a directory, not a file"); + continue; + } + detail::posix::fail(error, "Cannot open '" + name + "'"); + } + } +}; + +class NativeStorage::Writer { +public: + Writer(Writer&&) noexcept = default; + Writer& operator=(Writer&&) = delete; // would drop the temporary file of the writer it replaces + Writer(const Writer&) = delete; + Writer& operator=(const Writer&) = delete; + ~Writer() { + abandon(); + } + + void write(std::span bytes) { + if (!file) + throw std::logic_error("The write is committed or abandoned"); + while (!bytes.empty()) { + const auto written = ::write(file.get(), bytes.data(), bytes.size()); + if (written < 0 && errno == EINTR) + continue; + if (written < 0) + detail::posix::fail(errno, "Cannot write " + detail::quoted(components)); + bytes = bytes.subspan(static_cast(written)); + } + } + + void commit() { + if (!file) + throw std::logic_error("The write is committed or abandoned"); + if (::fsync(file.get()) != 0) { + const int error = errno; + abandon(); + detail::posix::fail(error, "Cannot write " + detail::quoted(components)); + } + std::scoped_lock lock(state->structure); + state->notify(StoragePoint::beforeCommit, name); + try { + state->confirm({walk.top(), fileDirectory()}); + } catch (...) { + abandon(); + throw; + } + const int parent = walk.top(); + if (mode == WriteMode::replace) { + try { + keepRights(parent); + } catch (...) { + abandon(); + throw; + } + } + const int result = mode == WriteMode::replace ? ::renameat(fileDirectory(), temporary.c_str(), parent, name.c_str()) + : detail::posix::renameNoReplace(parent, temporary.c_str(), parent, name.c_str()); + if (result != 0) { + const int error = errno; + abandon(); + detail::posix::fail(error, "Cannot commit " + detail::quoted(components)); + } + file.reset(); + if (privateDirectory) { + privateDirectory.reset(); + ::unlinkat(parent, privateName.c_str(), AT_REMOVEDIR); + } + // The directories are released once the last check is done: a committed writer holds nothing. + try { + state->confirm({parent}); + } catch (...) { + walk = {}; + throw; + } + walk = {}; + } + +private: + friend class NativeStorage; + Writer(std::shared_ptr storageState, State::Walk opened, std::vector path, std::string finalName, WriteMode writeMode) + : state(std::move(storageState)), walk(std::move(opened)), components(std::move(path)), name(std::move(finalName)), mode(writeMode) { } + + // Gives the temporary file the group, the permission bits (never setuid, setgid nor sticky) and the ACL of the file it replaces, + // read now, under the lock that serializes the storage's operations: whatever the storage moved to that name since + // beginWrite(), the new content is never published more widely than the file it replaces. Without a file to + // replace, the new file stays private (0600, no ACL). Its owner is the effective user. + void keepRights(int parent) { + struct stat target{}; + if (::fstatat(parent, name.c_str(), &target, AT_SYMLINK_NOFOLLOW) != 0) { + if (errno == ENOENT) + return; + detail::posix::fail(errno, "Cannot commit " + detail::quoted(components)); + } + if (!S_ISREG(target.st_mode)) + return; // a directory makes the rename fail; a link is replaced by the new file, not written through + // The group first: the group bits of the mode grant to that group, and a new file belongs to the effective group + // (or to its directory's). A group the effective user is not a member of cannot be given: the replacement is + // then refused rather than granting the bits to another group. + if (::fchown(file.get(), static_cast(-1), target.st_gid) != 0) + throw StorageError(StorageErrc::accessDenied, "Cannot keep the group of " + detail::quoted(components)); + detail::posix::copyAccessControl(parent, name, file.get(), detail::quoted(components)); + if (::fchmod(file.get(), static_cast(target.st_mode & 0777)) != 0) + detail::posix::fail(errno, "Cannot commit " + detail::quoted(components)); + } + + // The directory the temporary file is in: the private directory of a replacing write, otherwise the parent. + [[nodiscard]] int fileDirectory() const { + return privateDirectory ? privateDirectory.get() : walk.top(); + } + + void abandon() noexcept { + if (file) { + file.reset(); + ::unlinkat(fileDirectory(), temporary.c_str(), 0); + } + if (privateDirectory) { + privateDirectory.reset(); + ::unlinkat(walk.top(), privateName.c_str(), AT_REMOVEDIR); + } + } + + std::shared_ptr state; + State::Walk walk; + std::vector components; + std::string name; + WriteMode mode; + std::string temporary; + std::string privateName; + detail::posix::Fd privateDirectory; + detail::posix::Fd file; +}; + +inline NativeStorage::NativeStorage(const std::filesystem::path& location, RootOptions options, std::shared_ptr hooks) + : state(std::make_shared()) { + std::error_code error; + auto canonical = std::filesystem::canonical(location, error); + if (error) + throw StorageError(error == std::errc::no_such_file_or_directory ? StorageErrc::notFound : StorageErrc::ioError, + "Cannot declare the root: " + error.message()); + if (!std::filesystem::is_directory(canonical, error)) + throw StorageError(StorageErrc::notDirectory, "The root must be a directory"); + state->location = canonical; + for (const auto& component : canonical.relative_path()) + state->locationComponents.push_back(component.string()); + state->options = options; + state->hooks = std::move(hooks); + state->effectiveUser = state->hooks && state->hooks->effectiveUser ? *state->hooks->effectiveUser : static_cast(::geteuid()); + state->root = state->openLocation(StorageErrc::notFound); + state->rootIdentity = detail::posix::identityOf(detail::posix::statOf(state->root.get(), "Cannot inspect the root")); +} + +inline const std::filesystem::path& NativeStorage::location() const { + return state->location; +} + +inline DirectoryPage NativeStorage::list(std::string_view path, std::string_view after, std::size_t limit) { + const auto components = detail::storageComponents(path); + auto walk = state->start(); + std::deque pending(components.begin(), components.end()); + state->descend(walk, pending, 0); + state->notify(StoragePoint::resolved, components.empty() ? std::string_view{} : std::string_view(components.back())); + detail::posix::Fd readable = detail::posix::openAt(walk.top(), ".", O_RDONLY | O_DIRECTORY); + if (!readable) + detail::posix::fail(errno, "Cannot list " + detail::quoted(components)); + // A function object rather than decltype(&closedir): glibc's attributes on closedir would be dropped from the type. + struct CloseDirectory { + void operator()(DIR* stream) const noexcept { + ::closedir(stream); + } + }; + const std::unique_ptr directory(::fdopendir(readable.get())); + if (!directory) + detail::posix::fail(errno, "Cannot list " + detail::quoted(components)); + readable.release(); + std::vector entries; + while (true) { + errno = 0; // readdir() returns null both at the end and on an error + const auto* entry = ::readdir(directory.get()); + if (!entry) { + if (errno != 0) + detail::posix::fail(errno, "Cannot list " + detail::quoted(components)); + break; + } + const std::string_view name = entry->d_name; + if (isTemporaryName(name) || !isSafeFileName(name)) + continue; + struct stat status{}; + if (::fstatat(::dirfd(directory.get()), entry->d_name, &status, AT_SYMLINK_NOFOLLOW) == 0) + entries.push_back(detail::posix::infoOf(std::string(name), status)); + } + state->confirm({walk.top()}); + return detail::pageOf(std::move(entries), after, limit); +} + +inline EntryInfo NativeStorage::status(std::string_view path) { + const auto components = detail::storageComponents(path); + if (components.empty()) { + auto walk = state->start(); + auto info = detail::posix::infoOf({}, detail::posix::statOf(walk.top(), "Cannot inspect the root")); + state->confirm({walk.top()}); + return info; + } + auto [walk, name] = state->resolveParent(components); + state->notify(StoragePoint::resolved, name); + struct stat status{}; + if (::fstatat(walk.top(), name.c_str(), &status, AT_SYMLINK_NOFOLLOW) != 0) + detail::posix::fail(errno, "Cannot inspect " + detail::quoted(components)); + state->confirm({walk.top()}); + return detail::posix::infoOf(name, status); +} + +inline File NativeStorage::openRead(std::string_view path) { + const auto components = detail::entryComponents(path); + auto [walk, name] = state->resolveParent(components); + state->notify(StoragePoint::resolved, name); + auto file = state->openFinal(walk, name, O_RDONLY | O_NONBLOCK); + const auto status = detail::posix::statOf(file.get(), "Cannot inspect " + detail::quoted(components)); + if (S_ISDIR(status.st_mode)) + throw StorageError(StorageErrc::isDirectory, detail::quoted(components) + " is a directory"); + if (!S_ISREG(status.st_mode)) + throw StorageError(StorageErrc::accessDenied, detail::quoted(components) + " is not a regular file"); + const int flags = ::fcntl(file.get(), F_GETFL); + if (flags < 0 || ::fcntl(file.get(), F_SETFL, flags & ~O_NONBLOCK) != 0) + detail::posix::fail(errno, "Cannot read " + detail::quoted(components)); + state->confirm({walk.top()}); + return File{std::make_unique(std::move(file), static_cast(status.st_size))}; +} + +inline NativeStorage::Writer NativeStorage::beginWrite(std::string_view path, WriteMode mode) { + auto components = detail::entryComponents(path); + auto [walk, name] = state->resolveParent(components); + state->notify(StoragePoint::resolved, name); + struct stat status{}; + if (::fstatat(walk.top(), name.c_str(), &status, AT_SYMLINK_NOFOLLOW) == 0) { + if (mode == WriteMode::createNew) + throw StorageError(StorageErrc::alreadyExists, detail::quoted(components) + " already exists"); + if (S_ISDIR(status.st_mode)) + throw StorageError(StorageErrc::isDirectory, detail::quoted(components) + " is a directory"); + } + Writer writer{state, std::move(walk), std::move(components), std::move(name), mode}; + // A replacing write may replace a private file, now or by its commit: its temporary file must be private from its + // creation. A file created in the parent receives the ACL its directory passes on (a macOS ACL is not limited by the + // mode) before anyone can remove it, and someone who opens it in between keeps a descriptor on the content written + // later. So it is created in a private directory of its own (0700, its own inherited ACL removed before the file + // exists), where it inherits nothing, then renamed into place by the commit. + if (mode == WriteMode::replace) { + const auto what = detail::quoted(writer.components); + for (int attempt = 0; !writer.privateDirectory; ++attempt) { + writer.privateName = detail::temporaryName(); + if (::mkdirat(writer.walk.top(), writer.privateName.c_str(), 0700) != 0) { + if (errno != EEXIST || attempt == 8) + detail::posix::fail(errno, "Cannot write " + what); + continue; + } + writer.privateDirectory = detail::posix::openAt(writer.walk.top(), writer.privateName.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW); + if (!writer.privateDirectory) { + const int error = errno; + ::unlinkat(writer.walk.top(), writer.privateName.c_str(), AT_REMOVEDIR); + detail::posix::fail(error, "Cannot write " + what); + } + } + detail::posix::clearAccessControl(writer.privateDirectory.get(), what); + #if defined(__linux__) + if (::fremovexattr(writer.privateDirectory.get(), "system.posix_acl_default") != 0 && errno != ENODATA && !detail::posix::unsupported(errno)) + throw StorageError(StorageErrc::accessDenied, "Cannot make " + what + " private"); + #endif + if (::fchmod(writer.privateDirectory.get(), 0700) != 0) + detail::posix::fail(errno, "Cannot write " + what); + } + for (int attempt = 0; !writer.file; ++attempt) { + writer.temporary = detail::temporaryName(); + writer.file = detail::posix::openAt(writer.fileDirectory(), + writer.temporary.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, + mode == WriteMode::replace ? 0600 : 0644); + if (!writer.file && (errno != EEXIST || attempt == 8)) + detail::posix::fail(errno, "Cannot write " + detail::quoted(writer.components)); + } + state->notify(StoragePoint::temporaryCreated, writer.name); + return writer; +} + +inline void NativeStorage::createDirectory(std::string_view path) { + const auto components = detail::entryComponents(path); + auto [walk, name] = state->resolveParent(components); + std::scoped_lock lock(state->structure); + state->notify(StoragePoint::resolved, name); + if (::mkdirat(walk.top(), name.c_str(), 0755) != 0) + detail::posix::fail(errno, "Cannot create " + detail::quoted(components)); + state->confirm({walk.top()}); +} + +inline void NativeStorage::remove(std::string_view path) { + const auto components = detail::entryComponents(path); + auto [walk, name] = state->resolveParent(components); + std::scoped_lock lock(state->structure); + state->notify(StoragePoint::resolved, name); + struct stat status{}; + if (::fstatat(walk.top(), name.c_str(), &status, AT_SYMLINK_NOFOLLOW) != 0) + detail::posix::fail(errno, "Cannot remove " + detail::quoted(components)); + const int flags = S_ISDIR(status.st_mode) ? AT_REMOVEDIR : 0; + if (::unlinkat(walk.top(), name.c_str(), flags) != 0) { + const int error = errno; + // The entry changed type since it was inspected: remove what it is now, still relative to its directory. + if ((error == EISDIR || error == ENOTDIR || error == EPERM) && ::unlinkat(walk.top(), name.c_str(), flags ^ AT_REMOVEDIR) == 0) { + state->confirm({walk.top()}); + return; + } + detail::posix::fail(error == EEXIST ? ENOTEMPTY : error, "Cannot remove " + detail::quoted(components)); + } + state->confirm({walk.top()}); +} + +inline void NativeStorage::rename(std::string_view from, std::string_view to) { + const auto source = detail::entryComponents(from); + const auto target = detail::entryComponents(to); + auto [sourceWalk, sourceName] = state->resolveParent(source); + auto [targetWalk, targetName] = state->resolveParent(target); + std::scoped_lock lock(state->structure); + state->notify(StoragePoint::resolved, sourceName); + if (detail::posix::renameNoReplace(sourceWalk.top(), sourceName.c_str(), targetWalk.top(), targetName.c_str()) != 0) + detail::posix::fail(errno, "Cannot rename " + detail::quoted(source)); + state->confirm({sourceWalk.top(), targetWalk.top()}); +} + +#else // _WIN32 + +namespace detail::windows { + + #ifndef FILE_OPEN + #define FILE_OPEN 0x00000001 + #endif + #ifndef FILE_CREATE + #define FILE_CREATE 0x00000002 + #endif + #ifndef FILE_DIRECTORY_FILE + #define FILE_DIRECTORY_FILE 0x00000001 + #endif + #ifndef FILE_NON_DIRECTORY_FILE + #define FILE_NON_DIRECTORY_FILE 0x00000040 + #endif + #ifndef FILE_SYNCHRONOUS_IO_NONALERT + #define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 + #endif + #ifndef FILE_OPEN_REPARSE_POINT + #define FILE_OPEN_REPARSE_POINT 0x00200000 + #endif + #ifndef OBJ_CASE_INSENSITIVE + #define OBJ_CASE_INSENSITIVE 0x00000040L + #endif + +inline constexpr NTSTATUS statusObjectNameNotFound = static_cast(0xC0000034L); +inline constexpr NTSTATUS statusObjectPathNotFound = static_cast(0xC000003AL); +inline constexpr NTSTATUS statusObjectNameCollision = static_cast(0xC0000035L); +inline constexpr NTSTATUS statusObjectNameInvalid = static_cast(0xC0000033L); +inline constexpr NTSTATUS statusAccessDenied = static_cast(0xC0000022L); +inline constexpr NTSTATUS statusSharingViolation = static_cast(0xC0000043L); +inline constexpr NTSTATUS statusDeletePending = static_cast(0xC0000056L); +inline constexpr NTSTATUS statusNotADirectory = static_cast(0xC0000103L); +inline constexpr NTSTATUS statusFileIsADirectory = static_cast(0xC00000BAL); +inline constexpr NTSTATUS statusDirectoryNotEmpty = static_cast(0xC0000101L); + +class Handle { +public: + Handle() = default; + explicit Handle(HANDLE value) : handle(value == INVALID_HANDLE_VALUE ? nullptr : value) { } + Handle(Handle&& other) noexcept : handle(std::exchange(other.handle, nullptr)) { } + Handle& operator=(Handle&& other) noexcept { + if (this != &other) { + reset(); + handle = std::exchange(other.handle, nullptr); + } + return *this; + } + Handle(const Handle&) = delete; + Handle& operator=(const Handle&) = delete; + ~Handle() { + reset(); + } + + [[nodiscard]] HANDLE get() const noexcept { + return handle; + } + [[nodiscard]] explicit operator bool() const noexcept { + return handle != nullptr; + } + void reset() noexcept { + if (handle) + ::CloseHandle(handle); + handle = nullptr; + } + +private: + HANDLE handle{nullptr}; +}; + +struct Identity { + ULONGLONG volume{}; + std::array file{}; + bool operator==(const Identity&) const = default; +}; + +inline StorageErrc errcOf(DWORD error) { + switch (error) { + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + return StorageErrc::notFound; + case ERROR_FILE_EXISTS: + case ERROR_ALREADY_EXISTS: + return StorageErrc::alreadyExists; + case ERROR_DIRECTORY: + return StorageErrc::notDirectory; + case ERROR_DIR_NOT_EMPTY: + return StorageErrc::notEmpty; + case ERROR_ACCESS_DENIED: + case ERROR_WRITE_PROTECT: + return StorageErrc::accessDenied; + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + return StorageErrc::busy; + case ERROR_INVALID_NAME: + case ERROR_BAD_PATHNAME: + case ERROR_FILENAME_EXCED_RANGE: + return StorageErrc::invalidPath; + case ERROR_CANT_ACCESS_FILE: + case ERROR_STOPPED_ON_SYMLINK: + return StorageErrc::linkRefused; + default: + return StorageErrc::ioError; + } +} + +[[noreturn]] inline void fail(DWORD error, const std::string& what) { + throw StorageError(errcOf(error), what + ": " + std::system_category().message(static_cast(error))); +} + +[[noreturn]] inline void failLast(const std::string& what) { + fail(::GetLastError(), what); +} + +// The NT functions WebFront needs from ntdll.dll, which every process has loaded. +struct Ntdll { + // Not named CreateFile: defines that name as a macro. + using CreateFunction = + NTSTATUS(NTAPI*)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, PLARGE_INTEGER, ULONG, ULONG, ULONG, ULONG, PVOID, ULONG); + using ToDosFunction = ULONG(NTAPI*)(NTSTATUS); + using SetFunction = NTSTATUS(NTAPI*)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, ULONG); + + CreateFunction createFile{}; + ToDosFunction toDosError{}; + SetFunction setInformation{}; + + static const Ntdll& get() { + static const Ntdll functions = [] { + Ntdll found; + const auto library = ::GetModuleHandleW(L"ntdll.dll"); + if (library) { + found.createFile = reinterpret_cast(reinterpret_cast(::GetProcAddress(library, "NtCreateFile"))); + found.toDosError = reinterpret_cast(reinterpret_cast(::GetProcAddress(library, "RtlNtStatusToDosError"))); + found.setInformation = reinterpret_cast(reinterpret_cast(::GetProcAddress(library, "NtSetInformationFile"))); + } + return found; + }(); + if (!functions.createFile || !functions.toDosError || !functions.setInformation) + throw StorageError(StorageErrc::ioError, "ntdll.dll does not provide NtCreateFile and NtSetInformationFile"); + return functions; + } +}; + +[[noreturn]] inline void failStatus(NTSTATUS status, const std::string& what) { + switch (status) { + case statusObjectNameNotFound: + case statusObjectPathNotFound: + case statusDeletePending: + throw StorageError(StorageErrc::notFound, what + ": no such entry"); + case statusObjectNameCollision: + throw StorageError(StorageErrc::alreadyExists, what + ": the name exists"); + case statusObjectNameInvalid: + throw StorageError(StorageErrc::invalidPath, what + ": invalid name"); + case statusAccessDenied: + throw StorageError(StorageErrc::accessDenied, what + ": access denied"); + case statusSharingViolation: + throw StorageError(StorageErrc::busy, what + ": the entry is in use"); + case statusNotADirectory: + throw StorageError(StorageErrc::notDirectory, what + ": not a directory"); + case statusFileIsADirectory: + throw StorageError(StorageErrc::isDirectory, what + ": a directory"); + case statusDirectoryNotEmpty: + throw StorageError(StorageErrc::notEmpty, what + ": the directory is not empty"); + default: + fail(Ntdll::get().toDosError(status), what); + } +} + +inline std::wstring wide(std::string_view utf8) { + return detail::fromUtf8(utf8).wstring(); +} + +inline std::string utf8(std::wstring_view text) { + const auto bytes = std::filesystem::path(text).u8string(); + return {reinterpret_cast(bytes.data()), bytes.size()}; +} + +// Opens `name` relative to the directory `parent`, never following a reparse point (link or junction). +inline NTSTATUS openRelative(Handle& result, HANDLE parent, const std::wstring& name, ACCESS_MASK access, ULONG share, ULONG disposition, ULONG options) { + if (name.size() > 32767) + return statusObjectNameInvalid; + UNICODE_STRING unicode{}; + unicode.Buffer = const_cast(name.c_str()); + unicode.Length = static_cast(name.size() * sizeof(wchar_t)); + unicode.MaximumLength = unicode.Length; + OBJECT_ATTRIBUTES attributes{}; + attributes.Length = sizeof(attributes); + attributes.RootDirectory = parent; + attributes.ObjectName = &unicode; + attributes.Attributes = OBJ_CASE_INSENSITIVE; + IO_STATUS_BLOCK io{}; + HANDLE handle = nullptr; + const auto status = Ntdll::get().createFile(&handle, + access | SYNCHRONIZE | FILE_READ_ATTRIBUTES, + &attributes, + &io, + nullptr, + FILE_ATTRIBUTE_NORMAL, + share, + disposition, + options | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT, + nullptr, + 0); + if (status >= 0) + result = Handle{handle}; + return status; +} + +inline DWORD attributesOf(HANDLE handle, const std::string& what) { + FILE_ATTRIBUTE_TAG_INFO info{}; + if (!::GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &info, sizeof(info))) + failLast(what); + return info.FileAttributes; +} + +inline Identity identityOf(HANDLE handle) { + FILE_ID_INFO info{}; + if (!::GetFileInformationByHandleEx(handle, FileIdInfo, &info, sizeof(info))) + failLast("Cannot identify the root"); + Identity identity{info.VolumeSerialNumber, {}}; + std::copy(std::begin(info.FileId.Identifier), std::end(info.FileId.Identifier), identity.file.begin()); + return identity; +} + +inline std::chrono::system_clock::time_point timeOf(LONGLONG fileTime) { + // A FILETIME counts 100 ns intervals since 1601-01-01. + constexpr LONGLONG unixEpoch = 116444736000000000LL; + return std::chrono::system_clock::time_point{ + std::chrono::duration_cast(std::chrono::duration>{fileTime - unixEpoch})}; +} + +inline EntryInfo infoOf(std::string name, DWORD attributes, LONGLONG size, LONGLONG modified) { + EntryInfo info{.name = std::move(name), .modified = timeOf(modified), .readable = true, .writable = (attributes & FILE_ATTRIBUTE_READONLY) == 0}; + if (attributes & FILE_ATTRIBUTE_REPARSE_POINT) + info.type = EntryType::link; + else if (attributes & FILE_ATTRIBUTE_DIRECTORY) + info.type = EntryType::directory; + else { + info.type = EntryType::file; + info.size = static_cast(size); + } + return info; +} + +inline EntryInfo infoOf(std::string name, HANDLE handle, const std::string& what) { + FILE_BASIC_INFO basic{}; + FILE_STANDARD_INFO standard{}; + if (!::GetFileInformationByHandleEx(handle, FileBasicInfo, &basic, sizeof(basic)) + || !::GetFileInformationByHandleEx(handle, FileStandardInfo, &standard, sizeof(standard))) + failLast(what); + return infoOf(std::move(name), basic.FileAttributes, standard.EndOfFile.QuadPart, basic.LastWriteTime.QuadPart); +} + +// Renames the entry of `handle` to `name` in the directory `directory`, by NtSetInformationFile: SetFileInformationByHandle +// turns a bare name into an absolute path before the call, which a rename relative to a directory handle refuses +// (STATUS_INVALID_PARAMETER). FILE_RENAME_INFO has the layout of the NT FILE_RENAME_INFORMATION. +inline NTSTATUS renameHandle(HANDLE handle, HANDLE directory, const std::wstring& name, bool replace) { + constexpr ULONG fileRenameInformation = 10; + const auto nameBytes = name.size() * sizeof(wchar_t); + const auto size = offsetof(FILE_RENAME_INFO, FileName) + nameBytes; + std::vector buffer(size / sizeof(std::uint64_t) + 1); + auto* info = reinterpret_cast(buffer.data()); + info->ReplaceIfExists = replace ? TRUE : FALSE; + info->RootDirectory = directory; + info->FileNameLength = static_cast(nameBytes); + std::memcpy(reinterpret_cast(buffer.data()) + offsetof(FILE_RENAME_INFO, FileName), name.data(), nameBytes); + IO_STATUS_BLOCK io{}; + return Ntdll::get().setInformation(handle, &io, info, static_cast(size), fileRenameInformation); +} + +inline bool markDeleted(HANDLE handle) { + FILE_DISPOSITION_INFO disposition{}; + disposition.DeleteFile = TRUE; + return ::SetFileInformationByHandle(handle, FileDispositionInfo, &disposition, sizeof(disposition)) != FALSE; +} + +inline std::wstring finalPath(HANDLE handle) { + std::wstring path(512, L'\0'); + while (true) { + const auto length = ::GetFinalPathNameByHandleW(handle, path.data(), static_cast(path.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_NT); + if (length == 0) + return {}; + if (length < path.size()) { + path.resize(length); + return path; + } + path.resize(length + 1); + } +} + +// The content of a file opened relative to a directory of the root. +class HandleSource : public ByteSource { +public: + HandleSource(Handle opened, std::uint64_t length) : file(std::move(opened)), total(length) { } + + std::size_t read(std::span buffer) override { + std::size_t count = 0; + while (count < buffer.size()) { + DWORD got = 0; + const auto want = static_cast(std::min(buffer.size() - count, 1u << 30)); + if (!::ReadFile(file.get(), buffer.data() + count, want, &got, nullptr)) + failLast("Cannot read the file"); + if (got == 0) + break; + count += got; + } + return count; + } + [[nodiscard]] std::optional size() const override { + return total; + } + [[nodiscard]] bool seek(std::uint64_t offset) override { + LARGE_INTEGER position{}; + position.QuadPart = static_cast(std::min(offset, total)); + return ::SetFilePointerEx(file.get(), position, nullptr, FILE_BEGIN) != FALSE; + } + +private: + Handle file; + std::uint64_t total; +}; + +inline bool equalsAscii(std::wstring_view text, std::wstring_view expected) { + return std::ranges::equal(text, expected, [](wchar_t a, wchar_t b) { + const auto lower = [](wchar_t c) { + return c >= L'A' && c <= L'Z' ? static_cast(c - L'A' + L'a') : c; + }; + return lower(a) == lower(b); + }); +} + +/// The volume a canonical location is opened from, as CreateFileW takes it, and the components below it. +/// `C:\a` and `\\?\C:\a` give `\\?\C:\` and {a}; `\\server\share\a` and `\\?\UNC\server\share\a` give +/// `\\?\UNC\server\share\` and {a} (the share belongs to the volume: `\\?\UNC\server\` alone names nothing); +/// `\\?\Volume{...}\a` gives `\\?\Volume{...}\` and {a}. A `\\?\GLOBALROOT` path, which canonical() returns for a volume +/// without a DOS name, a server without a share and a relative path are refused (invalidPath). +/// +/// The native string is parsed rather than root_name(): MSVC returns `\\?` as the root name of `\\?\C:\a`, and leaves +/// the drive, `UNC` or the volume in the relative path. +inline std::pair> splitLocation(const std::filesystem::path& canonical) { + const auto unsupported = [] { + return StorageError(StorageErrc::invalidPath, "This root location has no volume WebFront can open"); + }; + std::wstring text = canonical.native(); + std::ranges::replace(text, L'/', L'\\'); + const auto split = [](std::wstring_view rest) { + std::vector parts; + for (const auto part : std::views::split(rest, L'\\')) + if (!part.empty()) + parts.emplace_back(part.begin(), part.end()); + return parts; + }; + const auto result = [](std::wstring volume, const std::vector& parts, std::size_t first) { + std::vector components; + for (auto part = parts.begin() + static_cast(first); part != parts.end(); ++part) + components.push_back(utf8(*part)); + return std::pair{std::move(volume), std::move(components)}; + }; + const auto share = [&](const std::vector& parts, std::size_t server) { + if (parts.size() < server + 2) + throw unsupported(); + return result(L"\\\\?\\UNC\\" + parts[server] + L"\\" + parts[server + 1] + L"\\", parts, server + 2); + }; + const auto isDrive = [](std::wstring_view part) { + return part.size() == 2 && part[1] == L':' && ((part[0] >= L'A' && part[0] <= L'Z') || (part[0] >= L'a' && part[0] <= L'z')); + }; + if (text.starts_with(L"\\\\?\\") || text.starts_with(L"\\\\.\\")) { + const auto parts = split(std::wstring_view(text).substr(4)); + if (parts.empty() || equalsAscii(parts[0], L"GLOBALROOT")) + throw unsupported(); + if (equalsAscii(parts[0], L"UNC")) + return share(parts, 1); + // A drive (`C:`) or a volume (`Volume{...}`): both name a volume root. + return result(L"\\\\?\\" + parts[0] + L"\\", parts, 1); + } + if (text.starts_with(L"\\\\")) + return share(split(std::wstring_view(text).substr(2)), 0); + const auto parts = split(text); + if (parts.empty() || !isDrive(parts[0])) + throw unsupported(); + return result(L"\\\\?\\" + parts[0] + L"\\", parts, 1); +} + +/// True when the final path `path` is `root` or below it, letter case aside. A root at the top of its volume already ends +/// with a separator (`\Device\HarddiskVolume3\`): its entries follow it directly. +inline bool isBelow(std::wstring_view path, std::wstring_view root) { + if (path.empty() || root.empty() || path.size() < root.size()) + return false; + if (::CompareStringOrdinal(path.data(), static_cast(root.size()), root.data(), static_cast(root.size()), TRUE) != CSTR_EQUAL) + return false; + return path.size() == root.size() || root.back() == L'\\' || path[root.size()] == L'\\'; +} + +inline constexpr ACCESS_MASK directoryAccess = FILE_LIST_DIRECTORY | FILE_TRAVERSE; +// The directories of an operation are held without FILE_SHARE_DELETE: nobody can rename or remove them meanwhile. +inline constexpr ULONG heldSharing = FILE_SHARE_READ | FILE_SHARE_WRITE; +inline constexpr ULONG fullSharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; + +} // namespace detail::windows + +struct NativeStorage::State { + using Handle = detail::windows::Handle; + using Identity = detail::windows::Identity; + + std::filesystem::path location; + std::wstring volume; + std::vector locationComponents; + RootOptions options; + std::shared_ptr hooks; + Handle root; + Identity rootIdentity; + std::wstring rootPath; + std::mutex structure; + std::atomic moved{false}; + + struct Walk { + std::vector directories; + std::vector names; + + [[nodiscard]] HANDLE top() const { + return directories.back().get(); + } + }; + + void notify(StoragePoint point, std::string_view name) const { + if (hooks && hooks->at) + hooks->at(point, name); + } + + // Opens a directory relative to `parent`, refusing reparse points. + static Handle + openDirectory(HANDLE parent, const std::string& name, ULONG sharing, const std::string& what, ACCESS_MASK access = detail::windows::directoryAccess) { + Handle directory; + const auto status = detail::windows::openRelative(directory, parent, detail::windows::wide(name), access, sharing, FILE_OPEN, FILE_DIRECTORY_FILE); + if (status == detail::windows::statusNotADirectory) { + Handle entry; + if (detail::windows::openRelative(entry, parent, detail::windows::wide(name), 0, detail::windows::fullSharing, FILE_OPEN, 0) >= 0 + && (detail::windows::attributesOf(entry.get(), what) & FILE_ATTRIBUTE_REPARSE_POINT)) + throw StorageError(StorageErrc::linkRefused, what + " is a link"); + } + if (status < 0) + detail::windows::failStatus(status, what); + if (detail::windows::attributesOf(directory.get(), what) & FILE_ATTRIBUTE_REPARSE_POINT) + throw StorageError(StorageErrc::linkRefused, what + " is a link"); + return directory; + } + + // Opens the declared location from its volume, refusing reparse points on the way. + Handle openLocation(StorageErrc onMove, ULONG rootSharing) const { + // A root at the top of its volume (C:\, a share) is the volume itself, held like any root. + Handle current{::CreateFileW(volume.c_str(), + detail::windows::directoryAccess | FILE_READ_ATTRIBUTES | SYNCHRONIZE, + locationComponents.empty() ? rootSharing : detail::windows::fullSharing, + nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, + nullptr)}; + if (!current) + detail::windows::failLast("Cannot open the volume of the root"); + for (std::size_t index = 0; index < locationComponents.size(); ++index) { + const bool last = index + 1 == locationComponents.size(); + try { + // An ancestor is only traversed; the root is listed. + current = last ? openDirectory(current.get(), locationComponents[index], rootSharing, "The location") + : openDirectory(current.get(), locationComponents[index], detail::windows::fullSharing, "The location", FILE_TRAVERSE); + } catch (const StorageError& error) { + // Only a missing component, a non-directory or a reparse point shows that the location changed. + if (error.errc() != StorageErrc::notFound && error.errc() != StorageErrc::notDirectory && error.errc() != StorageErrc::linkRefused) + throw; + throw StorageError(onMove, "The root is no longer at its declared location"); + } + } + return current; + } + + // Opens the declared location and checks that it still designates the root: the handle an operation starts from. + Handle verifiedRoot(ULONG sharing) { + if (moved) + throw StorageError(StorageErrc::rootMoved, "The root is no longer at its declared location"); + try { + auto found = openLocation(StorageErrc::rootMoved, sharing); + if (detail::windows::identityOf(found.get()) != rootIdentity) + throw StorageError(StorageErrc::rootMoved, "The root is no longer at its declared location"); + return found; + } catch (const StorageError& error) { + if (error.errc() == StorageErrc::rootMoved) + moved = true; + throw; + } + } + + void verifyLocation() { + verifiedRoot(detail::windows::fullSharing); + } + + // The final path of a directory begins with the root's: its handles prevent the moves, this checks it still holds. + bool isUnderRoot(HANDLE directory) const { + return detail::windows::isBelow(detail::windows::finalPath(directory), rootPath); + } + + void confirm(std::initializer_list directories) { + for (const auto directory : directories) + if (!isUnderRoot(directory)) + throw StorageError(StorageErrc::confinementViolated, "A directory left the root during the operation"); + try { + verifyLocation(); + } catch (const StorageError& error) { + if (error.errc() != StorageErrc::rootMoved) + throw; + throw StorageError(StorageErrc::confinementViolated, "The root moved during the operation"); + } + } + + Walk start() { + Walk walk; + walk.directories.push_back(verifiedRoot(detail::windows::heldSharing)); + return walk; + } + + void descend(Walk& walk, const std::vector& components, std::size_t count) { + for (std::size_t index = 0; index < count; ++index) { + walk.names.push_back(components[index]); + walk.directories.push_back(openDirectory(walk.top(), components[index], detail::windows::heldSharing, detail::quoted(walk.names))); + notify(StoragePoint::componentOpened, components[index]); + } + } + + std::pair resolveParent(const std::vector& components) { + auto walk = start(); + descend(walk, components, components.size() - 1); + return {std::move(walk), components.back()}; + } + + // Opens an entry of the top directory, refusing a reparse point. + static Handle openEntry(const Walk& walk, const std::string& name, ACCESS_MASK access, ULONG sharing, ULONG options, const std::string& what) { + Handle entry; + const auto status = detail::windows::openRelative(entry, walk.top(), detail::windows::wide(name), access, sharing, FILE_OPEN, options); + if (status < 0) + detail::windows::failStatus(status, what); + if (detail::windows::attributesOf(entry.get(), what) & FILE_ATTRIBUTE_REPARSE_POINT) + throw StorageError(StorageErrc::linkRefused, what + " is a link"); + return entry; + } +}; + +class NativeStorage::Writer { +public: + Writer(Writer&&) noexcept = default; + Writer& operator=(Writer&&) = delete; // would drop the temporary file of the writer it replaces + Writer(const Writer&) = delete; + Writer& operator=(const Writer&) = delete; + ~Writer() { + abandon(); + } + + void write(std::span bytes) { + if (!file) + throw std::logic_error("The write is committed or abandoned"); + while (!bytes.empty()) { + DWORD written = 0; + const auto want = static_cast(std::min(bytes.size(), 1u << 30)); + if (!::WriteFile(file.get(), bytes.data(), want, &written, nullptr)) + detail::windows::failLast("Cannot write " + detail::quoted(components)); + bytes = bytes.subspan(written); + } + } + + void commit() { + if (!file) + throw std::logic_error("The write is committed or abandoned"); + if (!::FlushFileBuffers(file.get())) { + const auto error = ::GetLastError(); + abandon(); + detail::windows::fail(error, "Cannot write " + detail::quoted(components)); + } + std::scoped_lock lock(state->structure); + state->notify(StoragePoint::beforeCommit, name); + try { + state->confirm({walk.top()}); + } catch (...) { + abandon(); + throw; + } + if (const auto status = detail::windows::renameHandle(file.get(), walk.top(), detail::windows::wide(name), mode == WriteMode::replace); status < 0) { + abandon(); + detail::windows::failStatus(status, "Cannot commit " + detail::quoted(components)); + } + file.reset(); + // The directories, held without FILE_SHARE_DELETE, are released once the last check is done: a committed writer + // must not keep anyone from renaming or removing them. + try { + state->confirm({walk.top()}); + } catch (...) { + walk = {}; + throw; + } + walk = {}; + } + +private: + friend class NativeStorage; + Writer(std::shared_ptr storageState, State::Walk opened, std::vector path, std::string finalName, WriteMode writeMode) + : state(std::move(storageState)), walk(std::move(opened)), components(std::move(path)), name(std::move(finalName)), mode(writeMode) { } + + void abandon() noexcept { + if (!file) + return; + detail::windows::markDeleted(file.get()); + file.reset(); + } + + std::shared_ptr state; + State::Walk walk; + std::vector components; + std::string name; + WriteMode mode; + detail::windows::Handle file; +}; + +inline NativeStorage::NativeStorage(const std::filesystem::path& location, RootOptions options, std::shared_ptr hooks) + : state(std::make_shared()) { + std::error_code error; + auto canonical = std::filesystem::canonical(location, error); + if (error) + throw StorageError(error == std::errc::no_such_file_or_directory ? StorageErrc::notFound : StorageErrc::ioError, + "Cannot declare the root: " + error.message()); + if (!std::filesystem::is_directory(canonical, error)) + throw StorageError(StorageErrc::notDirectory, "The root must be a directory"); + state->location = canonical; + std::tie(state->volume, state->locationComponents) = detail::windows::splitLocation(canonical); + state->options = options; + state->hooks = std::move(hooks); + state->root = state->openLocation(StorageErrc::notFound, detail::windows::heldSharing); + state->rootIdentity = detail::windows::identityOf(state->root.get()); + state->rootPath = detail::windows::finalPath(state->root.get()); +} + +inline const std::filesystem::path& NativeStorage::location() const { + return state->location; +} + +inline DirectoryPage NativeStorage::list(std::string_view path, std::string_view after, std::size_t limit) { + const auto components = detail::storageComponents(path); + auto walk = state->start(); + state->descend(walk, components, components.size()); + state->notify(StoragePoint::resolved, components.empty() ? std::string_view{} : std::string_view(components.back())); + std::vector entries; + std::vector buffer(64 * 1024 / sizeof(std::uint64_t)); + auto kind = FileIdBothDirectoryRestartInfo; + while (::GetFileInformationByHandleEx(walk.top(), kind, buffer.data(), static_cast(buffer.size() * sizeof(std::uint64_t)))) { + kind = FileIdBothDirectoryInfo; + const auto* bytes = reinterpret_cast(buffer.data()); + while (true) { + const auto* entry = reinterpret_cast(bytes); + const std::wstring wideName(reinterpret_cast(bytes + offsetof(FILE_ID_BOTH_DIR_INFO, FileName)), + entry->FileNameLength / sizeof(wchar_t)); + // A name with an unpaired surrogate has no UTF-8 form: no path can name it, so it is not listed. + std::string name; + try { + name = detail::windows::utf8(wideName); + } catch (const std::system_error&) { + name.clear(); + } + if (!name.empty() && name != "." && name != ".." && !isTemporaryName(name) && isSafeFileName(name)) + entries.push_back(detail::windows::infoOf(name, entry->FileAttributes, entry->EndOfFile.QuadPart, entry->LastWriteTime.QuadPart)); + if (entry->NextEntryOffset == 0) + break; + bytes += entry->NextEntryOffset; + } + } + if (const auto error = ::GetLastError(); error != ERROR_NO_MORE_FILES) + detail::windows::fail(error, "Cannot list " + detail::quoted(components)); + state->confirm({walk.top()}); + return detail::pageOf(std::move(entries), after, limit); +} + +inline EntryInfo NativeStorage::status(std::string_view path) { + const auto components = detail::storageComponents(path); + if (components.empty()) { + auto walk = state->start(); + auto info = detail::windows::infoOf({}, walk.top(), "Cannot inspect the root"); + state->confirm({walk.top()}); + return info; + } + auto [walk, name] = state->resolveParent(components); + state->notify(StoragePoint::resolved, name); + detail::windows::Handle entry; + const auto status = detail::windows::openRelative(entry, walk.top(), detail::windows::wide(name), 0, detail::windows::fullSharing, FILE_OPEN, 0); + if (status < 0) + detail::windows::failStatus(status, "Cannot inspect " + detail::quoted(components)); + auto info = detail::windows::infoOf(name, entry.get(), "Cannot inspect " + detail::quoted(components)); + state->confirm({walk.top()}); + return info; +} + +inline File NativeStorage::openRead(std::string_view path) { + const auto components = detail::entryComponents(path); + auto [walk, name] = state->resolveParent(components); + state->notify(StoragePoint::resolved, name); + const auto what = detail::quoted(components); + auto file = State::openEntry(walk, name, FILE_READ_DATA, FILE_SHARE_READ | FILE_SHARE_DELETE, 0, what); + if (detail::windows::attributesOf(file.get(), what) & FILE_ATTRIBUTE_DIRECTORY) + throw StorageError(StorageErrc::isDirectory, what + " is a directory"); + LARGE_INTEGER size{}; + if (!::GetFileSizeEx(file.get(), &size)) + detail::windows::failLast("Cannot read " + what); + state->confirm({walk.top()}); + return File{std::make_unique(std::move(file), static_cast(size.QuadPart))}; +} + +inline NativeStorage::Writer NativeStorage::beginWrite(std::string_view path, WriteMode mode) { + auto components = detail::entryComponents(path); + auto [walk, name] = state->resolveParent(components); + state->notify(StoragePoint::resolved, name); + detail::windows::Handle existing; + if (detail::windows::openRelative(existing, walk.top(), detail::windows::wide(name), 0, detail::windows::fullSharing, FILE_OPEN, 0) >= 0) { + if (mode == WriteMode::createNew) + throw StorageError(StorageErrc::alreadyExists, detail::quoted(components) + " already exists"); + const auto attributes = detail::windows::attributesOf(existing.get(), detail::quoted(components)); + if ((attributes & FILE_ATTRIBUTE_DIRECTORY) && !(attributes & FILE_ATTRIBUTE_REPARSE_POINT)) + throw StorageError(StorageErrc::isDirectory, detail::quoted(components) + " is a directory"); + existing.reset(); + } + Writer writer{state, std::move(walk), std::move(components), std::move(name), mode}; + for (int attempt = 0; !writer.file; ++attempt) { + const auto status = detail::windows::openRelative(writer.file, + writer.walk.top(), + detail::windows::wide(detail::temporaryName()), + FILE_WRITE_DATA | DELETE, + 0, + FILE_CREATE, + FILE_NON_DIRECTORY_FILE); + if (status < 0 && (status != detail::windows::statusObjectNameCollision || attempt == 8)) + detail::windows::failStatus(status, "Cannot write " + detail::quoted(writer.components)); + } + state->notify(StoragePoint::temporaryCreated, writer.name); + return writer; +} + +inline void NativeStorage::createDirectory(std::string_view path) { + const auto components = detail::entryComponents(path); + auto [walk, name] = state->resolveParent(components); + std::scoped_lock lock(state->structure); + state->notify(StoragePoint::resolved, name); + detail::windows::Handle directory; + const auto status = detail::windows::openRelative(directory, + walk.top(), + detail::windows::wide(name), + detail::windows::directoryAccess, + detail::windows::fullSharing, + FILE_CREATE, + FILE_DIRECTORY_FILE); + if (status < 0) + detail::windows::failStatus(status, "Cannot create " + detail::quoted(components)); + directory.reset(); + state->confirm({walk.top()}); +} + +inline void NativeStorage::remove(std::string_view path) { + const auto components = detail::entryComponents(path); + auto [walk, name] = state->resolveParent(components); + std::scoped_lock lock(state->structure); + state->notify(StoragePoint::resolved, name); + detail::windows::Handle entry; + const auto status = detail::windows::openRelative(entry, walk.top(), detail::windows::wide(name), DELETE, detail::windows::fullSharing, FILE_OPEN, 0); + if (status < 0) + detail::windows::failStatus(status, "Cannot remove " + detail::quoted(components)); + if (!detail::windows::markDeleted(entry.get())) + detail::windows::failLast("Cannot remove " + detail::quoted(components)); + entry.reset(); + state->confirm({walk.top()}); +} + +inline void NativeStorage::rename(std::string_view from, std::string_view to) { + const auto source = detail::entryComponents(from); + const auto target = detail::entryComponents(to); + auto [sourceWalk, sourceName] = state->resolveParent(source); + auto [targetWalk, targetName] = state->resolveParent(target); + std::scoped_lock lock(state->structure); + state->notify(StoragePoint::resolved, sourceName); + detail::windows::Handle entry; + const auto status = + detail::windows::openRelative(entry, sourceWalk.top(), detail::windows::wide(sourceName), DELETE, detail::windows::fullSharing, FILE_OPEN, 0); + if (status < 0) + detail::windows::failStatus(status, "Cannot rename " + detail::quoted(source)); + if (const auto renamed = detail::windows::renameHandle(entry.get(), targetWalk.top(), detail::windows::wide(targetName), false); renamed < 0) + detail::windows::failStatus(renamed, "Cannot rename " + detail::quoted(source)); + entry.reset(); + state->confirm({sourceWalk.top(), targetWalk.top()}); +} + +#endif // _WIN32 + +static_assert(Storage); + +} // namespace webfront::fs diff --git a/include/webfront/system/SafePath.hpp b/include/webfront/system/SafePath.hpp index 92b2a2df..4573b830 100644 --- a/include/webfront/system/SafePath.hpp +++ b/include/webfront/system/SafePath.hpp @@ -1,12 +1,16 @@ /// @brief Relative paths received from the browser, checked to stay inside the directory they name a file of. #pragma once +#include +#include #include #include +#include #include #include #include #include +#include namespace webfront::fs { @@ -24,20 +28,61 @@ inline bool hasSafeCharacters(std::string_view path) { return path.find_first_of("\\:*?\"<>|\0"sv) == std::string_view::npos; } -// Appends a component unless it is empty, "." or ".." (or "...", which no path needs). -inline bool appendComponent(std::filesystem::path& path, std::string_view component) { +inline char lowerAscii(char c) { + return c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c; +} + +// The device names Windows reserves in every directory, whatever their extension and case: "con", "nul.txt" and +// "COM1.tar.gz" all name a device. The superscript digits ¹²³ also complete COM and LPT. +inline bool isReservedWindowsName(std::string_view component) { + auto stem = component.substr(0, component.find('.')); + while (stem.ends_with(' ')) + stem.remove_suffix(1); + std::string lower; + std::ranges::transform(stem, std::back_inserter(lower), lowerAscii); + static constexpr std::array devices{"con", "prn", "aux", "nul", "conin$", "conout$"}; + if (std::ranges::find(devices, lower) != devices.end()) + return true; + if (!lower.starts_with("com") && !lower.starts_with("lpt")) + return false; + const auto suffix = std::string_view(lower).substr(3); + return (suffix.size() == 1 && suffix[0] >= '1' && suffix[0] <= '9') || suffix == "\xC2\xB9" || suffix == "\xC2\xB2" || suffix == "\xC2\xB3"; +} + +// A file name every supported file system stores as written: not empty, not made of dots only ("." and ".." are +// links), no trailing dot or space (Windows drops them, so "a." would name "a"), no reserved Windows device name. +inline bool isSafeName(std::string_view component) { if (component.find_first_not_of('.') == std::string_view::npos) return false; + if (component.ends_with('.') || component.ends_with(' ')) + return false; + return !isReservedWindowsName(component); +} + +inline bool appendComponent(std::filesystem::path& path, std::string_view component) { + if (!isSafeName(component)) + return false; path /= fromUtf8(component); return true; } } // namespace detail +/// True for a single file name that safeRelativePath() would accept as a component: a name a storage can create on +/// every platform and that never names a parent, a device or another file. +inline bool isSafeFileName(std::string_view name) { + return !name.empty() && detail::hasSafeCharacters(name) && name.find('/') == std::string_view::npos && detail::isSafeName(name); +} + /// Converts a '/'-separated path received from the browser into a relative path that stays inside /// its directory. Rejects empty and absolute paths, empty, "." and ".." components, backslashes, /// colons (drive letters and alternate streams), the other characters Windows forbids in file names -/// (*?"<>|) and NUL, on every platform, with std::invalid_argument. +/// (*?"<>|) and NUL, components ending with a dot or a space and the device +/// names Windows reserves (CON, PRN, AUX, NUL, COM1 to COM9, LPT1 to LPT9, with any extension), on every +/// platform, with std::invalid_argument. +/// +/// This checks the syntax only. A path that passes may still leave its directory on disk through a symbolic link +/// or a junction: confinement is enforced while resolving it, relative to an opened directory (fs::NativeStorage). inline std::filesystem::path safeRelativePath(std::string_view path) { std::filesystem::path result; bool safe = detail::hasSafeCharacters(path); @@ -48,4 +93,24 @@ inline std::filesystem::path safeRelativePath(std::string_view path) { return result; } +/// The components of a '/'-separated path inside a storage root, checked as safeRelativePath() checks them. The empty +/// path names the root itself and yields no component. +/// @throws std::invalid_argument for a path safeRelativePath() would reject +inline std::vector safePathComponents(std::string_view path) { + std::vector components; + if (path.empty()) + return components; + bool safe = detail::hasSafeCharacters(path); + for (const auto part : std::views::split(path, '/')) { + const std::string_view component(part.begin(), part.end()); + safe = safe && detail::isSafeName(component); + if (!safe) + break; + components.emplace_back(component); + } + if (!safe) + throw std::invalid_argument("Unsafe path '" + std::string(path) + "'"); + return components; +} + } // namespace webfront::fs diff --git a/include/webfront/system/Storage.hpp b/include/webfront/system/Storage.hpp new file mode 100644 index 00000000..373f8113 --- /dev/null +++ b/include/webfront/system/Storage.hpp @@ -0,0 +1,235 @@ +/// @brief Writable storage confined to a root the application declares: the contract the services of ADR-020 read and +/// write through, whatever stores the bytes (a desktop file system, a simulated tree, FatFs or LittleFS on a device). +#pragma once + +#include "FileSystem.hpp" +#include "SafePath.hpp" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::fs { + +/// Why a storage operation failed. Each value has a stable bridge code (storageErrorCode()). +enum class StorageErrc { + notFound, ///< no entry has this name + alreadyExists, ///< the name is taken and the operation does not replace + notDirectory, ///< a component that must be a directory is not one + isDirectory, ///< a file operation names a directory + notEmpty, ///< removing a directory that still has entries + accessDenied, ///< the system or the storage refuses the access + invalidPath, ///< the path fails the syntax of SafePath, or names the root where an entry is needed + linkRefused, ///< a component is a link the root does not follow, or one that leaves the root + unsafeDirectory, ///< a directory of the root, or an ancestor, can be moved by another user (POSIX) + rootMoved, ///< the declared location no longer designates the root opened at declaration + confinementViolated, ///< a directory left the root during the operation: detected, the operation was abandoned + busy, ///< another process holds the entry in a way that prevents the operation (Windows sharing) + ioError, ///< any other failure of the underlying storage +}; + +/// The bridge code of a storage error, `storage.` (for example `storage.rootMoved`). +[[nodiscard]] constexpr std::string_view storageErrorCode(StorageErrc errc) noexcept { + switch (errc) { + case StorageErrc::notFound: + return "storage.notFound"; + case StorageErrc::alreadyExists: + return "storage.alreadyExists"; + case StorageErrc::notDirectory: + return "storage.notDirectory"; + case StorageErrc::isDirectory: + return "storage.isDirectory"; + case StorageErrc::notEmpty: + return "storage.notEmpty"; + case StorageErrc::accessDenied: + return "storage.accessDenied"; + case StorageErrc::invalidPath: + return "storage.invalidPath"; + case StorageErrc::linkRefused: + return "storage.linkRefused"; + case StorageErrc::unsafeDirectory: + return "storage.unsafeDirectory"; + case StorageErrc::rootMoved: + return "storage.rootMoved"; + case StorageErrc::confinementViolated: + return "storage.confinementViolated"; + case StorageErrc::busy: + return "storage.busy"; + case StorageErrc::ioError: + break; + } + return "storage.ioError"; +} + +/** + * @brief The failure of a storage operation. It is a BridgeError: a service callback that lets it propagate rejects the + * JavaScript Promise with an `Error` whose `code` is storageErrorCode(errc()). + * + * The message names the path relative to the root, never the root's location on the host (ADR-020: a host path never + * reaches JavaScript unless the application sends it). + */ +class StorageError : public BridgeError { +public: + StorageError(StorageErrc errc, const std::string& message) : BridgeError(std::string(storageErrorCode(errc)), message), errcValue(errc) { } + + [[nodiscard]] StorageErrc errc() const noexcept { + return errcValue; + } + +private: + StorageErrc errcValue; +}; + +enum class EntryType { + file, + directory, + link, ///< a symbolic link or another reparse point, listed without being followed + other ///< a device, a socket, a pipe: never opened +}; + +/// What a listing or status() reports of an entry. +struct EntryInfo { + std::string name; ///< the entry's name in its directory; empty for the root + EntryType type{EntryType::other}; + std::uint64_t size{}; ///< in bytes, for a file; 0 otherwise + std::chrono::system_clock::time_point modified{}; + /// Indicative rights of the running process, derived from the entry's attributes (POSIX mode bits for the owner, + /// the group and the others; the read-only attribute on Windows; ACLs are not examined). An operation can still + /// be refused with accessDenied. + bool readable{}; + bool writable{}; + + bool operator==(const EntryInfo&) const = default; +}; + +/// One page of a directory listing. +struct DirectoryPage { + std::vector entries; ///< sorted by name, byte by byte + /// Present when entries remain: pass it as `after` to list() to read the next page. + std::optional next; +}; + +/// What committing a write does when the name exists. +enum class WriteMode { + createNew, ///< refuse with alreadyExists + replace ///< replace the file atomically; a directory is never replaced +}; + +/// The number of entries list() returns at most, whatever its caller asks. +inline constexpr std::size_t maxStoragePageSize = 1000; + +/// A write in progress: the bytes go to a temporary entry, invisible under the final name until commit() renames it +/// atomically. Destroying an uncommitted writer removes the temporary entry, so an interrupted write leaves no partial +/// file behind. +template +concept StorageWriter = requires(W writer, std::span bytes) { + writer.write(bytes); + writer.commit(); +}; + +/** + * @brief A writable storage confined to one root. + * + * Paths are '/'-separated and relative to the root, checked by safePathComponents() (the empty path is the root); + * names starting with temporaryPrefix are reserved to the temporary files of writes. + * Every operation is resolved inside the root and fails with a StorageError; a storage never follows a component + * outside its root. + * + * - `list(dir, after, limit)`: the entries of a directory whose names sort after `after` (empty: from the first), + * at most `limit` (bounded by maxStoragePageSize). Pages are stable: an entry present during the whole + * listing appears exactly once, whatever is added or removed meanwhile. + * - `status(path)`: the entry itself, a link not followed. + * - `openRead(path)`: the content of a file. + * - `beginWrite(path, mode)`: a StorageWriter. + * - `createDirectory(path)`, `remove(path)` (a file, a link or an empty directory), `rename(from, to)` (never + * replaces). + */ +template +concept Storage = requires(S& storage, std::string_view path, std::size_t limit, std::span bytes) { + { storage.list(path, path, limit) } -> std::same_as; + { storage.status(path) } -> std::same_as; + { storage.openRead(path) } -> std::same_as; + { storage.beginWrite(path, WriteMode::createNew) } -> StorageWriter; + storage.createDirectory(path); + storage.remove(path); + storage.rename(path, path); +}; + +/// The prefix a storage reserves for the temporary files of its writes in progress: no path may have a component that +/// starts with it, in any letter case (invalidPath), and listings omit such entries. The case does not matter because +/// case-insensitive volumes (macOS by default, Windows) name the same file with ".WF-TMP-": the prefix is ASCII, and no +/// other character folds to its letters. +inline constexpr std::string_view temporaryPrefix = ".wf-tmp-"; + +/// True when a name starts with temporaryPrefix, whatever the case of its letters. +[[nodiscard]] inline bool isTemporaryName(std::string_view name) noexcept { + if (name.size() < temporaryPrefix.size()) + return false; + for (std::size_t index = 0; index < temporaryPrefix.size(); ++index) { + const char c = name[index]; + if ((c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c) != temporaryPrefix[index]) + return false; + } + return true; +} + +namespace detail { + +/// The components of a path given to a storage operation, or StorageError(invalidPath). +inline std::vector storageComponents(std::string_view path) { + std::vector components; + try { + components = safePathComponents(path); + } catch (const std::invalid_argument&) { + throw StorageError(StorageErrc::invalidPath, "Invalid storage path '" + std::string(path) + "'"); + } + for (const auto& component : components) + if (isTemporaryName(component)) + throw StorageError(StorageErrc::invalidPath, "Names starting with '" + std::string(temporaryPrefix) + "' are reserved"); + return components; +} + +/// The components of a path that must name an entry, not the root. +inline std::vector entryComponents(std::string_view path) { + auto components = storageComponents(path); + if (components.empty()) + throw StorageError(StorageErrc::invalidPath, "The operation needs an entry, not the root"); + return components; +} + +/// Sorts a whole directory and keeps the page after `after`. +inline DirectoryPage pageOf(std::vector entries, std::string_view after, std::size_t limit) { + if (!after.empty() && !isSafeFileName(after)) + throw StorageError(StorageErrc::invalidPath, "Invalid listing cursor"); + limit = std::clamp(limit, 1, maxStoragePageSize); + std::ranges::sort(entries, {}, &EntryInfo::name); + auto first = after.empty() ? entries.begin() : std::ranges::upper_bound(entries, after, {}, &EntryInfo::name); + DirectoryPage page; + const auto count = std::min(limit, static_cast(entries.end() - first)); + page.entries.assign(std::make_move_iterator(first), std::make_move_iterator(first + static_cast(count))); + if (first + static_cast(count) != entries.end()) + page.next = page.entries.back().name; + return page; +} + +/// Joins components for a message. +inline std::string joinComponents(const std::vector& components) { + std::string joined; + for (const auto& component : components) + joined += (joined.empty() ? "" : "/") + component; + return joined; +} + +} // namespace detail + +} // namespace webfront::fs diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index f9799092..8b53e62b 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -26,7 +26,7 @@ endif() set(TESTS_LIST) list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp HTTPRoutesTests.cpp HTTPRangeTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp IndexFSTests.cpp) -list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp) +list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp StorageTests.cpp NativeStorageTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp BroadcastTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationStdioTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp) diff --git a/test/unit/NativeStorageTests.cpp b/test/unit/NativeStorageTests.cpp new file mode 100644 index 00000000..ea233f12 --- /dev/null +++ b/test/unit/NativeStorageTests.cpp @@ -0,0 +1,1250 @@ +#include "TemporaryDirectory.hpp" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 + #include + #include + #if defined(__linux__) + #include + #endif + #include + #include +#endif + +using namespace std; +using namespace webfront; +namespace stdfs = std::filesystem; + +namespace { + +string readAll(fs::File file) { + string content; + array buffer{}; + while (!file.eof()) { + const auto count = file.read(buffer); + content.append(buffer.data(), count); + if (count == 0) + break; + } + return content; +} + +void writeFile(fs::NativeStorage& storage, string_view path, string_view content, fs::WriteMode mode = fs::WriteMode::createNew) { + auto writer = storage.beginWrite(path, mode); + writer.write(span(content.data(), content.size())); + writer.commit(); +} + +void writeDisk(const stdfs::path& path, string_view content) { + ofstream(path, ios::binary) << content; +} + +string readDisk(const stdfs::path& path) { + ifstream file(path, ios::binary); + return {istreambuf_iterator(file), {}}; +} + +template +fs::StorageErrc errorOf(Operation&& operation) { + try { + operation(); + } catch (const fs::StorageError& error) { + return error.errc(); + } + FAIL("The operation did not fail"); + return fs::StorageErrc::ioError; +} + +// The names of a directory on disk, temporary files included. +vector namesOn(const stdfs::path& directory) { + vector names; + for (const auto& entry : stdfs::directory_iterator(directory)) + names.push_back(entry.path().filename().string()); + ranges::sort(names); + return names; +} + +// The temporary file of the single write in progress under `root`: in the root for a new file, in the private directory +// of the write for a replacing one. +stdfs::path temporaryOf(const stdfs::path& root) { + for (const auto& entry : stdfs::directory_iterator(root)) { + if (!fs::isTemporaryName(entry.path().filename().string())) + continue; + if (!entry.is_directory()) + return entry.path(); + const auto inner = stdfs::directory_iterator(entry.path()); + REQUIRE(inner != stdfs::directory_iterator()); + return inner->path(); + } + FAIL("No temporary file under the root"); + return {}; +} + +// A link at `link` to the directory `target`: a symbolic link on POSIX, a junction on Windows (which needs no privilege). +void linkDirectory(const stdfs::path& target, const stdfs::path& link) { +#ifdef _WIN32 + const auto command = "cmd /c mklink /J \"" + link.string() + "\" \"" + target.string() + "\" >NUL"; + REQUIRE(std::system(command.c_str()) == 0); +#else + stdfs::create_directory_symlink(target, link); +#endif +} + +// A root and, beside it, a directory outside the root that no operation may reach. +struct Sandbox { + test::TemporaryDirectory base; + stdfs::path root = base.path() / "root"; + stdfs::path outside = base.path() / "outside"; + + Sandbox() { + stdfs::create_directory(root); + stdfs::create_directory(outside); + writeDisk(outside / "secret.txt", "secret"); +#ifndef _WIN32 + // The tests' ownership checks need directories nobody else can write in, whatever the umask. + for (const auto& directory : {base.path(), root, outside}) + stdfs::permissions(directory, stdfs::perms::group_write | stdfs::perms::others_write, stdfs::perm_options::remove); +#endif + } + + [[nodiscard]] bool outsideUntouched() const { + return namesOn(outside) == vector{"secret.txt"} && readDisk(outside / "secret.txt") == "secret"; + } +}; + +shared_ptr hooksAt(function at) { + auto hooks = make_shared(); + hooks->at = std::move(at); + return hooks; +} + +} // namespace + +SCENARIO("A native storage reads and writes under its root") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + + THEN("its location is the canonical root") { + REQUIRE(storage.location() == stdfs::canonical(sandbox.root)); + } + GIVEN("entries created through it") { + storage.createDirectory("docs"); + writeFile(storage, "docs/a.txt", "alpha"); + writeFile(storage, "b.txt", "beta"); + + THEN("they are on disk, listed, inspected and read") { + REQUIRE(readDisk(sandbox.root / "docs" / "a.txt") == "alpha"); + auto page = storage.list(""); + REQUIRE(page.entries.size() == 2); + REQUIRE(page.entries[0].name == "b.txt"); + REQUIRE(page.entries[0].type == fs::EntryType::file); + REQUIRE(page.entries[0].size == 4); + REQUIRE(page.entries[0].readable); + REQUIRE(page.entries[0].writable); + REQUIRE(page.entries[1].type == fs::EntryType::directory); + REQUIRE(storage.status("docs/a.txt").size == 5); + REQUIRE(storage.status("").type == fs::EntryType::directory); + auto file = storage.openRead("docs/a.txt"); + REQUIRE(file.knownSize() == 5u); + REQUIRE(readAll(std::move(file)) == "alpha"); + } + THEN("a file is read from any position") { + auto file = storage.openRead("docs/a.txt"); + array buffer{}; + REQUIRE(file.seek(3)); + REQUIRE(file.read(buffer) == 2); + REQUIRE(string_view(buffer.data(), 2) == "ha"); + } + THEN("a write replaces atomically only when asked to") { + REQUIRE(errorOf([&] { + writeFile(storage, "b.txt", "other"); + }) + == fs::StorageErrc::alreadyExists); + writeFile(storage, "b.txt", "gamma", fs::WriteMode::replace); + REQUIRE(readDisk(sandbox.root / "b.txt") == "gamma"); + REQUIRE(errorOf([&] { + writeFile(storage, "docs", "x", fs::WriteMode::replace); + }) + == fs::StorageErrc::isDirectory); + } + THEN("entries are renamed without replacing and removed") { + REQUIRE(errorOf([&] { + storage.rename("b.txt", "docs/a.txt"); + }) + == fs::StorageErrc::alreadyExists); + storage.rename("b.txt", "docs/b.txt"); + REQUIRE(stdfs::exists(sandbox.root / "docs" / "b.txt")); + REQUIRE(errorOf([&] { + storage.remove("docs"); + }) + == fs::StorageErrc::notEmpty); + storage.remove("docs/a.txt"); + storage.remove("docs/b.txt"); + storage.remove("docs"); + REQUIRE(namesOn(sandbox.root).empty()); + } + THEN("operations through a file or a missing entry fail with their reason") { + REQUIRE(errorOf([&] { + storage.list("b.txt"); + }) + == fs::StorageErrc::notDirectory); + REQUIRE(errorOf([&] { + storage.openRead("b.txt/x"); + }) + == fs::StorageErrc::notDirectory); + REQUIRE(errorOf([&] { + storage.openRead("missing.txt"); + }) + == fs::StorageErrc::notFound); + REQUIRE(errorOf([&] { + storage.openRead("docs"); + }) + == fs::StorageErrc::isDirectory); + REQUIRE(errorOf([&] { + storage.createDirectory("docs"); + }) + == fs::StorageErrc::alreadyExists); + } + } + GIVEN("paths SafePath rejects") { + auto path = GENERATE(as{}, "../outside/secret.txt", "/etc/passwd", "a/../../outside", "C:/x", "nul", "a\\..\\b"); + THEN("they are refused before touching the disk") { + REQUIRE(errorOf([&] { + storage.openRead(path); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.createDirectory(path); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(sandbox.outsideUntouched()); + } + } + GIVEN("a location that is not a directory") { + writeDisk(sandbox.base.path() / "file", "x"); + THEN("it cannot be declared") { + REQUIRE(errorOf([&] { + fs::NativeStorage{sandbox.base.path() / "missing"}; + }) + == fs::StorageErrc::notFound); + REQUIRE(errorOf([&] { + fs::NativeStorage{sandbox.base.path() / "file"}; + }) + == fs::StorageErrc::notDirectory); + } + } +} + +SCENARIO("A native storage reserves the names of its temporary files") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + REQUIRE(errorOf([&] { + writeFile(storage, ".wf-tmp-report.txt", "report"); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.rename("a", ".wf-tmp-a"); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(namesOn(sandbox.root).empty()); + GIVEN("a write in progress, its temporary file named in another case") { + auto writer = storage.beginWrite("report.txt", fs::WriteMode::createNew); + writer.write(span("partial", 7)); + const auto temporary = namesOn(sandbox.root).at(0); + auto upper = temporary; + ranges::transform(upper, upper.begin(), [](char c) { + return c >= 'a' && c <= 'z' ? static_cast(c - 'a' + 'A') : c; + }); + THEN("it can be neither read nor published, on a case-insensitive volume as elsewhere") { + // macOS (by default) and Windows volumes name the same file in any case: the reservation must cover it. + if (!stdfs::exists(sandbox.root / upper)) + WARN("This volume is case-sensitive: the other case names no file here"); + REQUIRE(errorOf([&] { + storage.openRead(upper); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.rename(upper, "published.txt"); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.remove(upper); + }) + == fs::StorageErrc::invalidPath); + REQUIRE_FALSE(stdfs::exists(sandbox.root / "published.txt")); + } + } +} + +SCENARIO("An interrupted write leaves no partial file") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + writeFile(storage, "kept.txt", "original"); + + GIVEN("writes destroyed before their commit, new or replacing") { + { + auto writer = storage.beginWrite("new.txt", fs::WriteMode::createNew); + writer.write(span("partial", 7)); + REQUIRE(namesOn(sandbox.root).size() == 2); // kept.txt and the temporary file + REQUIRE(storage.list("").entries.size() == 1); + REQUIRE(errorOf([&] { + storage.status("new.txt"); + }) + == fs::StorageErrc::notFound); + } + { + auto writer = storage.beginWrite("kept.txt", fs::WriteMode::replace); + writer.write(span("half", 4)); + } + THEN("neither the partial file nor the temporary one remains, and the replaced file is intact") { + REQUIRE(namesOn(sandbox.root) == vector{"kept.txt"}); + REQUIRE(readDisk(sandbox.root / "kept.txt") == "original"); + } + } +} + +SCENARIO("A committed writer holds none of its directories") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + storage.createDirectory("dir"); + auto writer = storage.beginWrite("dir/file.txt", fs::WriteMode::createNew); + writer.write(span("data", 4)); + writer.commit(); + // The writer stays alive: on Windows, handles it kept without FILE_SHARE_DELETE would make these fail. + std::error_code renamed, removed; + stdfs::rename(sandbox.root / "dir", sandbox.root / "moved", renamed); + REQUIRE_FALSE(renamed); + stdfs::remove(sandbox.root / "moved" / "file.txt", removed); + REQUIRE_FALSE(removed); + stdfs::remove(sandbox.root / "moved", removed); + REQUIRE_FALSE(removed); +} + +SCENARIO("Native listings are paginated and stable") { + Sandbox sandbox; + for (int index = 10; index < 40; ++index) + writeDisk(sandbox.root / ("f" + to_string(index)), "x"); +#ifndef _WIN32 + writeDisk(sandbox.root / "trailing.", "unaddressable"); // a name SafePath rejects is not listed +#endif + fs::NativeStorage storage(sandbox.root); + + auto first = storage.list("", {}, 10); + REQUIRE(first.entries.size() == 10); + REQUIRE(first.next == "f19"); + writeDisk(sandbox.root / "f05", "x"); + writeDisk(sandbox.root / "f195", "x"); + stdfs::remove(sandbox.root / "f30"); + vector seen; + for (auto& entry : first.entries) + seen.push_back(entry.name); + for (auto after = first.next; after;) { + auto page = storage.list("", *after, 10); + for (auto& entry : page.entries) + seen.push_back(entry.name); + after = page.next; + } + vector expected; + for (int index = 10; index < 40; ++index) + if (index != 30) + expected.push_back("f" + to_string(index)); + expected.push_back("f195"); + ranges::sort(expected); + REQUIRE(seen == expected); +} + +SCENARIO("Links never lead a native storage outside its root") { + Sandbox sandbox; + stdfs::create_directory(sandbox.root / "inside"); + writeDisk(sandbox.root / "inside" / "note.txt", "note"); + linkDirectory(sandbox.outside, sandbox.root / "escape"); + + GIVEN("a root that refuses links (the default)") { + fs::NativeStorage storage(sandbox.root); + THEN("every operation through the link is refused and the outside is untouched") { + REQUIRE(errorOf([&] { + storage.list("escape"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.openRead("escape/secret.txt"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + writeFile(storage, "escape/new.txt", "x"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + writeFile(storage, "escape/secret.txt", "x", fs::WriteMode::replace); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.createDirectory("escape/dir"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.remove("escape/secret.txt"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.rename("escape/secret.txt", "stolen.txt"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.rename("inside/note.txt", "escape/note.txt"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(sandbox.outsideUntouched()); + } + THEN("the link is listed as a link, not followed") { + auto page = storage.list(""); + REQUIRE(page.entries.size() == 2); + REQUIRE(page.entries[0].name == "escape"); + REQUIRE(page.entries[0].type == fs::EntryType::link); + REQUIRE(storage.status("escape").type == fs::EntryType::link); + } + THEN("removing the link removes the link only") { + storage.remove("escape"); + REQUIRE_FALSE(stdfs::exists(stdfs::symlink_status(sandbox.root / "escape"))); + REQUIRE(sandbox.outsideUntouched()); + } + } +#ifndef _WIN32 + GIVEN("a file link to the outside") { + stdfs::create_symlink(sandbox.outside / "secret.txt", sandbox.root / "secret-link"); + fs::NativeStorage storage(sandbox.root); + THEN("it is not read, and replacing it replaces the link, not its target") { + REQUIRE(errorOf([&] { + storage.openRead("secret-link"); + }) + == fs::StorageErrc::linkRefused); + writeFile(storage, "secret-link", "replaced", fs::WriteMode::replace); + REQUIRE(stdfs::is_regular_file(stdfs::symlink_status(sandbox.root / "secret-link"))); + REQUIRE(sandbox.outsideUntouched()); + } + } + GIVEN("a root that follows links inside it") { + stdfs::create_directory_symlink("inside", sandbox.root / "alias"); + stdfs::create_symlink("../inside/note.txt", sandbox.root / "inside" / "self"); + stdfs::create_directory_symlink("../../outside", sandbox.root / "inside" / "up"); + stdfs::create_symlink(sandbox.outside / "secret.txt", sandbox.root / "absolute"); + stdfs::create_symlink("loop", sandbox.root / "loop"); + stdfs::create_symlink("..", sandbox.root / "parent"); + fs::NativeStorage storage(sandbox.root, {.links = fs::LinkPolicy::followInside}); + THEN("a link whose resolution stays inside is followed") { + REQUIRE(readAll(storage.openRead("alias/note.txt")) == "note"); + REQUIRE(readAll(storage.openRead("inside/self")) == "note"); + writeFile(storage, "alias/added.txt", "added"); + REQUIRE(readDisk(sandbox.root / "inside" / "added.txt") == "added"); + REQUIRE(storage.list("alias").entries.size() == 4); // note.txt, self, up, added.txt + } + THEN("a link that leaves the root, an absolute link and a loop are refused") { + REQUIRE(errorOf([&] { + storage.list("escape"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.openRead("inside/up/secret.txt"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + writeFile(storage, "inside/up/new.txt", "x"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.openRead("absolute"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.openRead("loop"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(sandbox.outsideUntouched()); + } + } +#endif +} + +SCENARIO("A component replaced by a link during the resolution does not lead outside") { + Sandbox sandbox; + + // Before each operation: root/a/b/file.txt. When `a` has been opened and `b` not yet, b is replaced by a link to + // the outside directory, as a concurrent local process could do between two resolution steps. + auto prepare = [&] { + stdfs::remove_all(sandbox.root / "a"); + stdfs::create_directories(sandbox.root / "a" / "b"); + writeDisk(sandbox.root / "a" / "b" / "secret.txt", "inner"); + }; + auto swapB = hooksAt([&](fs::StoragePoint point, string_view name) { + if (point == fs::StoragePoint::componentOpened && name == "a") { + stdfs::rename(sandbox.root / "a" / "b", sandbox.root / "b-moved"); + linkDirectory(sandbox.outside, sandbox.root / "a" / "b"); + } + }); + fs::NativeStorage storage(sandbox.root, {}, swapB); + + const vector> operations{[&] { + storage.openRead("a/b/secret.txt"); + }, + [&] { + storage.list("a/b"); + }, + [&] { + writeFile(storage, "a/b/new.txt", "x"); + }, + [&] { + writeFile(storage, "a/b/secret.txt", "x", fs::WriteMode::replace); + }, + [&] { + storage.createDirectory("a/b/dir"); + }, + [&] { + storage.remove("a/b/secret.txt"); + }, + [&] { + storage.rename("a/b/secret.txt", "stolen.txt"); + }, + [&] { + storage.status("a/b/secret.txt"); + }}; + const auto operation = operations[static_cast(GENERATE(Catch::Generators::range(0, 8)))]; + prepare(); + stdfs::remove_all(sandbox.root / "b-moved"); + REQUIRE(errorOf(operation) == fs::StorageErrc::linkRefused); + REQUIRE(sandbox.outsideUntouched()); +} + +SCENARIO("A final file replaced by a link after the resolution does not lead outside") { + Sandbox sandbox; + auto swapFile = hooksAt([&](fs::StoragePoint point, string_view name) { + if (point == fs::StoragePoint::resolved && name == "target.txt") { + stdfs::remove(sandbox.root / "target.txt"); +#ifdef _WIN32 + linkDirectory(sandbox.outside, sandbox.root / "target.txt"); +#else + stdfs::create_symlink(sandbox.outside / "secret.txt", sandbox.root / "target.txt"); +#endif + } + }); + fs::NativeStorage storage(sandbox.root, {}, swapFile); + writeDisk(sandbox.root / "target.txt", "inner"); + + WHEN("it is read") { + THEN("the link is refused") { + REQUIRE(errorOf([&] { + storage.openRead("target.txt"); + }) + == fs::StorageErrc::linkRefused); + } + } + WHEN("it is removed") { + storage.remove("target.txt"); + THEN("the link goes, not the outside file") { + REQUIRE_FALSE(stdfs::exists(stdfs::symlink_status(sandbox.root / "target.txt"))); + } + } + WHEN("it is inspected") { + THEN("the link is reported, not followed") { + REQUIRE(storage.status("target.txt").type == fs::EntryType::link); + } + } + REQUIRE(sandbox.outsideUntouched()); +} + +#ifndef _WIN32 +SCENARIO("Repeated races between a link swap and the operations never reach the outside") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + stdfs::create_directory(sandbox.root / "a"); + atomic stop{false}; + // Swaps `a` between a real directory and a link to the outside, as fast as it can. + thread swapper([&] { + const auto directory = sandbox.root / "a"; + const auto parked = sandbox.root / "parked"; + const auto link = sandbox.base.path() / "link"; + while (!stop) { + std::error_code ignored; + stdfs::create_directory_symlink(sandbox.outside, link, ignored); + stdfs::rename(directory, parked, ignored); + stdfs::rename(link, directory, ignored); + std::this_thread::yield(); + stdfs::rename(directory, link, ignored); + stdfs::rename(parked, directory, ignored); + } + }); + int refused = 0; + auto attempt = [&](auto&& operation) { + try { + operation(); + } catch (const fs::StorageError& error) { + refused += error.errc() == fs::StorageErrc::linkRefused; + } + }; + for (int iteration = 0; iteration < 2000; ++iteration) { + const auto name = "f" + to_string(iteration); + attempt([&] { + writeFile(storage, "a/" + name, "x"); + }); + attempt([&] { + storage.createDirectory("a/d" + name); + }); + attempt([&] { + storage.remove("a/secret.txt"); + }); + attempt([&] { + storage.rename("a/secret.txt", "stolen" + name); + }); + attempt([&] { + readAll(storage.openRead("a/secret.txt")); + FAIL("The outside file was read"); + }); + } + stop = true; + swapper.join(); + REQUIRE(sandbox.outsideUntouched()); + REQUIRE(refused > 0); // the operations did meet the link +} + +SCENARIO("A directory moved out of the root by the same user is detected before the commit") { + Sandbox sandbox; + stdfs::create_directories(sandbox.root / "a" / "b"); + const auto moved = sandbox.outside / "b"; + + GIVEN("a directory moved out while the temporary file is written") { + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::temporaryCreated) + stdfs::rename(sandbox.root / "a" / "b", moved); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + auto writer = storage.beginWrite("a/b/file.txt", fs::WriteMode::createNew); + writer.write(span("data", 4)); + THEN("the commit is abandoned with confinementViolated, without a file nor a temporary file outside") { + REQUIRE(errorOf([&] { + writer.commit(); + }) + == fs::StorageErrc::confinementViolated); + REQUIRE(stdfs::is_empty(moved)); + } + } + GIVEN("a directory moved out just before the commit's check") { + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::beforeCommit) + stdfs::rename(sandbox.root / "a", sandbox.outside / "a"); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + THEN("the rename does not happen") { + REQUIRE(errorOf([&] { + writeFile(storage, "a/b/file.txt", "data"); + }) + == fs::StorageErrc::confinementViolated); + REQUIRE(stdfs::is_empty(sandbox.outside / "a" / "b")); + } + } + GIVEN("a directory moved out between its opening and the operation") { + bool once = true; + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::resolved && std::exchange(once, false)) + stdfs::rename(sandbox.root / "a" / "b", moved); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + THEN("the operation reports the violation it detected afterwards") { + REQUIRE(errorOf([&] { + storage.createDirectory("a/b/dir"); + }) + == fs::StorageErrc::confinementViolated); + REQUIRE(errorOf([&] { + storage.status("a/b"); + }) + == fs::StorageErrc::notFound); + } + } +} + +SCENARIO("A root moved by the same user is no longer used") { + Sandbox sandbox; + const auto elsewhere = sandbox.base.path() / "elsewhere"; + + GIVEN("a root moved before an operation") { + fs::NativeStorage storage(sandbox.root); + stdfs::rename(sandbox.root, elsewhere); + THEN("every operation fails with rootMoved, without effect, even once a directory is back at the location") { + REQUIRE(errorOf([&] { + storage.createDirectory("dir"); + }) + == fs::StorageErrc::rootMoved); + REQUIRE(stdfs::is_empty(elsewhere)); + stdfs::rename(elsewhere, sandbox.root); + REQUIRE(errorOf([&] { + storage.list(""); + }) + == fs::StorageErrc::rootMoved); + REQUIRE(stdfs::is_empty(sandbox.root)); + } + } + GIVEN("another directory put at the location") { + fs::NativeStorage storage(sandbox.root); + stdfs::rename(sandbox.root, elsewhere); + stdfs::create_directory(sandbox.root); + THEN("it is not taken for the root") { + REQUIRE(errorOf([&] { + writeFile(storage, "file.txt", "x"); + }) + == fs::StorageErrc::rootMoved); + REQUIRE(stdfs::is_empty(sandbox.root)); + } + } + GIVEN("a root moved during a write") { + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::temporaryCreated) + stdfs::rename(sandbox.root, elsewhere); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + THEN("the commit is abandoned with confinementViolated") { + REQUIRE(errorOf([&] { + writeFile(storage, "file.txt", "x"); + }) + == fs::StorageErrc::confinementViolated); + REQUIRE(stdfs::is_empty(elsewhere)); + } + } +} + +SCENARIO("POSIX directories another user could move refuse the root or the operation") { + Sandbox sandbox; + const auto otherUser = ::geteuid() == 4242u ? 4243u : 4242u; + const auto base = stdfs::canonical(sandbox.base.path()); + const auto root = base / "root"; + auto hooks = make_shared(); + map overrides; + hooks->facts = [&](const stdfs::path& path, fs::DirectoryFacts& facts) { + if (auto found = overrides.find(path); found != overrides.end()) + facts = found->second; + }; + const auto own = static_cast(::geteuid()); + auto facts = [](uint32_t owner, uint32_t mode) { + return fs::DirectoryFacts{owner, S_IFDIR | mode}; + }; + + GIVEN("a root owned by another user, even in mode 0755") { + overrides[root] = facts(otherUser, 0755); + THEN("its declaration is refused") { + REQUIRE(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + } + } + GIVEN("a root its group can write") { + stdfs::permissions(sandbox.root, stdfs::perms::group_write, stdfs::perm_options::add); + THEN("its declaration is refused, unless the root is declared shared") { + REQUIRE(errorOf([&] { + fs::NativeStorage(sandbox.root); + }) + == fs::StorageErrc::unsafeDirectory); + fs::NativeStorage shared(sandbox.root, {.shared = true}); + shared.createDirectory("dir"); + } + } + GIVEN("an ancestor owned by another user, in mode 0755") { + overrides[base] = facts(otherUser, 0755); + THEN("the declaration is refused") { + REQUIRE(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + } + } + GIVEN("an ancestor writable by the others") { + overrides[base] = facts(own, 0777); + THEN("the declaration is refused") { + REQUIRE(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + } + } + GIVEN("a sticky ancestor owned by another user") { + overrides[base] = facts(otherUser, 01777); + THEN("the declaration is refused") { + REQUIRE(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + } + } + GIVEN("a sticky ancestor of the superuser, as /tmp") { + overrides[base] = facts(0, 01777); + THEN("a next element of the effective user is accepted") { + fs::NativeStorage storage(sandbox.root, {}, hooks); + storage.createDirectory("dir"); + } + THEN("a next element of another user is refused") { + overrides[root] = facts(otherUser, 0755); + REQUIRE(errorOf([&] { + fs::NativeStorage(sandbox.root, {}, hooks); + }) + == fs::StorageErrc::unsafeDirectory); + } + } + GIVEN("a root declared, then an ancestor that becomes unsafe") { + fs::NativeStorage storage(sandbox.root, {}, hooks); + overrides[base] = facts(otherUser, 0755); + THEN("the next operation is refused before any effect") { + REQUIRE(errorOf([&] { + storage.createDirectory("dir"); + }) + == fs::StorageErrc::unsafeDirectory); + REQUIRE(stdfs::is_empty(sandbox.root)); + } + } + GIVEN("directories inside the root another user could move") { + stdfs::create_directories(sandbox.root / "group" / "deep"); + stdfs::create_directories(sandbox.root / "foreign" / "deep"); + stdfs::permissions(sandbox.root / "group", stdfs::perms::group_write, stdfs::perm_options::add); + overrides[root / "foreign"] = facts(otherUser, 0755); + fs::NativeStorage storage(sandbox.root, {}, hooks); + THEN("operations traversing them are refused before any effect") { + REQUIRE(errorOf([&] { + storage.createDirectory("group/deep/new"); + }) + == fs::StorageErrc::unsafeDirectory); + REQUIRE(errorOf([&] { + writeFile(storage, "foreign/deep/new.txt", "x"); + }) + == fs::StorageErrc::unsafeDirectory); + REQUIRE(stdfs::is_empty(sandbox.root / "group" / "deep")); + REQUIRE(stdfs::is_empty(sandbox.root / "foreign" / "deep")); + } + } + GIVEN("directories the storage creates, whatever the umask") { + const auto previous = ::umask(0); + fs::NativeStorage storage(sandbox.root); + storage.createDirectory("created"); + writeFile(storage, "created/file.txt", "x"); + ::umask(previous); + THEN("they stay usable by the storage") { + REQUIRE((stdfs::status(sandbox.root / "created").permissions() & (stdfs::perms::group_write | stdfs::perms::others_write)) == stdfs::perms::none); + REQUIRE(storage.list("created").entries.size() == 1); + } + } +} + + #if defined(__APPLE__) +SCENARIO("macOS ACLs that let another user change a directory refuse the root or the operation") { + Sandbox sandbox; + auto grant = [](const stdfs::path& directory, const string& who) { + const auto command = "chmod +a '" + who + " allow add_file,add_subdirectory,delete_child' '" + directory.string() + "'"; + REQUIRE(std::system(command.c_str()) == 0); + }; + + GIVEN("a root in mode 0700 whose ACL lets everyone add and remove entries") { + stdfs::permissions(sandbox.root, stdfs::perms::owner_all, stdfs::perm_options::replace); + grant(sandbox.root, "everyone"); + THEN("its declaration is refused, unless the root is declared shared") { + REQUIRE(errorOf([&] { + fs::NativeStorage(sandbox.root); + }) + == fs::StorageErrc::unsafeDirectory); + fs::NativeStorage shared(sandbox.root, {.shared = true}); + shared.createDirectory("dir"); + } + } + GIVEN("an ancestor whose ACL lets everyone remove its entries") { + grant(sandbox.base.path(), "everyone"); + THEN("the declaration is refused") { + REQUIRE(errorOf([&] { + fs::NativeStorage(sandbox.root); + }) + == fs::StorageErrc::unsafeDirectory); + } + } + GIVEN("a directory inside the root granted to everyone after the declaration") { + fs::NativeStorage storage(sandbox.root); + stdfs::create_directories(sandbox.root / "shared" / "deep"); + grant(sandbox.root / "shared", "everyone"); + THEN("operations through it are refused before any effect") { + REQUIRE(errorOf([&] { + storage.createDirectory("shared/deep/new"); + }) + == fs::StorageErrc::unsafeDirectory); + REQUIRE(stdfs::is_empty(sandbox.root / "shared" / "deep")); + } + } + GIVEN("a root whose ACL passes those rights to everyone, only to its descendants") { + stdfs::permissions(sandbox.root, stdfs::perms::owner_all, stdfs::perm_options::replace); + const auto command = "chmod +a 'everyone allow add_file,add_subdirectory,delete_child,file_inherit,directory_inherit,only_inherit' '" + + sandbox.root.string() + "'"; + REQUIRE(std::system(command.c_str()) == 0); + THEN("the root is accepted, and a subdirectory that inherits the rights is refused when traversed") { + fs::NativeStorage storage(sandbox.root); + storage.createDirectory("inherits"); + REQUIRE(errorOf([&] { + storage.list("inherits"); + }) + == fs::StorageErrc::unsafeDirectory); + } + } + GIVEN("an ACL that grants those rights to the effective user only") { + grant(sandbox.root, "user:" + string(::getpwuid(::geteuid())->pw_name)); + THEN("the root is accepted") { + fs::NativeStorage storage(sandbox.root); + storage.createDirectory("dir"); + } + } +} + #endif + +SCENARIO("A replaced file keeps its permission bits") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + writeDisk(sandbox.root / "private.txt", "old"); + stdfs::permissions(sandbox.root / "private.txt", stdfs::perms::owner_read | stdfs::perms::owner_write, stdfs::perm_options::replace); + writeFile(storage, "private.txt", "new secret", fs::WriteMode::replace); + REQUIRE(readDisk(sandbox.root / "private.txt") == "new secret"); + REQUIRE(stdfs::status(sandbox.root / "private.txt").permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); +} + +SCENARIO("A replaced file keeps its access control list") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + const auto file = sandbox.root / "guarded.txt"; + writeDisk(file, "old"); + #if defined(__APPLE__) + GIVEN("an ACL that denies another user reading the file") { + REQUIRE(std::system(("chmod +a 'user:nobody deny read' '" + file.string() + "'").c_str()) == 0); + writeFile(storage, "guarded.txt", "new secret", fs::WriteMode::replace); + THEN("the new file keeps it") { + REQUIRE(readDisk(file) == "new secret"); + REQUIRE(std::system(("ls -le '" + file.string() + "' | grep -q 'user:nobody deny read'").c_str()) == 0); + } + } + GIVEN("an ACL that denies everyone, the effective user included, reading the file") { + REQUIRE(std::system(("chmod +a 'everyone deny read' '" + file.string() + "'").c_str()) == 0); + THEN("the ACL cannot be read, so the replacement is refused and the file left as it was") { + REQUIRE(errorOf([&] { + storage.openRead("guarded.txt"); + }) + == fs::StorageErrc::accessDenied); + REQUIRE(errorOf([&] { + writeFile(storage, "guarded.txt", "new secret", fs::WriteMode::replace); + }) + == fs::StorageErrc::accessDenied); + REQUIRE(std::system(("ls -le '" + file.string() + "' | grep -q 'everyone deny read'").c_str()) == 0); + REQUIRE(namesOn(sandbox.root) == vector{"guarded.txt"}); + } + } + #else + // The POSIX access ACL in its extended attribute form (version 2, then tag, permissions and identifier per entry), + // written directly so that the test needs no setfacl: the owner reads and writes, the user nobody (65534) gets + // nothing, the group and the others read. + const auto entry = [](std::uint16_t tag, std::uint16_t permissions, std::uint32_t id) { + std::array bytes{}; + for (int index = 0; index < 2; ++index) { + bytes[static_cast(index)] = static_cast(tag >> (8 * index)); + bytes[static_cast(index + 2)] = static_cast(permissions >> (8 * index)); + } + for (int index = 0; index < 4; ++index) + bytes[static_cast(index + 4)] = static_cast(id >> (8 * index)); + return string(bytes.data(), bytes.size()); + }; + constexpr std::uint32_t undefined = 0xFFFFFFFF, nobody = 65534; + const string acl = string("\x02\0\0\0", 4) + entry(0x01, 6, undefined) + entry(0x02, 0, nobody) + entry(0x04, 4, undefined) + entry(0x10, 4, undefined) + + entry(0x20, 4, undefined); + const char* key = "system.posix_acl_access"; + if (::setxattr(file.c_str(), key, acl.data(), acl.size(), 0) != 0) + SKIP("This file system has no POSIX ACL"); + writeFile(storage, "guarded.txt", "new secret", fs::WriteMode::replace); + REQUIRE(readDisk(file) == "new secret"); + string kept(256, '\0'); + const auto size = ::getxattr(file.c_str(), key, kept.data(), kept.size()); + REQUIRE(size > 0); + kept.resize(static_cast(size)); + REQUIRE(kept.find(entry(0x02, 0, nobody)) != string::npos); + #endif +} + +SCENARIO("A replaced file without an ACL gets none from its directory") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + const auto file = sandbox.root / "plain.txt"; + writeDisk(file, "old"); + stdfs::permissions(file, stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read, stdfs::perm_options::replace); + #if defined(__APPLE__) + // Entries the directory passes on to new files: the temporary file receives them, the file it replaces had none. + REQUIRE(std::system(("chmod +a 'user:nobody allow read,file_inherit' '" + sandbox.root.string() + "'").c_str()) == 0); + writeFile(storage, "plain.txt", "new secret", fs::WriteMode::replace); + REQUIRE(std::system(("ls -le '" + file.string() + "' | grep -q nobody").c_str()) != 0); + #else + // A default ACL of the directory that lets the user nobody (65534) read new files. + const auto entry = [](std::uint16_t tag, std::uint16_t permissions, std::uint32_t id) { + std::array bytes{}; + for (int index = 0; index < 2; ++index) { + bytes[static_cast(index)] = static_cast(tag >> (8 * index)); + bytes[static_cast(index + 2)] = static_cast(permissions >> (8 * index)); + } + for (int index = 0; index < 4; ++index) + bytes[static_cast(index + 4)] = static_cast(id >> (8 * index)); + return string(bytes.data(), bytes.size()); + }; + constexpr std::uint32_t undefined = 0xFFFFFFFF; + const string defaults = string("\x02\0\0\0", 4) + entry(0x01, 7, undefined) + entry(0x02, 4, 65534) + entry(0x04, 5, undefined) + entry(0x10, 5, undefined) + + entry(0x20, 5, undefined); + if (::setxattr(sandbox.root.c_str(), "system.posix_acl_default", defaults.data(), defaults.size(), 0) != 0) + SKIP("This file system has no POSIX ACL"); + writeFile(storage, "plain.txt", "new secret", fs::WriteMode::replace); + REQUIRE(::getxattr(file.c_str(), "system.posix_acl_access", nullptr, 0) < 0); + #endif + REQUIRE(readDisk(file) == "new secret"); + REQUIRE(stdfs::status(file).permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read)); +} + +SCENARIO("A commit takes the rights of the file it replaces at that moment") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + writeDisk(sandbox.root / "doc.txt", "public"); + stdfs::permissions(sandbox.root / "doc.txt", + stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read | stdfs::perms::others_read, + stdfs::perm_options::replace); + auto writer = storage.beginWrite("doc.txt", fs::WriteMode::replace); + writer.write(span("new", 3)); + // Meanwhile the storage itself puts a private file under that name. + writeDisk(sandbox.root / "private.txt", "private"); + stdfs::permissions(sandbox.root / "private.txt", stdfs::perms::owner_read | stdfs::perms::owner_write, stdfs::perm_options::replace); + storage.remove("doc.txt"); + storage.rename("private.txt", "doc.txt"); + writer.commit(); + REQUIRE(readDisk(sandbox.root / "doc.txt") == "new"); + REQUIRE(stdfs::status(sandbox.root / "doc.txt").permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); +} + +SCENARIO("Running out of descriptors does not mark the root as moved") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + struct ::rlimit previous{}; + REQUIRE(::getrlimit(RLIMIT_NOFILE, &previous) == 0); + auto lowered = previous; + lowered.rlim_cur = std::min(previous.rlim_cur, 256); + REQUIRE(::setrlimit(RLIMIT_NOFILE, &lowered) == 0); + vector held; + for (int descriptor = ::dup(0); descriptor >= 0; descriptor = ::dup(0)) + held.push_back(descriptor); + // One descriptor left: `/` opens, the next component of the declared location does not. + REQUIRE_FALSE(held.empty()); + ::close(held.back()); + held.pop_back(); + const auto exhausted = errorOf([&] { + storage.createDirectory("dir"); + }); + for (const int descriptor : held) + ::close(descriptor); + REQUIRE(::setrlimit(RLIMIT_NOFILE, &previous) == 0); + REQUIRE(exhausted != fs::StorageErrc::rootMoved); + storage.createDirectory("dir"); + REQUIRE(stdfs::is_directory(sandbox.root / "dir")); +} + + #if defined(__APPLE__) +SCENARIO("The temporary file of a replacing write keeps no inherited ACL") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + writeDisk(sandbox.root / "private.txt", "old"); + stdfs::permissions(sandbox.root / "private.txt", stdfs::perms::owner_read | stdfs::perms::owner_write, stdfs::perm_options::replace); + // The ACL the directory passes on lets everyone read new files: not the temporary file of a private one. + REQUIRE(std::system(("chmod +a 'everyone allow read,file_inherit' '" + sandbox.root.string() + "'").c_str()) == 0); + auto writer = storage.beginWrite("private.txt", fs::WriteMode::replace); + writer.write(span("secret", 6)); + // The temporary file lives in a private directory created without the inherited entries, so it never had them. + const auto temporary = temporaryOf(sandbox.root); + REQUIRE(std::system(("ls -led '" + temporary.parent_path().string() + "' | grep -q everyone").c_str()) != 0); + REQUIRE(std::system(("ls -le '" + temporary.string() + "' | grep -q everyone").c_str()) != 0); + writer.commit(); + REQUIRE(std::system(("ls -le '" + (sandbox.root / "private.txt").string() + "' | grep -q everyone").c_str()) != 0); + REQUIRE(stdfs::status(sandbox.root / "private.txt").permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); +} + #endif + +SCENARIO("A replacing write is private from the creation of its temporary file") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + // No file to replace when the write begins: a private one may appear under that name before the commit. + auto writer = storage.beginWrite("later.txt", fs::WriteMode::replace); + writer.write(span("secret", 6)); + const auto temporary = temporaryOf(sandbox.root); + REQUIRE(fs::isTemporaryName(temporary.parent_path().filename().string())); + REQUIRE(stdfs::status(temporary).permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); + REQUIRE(stdfs::status(temporary.parent_path()).permissions() == stdfs::perms::owner_all); + writer.commit(); + REQUIRE(readDisk(sandbox.root / "later.txt") == "secret"); + REQUIRE(stdfs::status(sandbox.root / "later.txt").permissions() == (stdfs::perms::owner_read | stdfs::perms::owner_write)); + REQUIRE(namesOn(sandbox.root) == vector{"later.txt"}); +} + +SCENARIO("A replaced file keeps its group") { + // A group of the effective user other than its effective group, which a new file would not get. + const int count = ::getgroups(0, nullptr); + vector groups(static_cast(max(count, 0))); + if (count > 0) + groups.resize(static_cast(::getgroups(count, groups.data()))); + const auto other = ranges::find_if(groups, [](gid_t group) { + return group != ::getegid(); + }); + if (other == groups.end()) + SKIP("The effective user belongs to no other group"); + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root); + const auto file = sandbox.root / "shared.txt"; + writeDisk(file, "old"); + REQUIRE(::chown(file.c_str(), static_cast(-1), *other) == 0); + stdfs::permissions(file, stdfs::perms::owner_read | stdfs::perms::owner_write | stdfs::perms::group_read, stdfs::perm_options::replace); + writeFile(storage, "shared.txt", "new", fs::WriteMode::replace); + struct ::stat status{}; + REQUIRE(::stat(file.c_str(), &status) == 0); + REQUIRE(status.st_gid == *other); + REQUIRE((status.st_mode & 0777) == 0640); + REQUIRE(readDisk(file) == "new"); +} + +SCENARIO("A link followed inside the root never reaches a temporary file") { + Sandbox sandbox; + fs::NativeStorage storage(sandbox.root, {.links = fs::LinkPolicy::followInside}); + auto writer = storage.beginWrite("report.txt", fs::WriteMode::createNew); + writer.write(span("partial", 7)); + const auto temporary = namesOn(sandbox.root).at(0); + stdfs::create_symlink(temporary, sandbox.root / "alias"); + stdfs::create_directory(sandbox.root / "dir"); + stdfs::create_symlink("../" + temporary, sandbox.root / "dir" / "deep"); + REQUIRE(errorOf([&] { + storage.openRead("alias"); + }) + == fs::StorageErrc::linkRefused); + REQUIRE(errorOf([&] { + storage.openRead("dir/deep"); + }) + == fs::StorageErrc::linkRefused); + writer.commit(); + REQUIRE(readAll(storage.openRead("report.txt")) == "partial"); +} + +SCENARIO("A root under the real /tmp of the superuser is accepted") { + // /tmp is owned by the superuser, writable by all and sticky: an element of the effective user under it is safe. + std::error_code error; + if (!stdfs::is_directory("/tmp", error)) + SKIP("No /tmp on this system"); + struct ::stat status{}; + REQUIRE(::stat("/tmp", &status) == 0); + if (status.st_uid != 0 || (status.st_mode & S_ISVTX) == 0) + SKIP("/tmp is not a sticky directory of the superuser here"); + const auto root = stdfs::path("/tmp") / ("webfront_storage_" + to_string(::getpid())); + stdfs::create_directory(root); + stdfs::permissions(root, stdfs::perms::owner_all, stdfs::perm_options::replace); + fs::NativeStorage storage(root); + writeFile(storage, "file.txt", "x"); + REQUIRE(storage.list("").entries.size() == 1); + stdfs::remove_all(root); +} +#endif + +#ifdef _WIN32 +SCENARIO("Windows opens a root from its drive, its share or its volume") { + using Split = std::pair>; + const auto split = [](const wchar_t* path) { + return fs::detail::windows::splitLocation(path); + }; + REQUIRE(split(LR"(C:\a\b)") + == Split{ + LR"(\\?\C:\)", + {"a", "b"} + }); + REQUIRE(split(LR"(C:\)") == Split{LR"(\\?\C:\)", {}}); + REQUIRE(split(LR"(\\server\share\a)") == Split{LR"(\\?\UNC\server\share\)", {"a"}}); + REQUIRE(split(LR"(\\server\share)") == Split{LR"(\\?\UNC\server\share\)", {}}); + // Extended paths, whose root name MSVC reports as `\\?`. + REQUIRE(split(LR"(\\?\C:\a\b)") + == Split{ + LR"(\\?\C:\)", + {"a", "b"} + }); + REQUIRE(split(LR"(\\?\UNC\server\share\a)") == Split{LR"(\\?\UNC\server\share\)", {"a"}}); + REQUIRE(split(LR"(\\?\Volume{12345678-0000-0000-0000-000000000000}\a)") == Split{LR"(\\?\Volume{12345678-0000-0000-0000-000000000000}\)", {"a"}}); + for (const auto* refused : {LR"(\\server)", LR"(\\?\UNC\server)", LR"(\\?\GLOBALROOT\Device\HarddiskVolume1\a)", LR"(\\?\globalroot\Device\X)", LR"(a\b)"}) + REQUIRE(errorOf([&] { + split(refused); + }) + == fs::StorageErrc::invalidPath); +} + +SCENARIO("Windows finds a directory below a root at the top of its volume") { + using fs::detail::windows::isBelow; + REQUIRE(isBelow(LR"(\Device\HarddiskVolume3\Users)", LR"(\Device\HarddiskVolume3\)")); + REQUIRE(isBelow(LR"(\Device\HarddiskVolume3\)", LR"(\Device\HarddiskVolume3\)")); + REQUIRE(isBelow(LR"(\Device\HarddiskVolume3\a\b)", LR"(\device\harddiskvolume3\A)")); + REQUIRE_FALSE(isBelow(LR"(\Device\HarddiskVolume3\ab)", LR"(\Device\HarddiskVolume3\a)")); + REQUIRE_FALSE(isBelow(LR"(\Device\HarddiskVolume4\a)", LR"(\Device\HarddiskVolume3\)")); + + GIVEN("a root declared at the top of the volume of the temporary directory") { + Sandbox sandbox; + const auto root = stdfs::canonical(sandbox.root).root_path(); + const auto relative = stdfs::canonical(sandbox.root).relative_path().generic_string(); + fs::NativeStorage storage(root); + THEN("its subdirectories are listed and written in, inside the root") { + REQUIRE_FALSE(storage.list("").entries.empty()); + storage.createDirectory(relative + "/dir"); + REQUIRE(stdfs::is_directory(sandbox.root / "dir")); + REQUIRE(storage.list(relative).entries.size() == 1); + writeFile(storage, relative + "/dir/file.txt", "data"); + REQUIRE(readDisk(sandbox.root / "dir" / "file.txt") == "data"); + } + } +} + +SCENARIO("Windows holds the directories of an operation so that nobody moves them") { + Sandbox sandbox; + stdfs::create_directories(sandbox.root / "a" / "b"); + std::error_code rootRename, directoryRename, ancestorRename, baseRename; + + GIVEN("moves attempted while the temporary file is written and before the commit") { + auto hooks = hooksAt([&](fs::StoragePoint point, string_view) { + if (point == fs::StoragePoint::temporaryCreated) { + stdfs::rename(sandbox.root / "a" / "b", sandbox.outside / "b", directoryRename); + // An ancestor of the root is not held: NTFS refuses to rename a directory below which a handle is open. + stdfs::rename(sandbox.base.path(), sandbox.base.path().string() + "-moved", baseRename); + } + if (point == fs::StoragePoint::beforeCommit) + stdfs::rename(sandbox.root / "a", sandbox.outside / "a", ancestorRename); + }); + fs::NativeStorage storage(sandbox.root, {}, hooks); + stdfs::rename(sandbox.root, sandbox.base.path() / "elsewhere", rootRename); + writeFile(storage, "a/b/file.txt", "data"); + THEN("each move fails and the write ends under the root") { + REQUIRE(rootRename); + REQUIRE(directoryRename); + REQUIRE(ancestorRename); + REQUIRE(baseRename); + REQUIRE(readDisk(sandbox.root / "a" / "b" / "file.txt") == "data"); + REQUIRE(sandbox.outsideUntouched()); + } + } +} +#endif diff --git a/test/unit/StorageTests.cpp b/test/unit/StorageTests.cpp new file mode 100644 index 00000000..7d1ace35 --- /dev/null +++ b/test/unit/StorageTests.cpp @@ -0,0 +1,420 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace webfront; + +namespace { + +string readAll(fs::File file) { + string content; + array buffer{}; + while (!file.eof()) { + const auto count = file.read(buffer); + content.append(buffer.data(), count); + if (count == 0) + break; + } + return content; +} + +template +void writeFile(S& storage, string_view path, string_view content, fs::WriteMode mode = fs::WriteMode::createNew) { + auto writer = storage.beginWrite(path, mode); + writer.write(span(content.data(), content.size())); + writer.commit(); +} + +template +fs::StorageErrc errorOf(Operation&& operation) { + try { + operation(); + } catch (const fs::StorageError& error) { + return error.errc(); + } + FAIL("The operation did not fail"); + return fs::StorageErrc::ioError; +} + +template +vector allNames(S& storage, string_view directory, size_t pageSize) { + vector names; + string after; + while (true) { + auto page = storage.list(directory, after, pageSize); + for (auto& entry : page.entries) + names.push_back(entry.name); + if (!page.next) + return names; + after = *page.next; + } +} + +} // namespace + +SCENARIO("SafePath refuses the names Windows reserves, on every platform") { + GIVEN("a reserved device name, whatever its case and extension, or a name Windows would alter") { + auto name = GENERATE(as{}, + "con", + "CON", + "Con.txt", + "nul", + "nul.tar.gz", + "aux", + "prn", + "com1", + "COM9.log", + "lpt1", + "LPT9", + "com\xC2\xB9", + "conin$", + "CONOUT$", + "con .txt", + "a.", + "a ", + "dir/nul/x"); + THEN("safeRelativePath, safePathComponents and isSafeFileName reject it") { + REQUIRE_THROWS_AS(fs::safeRelativePath(name), invalid_argument); + REQUIRE_THROWS_AS(fs::safePathComponents(name), invalid_argument); + REQUIRE_FALSE(fs::isSafeFileName(name)); + } + } + GIVEN("names that only resemble them") { + auto name = GENERATE(as{}, "console", "com10", "lpt0", "com", "nullable.txt", "a.b", "auxiliary", ".hidden"); + THEN("they are accepted") { + REQUIRE(fs::isSafeFileName(name)); + REQUIRE(fs::safePathComponents("dir/" + name) == vector{"dir", name}); + } + } + GIVEN("the empty path") { + THEN("it names the root of a storage") { + REQUIRE(fs::safePathComponents("").empty()); + } + } +} + +SCENARIO("A storage error is a bridge error with a storage code") { + const fs::StorageError error(fs::StorageErrc::rootMoved, "moved"); + const BridgeError& bridge = error; + REQUIRE(bridge.code() == "storage.rootMoved"); + REQUIRE(string(bridge.what()) == "moved"); + REQUIRE(fs::storageErrorCode(fs::StorageErrc::confinementViolated) == "storage.confinementViolated"); + for (auto errc : {fs::StorageErrc::notFound, + fs::StorageErrc::alreadyExists, + fs::StorageErrc::notDirectory, + fs::StorageErrc::isDirectory, + fs::StorageErrc::notEmpty, + fs::StorageErrc::accessDenied, + fs::StorageErrc::invalidPath, + fs::StorageErrc::linkRefused, + fs::StorageErrc::unsafeDirectory, + fs::StorageErrc::rootMoved, + fs::StorageErrc::confinementViolated, + fs::StorageErrc::busy, + fs::StorageErrc::ioError}) + REQUIRE(BridgeError::isValidCode(fs::storageErrorCode(errc))); +} + +SCENARIO("A file reads its bytes through a provider's byte source") { + struct Source : fs::ByteSource { + string bytes{"0123456789"}; + size_t position{}; + size_t read(span buffer) override { + const auto count = min(buffer.size(), bytes.size() - position); + copy_n(bytes.data() + position, count, buffer.data()); + position += count; + return count; + } + [[nodiscard]] optional size() const override { + return bytes.size(); + } + [[nodiscard]] bool seek(uint64_t offset) override { + position = static_cast(min(offset, bytes.size())); + return true; + } + }; + fs::File file{make_unique()}; + REQUIRE(file.knownSize() == 10u); + REQUIRE(readAll(std::move(file)) == "0123456789"); + + fs::File again{make_unique()}; + REQUIRE(again.seek(7)); + array buffer{}; + REQUIRE(again.read(buffer) == 3); + REQUIRE(again.eof()); + REQUIRE(again.seek(2)); + REQUIRE_FALSE(again.eof()); + REQUIRE_THROWS_AS(fs::File{unique_ptr{}}, invalid_argument); +} + +SCENARIO("The simulated storage follows the storage contract") { + fs::MemoryStorage storage; + + GIVEN("files and directories created through it") { + storage.createDirectory("docs"); + writeFile(storage, "docs/a.txt", "alpha"); + writeFile(storage, "b.txt", "beta"); + + THEN("they are listed, inspected and read") { + auto page = storage.list("", {}, 10); + REQUIRE(page.entries.size() == 2); + REQUIRE(page.entries[0].name == "b.txt"); + REQUIRE(page.entries[0].type == fs::EntryType::file); + REQUIRE(page.entries[0].size == 4); + REQUIRE(page.entries[1].name == "docs"); + REQUIRE(page.entries[1].type == fs::EntryType::directory); + REQUIRE_FALSE(page.next); + REQUIRE(storage.status("docs/a.txt").size == 5); + REQUIRE(storage.status("").type == fs::EntryType::directory); + REQUIRE(readAll(storage.openRead("docs/a.txt")) == "alpha"); + } + THEN("a write creating a name that exists is refused, a replacing one replaces it") { + REQUIRE(errorOf([&] { + writeFile(storage, "b.txt", "other"); + }) + == fs::StorageErrc::alreadyExists); + writeFile(storage, "b.txt", "gamma", fs::WriteMode::replace); + REQUIRE(readAll(storage.openRead("b.txt")) == "gamma"); + REQUIRE(errorOf([&] { + writeFile(storage, "docs", "x", fs::WriteMode::replace); + }) + == fs::StorageErrc::isDirectory); + } + THEN("an opened file keeps its bytes when the file is replaced") { + auto file = storage.openRead("b.txt"); + writeFile(storage, "b.txt", "replaced", fs::WriteMode::replace); + REQUIRE(readAll(std::move(file)) == "beta"); + } + THEN("removing and renaming follow the contract") { + REQUIRE(errorOf([&] { + storage.remove("docs"); + }) + == fs::StorageErrc::notEmpty); + REQUIRE(errorOf([&] { + storage.rename("docs", "docs/inner"); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.rename("b.txt", "docs/a.txt"); + }) + == fs::StorageErrc::alreadyExists); + storage.rename("b.txt", "docs/b.txt"); + REQUIRE(errorOf([&] { + storage.status("b.txt"); + }) + == fs::StorageErrc::notFound); + storage.remove("docs/a.txt"); + storage.remove("docs/b.txt"); + storage.remove("docs"); + REQUIRE(storage.list("").entries.empty()); + } + THEN("operations through a file or a missing directory fail with their reason") { + REQUIRE(errorOf([&] { + storage.list("b.txt"); + }) + == fs::StorageErrc::notDirectory); + REQUIRE(errorOf([&] { + storage.openRead("missing/x"); + }) + == fs::StorageErrc::notFound); + REQUIRE(errorOf([&] { + storage.openRead("docs"); + }) + == fs::StorageErrc::isDirectory); + REQUIRE(errorOf([&] { + storage.createDirectory("docs"); + }) + == fs::StorageErrc::alreadyExists); + } + } + + GIVEN("a write in progress") { + auto writer = make_unique(storage.beginWrite("draft.txt", fs::WriteMode::createNew)); + writer->write(span("partial", 7)); + THEN("nothing is visible before the commit") { + REQUIRE(errorOf([&] { + storage.status("draft.txt"); + }) + == fs::StorageErrc::notFound); + } + WHEN("the writer is destroyed without committing, as an interrupted write") { + writer.reset(); + THEN("no partial file exists") { + REQUIRE(storage.list("").entries.empty()); + } + } + WHEN("it commits") { + writer->commit(); + THEN("the whole file appears at once") { + REQUIRE(readAll(storage.openRead("draft.txt")) == "partial"); + REQUIRE_THROWS_AS(writer->commit(), logic_error); + } + } + } + + GIVEN("rights refused by the simulated system") { + storage.createDirectory("locked"); + writeFile(storage, "locked/secret.txt", "s"); + writeFile(storage, "readonly.txt", "r"); + storage.setAccess("locked", false, false); + storage.setAccess("readonly.txt", true, false); + THEN("operations needing them fail with accessDenied") { + REQUIRE(errorOf([&] { + storage.list("locked"); + }) + == fs::StorageErrc::accessDenied); + REQUIRE(errorOf([&] { + storage.openRead("locked/secret.txt"); + }) + == fs::StorageErrc::accessDenied); + REQUIRE(errorOf([&] { + writeFile(storage, "locked/new.txt", "n"); + }) + == fs::StorageErrc::accessDenied); + REQUIRE(errorOf([&] { + writeFile(storage, "readonly.txt", "w", fs::WriteMode::replace); + }) + == fs::StorageErrc::accessDenied); + REQUIRE(readAll(storage.openRead("readonly.txt")) == "r"); + auto info = storage.status("readonly.txt"); + REQUIRE(info.readable); + REQUIRE_FALSE(info.writable); + } + } + + GIVEN("paths that leave the root or that SafePath rejects") { + auto path = GENERATE(as{}, "../x", "/etc/passwd", "a/../b", "a//b", "C:/x", "a\\b", "nul.txt", "a/./b", ".."); + THEN("every operation refuses them with invalidPath") { + REQUIRE(errorOf([&] { + storage.status(path); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.list(path); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.openRead(path); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + (void)storage.beginWrite(path, fs::WriteMode::replace); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.createDirectory(path); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.remove(path); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.rename("x", path); + }) + == fs::StorageErrc::invalidPath); + } + } + GIVEN("names starting with the prefix reserved to temporary files") { + THEN("they are refused, so that a listing never hides a committed file") { + REQUIRE(errorOf([&] { + writeFile(storage, ".wf-tmp-report.txt", "report"); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.createDirectory("dir/.wf-tmp-x"); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.status(".wf-tmp-report.txt"); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(fs::isSafeFileName(".wf-tmp-report.txt")); // SafePath alone accepts it: the reservation is the storage's + for (auto name : {".WF-TMP-report.txt", ".Wf-Tmp-x", ".wF-tMp-"}) + REQUIRE(errorOf([&] { + storage.status(name); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(fs::isTemporaryName(".WF-tmp-a")); + REQUIRE_FALSE(fs::isTemporaryName(".wf-tmp")); + REQUIRE_FALSE(fs::isTemporaryName("x.wf-tmp-a")); + } + } + GIVEN("operations that need an entry") { + THEN("the root is refused") { + REQUIRE(errorOf([&] { + storage.remove(""); + }) + == fs::StorageErrc::invalidPath); + REQUIRE(errorOf([&] { + storage.openRead(""); + }) + == fs::StorageErrc::invalidPath); + } + } +} + +SCENARIO("Listing pages are stable while the directory changes") { + fs::MemoryStorage storage; + for (int index = 10; index < 40; ++index) + writeFile(storage, "f" + to_string(index), "x"); + + GIVEN("a listing read page by page") { + auto first = storage.list("", {}, 10); + REQUIRE(first.entries.size() == 10); + REQUIRE(first.entries.front().name == "f10"); + REQUIRE(first.next == "f19"); + + WHEN("entries are added before and after the cursor and removed after it") { + writeFile(storage, "f05", "x"); + writeFile(storage, "f195", "x"); + writeFile(storage, "f99", "x"); + storage.remove("f30"); + set seen; + for (auto& entry : first.entries) + seen.insert(entry.name); + string after = *first.next; + while (true) { + auto page = storage.list("", after, 10); + for (auto& entry : page.entries) + REQUIRE(seen.insert(entry.name).second); + if (!page.next) + break; + after = *page.next; + } + THEN("every entry present during the whole listing appears exactly once") { + for (int index = 10; index < 40; ++index) + if (index != 30) + REQUIRE(seen.contains("f" + to_string(index))); + REQUIRE(seen.contains("f195")); + REQUIRE(seen.contains("f99")); + REQUIRE_FALSE(seen.contains("f05")); + } + } + } + GIVEN("a page size out of bounds") { + THEN("it is brought back into [1, maxStoragePageSize]") { + REQUIRE(storage.list("", {}, 0).entries.size() == 1); + REQUIRE(storage.list("", {}, 1'000'000).entries.size() == 30); + REQUIRE(allNames(storage, "", 7).size() == 30); + } + } + GIVEN("an invalid cursor") { + THEN("the listing is refused") { + REQUIRE(errorOf([&] { + storage.list("", "../f10"); + }) + == fs::StorageErrc::invalidPath); + } + } +}