Laravel PHP · Inline✓ Human-reviewed

Private temporary workspaces in Laravel PHP

Replace the temporary-directory wrapper with an application-owned workspace lifecycle: exclusive creation, trusted paths, explicit cleanup, and failure tests.

Approved 2026-12-04T12:03:49.748794Z · Submission 29

Private temporary workspaces in Laravel PHP

Scope and provenance

Reference: Spatie's MIT-licensed spatie/temporary-directory 2.4.0, commit 32cbb9645b28839cf4f476708e99a2c70e6802c9. Read src/TemporaryDirectory.php, its exception classes, and tests/TemporaryDirectoryTest.php at that revision. Retain the upstream MIT notice if copying or adapting source. This is newly written guidance, not a relicensing of upstream code.

Target baseline: laravel/framework commit 1b57d01aa866b042a75683bd9ef3517008c632fc; inspect the application's locked version before using its filesystem facade. This guidance has not been exercised in your application. Implement and run the checks below before relying on it.

Replace one bounded behavior: a private workspace for one export, conversion, or job, with fixed application-owned filenames and cleanup before returning. Do not reproduce the fluent API, arbitrary user-selected locations, force(), or its heuristic for guessing whether a path is a file. Keep the package if these are essential and you cannot inventory the callers.

Behavior to preserve deliberately

Upstream creates a random child under a configured/system temporary directory, rejects an existing path unless forced, optionally deletes on destruction, creates parents in path(), and returns a boolean for deletion failures. Its default permission is 0777 before the process umask. deleteDirectory() unlinks symlinks rather than following them. These are source observations, not recommendations to copy every default.

For this slice, deliberately tighten permissions to 0700, use cryptographic randomness, do not overwrite existing directories, and clean up in finally, not just a destructor. Identify any caller depending on the different behavior before removing the dependency.

Application-owned implementation

  1. Search for TemporaryDirectory, deleteWhenDestroyed, force, name, location, empty, and path calls. Record whether the output is read during the request or later by a streamed response/worker. The workspace must outlive its final reader.
  2. Provision an application-owned root outside the public disk, such as storage/app/private/workspaces. It and its ancestors must not be writable by untrusted tenants. Use a local filesystem; object storage is not a substitute for native temp paths.
  3. Put this lifecycle directly in the export/job owner, extracting a reusable workspace class only when several consumers need it. The following is an illustrative integration fragment, not a complete export handler:
use Illuminate\Support\Facades\File;
use RuntimeException;

$root = storage_path('app/private/workspaces'); // provisioned trusted root
$path = $root.DIRECTORY_SEPARATOR.bin2hex(random_bytes(16));
if (! mkdir($path, 0700)) {
    throw new RuntimeException('Cannot create private workspace');
}

try {
    $output = $path.DIRECTORY_SEPARATOR.'result.json';
    // Write, close, and consume the export here; never return this temporary path.
} finally {
    if (! File::deleteDirectory($path)) {
        logger()->warning('Workspace cleanup failed', ['workspace' => basename($path)]);
    }
}
  1. Check every write/close/read operation; PHP filesystem functions may return false. Handle creation failure without deleting a directory this invocation did not create. Decide how cleanup failure is reported without hiding the original export exception.
  2. Use only fixed filenames or a strict component allowlist. ../, absolute paths, drive prefixes, separators, NULs, and archive symlink entries must not become paths. Joining strings or checking a textual prefix is not a containment boundary. Do not extract untrusted archives in this slice.
  3. For asynchronous consumers, move final output to durable private storage and hand off that identifier, or let the worker own the workspace. For streams, keep cleanup inside the streaming callback after the last read. Hard kills bypass finally; if leftovers matter, add a bounded age-based janitor only for this dedicated root, never a general filesystem sweep.

Verification before removing the package

Add feature tests around the real export/job, not only a helper:

  • Two simultaneous operations get different directories and outputs; neither can see the other's files.
  • Success returns the final bytes/durable artifact and leaves no owned workspace. A deliberate exception after a write also cleans up.
  • A read-only/missing root fails visibly and does not touch another directory. A preexisting path is not overwritten.
  • A symlink created inside the workspace to a separate sentinel directory does not cause cleanup to delete the sentinel. Confirm this on the deployment filesystem and PHP version.
  • User filenames such as ../sentinel, /etc/passwd, and a/b are rejected before any filesystem mutation.
  • A streamed download remains readable until completion; a queued job does not receive an already-deleted path.

Run the focused application's php artisan test --filter=Workspace, then its export/job suite with the real local filesystem. Do not use Storage::fake() as proof of native deletion or symlink behavior. Compare the previous package-backed path with the replacement on the same fixtures. Only then remove direct package usage and run composer why spatie/temporary-directory; leave transitive dependencies alone.