Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.29% covered (success)
94.29%
66 / 70
66.67% covered (warning)
66.67%
4 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
Ingest
94.29% covered (success)
94.29%
66 / 70
66.67% covered (warning)
66.67%
4 / 6
24.11
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 ingest
92.50% covered (success)
92.50%
37 / 40
0.00% covered (danger)
0.00%
0 / 1
7.02
 validate
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
11.02
 imageDimensions
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 safeFilename
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 sanitizeSvgMarkup
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Assets;
6
7use Celema\Quma\Database;
8use Cosray\Actor;
9use Cosray\Config;
10use Cosray\Exception\IngestError;
11use Cosray\Exception\RuntimeException;
12use Cosray\Storage\Storage;
13use Cosray\Uid;
14use Cosray\Util\Svg;
15use finfo;
16use Throwable;
17
18/**
19 * Catalogs raw bytes as an asset: validation, SVG sanitising, hash dedup,
20 * the storage write, and the catalog row. The upload controller and
21 * importers share this one pipeline.
22 */
23final class Ingest
24{
25    private readonly Storage $storage;
26
27    public function __construct(
28        private readonly Config $config,
29        private readonly Database $db,
30    ) {
31        $this->storage = new Storage($config);
32    }
33
34    /** @param array<string, mixed> $meta */
35    public function ingest(
36        string $contents,
37        string $filename,
38        string $mediatype,
39        ?Actor $actor = null,
40        array $meta = [],
41    ): IngestResult {
42        $filename = self::safeFilename($filename);
43        $mime = $this->validate($contents, $filename, $mediatype);
44
45        // SVGs are served from the site origin, so a stored `<script>` or
46        // `onload` would run there. Clean the markup before it lands in the
47        // pool; hash and byte count are taken from the sanitized bytes.
48        if ($mime === 'image/svg+xml' || strtolower(pathinfo($filename, PATHINFO_EXTENSION)) === 'svg') {
49            $clean = self::sanitizeSvgMarkup($contents);
50
51            if ($clean === null) {
52                throw IngestError::unsafeSvg();
53            }
54
55            $contents = $clean;
56        }
57
58        $hash = hash('sha256', $contents);
59        $existing = $this->db
60            ->assets
61            ->byHash([
62                'hash' => $hash,
63                'disk' => $this->storage->disk,
64            ])
65            ->first();
66
67        if ($existing) {
68            return new IngestResult($existing, created: false);
69        }
70
71        [$width, $height] = $this->imageDimensions($mediatype, $contents);
72        $uidConfig = $this->config->uid;
73        $uid = new Uid($uidConfig->alphabet, $uidConfig->length)->generate();
74        $key = Storage::key($uid, $filename);
75        $this->storage->write($key, $contents);
76
77        $row = [
78            'uid' => $uid,
79            'disk' => $this->storage->disk,
80            'key' => $key,
81            'filename' => $filename,
82            'mime' => $mime,
83            'bytes' => strlen($contents),
84            'width' => $width,
85            'height' => $height,
86            'hash' => $hash,
87            'meta' => $meta === [] ? '{}' : json_encode($meta),
88            'creator' => ($actor ?? Actor::system())->id,
89        ];
90
91        try {
92            $this->db->assets->create($row)->one();
93        } catch (Throwable $e) {
94            $this->storage->delete($key);
95
96            throw $e;
97        }
98
99        return new IngestResult($row, created: true);
100    }
101
102    /** @return string the detected mime type */
103    private function validate(string $contents, string $filename, string $mediatype): string
104    {
105        $upload = $this->config->upload;
106        $mimeTypes = match ($mediatype) {
107            'file' => $upload->file,
108            'image' => $upload->image,
109            'video' => $upload->video,
110            default => throw new RuntimeException('Media type not supported: ' . $mediatype),
111        };
112
113        if ($filename === '') {
114            throw IngestError::unknownFilename();
115        }
116
117        if (strlen($contents) > $upload->maxSize) {
118            throw IngestError::tooLarge(strlen($contents), $upload->maxSize);
119        }
120
121        $mime = (string) new finfo(FILEINFO_MIME_TYPE)->buffer($contents);
122        $allowedExtensions = $mimeTypes[$mime] ?? null;
123
124        if (!$allowedExtensions) {
125            throw IngestError::disallowedType($mime);
126        }
127
128        $ext = pathinfo($filename, PATHINFO_EXTENSION) ?: null;
129
130        if (!$ext || !in_array(strtolower($ext), $allowedExtensions, true)) {
131            throw IngestError::wrongExtension($ext, $allowedExtensions, $mime);
132        }
133
134        return $mime;
135    }
136
137    /** @return array{0: ?int, 1: ?int} */
138    private function imageDimensions(string $mediatype, string $contents): array
139    {
140        if ($mediatype !== 'image') {
141            return [null, null];
142        }
143
144        // getimagesizefromstring warns on undecodable input (e.g. SVG bytes);
145        // unreadable dimensions are an expected outcome here, not an error.
146        set_error_handler(static fn(): bool => true);
147
148        try {
149            $info = getimagesizefromstring($contents);
150        } finally {
151            restore_error_handler();
152        }
153
154        return $info === false ? [null, null] : [$info[0], $info[1]];
155    }
156
157    /**
158     * Reduce a client-supplied upload name to a safe on-disk basename:
159     * strip every directory component (and any `../`), drop control
160     * characters, and trim leading/trailing dots and spaces.
161     */
162    public static function safeFilename(string $name): string
163    {
164        $name = basename($name);
165        $name = preg_replace('/[\x00-\x1F\x7F]/', '', $name) ?? '';
166
167        return trim($name, ' .');
168    }
169
170    /**
171     * Rebuild SVG markup from an allowlist: no scripts, event handlers or
172     * remote references. Returns null when the markup is rejected: empty,
173     * malformed, not an SVG document, or declaring its own DTD entities.
174     */
175    public static function sanitizeSvgMarkup(string $svg): ?string
176    {
177        return Svg::sanitize($svg);
178    }
179}