Skip to content

Commit

Permalink
Cleanup uploaded files for PSR-15 handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
mnapoli committed Jan 29, 2024
1 parent d789c22 commit c77d9f5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/Event/Http/Psr15Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public function __construct(RequestHandlerInterface $psr15Handler)

public function handleRequest(HttpRequestEvent $event, Context $context): HttpResponse
{
Psr7Bridge::cleanupUploadedFiles();

$request = Psr7Bridge::convertRequest($event, $context);

$response = $this->psr15Handler->handle($request);
Expand Down
19 changes: 18 additions & 1 deletion src/Event/Http/Psr7Bridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
*/
final class Psr7Bridge
{
private const UPLOADED_FILES_PREFIX = 'bref_upload_';

/**
* Create a PSR-7 server request from an AWS Lambda HTTP event.
*/
Expand Down Expand Up @@ -106,7 +108,7 @@ private static function parseBodyAndUploadedFiles(HttpRequestEvent $event): arra
$parsedBody = [];
foreach ($document->getParts() as $part) {
if ($part->isFile()) {
$tmpPath = tempnam(sys_get_temp_dir(), 'bref_upload_');
$tmpPath = tempnam(sys_get_temp_dir(), self::UPLOADED_FILES_PREFIX);
if ($tmpPath === false) {
throw new RuntimeException('Unable to create a temporary directory');
}
Expand Down Expand Up @@ -166,4 +168,19 @@ private static function parseKeyAndInsertValueInArray(array &$array, string $key

$pointer = $value;
}

/**
* Cleanup previously uploaded files.
*/
public static function cleanupUploadedFiles(): void
{
$tmpFiles = glob(sys_get_temp_dir() . '/' . self::UPLOADED_FILES_PREFIX . '*');

This comment has been minimized.

Copy link
@smaury

smaury Jan 29, 2024

If you're not planning to delete files at the end of the current request - where you still have the precise filenames - but rather at the beginning of the next one, I recommend using a stricter RegEx for glob to minimize the risk of deleting unintended files.

Since tempnam generates files with a 6-character long alphanumeric suffix, you can create a more precise glob pattern like this:

$tmpFiles = glob(sys_get_temp_dir() . '/' . self::UPLOADED_FILES_PREFIX . '[A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9]');

I know it's ugly but AFAIK you can't do [A-Za-z0-9]{6} in glob.

This comment has been minimized.

Copy link
@mnapoli

mnapoli Jan 31, 2024

Author Member

Thank you, I updated the PR 👍

if ($tmpFiles !== false) {
foreach ($tmpFiles as $file) {
if(is_file($file)) {

Check failure on line 180 in src/Event/Http/Psr7Bridge.php

View workflow job for this annotation

GitHub Actions / PHP CodeSniffer

Expected 1 space after IF keyword; 0 found
unlink($file);
}
}
}
}
}

0 comments on commit c77d9f5

Please # to comment.