Proposal: Pluggable File Backend for the Files Module #404
caseysoftware
started this conversation in
Ideas / Feature Requests
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Status: Draft v3 (proposal) · Milestone: web2project v6.0 · Baseline:
master@40263b7Related issues: #376 (part 1, closed), #394 (Phase 1), #395 (Phase 2), #419 (Phase 3), #420 (Phase 4), #421 (Phase 5). Folder fixes that land before Phase 1: #405, #406, #407, #408, #409, #410, #411. Open questions: #412, #413, #414, #415, #416, #417, #418.
1. Background
The
module:filesissues form a roadmap:#395's original "improve the file list and folders" item is covered by the folder bug issues #405, #406, #407, #408, #409, #410, #411, which are fixed before Phase 1 starts.
2. Current state (
master@40263b7)A partial seam already exists:
w2p_Interfaces_FileSystemdefinesisWritable,move,duplicate,moveTemp,delete,exists,read.w2p_FileSystem_Localis the only implementation, writing toW2P_BASE_DIR/files/{project_id}/{file_real_filename}.CFile::getFileSystem()hard-codesnew w2p_FileSystem_Local();setFileSystem()allows injection (used for tests).CFilemethods (deleteFile,moveFile,duplicateFile,moveTemp,isWritable) are@deprecatedand delegate to the backend.composer.jsonalready pulls in adodb and carbon, so adding a Composer dependency is not a new practice. It declares no PHP version.modules/files/index.php), so that part of Rearchitect the Files Module, part 2: storage abstraction (Phase 1) #394 is done.files/.htaccessuses Apache 2.2 syntax (deny from all);files/temp/.htaccesssaysAllow from all. There are no nginx rules. Nothing in the app links to either folder by URL.Problems with the current interface:
moveTemptakes$_FILESinfo and callsmove_uploaded_file. Remote backends can't implement this meaningfully.$project_id+$filename, assuming a project-based directory tree.readechoes to output instead of returning a stream, which blocks redirects/signed URLs and hurts testing.$AppUI->setMsg(),die(), and mutateCFile.filestable doesn't record which backend holds a file, so migration and mixed backends are impossible.file_folder) are DB-only, and the folder UI is broken (see section 10).3. Goals and non-goals
Goals
localas the zero-config default and fully backward compatible with existing installs.Non-goals (6.0)
W2P_BASE_DIR/files; Phase 1 secures it with server deny rules instead.4. Target backends
files/)Box is deferred: no mainstream Flysystem adapter was found.
5. Approach: build on Flysystem
Flysystem (
league/flysystem) is a filesystem abstraction with a uniform API over many storage services. Its adapters fall into two groups, which matters for risk:Phases 1–4 use official adapters only; Phase 5 depends on community adapters.
5.1 Layering
web2project keeps a thin facade over Flysystem instead of exposing Flysystem types throughout the module. That preserves our freedom to swap the library or hand-write a driver.
New pieces:
w2p_Storage_Driver(interface):getName(),describe()(label + config field schema for the admin UI),build(array $config): FilesystemAdapter. One small class per backend; this is the only place that touches adapter-specific classes.w2p_Storage_Registry: maps backend names to drivers. Core registerslocalandmemory; optional packages register more via a module hook (hook_registerStorageDrivers).w2p_Storage_Service: wraps a FlysystemFilesystem; translates Flysystem exceptions intow2p_Storage_Exceptionsubclasses (NotFound,AccessDenied,Unavailable); exposes optionaldownloadUrl($key, $ttl)when the adapter/config supports temporary URLs; exposeshealthCheck().w2p_Storage_Factory:forBackend(string $name): w2p_Storage_Service, memoized, reads config.What the facade calls underneath:
writeStream,readStream,fileExists,delete,copy,move,listContents(for scan/import),fileSize/mimeType/lastModified(forstat),createDirectory(where relevant), and temporary-URL generation where an adapter supports it.5.2 Mapping to our concerns
$_FILES[...]['tmp_name']and callsput()->writeStream. Nomove_uploaded_fileinside backends.get()returns a stream passed to the response; or redirect todownloadUrl()when enabled.LocalFilesystemAdapterrooted atW2P_BASE_DIR/files(fixed, not configurable), keys{project_id}/{real_filename}: identical to today's layout, so no migration.listContents($prefix, deep: true)iterated lazily.5.3 Handling the gaps Flysystem doesn't close
file_storage_key, never reconstruct it; benchmark listing on realistic folder sizes before shipping Phase 5.healthCheck().upload_max_filesize,post_max_size, andmemory_limit. Direct-to-bucket upload (presigned POST/PUT) is a later phase (Pull direct-to-storage upload forward? #418).w2p_FileSystem_Indexerreads file content. With remote backends it must read via the facade and should index once at upload (or on scan), not on every request (How does the search indexer handle remote files? #414).5.4 Dependencies and PHP baseline
"php": ">=8.2"tocomposer.json. Flysystem 3.x requires PHP ^8.0.2, so it fits; PHPUnit 11 already needs 8.2.league/flysystem3.x and the official local adapter only (small, no cloud SDKs).web2project/storage-s3,-webdav,-sftp,-azure,-gcs,-dropbox,-gdrive,-onedrive) that requires its adapter and registers its driver, so installs that never use S3 never pull the AWS SDK. Packaging is still open (Packaging for optional backends #417).composer requirecommand.6. Data model changes
Additive migration on
files:file_backend'local'file_storage_keyfile_etagBackend configuration (#413):
active_backend(name) plus per-backend config as JSON in system config or a smallstorage_backendstable.env:W2P_S3_SECRET), preferred in production.7. Key strategy
{project_id}/{file_real_filename}(matches today's local layout).CFile::getStorageKey()owns key generation; backends treat keys as opaque. Keys are sanitized (no.., no leading/, length-limited) before any backend call.8. Resolution, upload, and download
Resolution.
CFile::getFileSystem()becomesgetStorage(): reads and deletes resolve byfile_backend; new uploads useactive_backend. After a switch, old files keep working with no forced migration. KeepsetFileSystem()for test injection and keep the deprecated methods as thin shims for one release.Upload (proxied): controller validates (nonce, size, type, permissions) ->
put()with a stream -> store key and metadata ->store(). If the DB write fails afterput, run a compensatingdelete.Download: ACL check, then either redirect to a short-lived signed URL (when the backend supports it and
direct_download=true) or stream throughget()with correctContent-Type/Content-Disposition.On #395's "should w2p be a proxy?": proxy by default (simple ACL enforcement and auditing, works behind firewalls), with opt-in direct download for object-storage backends. Direct upload is deferred (#418).
9. Onboarding / configuration flow
New admin screen System Admin > Files Storage (Phase 2):
describe()schema generates the form.healthCheck()and reports specific failures (auth, bucket missing, not writable, token expired).Then, in Phase 3:
listContents()and reconciles againstfiles:CFile::hook_cron), usingfile_etag/modified time. Off by default.10. Folders
file_folderstays a DB concept in 6.0 (virtual folders), so renaming a folder never moves objects. Scan/import maps backend prefixes (or Drive/OneDrive folders) to virtual folders when creating rows. Mirroring web2project folders into the backend's native hierarchy is a possible later option.The folder UI on
masteris broken in several ways, and Phase 1 builds on it, so these are fixed first:folders_table.php: stubbed record count and always-false checks #408folders_table.phphas a stubbed record count and checks that are always false.11. Migration between backends
CLI/admin task
files:migrate --from=local --to=s3 [--delete-source] [--dry-run](Phase 3): for each row wherefile_backend = from, streamget->put, verify size (and checksum where available), updatefile_backend/file_storage_key, optionally delete the source. State lives in the row, so it is resumable and safe to re-run.12. Security considerations
files/.htaccessandfiles/temp/.htaccess(which currently saysAllow from all) with Apache 2.4 rules (Require all denied, with an<IfModule !mod_authz_core.c>fallback for 2.2), and ships an nginx example that denies/files/. The local driver also confirms resolved paths stay underfiles/.w2p_Controllers_Base::process()(classes/w2p/Controllers/Base.class.phpL53) has an empty body, so forms handled by the base controller, includingdo_folder_aed, accept posts without a valid__nonce.do_file_aed.phpanddo_files_bulk_aed.phpdon't use the controller and check no nonce at all. Upload, move, duplicate and delete change stored data and, from Phase 2, remote storage, so every Files and Folders handler must reject a missing or wrong nonce. The Add File form already sends__nonce; the folder and bulk forms need it added.13. Backward compatibility
localwith an identical on-disk layout; legacy rows work unchanged.w2p_Interfaces_FileSystemandw2p_FileSystem_Localremain for one release as an adapter around the new service; deprecatedCFilemethods keep delegating.14. Testing
CFileand controllers.store(), OAuth refresh path, nonce rejection on every Files/Folders handler,/files/returning 403 on Apache 2.4.15. Phasing
All issues are in the web2project v6.0 milestone.
w2p_Storage_*facade, registry, local + in-memory drivers; new columns; backends stop touching$_FILES/$AppUI; nonce checks; Apache 2.4 + nginx deny ruleshealthCheck; S3-compatible driver; proxied download with optional signed URL16. Open questions
Decided: PHP 8.2 or later is the 6.0 baseline (section 5.4).
storage-extrasbundle, and where they live?All reactions