Files
compras/app/Services/PrivateAuditFiles.php
T
nala 060c119ba1
tests / ci (push) Waiting to run
commit compras2 2811
2026-11-28 15:45:52 +02:00

152 lines
6.3 KiB
PHP

<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use LogicException;
use RuntimeException;
/** Only new, individually tracked files in an owned QA workspace; never recursive deletion. */
final class PrivateAuditFiles
{
public readonly string $relative;
private string $root;
/** @var list<string> */
private array $createdFiles = [];
/** @var list<string> */
private array $createdDirectories = [];
public function __construct(User $actor)
{
$disk = Storage::disk('local');
$boundary = realpath(base_path('storage/framework/testing'));
$storageRoot = realpath($disk->path(''));
abort_unless($actor->id === auth()->id() && $actor->tenant_id !== null && $boundary !== false && $storageRoot !== false
&& $this->within($storageRoot, $boundary), 503, 'A exportação requer armazenamento QA isolado.');
$public = realpath(public_path());
abort_if($public !== false && $this->within($storageRoot, $public), 503, 'O pacote de auditoria não pode usar armazenamento público.');
$this->relative = 'audit-exports/'.$actor->tenant_id.'/'.$actor->id.'/'.Str::uuid();
$this->root = $disk->path($this->relative);
$parent = $storageRoot;
foreach (['audit-exports', (string) $actor->tenant_id, (string) $actor->id] as $component) {
$parent .= DIRECTORY_SEPARATOR.$component;
abort_if(is_link($parent), 409, 'Preserve o armazenamento privado sem ligações externas.');
if (! file_exists($parent) && ! mkdir($parent, 0700)) {
throw new RuntimeException('Não foi possível preparar o armazenamento privado.');
}
$resolved = realpath($parent);
abort_unless($resolved !== false && is_dir($resolved) && $this->within($resolved, $storageRoot), 409);
}
abort_if(file_exists($this->root) || is_link($this->root), 409);
if (! mkdir($this->root, 0700)) {
throw new RuntimeException('Não foi possível preparar o directório privado.');
}
$this->createdDirectories[] = $this->root;
}
private function within(string $path, string $boundary): bool
{
$path = str_replace('\\', '/', $path);
$boundary = rtrim(str_replace('\\', '/', $boundary), '/').'/';
return PHP_OS_FAMILY === 'Windows' ? str_starts_with(strtolower($path), strtolower($boundary)) : str_starts_with($path, $boundary);
}
public function path(string $member): string
{
if (! preg_match('/\A[a-z0-9_\/.\-]+\z/D', $member) || str_starts_with($member, '/') || str_contains($member, '..') || str_contains($member, '//')) {
throw new LogicException('Nome interno do pacote inválido.');
}
$directory = $this->root;
$parts = explode('/', $member);
array_pop($parts);
foreach ($parts as $part) {
$directory .= DIRECTORY_SEPARATOR.$part;
if (! file_exists($directory)) {
if (! mkdir($directory, 0700)) {
throw new RuntimeException('Não foi possível preparar um membro do pacote.');
}
$this->createdDirectories[] = $directory;
}
if (is_link($directory) || ! is_dir($directory)) {
throw new LogicException('Preserve o directório privado de preparação.');
}
}
$target = $this->root.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $member);
if (file_exists($target) || is_link($target)) {
throw new LogicException('Não substituir um membro já preparado.');
}
return $target;
}
/** Register only a file that this operation has successfully created. */
public function created(string $path): void
{
$resolved = realpath($path);
$root = realpath($this->root);
if ($resolved === false || $root === false || ! $this->within($resolved, $root) || is_link($path) || ! is_file($resolved)) {
throw new LogicException('Ficheiro fora do pacote privado.');
}
$this->createdFiles[] = $path;
}
/** @param iterable<string>|string $content
* @return array{file:string,path:string,size:int,sha256:string}
*/
public function write(string $member, iterable|string $content): array
{
$path = $this->path($member);
$stream = fopen($path, 'xb');
if ($stream === false) {
throw new RuntimeException('Não foi possível escrever o pacote privado.');
}
try {
$this->created($path);
foreach (is_string($content) ? [$content] : $content as $chunk) {
if (fwrite($stream, $chunk) !== strlen($chunk)) {
throw new RuntimeException('Escrita incompleta do pacote privado.');
}
}
} finally {
fclose($stream);
}
$size = filesize($path);
$sha = hash_file('sha256', $path);
if ($size === false || $sha === false) {
throw new RuntimeException('Não foi possível verificar o membro preparado.');
}
return ['file' => $member, 'path' => $path, 'size' => $size, 'sha256' => $sha];
}
/** @param list<string> $keep Absolute paths created by this instance only. */
public function cleanup(array $keep = []): void
{
$root = realpath($this->root);
if ($root === false || is_link($this->root)) {
return;
}
foreach (array_reverse($this->createdFiles) as $path) {
$resolved = realpath($path);
if (! in_array($path, $keep, true) && $resolved !== false && $this->within($resolved, $root) && ! is_link($path) && is_file($resolved)) {
unlink($path);
}
}
foreach (array_reverse($this->createdDirectories) as $directory) {
$resolved = realpath($directory);
if ($resolved !== false && ($resolved === $root || $this->within($resolved, $root)) && ! is_link($directory) && is_dir($directory)) {
// Unknown/untracked files are deliberately preserved, not removed recursively.
if (count(scandir($directory) ?: []) === 2) {
rmdir($directory);
}
}
}
}
}