Files
projectsend/app/Modules/Audit/ActivityLogger.php
ignacionelson 88c182cf3b Preview video, audio and PDF, not only images
v1 could preview four kinds of file in a modal — images, video, audio and
PDF. v2 previewed only images, and not by decision: preview shipped as part
of the image *thumbnail* work (1c68aa1), so "previewable" quietly became a
synonym for "GD can decode it". FileThumbnailController::preview() gated on
ThumbnailGenerator::SUPPORTED_MIME_TYPES, the frontend mirrored the same
four types, and the dialog was a hardcoded <img>.

Rather than widen that list — it drives pathFor(), extensionFor(),
generate() and FileDiskCleanup, and a video reaching getimagesize() is a
500 — this separates the two questions. PreviewKind now answers "may these
bytes be served inline, and what element renders them?", while
ThumbnailGenerator keeps answering the narrower "can this app decode it
itself?", which is what renditions, the cache and the watermark hook
actually depend on. Image delegates to it so the two cannot drift.

The allowlist stays a security boundary: mime_type is sniffed from the
bytes, so text/html and image/svg+xml remain excluded, and PreviewKind is
deliberately narrower than "formats a browser might cope with" — no
quicktime, avi or matroska, because an embedded player for those shows a
black rectangle. Those still download exactly as before.

docs/security-audit-2026-08-05.md finding 1 recorded that adding
application/pdf "should be a conscious decision". This is that decision,
and three things were measured rather than assumed:

- An <iframe sandbox> cannot be used. Chrome refuses to run its PDF viewer
  in a sandboxed frame at all (ERR_BLOCKED_BY_CLIENT, with or without
  allow-same-origin) — the attribute removes the feature, it does not
  harden it.
- nginx's `Content-Security-Policy: sandbox; default-src 'none'` on
  /protected-files/ does work (a <video> frame lands in an opaque origin),
  but Chrome exempts its PDF viewer from it, so it is not what protects
  the PDF case.
- What does is the allowlist plus the browser's own PDF sandbox, where PDF
  JavaScript has no DOM and no cookies.

Range requests were verified end to end: 206 with a correct Content-Range,
a byte-perfect file reassembled from three ranges, and a real browser
seeking to 10s of a 20s clip. nginx drops the upstream Content-Length on
the X-Accel path, so there is no collision.

Two settings, both defaulting on so no installation loses what it has:
clients_can_preview_files and public_listing_preview_enabled. Staff are
never gated. The anonymous side needed a route of its own — there was no
public preview endpoint — with its own throttle bucket, since a bare
throttle: shares one counter across that whole block.

A preview now logs at most one FilePreviewed per viewer per file per five
minutes: a <video> turns one deliberate act into a long tail of Range
requests, and a row each would bury the log.

Also fixes a layout bug the tests could never catch. A portal file row was
flex justify-between with three children — name, comment trigger, download
— so the middle one settled wherever the name happened to end and the
comment icon sat at a different place on every row. The name block now
takes the slack and every action lives in one trailing group, with the
comment trigger in a fixed-width slot so the icons form a column. And
because half the previewable files have no thumbnail to click — a PDF, an
mp3 and an mp4 all render as a generic icon — every row gains an explicit
PreviewAction beside DownloadAction, matching whatever style that theme
gives its download control.
2026-08-21 14:14:23 -03:00

140 lines
5.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Audit;
use App\Models\User;
use App\Modules\Platform\Settings\Setting;
use App\Modules\Platform\Settings\Settings;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
class ActivityLogger
{
public function __construct(
private readonly Settings $settings,
) {}
/**
* Record an action. The actor defaults to the authenticated user;
* pass one explicitly for flows without a session (CLI, setup).
* Actor and subject names are snapshotted so entries survive
* deletions.
*
* @param array<string, mixed> $context
*/
public function log(Action $action, ?User $actor = null, ?Model $subject = null, array $context = []): void
{
$user = $actor ?? Auth::user();
// How the action arrived is resolved here rather than at each call
// site: the API reuses the same controllers and services the UI does
// (FileDownloadController and StoreUploadedFile are both shared
// verbatim), so asking every caller to remember would guarantee
// gaps. Reading the current request's credential is the same kind of
// implicit lookup this class already does for the actor and the IP.
$token = $user?->currentAccessToken();
ActivityLog::query()->create([
'actor_id' => $user?->getKey(),
'actor_name' => $user?->name,
'actor_type' => $user?->type->value,
'origin' => $this->originFor($user, $token),
'api_token_id' => $token?->getKey(),
// Snapshotted beside the id for the same reason actor_name is:
// a revoked token must not leave its entries pointing at nothing.
'api_token_name' => $token?->getAttribute('name'),
'action' => $action,
'subject_type' => $subject?->getMorphClass(),
'subject_id' => $subject?->getKey(),
'subject_name' => $this->subjectName($subject),
'context' => $context === [] ? null : $context,
'ip_address' => $this->shouldRecordIp($action, $user) ? request()->ip() : null,
'created_at' => now(),
]);
}
/**
* Setting::DownloadIpLogging governs download-shaped entries and
* file previews alike — both are ways of viewing a file's contents,
* so previews would otherwise leak IPs through a privacy setting a
* client believes covers "viewing my files." A security audit trail
* (staff actions, logins, …) always records IP regardless, since
* that's an operational concern, not a client-privacy one.
*/
/**
* A token means the API; an actor without one means a browser session.
* No actor at all is either a console command or a request from
* somebody not signed in — and those are not the same thing, so
* something has to tell them apart rather than both landing on System.
* (Scheduled tasks do not reach here at all: they call logSystem(),
* which sets System outright.)
*
* That something is a matched route, not App::runningInConsole():
* the whole test suite runs in console, so the console check would
* classify every HTTP test as System and quietly make this
* untestable — the failure mode being that it looks right in
* production and nothing proves it. A console command and a queued job
* have no route; a request does.
*/
private function originFor(?User $actor, mixed $token): ActivityOrigin
{
if ($token !== null) {
return ActivityOrigin::Api;
}
if ($actor !== null) {
return ActivityOrigin::Ui;
}
return request()->route() === null ? ActivityOrigin::System : ActivityOrigin::Public;
}
private function shouldRecordIp(Action $action, ?User $actor): bool
{
if (! in_array($action, [Action::FileDownloaded, Action::FilePreviewed, Action::ShareLinkDownloaded, Action::PublicFileDownloaded, Action::PublicFilePreviewed], true)) {
return true;
}
return match ($this->settings->get(Setting::DownloadIpLogging)) {
'none' => false,
'anonymous_only' => $actor === null,
default => true,
};
}
/**
* Record an action as the system itself, never attributing the
* authenticated user (compliance jobs, scheduled work).
*
* @param array<string, mixed> $context
*/
public function logSystem(Action $action, array $context = []): void
{
ActivityLog::query()->create([
'actor_id' => null,
'actor_name' => null,
'actor_type' => null,
'origin' => ActivityOrigin::System,
'action' => $action,
'subject_type' => null,
'subject_id' => null,
'subject_name' => null,
'context' => $context === [] ? null : $context,
'created_at' => now(),
]);
}
private function subjectName(?Model $subject): ?string
{
if ($subject === null) {
return null;
}
$name = $subject->getAttribute('name') ?? $subject->getAttribute('title');
return is_string($name) ? $name : null;
}
}