From 2f4fd8a9cd053eba9ac80207e26de0c42004b5d5 Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Fri, 20 Nov 2026 19:04:19 +0300 Subject: [PATCH] feat(media): prepare Engine 9 major migration --- .github/workflows/php.yml | 31 +-- AGENTS.md | 6 +- CHANGELOG.md | 19 ++ CONTRIBUTING.md | 39 ++-- CONTRIBUTING_ru.md | 38 ++-- README.md | 91 +++++++++ README.ru.md | 91 +++++++++ SECURITY.md | 21 ++ SECURITY.ru.md | 21 ++ composer.json | 23 ++- src/Config/app.php | 12 +- src/ImageProcessing.php | 122 +++++++++++- src/Install.php | 5 +- src/RateLimiter.php | 12 +- src/RemoteImageDownloader.php | 5 + src/Uploader.php | 48 +++-- src/UriDispatcher.php | 10 +- src/Util.php | 45 +++-- src/plugin/media/app/controller/Image.php | 5 + src/plugin/media/app/controller/Index.php | 23 ++- .../media/app/controller/Processing.php | 16 +- src/plugin/media/app/controller/Project.php | 51 ++++- src/plugin/media/app/controller/Upload.php | 65 +++--- tests/image_paths_and_limits.php | 83 ++++++++ tests/image_processing_limits.php | 121 ++++++++++++ tests/processing_response_type.php | 54 +++++ tests/project_registration.php | 145 ++++++++++++++ tests/remote_image_downloader.php | 5 + tests/upload_request_contract.php | 187 ++++++++++++++++++ tests/uploader_file_validation.php | 53 +++++ 30 files changed, 1275 insertions(+), 172 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100644 README.ru.md create mode 100644 SECURITY.md create mode 100644 SECURITY.ru.md create mode 100644 tests/image_paths_and_limits.php create mode 100644 tests/image_processing_limits.php create mode 100644 tests/processing_response_type.php create mode 100644 tests/project_registration.php create mode 100644 tests/upload_request_contract.php create mode 100644 tests/uploader_file_validation.php diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index 09e86a8..f938864 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -2,7 +2,6 @@ name: PHP package checks on: push: - branches: [main, master] pull_request: branches: [main, master] workflow_dispatch: @@ -12,12 +11,14 @@ permissions: jobs: verify: - name: PHP ${{ matrix.php }} + name: PHP ${{ matrix.php }} / ${{ matrix.dependencies }} dependencies runs-on: ubuntu-24.04 + timeout-minutes: 15 strategy: fail-fast: false matrix: php: ['8.1', '8.5'] + dependencies: ['lowest', 'latest'] steps: - name: Checkout uses: actions/checkout@v7 @@ -32,19 +33,21 @@ jobs: coverage: none - name: Validate Composer manifest and lock - run: composer validate --no-check-publish --no-interaction - - - name: Install locked dependencies - run: composer install --prefer-dist --no-interaction --no-progress --no-scripts - - - name: Check PHP syntax - run: find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l + run: composer validate --strict --no-check-publish --no-interaction - - name: Run declared tests - shell: bash + - name: Install dependencies run: | - if php -r '$composer = json_decode(file_get_contents("composer.json"), true); exit(isset($composer["scripts"]["test"]) ? 0 : 1);'; then - composer test --no-interaction + if [ "${{ matrix.dependencies }}" = "lowest" ]; then + composer update --prefer-lowest --prefer-stable --prefer-dist --no-interaction --no-progress --no-scripts else - echo 'No test script is declared for this package.' + composer update --prefer-dist --no-interaction --no-progress --no-scripts fi + + - name: Audit dependencies + run: composer audit --locked --no-interaction + + - name: Check PHP syntax + run: composer lint + + - name: Run tests + run: composer test --no-interaction diff --git a/AGENTS.md b/AGENTS.md index d0a38b2..94bf4a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,11 +26,11 @@ Опорные файлы: `CONTRIBUTING.md`. -`composer.json`: triangle/media; runtime "^8.1"; triangle/engine. +`composer.json`: triangle/media; runtime "^8.1"; `triangle/engine:^9.0`. -Именованных test/lint/build-скриптов в проверенных JSON-манифестах нет. Перед запуском выбери существующую команду из CI, конфигурации тестов или Makefile; не выдавай предполагаемую команду за проверенную. +Проверки: `composer run lint`, `composer run test`, `composer run check`, `composer audit --locked`. Интеграционный запуск зависит от PHP extensions и сервисов Triangle Engine; перед утверждениями о runtime проверяй фактическое окружение. -Команды выше найдены в манифестах, а не проверены запуском. Перед выполнением прочитай их реализацию, нужные переменные и внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test. +Перед выполнением проверок читай их реализацию и нужные внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test. ### Ограничения реализации diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..f07a442 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,19 @@ +# Changelog + +Notable changes are documented here. This project follows Semantic Versioning. + +## 2.0.0 - Unreleased + +### Changed + +- Require Triangle Engine 9 and its Server 7 runtime. +- Expand CI to PHP 8.1 and 8.5 with lowest and latest dependency sets, Composer audit, lint, and executable tests. +- Add English and Russian installation, configuration, endpoint, and security guidance. +- Standardize PHP copyright and SPDX headers to AGPL-3.0-or-later. + +### Fixed + +- Enforce the project-registration setting and validate registration requests. +- Reject image identifiers that could escape the configured image directory. +- Enforce frame and pixel limits when processing previously stored images. +- Return transformed image bytes with the configured image MIME type. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3c7f67f..8538c58 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,34 +1,25 @@ -# Contributing to the Project -[Документ на русском языке](CONTRIBUTING_ru.md) - -We welcome you to our project and thank you for your interest in our code! - -## Getting Started +# Contributing to Triangle Media -Before you begin, please familiarize yourself with our rules and guidelines: - -- Code of Conduct -- Code Style Guide +[Документ на русском языке](CONTRIBUTING_ru.md) -## How to Contribute +Thank you for helping improve the Triangle Media plugin. -There are many ways you can contribute to the project: +Before opening a change, read the [Code of Conduct](CODE_OF_CONDUCT.md), [Security policy](SECURITY.md), and [project documentation](README.md). -- Suggest improvements or new features -- Submit bug fixes -- Improve documentation +## Local checks -## Creating a Pull Request +Use PHP 8.1 or newer with the required `curl`, `fileinfo`, and `imagick` extensions. Run: -1. Fork the repository. -2. Create a new branch. -3. Make your changes. -4. Submit a pull request. +```sh +composer validate --strict --no-check-publish --no-interaction +composer run check --no-interaction +composer audit --locked --no-interaction +``` -Please ensure that your code adheres to our code style guide and all tests pass. +Changes to image upload, URL fetching, storage paths, or filters should include a focused regression test. Do not add credentials, production data, or generated image files to a pull request. -## Contact +## Pull requests -If you have any questions, feel free to reach out to us through the GitHub issues system. +Keep the change focused, describe any compatibility impact, and include the commands and results of the checks you ran. GitHub Actions tests PHP 8.1 and 8.5 with lowest and latest allowed dependencies. -Thank you for your contribution! +For general questions, use GitHub Issues. Report suspected vulnerabilities privately using GitHub's **Report a vulnerability** feature; do not publish exploit details in an issue. diff --git a/CONTRIBUTING_ru.md b/CONTRIBUTING_ru.md index f504204..fe57c28 100644 --- a/CONTRIBUTING_ru.md +++ b/CONTRIBUTING_ru.md @@ -1,33 +1,25 @@ -# Вклад в проект +# Вклад в Triangle Media -Мы рады приветствовать вас в нашем проекте и благодарим за ваш интерес к нашему коду! +[English version](CONTRIBUTING.md) -## Как начать +Спасибо, что помогаете улучшать плагин Triangle Media. -Перед тем как начать, пожалуйста, ознакомьтесь с нашими правилами и руководствами: +Перед отправкой изменений прочитайте [Кодекс поведения](CODE_OF_CONDUCT_ru.md), [политику безопасности](SECURITY.ru.md) и [документацию проекта](README.ru.md). -- Кодекс поведения -- Руководство по стилю кода +## Локальные проверки -## Как внести свой вклад +Нужны PHP 8.1 или новее и расширения `curl`, `fileinfo`, `imagick`. Выполните: -Есть много способов внести свой вклад в проект: +```sh +composer validate --strict --no-check-publish --no-interaction +composer run check --no-interaction +composer audit --locked --no-interaction +``` -- Предложить улучшения или новые функции -- Отправить исправления ошибок -- Улучшить документацию +Изменения загрузки, получения изображений по URL, путей хранения и фильтров должны сопровождаться регрессионным тестом. Не добавляйте в pull request учётные данные, production-данные и сгенерированные изображения. -## Создание запроса на слияние (Pull Request) +## Pull request -1. Сделайте форк репозитория. -2. Создайте новую ветку. -3. Внесите свои изменения. -4. Отправьте запрос на слияние. +Не расширяйте scope без необходимости, описывайте влияние на совместимость и указывайте команды с результатами проверок. GitHub Actions запускает PHP 8.1 и 8.5 с минимальными и последними допустимыми зависимостями. -Пожалуйста, убедитесь, что ваш код соответствует нашему руководству по стилю кода и все тесты проходят. - -## Связь - -Если у вас есть вопросы, не стесняйтесь обращаться к нам через систему вопросов GitHub. - -Спасибо за ваш вклад! +Общие вопросы задавайте в GitHub Issues. О возможной уязвимости сообщайте приватно через функцию GitHub **Report a vulnerability**; не публикуйте подробности эксплуатации в issue. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4ededc3 --- /dev/null +++ b/README.md @@ -0,0 +1,91 @@ +# Triangle Media + +Triangle Media is an image plugin for applications built with Triangle Engine. It accepts image uploads and remote image URLs, validates and converts accepted images to PNG, stores image metadata through the application's configured database connection, and can serve resized or transformed image responses. + +## Compatibility + +- PHP 8.1 or newer +- Triangle Engine 9 +- PHP extensions: `curl`, `fileinfo`, and `imagick` +- A writable image directory and a database connection configured by the host application + +The latest published package tag is `v1.1.0`, which requires Triangle Engine `^8.1`. This branch prepares the next major version for Triangle Engine 9 and its Server 7 runtime; that migration is not a published stable release yet. The next major version will not support the Engine 8 dependency line. + +## Installation + +For the currently published Engine 8 package: + +```sh +composer require triangle/media:^1.1 +``` + +After the Engine 9 compatible `2.0.0` release is published, install it with `composer require triangle/media:^2.0`. + +Triangle Engine discovers the plugin controllers through Composer autoloading. The plugin's `Triangle\Media\Install::install()` method copies missing default settings from `src/Config` into `config/plugin/triangle/media`; it preserves existing application settings. The host application's plugin lifecycle should call it when installing the package. + +The plugin does not include view templates. Install `triangle/view` to use the bundled view routes, then provide `index`, `form`, and `image` templates in the host application. The host may instead replace those controllers with its own presentation layer. + +## Default controller paths + +With Triangle Engine's default `app.plugin_uri` setting, the controllers are available at these paths: + +| Path | Method | Behavior | +| --- | --- | --- | +| `/app/media` | `GET` | Renders the `index` view and sets a `token` cookie when the request includes a token. | +| `/app/media/project` | `GET`, `POST` | Returns `403` while project registration is disabled. When enabled, `GET` renders `form` and `POST` validates the fields, stores the project, and returns its token. | +| `/app/media/upload` | `POST` | Accepts an uploaded image or a remote image URL after checking the project token. | +| `/app/media/image/{image-id}` | `GET` | Renders the `image` view for an existing image. | +| `/app/media/processing/{image-id}/{filters...}` | `GET` | Applies the configured image filters and returns the generated image bytes. | + +The prefix changes if the host application overrides `app.plugin_uri`. Configure the router, access control, and rate limits at the application or reverse-proxy boundary as appropriate for the deployment. + +## Configuration + +The defaults are installed at `config/plugin/triangle/media/app.php`: + +| Setting | Default | Purpose | +| --- | --- | --- | +| `enable` | `true` | Enables plugin configuration. | +| `project_registration` | `false` | Allows project registration through the project controller when enabled. | +| `image_uri` | `https://example.ru/media/` | Public base URI returned for uploaded images; replace it with the deployed media URL. | +| `image_path` | `public_path() . '/media/upload/'` | Writable storage directory for converted images. | +| `max_file_size` | 15 MiB | Maximum accepted source-file size. | +| `max_image_pixels` | 40,000,000 | Maximum total decoded pixels across frames. | +| `max_image_frames` | 50 | Maximum number of frames in an input image. | +| `max_image_memory` | 256 MiB | ImageMagick memory and map resource limit. | +| `max_image_disk` | 512 MiB | ImageMagick disk resource limit. | +| `max_image_time` | 10 seconds | ImageMagick processing time limit. | +| `rate_limiter.enable` | `false` | Enables the configured request rate limiter. | +| `rate_limiter.quota` / `cycle` | `3` / `60` | Allowed requests per cycle when rate limiting is enabled. | + +The accepted source MIME types, target PNG format, database collection names, and transformation patterns are also configurable in this file. Treat configuration values as application policy: verify the public URI, storage permissions, and resource limits before exposing upload routes. + +Installation preserves an existing application configuration. After upgrading an older installation, check `project_registration` explicitly and set it to `false` if anonymous project creation is not intended. + +The host application must provide compatible `db()` and `storage()` adapters. The database adapter must support `insert($table, $record)` and `where($field, $value)->getOne($table)`. The storage adapter must support `get($key)`, `set($key, $value, $ttl)` and `increment($key)`. Triangle Engine supplies `config()`, request IP resolution, and response helpers. `triangle/view` supplies `view()`; the host application supplies the `index`, `form`, and `image` templates. The package does not bundle database or storage adapters. + +## Upload behavior + +The upload controller accepts either a multipart file under the `file` field or a remote URL in the `link` field. Both paths validate the source MIME type and size. The uploader converts successful images to PNG, stores the image record through the Engine database helper, and returns the image identifier, URL, MIME type, dimensions, dominant color, and output size. + +Remote image downloads use HTTP or HTTPS on standard ports, reject credentials and non-public IP addresses, pin DNS resolution to a validated address, do not follow redirects, and enforce a download byte limit and timeout. These controls reduce server-side request forgery risk; they do not replace outbound network policy at the host level. + +The processing controller supports the configured `crop`, `resize`, `pixelize`, and `cover` filters. Results are cached through the host application's storage service. + +## Development checks + +```sh +composer validate --strict --no-check-publish --no-interaction +composer run check --no-interaction +composer audit --locked --no-interaction +``` + +The URL security test rejects local, reserved, and non-standard URL targets. Image decoding and conversion require the `imagick` extension; the repository's local test does not replace an end-to-end upload test against the host application's database, router, storage, and view configuration. + +## License + +AGPL-3.0-or-later. See [LICENSE](LICENSE). + +## Documentation + +The current project handbook is available at [server.localzet.com/projects/media](https://server.localzet.com/projects/media), with [English guides](https://server.localzet.com/projects/media/en). diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000..6774b9f --- /dev/null +++ b/README.ru.md @@ -0,0 +1,91 @@ +# Triangle Media + +Triangle Media — плагин для изображений в приложениях на Triangle Engine. Он принимает загружаемые файлы и ссылки на изображения, проверяет и преобразует допустимые файлы в PNG, сохраняет метаданные через подключение к базе данных приложения и может отдавать изображения с изменениями размера и другими фильтрами. + +## Совместимость + +- PHP 8.1 или новее +- Triangle Engine 9 +- Расширения PHP: `curl`, `fileinfo` и `imagick` +- Доступный для записи каталог изображений и настроенная в приложении база данных + +Последний опубликованный тег пакета — `v1.1.0`, он требует Triangle Engine `^8.1`. Эта ветка подготавливает следующую основную версию для Triangle Engine 9 и Server 7; миграция ещё не опубликована как стабильный релиз. Следующая основная версия не будет совместима с Engine 8. + +## Установка + +Для опубликованной версии с Engine 8: + +```sh +composer require triangle/media:^1.1 +``` + +После публикации совместимого с Engine 9 релиза `2.0.0` устанавливайте его командой `composer require triangle/media:^2.0`. + +Triangle Engine обнаруживает контроллеры плагина через Composer autoload. Метод `Triangle\Media\Install::install()` копирует отсутствующие настройки по умолчанию из `src/Config` в `config/plugin/triangle/media`, сохраняя уже существующие настройки приложения. При установке пакета его должен вызвать механизм установки плагинов приложения. + +В пакете нет шаблонов представлений. Чтобы использовать встроенные маршруты с представлениями, установите `triangle/view` и добавьте в приложение шаблоны `index`, `form` и `image`. Вместо этого приложение может заменить контроллеры собственным слоем представления. + +## Пути контроллеров по умолчанию + +При стандартной настройке Triangle Engine `app.plugin_uri` контроллеры доступны по следующим путям: + +| Путь | Метод | Назначение | +| --- | --- | --- | +| `/app/media` | `GET` | Отображает `index`; устанавливает cookie `token`, если запрос содержит токен. | +| `/app/media/project` | `GET`, `POST` | Возвращает `403`, пока регистрация проектов выключена. Если она включена, `GET` отображает `form`, а `POST` проверяет поля, сохраняет проект и возвращает его токен. | +| `/app/media/upload` | `POST` | Принимает загруженный файл или ссылку после проверки токена проекта. | +| `/app/media/image/{image-id}` | `GET` | Отображает `image` для существующего изображения. | +| `/app/media/processing/{image-id}/{filters...}` | `GET` | Применяет заданные фильтры и возвращает байты изображения. | + +Префикс меняется, если приложение переопределяет `app.plugin_uri`. Настройте маршрутизацию, контроль доступа и ограничения частоты запросов на уровне приложения или обратного прокси в соответствии с условиями эксплуатации. + +## Настройки + +Параметры по умолчанию устанавливаются в `config/plugin/triangle/media/app.php`: + +| Параметр | Значение по умолчанию | Назначение | +| --- | --- | --- | +| `enable` | `true` | Включает конфигурацию плагина. | +| `project_registration` | `false` | Разрешает регистрацию проектов через контроллер, если настройка включена. | +| `image_uri` | `https://example.ru/media/` | Публичный базовый адрес изображений; замените его на адрес вашего сервиса. | +| `image_path` | `public_path() . '/media/upload/'` | Каталог для преобразованных изображений; приложение должно разрешать запись. | +| `max_file_size` | 15 МиБ | Максимальный размер исходного файла. | +| `max_image_pixels` | 40 000 000 | Максимальное суммарное число пикселей во всех кадрах. | +| `max_image_frames` | 50 | Максимальное число кадров во входном изображении. | +| `max_image_memory` | 256 МиБ | Лимит памяти ImageMagick и его map-ресурса. | +| `max_image_disk` | 512 МиБ | Лимит дискового ресурса ImageMagick. | +| `max_image_time` | 10 секунд | Ограничение времени обработки ImageMagick. | +| `rate_limiter.enable` | `false` | Включает настроенный ограничитель частоты запросов. | +| `rate_limiter.quota` / `cycle` | `3` / `60` | Допустимое число запросов за период при включённом ограничителе. | + +В этом файле также настраиваются допустимые MIME-типы, формат PNG, имена таблиц/коллекций и шаблоны преобразований. Считайте настройки частью политики приложения: перед открытием загрузки проверьте публичный URL, права каталога и ограничения ресурсов. + +Установка сохраняет существующую конфигурацию приложения. После обновления старой установки отдельно проверьте `project_registration` и установите `false`, если анонимная регистрация проектов не нужна. + +Приложение должно предоставить совместимые адаптеры `db()` и `storage()`. Адаптер базы данных должен поддерживать `insert($table, $record)` и `where($field, $value)->getOne($table)`. Адаптер хранения должен поддерживать `get($key)`, `set($key, $value, $ttl)` и `increment($key)`. Triangle Engine предоставляет `config()`, разрешение IP запроса и функции ответа. Функцию `view()` предоставляет `triangle/view`; шаблоны `index`, `form` и `image` добавляет приложение. Пакет не включает адаптеры базы данных или хранения. + +## Загрузка изображений + +Контроллер загрузки принимает multipart-файл в поле `file` или ссылку в поле `link`. В обоих случаях проверяются MIME-тип и размер. Загрузчик преобразует изображение в PNG, сохраняет запись через помощник базы данных Engine и возвращает идентификатор, URL, MIME-тип, размеры, основной цвет и размер результата. + +Для загрузки по ссылке разрешены HTTP и HTTPS на стандартных портах. Плагин запрещает URL с учётными данными и адреса из непубличных диапазонов, закрепляет проверенный DNS-адрес на время запроса, не переходит по редиректам и ограничивает объём данных и время загрузки. Эти меры уменьшают риск SSRF, но не заменяют сетевые ограничения исходящих подключений на уровне хоста. + +Контроллер обработки поддерживает настроенные фильтры `crop`, `resize`, `pixelize` и `cover`. Результаты кэшируются через сервис хранения приложения. + +## Проверки разработки + +```sh +composer validate --strict --no-check-publish --no-interaction +composer run check --no-interaction +composer audit --locked --no-interaction +``` + +Тест безопасности URL отклоняет локальные, зарезервированные и нестандартные адреса. Декодирование и преобразование изображений требуют расширения `imagick`; локальный тест не заменяет интеграционную проверку загрузки с базой данных, маршрутизатором, кэшем и шаблонами приложения. + +## Лицензия + +AGPL-3.0-or-later. См. [LICENSE](LICENSE). + +## Документация + +Справочник проекта: [server.localzet.com/projects/media](https://server.localzet.com/projects/media). [Англоязычные руководства](https://server.localzet.com/projects/media/en). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..08b84bc --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security policy + +## Supported versions + +The latest published release is `v1.1.0`, which targets Triangle Engine `^8.1`. This branch prepares `2.0.0` for Engine 9, but that version has not been released. Report vulnerabilities with the exact package version and Engine version; the release and support status of `2.0.0` will be stated when it is published. + +## Report a vulnerability + +Please report suspected vulnerabilities privately through GitHub's **Report a vulnerability** feature for this repository. Include the affected version, the relevant endpoint or configuration, and a minimal reproduction. Do not include real project tokens, uploaded private images, or production data. + +## Deployment guidance + +- Keep project registration disabled unless the application intentionally offers public registration. +- Protect upload and registration routes with application authentication or an appropriate reverse-proxy policy. +- Configure only trusted reverse proxies in the Engine request settings; forwarded client-IP headers are ignored for untrusted peers. +- Enable the plugin rate limiter and configure its backing cache before exposing public upload routes. +- Replace the example `image_uri`, use a private writable storage directory where possible, and restrict outbound network access from the server. +- Keep `ext-imagick` patched and apply conservative ImageMagick policy limits in addition to the per-request limits configured by the plugin. +- Treat project tokens as bearer credentials; do not place them in logs, public links, or analytics events. + +The URL downloader blocks non-public destinations, pins a validated address, disables redirects and proxies, and enforces transfer limits. These controls do not replace network egress filtering or application-level authorization. diff --git a/SECURITY.ru.md b/SECURITY.ru.md new file mode 100644 index 0000000..c73a477 --- /dev/null +++ b/SECURITY.ru.md @@ -0,0 +1,21 @@ +# Политика безопасности + +## Поддерживаемые версии + +Последний опубликованный релиз — `v1.1.0` для Triangle Engine `^8.1`. Эта ветка подготавливает `2.0.0` для Engine 9, но версия ещё не выпущена. В сообщении об уязвимости укажите точные версии пакета и Engine; статус поддержки `2.0.0` будет опубликован вместе с релизом. + +## Сообщить об уязвимости + +Отправьте сообщение приватно через функцию GitHub **Report a vulnerability** в этом репозитории. Укажите версию, затронутый маршрут или настройку и минимальный способ воспроизведения. Не прикладывайте настоящие токены проектов, закрытые изображения и данные production. + +## Рекомендации по эксплуатации + +- Оставляйте регистрацию проектов выключенной, если приложению действительно не нужна открытая регистрация. +- Защитите маршруты регистрации и загрузки авторизацией приложения или правилами обратного прокси. +- Укажите только доверенные прокси в настройках запросов Engine: для остальных узлов forwarded-заголовки с IP клиента игнорируются. +- Перед открытием загрузки включите ограничитель частоты запросов и настройте используемый им кэш. +- Замените пример `image_uri`, по возможности используйте непубличный каталог с правом записи и ограничьте исходящие сетевые подключения сервера. +- Обновляйте `ext-imagick` и дополните per-request ограничения ImageMagick консервативной системной политикой. +- Считайте токены проектов bearer-учётными данными: не помещайте их в логи, публичные ссылки и события аналитики. + +Загрузчик ссылок блокирует непубличные адреса, закрепляет прошедший проверку IP, отключает редиректы и прокси и ограничивает передачу данных. Эти меры не заменяют сетевую фильтрацию исходящих подключений и авторизацию на уровне приложения. diff --git a/composer.json b/composer.json index 34e9a53..c88a010 100644 --- a/composer.json +++ b/composer.json @@ -1,11 +1,16 @@ { "name": "triangle/media", - "description": "Triangle Media Plugin", + "description": "Image upload, processing, and delivery plugin for Triangle Engine", "type": "library", + "homepage": "https://github.com/Triangle-org/Media", + "readme": "README.md", "keywords": [ "localzet", - "Triangle", - "Media" + "triangle", + "engine", + "media", + "image-upload", + "image-processing" ], "license": "AGPL-3.0-or-later", "authors": [ @@ -22,11 +27,14 @@ }, "require": { "php": "^8.1", - "triangle/engine": "^8.1", + "triangle/engine": "^9.0", "ext-curl": "*", "ext-fileinfo": "*", "ext-imagick": "*" }, + "suggest": { + "triangle/view": "Required by the bundled HTML view routes unless the host application replaces them." + }, "autoload": { "psr-4": { "Triangle\\Media\\": "src/", @@ -34,7 +42,12 @@ } }, "scripts": { - "test": "php tests/remote_image_downloader.php" + "lint": "find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l", + "test": "php tests/remote_image_downloader.php && php tests/project_registration.php && php tests/upload_request_contract.php && php tests/uploader_file_validation.php && php tests/processing_response_type.php && php tests/image_paths_and_limits.php && php tests/image_processing_limits.php", + "check": [ + "@lint", + "@test" + ] }, "config": { "platform": { diff --git a/src/Config/app.php b/src/Config/app.php index aa911fc..ef3511a 100644 --- a/src/Config/app.php +++ b/src/Config/app.php @@ -1,20 +1,20 @@ * - * @copyright Copyright (c) 2018-2020 Zorin Projects - * @copyright Copyright (c) 2020-2022 NONA Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * - * @license https://www.localzet.ru/license GNU GPLv3 License + * @license AGPL-3.0-or-later */ return [ 'enable' => true, - 'project_registration' => true, + 'project_registration' => false, 'image_uri' => 'https://example.ru/media/', // URL для изображений 'image_path' => public_path() . '/media/upload/', // Директория для изображений diff --git a/src/ImageProcessing.php b/src/ImageProcessing.php index b37ccbc..36ac063 100644 --- a/src/ImageProcessing.php +++ b/src/ImageProcessing.php @@ -1,15 +1,15 @@ * - * @copyright Copyright (c) 2018-2020 Zorin Projects - * @copyright Copyright (c) 2020-2022 NONA Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * - * @license https://www.localzet.ru/license GNU GPLv3 License + * @license AGPL-3.0-or-later */ namespace Triangle\Media; @@ -86,10 +86,18 @@ public function cropImage($cropWidth, $cropHeight = null, $x = null, $y = null) $cropHeight = $cropWidth; } + $cropWidth = (int)$cropWidth; + $cropHeight = (int)$cropHeight; + self::assertDimensionsWithinLimit($cropWidth, $cropHeight); + if ($x == null || $y == null) { $ratio = max($cropHeight / $this->height, $cropWidth / $this->width); - $this->imagick->scaleImage($ratio * $this->width, $ratio * $this->height); + $scaledWidth = (int)ceil($ratio * $this->width); + $scaledHeight = (int)ceil($ratio * $this->height); + self::assertDimensionsWithinLimit($scaledWidth, $scaledHeight); + + $this->imagick->scaleImage($scaledWidth, $scaledHeight); $this->recalculateDimensions(); @@ -98,6 +106,12 @@ public function cropImage($cropWidth, $cropHeight = null, $x = null, $y = null) $this->imagick->cropImage($cropWidth, $cropHeight, $x, $y); } else { + $x = (int)$x; + $y = (int)$y; + if ($x < 0 || $y < 0 || $x > $this->width - $cropWidth || $y > $this->height - $cropHeight) { + throw new Exception('Crop area is outside the source image.'); + } + $this->imagick->cropImage($cropWidth, $cropHeight, $x, $y); } @@ -118,10 +132,23 @@ public function cropImage($cropWidth, $cropHeight = null, $x = null, $y = null) */ public function resizeImage($resizeWidth, $resizeHeight = 0) { - if (!$resizeWidth && !$resizeHeight) { + $resizeWidth = (int)$resizeWidth; + $resizeHeight = (int)$resizeHeight; + + if ($resizeWidth < 0 || $resizeHeight < 0 || (!$resizeWidth && !$resizeHeight)) { throw new Exception('Incorrect input dimensions'); } + if ($resizeWidth > 0 && $resizeHeight > 0) { + self::assertDimensionsWithinLimit($resizeWidth, $resizeHeight); + } elseif ($resizeWidth > 0) { + $scaledHeight = (int)ceil($this->height * ($resizeWidth / $this->width)); + self::assertDimensionsWithinLimit($resizeWidth, $scaledHeight); + } else { + $scaledWidth = (int)ceil($this->width * ($resizeHeight / $this->height)); + self::assertDimensionsWithinLimit($scaledWidth, $resizeHeight); + } + if ($resizeWidth == 0) { $this->imagick->scaleImage(0, $resizeHeight); } elseif ($resizeHeight == 0) { @@ -147,7 +174,8 @@ public function resizeImage($resizeWidth, $resizeHeight = 0) */ public function pixelizeImage($pixels) { - if (!$pixels) { + $pixels = (int)$pixels; + if ($pixels < 1 || $pixels > max($this->width, $this->height)) { throw new Exception('Incorrect ratio'); } @@ -214,6 +242,7 @@ public function addCover($color, $width = 1000, $maxWidthRatio = 0.6, $margin = * than the 60% of cover's width */ $coverHeight = $margin * 2 + $this->height; + self::assertDimensionsWithinLimit((int)$width, (int)$coverHeight); /** * Create a new image as a cover @@ -256,6 +285,55 @@ public function getImageBlob() return $this->imagick->getImageBlob(); } + /** + * Run image work with process-wide ImageMagick resource limits applied. + */ + public static function withResourceLimits(callable $callback): mixed + { + $originalLimits = []; + $memoryLimit = (int)config('plugin.triangle.media.app.max_image_memory', 268435456); + $limits = [ + Imagick::RESOURCETYPE_MEMORY => $memoryLimit, + Imagick::RESOURCETYPE_MAP => $memoryLimit, + Imagick::RESOURCETYPE_DISK => (int)config('plugin.triangle.media.app.max_image_disk', 536870912), + Imagick::RESOURCETYPE_THREAD => 1, + Imagick::RESOURCETYPE_TIME => (int)config('plugin.triangle.media.app.max_image_time', 10), + ]; + + try { + foreach ($limits as $resource => $limit) { + $originalLimits[$resource] = Imagick::getResourceLimit($resource); + if ($limit < 1 || !Imagick::setResourceLimit($resource, $limit)) { + throw new \RuntimeException('Unable to apply the configured image processing resource limit.'); + } + } + + return $callback(); + } finally { + foreach ($originalLimits as $resource => $limit) { + @Imagick::setResourceLimit($resource, $limit); + } + } + } + + /** @internal */ + public static function assertDimensionsWithinLimit(int $width, int $height): void + { + $maxPixels = (int)config('plugin.triangle.media.app.max_image_pixels', 40000000); + if ($width < 1 || $height < 1 || $maxPixels < 1 || $width > intdiv($maxPixels, $height)) { + throw new Exception('Image dimensions exceed the configured pixel limit.'); + } + } + + /** @internal */ + public static function assertFrameCountWithinLimit(int $frameCount): void + { + $maxFrames = (int)config('plugin.triangle.media.app.max_image_frames', 50); + if ($frameCount < 1 || $maxFrames < 1 || $frameCount > $maxFrames) { + throw new Exception('Image frame count exceeds the configured limit.'); + } + } + /** * Defines available image formats * @@ -290,6 +368,34 @@ private function readImage($path) { $this->path = $path; + $probe = new Imagick(); + try { + $probe->pingImage($path); + self::assertFrameCountWithinLimit($probe->getNumberImages()); + + $maxPixels = (int)config('plugin.triangle.media.app.max_image_pixels', 40000000); + if ($maxPixels < 1) { + throw new Exception('Image pixel limit must be greater than zero.'); + } + + $totalPixels = 0; + foreach ($probe as $frame) { + $frameWidth = $frame->getImageWidth(); + $frameHeight = $frame->getImageHeight(); + if ($frameWidth < 1 || $frameHeight < 1 || $frameWidth > intdiv($maxPixels, $frameHeight)) { + throw new Exception('Image dimensions exceed the configured pixel limit.'); + } + + $framePixels = $frameWidth * $frameHeight; + if ($framePixels > $maxPixels - $totalPixels) { + throw new Exception('Image frames exceed the configured total pixel limit.'); + } + $totalPixels += $framePixels; + } + } finally { + $probe->clear(); + } + $readResult = @$this->imagick->readImage($path); $this->extension = $this->imagick->getImageFormat(); diff --git a/src/Install.php b/src/Install.php index ebfe6fc..c6c7720 100644 --- a/src/Install.php +++ b/src/Install.php @@ -5,8 +5,9 @@ * @link https://github.com/Triangle-org/Media * * @author Ivan Zorin - * @copyright Copyright (c) 2018-2024 Localzet Group - * @license GNU Affero General Public License, version 3 + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + * @license AGPL-3.0-or-later * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as diff --git a/src/RateLimiter.php b/src/RateLimiter.php index 531eb5b..db1006d 100644 --- a/src/RateLimiter.php +++ b/src/RateLimiter.php @@ -1,15 +1,15 @@ * - * @copyright Copyright (c) 2018-2020 Zorin Projects - * @copyright Copyright (c) 2020-2022 NONA Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * - * @license https://www.localzet.ru/license GNU GPLv3 License + * @license AGPL-3.0-or-later */ namespace Triangle\Media; @@ -18,7 +18,7 @@ /** * @singleton * - * Simple rate limiter module powered by Memcache + * Simple rate limiter backed by the host application's storage service. * * @example * if (RateLimiter::instance()->isEnabled()) { diff --git a/src/RemoteImageDownloader.php b/src/RemoteImageDownloader.php index 7f3efc0..e655da0 100644 --- a/src/RemoteImageDownloader.php +++ b/src/RemoteImageDownloader.php @@ -1,4 +1,9 @@ * - * @copyright Copyright (c) 2018-2020 Zorin Projects - * @copyright Copyright (c) 2020-2022 NONA Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * - * @license https://www.localzet.ru/license GNU GPLv3 License + * @license AGPL-3.0-or-later */ namespace Triangle\Media; +use Triangle\Engine\File; + /** * Parent class, which describes acceptable extension, * file size and methods that check these parameters. @@ -27,12 +29,14 @@ class Uploader */ public $projectId = ''; + private ?string $authorIp; + /** * Check uploads dir, prepare project's ID * * @param string $projectId */ - public function __construct($projectId) + public function __construct($projectId, ?string $authorIp = null) { $uploadDirectory = config('plugin.triangle.media.app.image_path'); if (!is_string($uploadDirectory) || $uploadDirectory === '') { @@ -46,6 +50,7 @@ public function __construct($projectId) } $this->projectId = $projectId; + $this->authorIp = $authorIp; } /** @@ -130,13 +135,9 @@ protected function saveFileToUploadDir($filepath) $image = new \Imagick(); $image->pingImage($path); $frames = $image->getNumberImages(); - $maxFrames = (int)config('plugin.triangle.media.app.max_image_frames', 50); $maxPixels = (int)config('plugin.triangle.media.app.max_image_pixels', 40000000); $totalPixels = 0; - if ($frames < 1 || $frames > $maxFrames) { - $image->clear(); - throw new \RuntimeException('Image frame count exceeds the configured limit.'); - } + ImageProcessing::assertFrameCountWithinLimit($frames); foreach ($image as $frame) { $totalPixels += $frame->getImageWidth() * $frame->getImageHeight(); if ($totalPixels > $maxPixels) { @@ -211,7 +212,11 @@ protected function saveFileToUploadDir($filepath) */ protected function getAuthor() { - return getRequestIp(); + if ($this->authorIp !== null) { + return $this->authorIp; + } + + return function_exists('request') ? request()->getRequestIp() : null; } /** @@ -294,7 +299,7 @@ protected function upload($file, $size, $mime) /** * Public function for file uploading via POST form-data * - * @param null|array|\localzet\FrameX\Http\UploadFile $data - image file from $_FILES + * @param File $data Uploaded image file. * * @throws \Exception * @@ -303,13 +308,22 @@ protected function upload($file, $size, $mime) */ public function uploadFile($data) { - if (!file_exists($data->getPathname())) { - throw new \Exception('File is missing ' . $data->getPathname()); + if (!$data instanceof File || !$data->isValid()) { + throw new \InvalidArgumentException('The uploaded file is invalid.'); + } + + $path = $data->getPathname(); + if (!is_file($path)) { + throw new \RuntimeException('The uploaded file is missing.'); } - $mime = mime_content_type($data->getPathname()); + $size = filesize($path); + $mime = mime_content_type($path); + if (!is_int($size) || !is_string($mime)) { + throw new \RuntimeException('Unable to inspect the uploaded file.'); + } - return $this->upload($data->getPathname(), filesize($data->getPathname()), $mime); + return $this->upload($path, $size, $mime); } /** diff --git a/src/UriDispatcher.php b/src/UriDispatcher.php index ad65717..4022c60 100644 --- a/src/UriDispatcher.php +++ b/src/UriDispatcher.php @@ -1,15 +1,15 @@ * - * @copyright Copyright (c) 2018-2020 Zorin Projects - * @copyright Copyright (c) 2020-2022 NONA Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * - * @license https://www.localzet.ru/license GNU GPLv3 License + * @license AGPL-3.0-or-later */ namespace Triangle\Media; diff --git a/src/Util.php b/src/Util.php index 0e41a7d..bb89835 100644 --- a/src/Util.php +++ b/src/Util.php @@ -1,15 +1,15 @@ * - * @copyright Copyright (c) 2018-2020 Zorin Projects - * @copyright Copyright (c) 2020-2022 NONA Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later * - * @license https://www.localzet.ru/license GNU GPLv3 License + * @license AGPL-3.0-or-later */ namespace Triangle\Media; @@ -40,12 +40,12 @@ static function getImageUri($id) */ static function imageNameToId($name) { - $defaultExtension = config('plugin.triangle.media.app.target_ext'); + $defaultExtension = (string)config('plugin.triangle.media.app.target_ext'); /** * Allow getting images with extension at the end of uri */ - if (preg_match('/(?P[\w-]+)\.' . $defaultExtension . '$/', $name, $matches)) { + if (preg_match('/\A(?P[a-zA-Z0-9_-]{1,128})\.' . preg_quote($defaultExtension, '/') . '\z/iD', $name, $matches)) { return $matches['id']; } @@ -71,12 +71,35 @@ static function imageNameToId($name) */ static function getPathToImageSource($id) { - $imageUrl = config('plugin.triangle.media.app.image_path') . $id . '.' . config('plugin.triangle.media.app.target_ext'); + $directory = config('plugin.triangle.media.app.image_path'); + $extension = config('plugin.triangle.media.app.target_ext'); - if (!file_exists($imageUrl)) { - throw new \Exception('Файл не существует в' . config('plugin.triangle.media.app.image_path') . $id . '.' . config('plugin.triangle.media.app.target_ext')); + if (!is_string($id) || !preg_match('/\A[a-zA-Z0-9_-]{1,128}\z/D', $id) + || !is_string($directory) || $directory === '' + || !is_string($extension) || !preg_match('/\A[a-zA-Z0-9]{1,8}\z/D', $extension)) { + throw new \InvalidArgumentException('Invalid image identifier or storage configuration.'); } - return $imageUrl; + $imageRoot = realpath($directory); + if ($imageRoot === false) { + throw new \RuntimeException('Configured image directory does not exist.'); + } + + $imageUrl = $imageRoot . DIRECTORY_SEPARATOR . $id . '.' . $extension; + + if (!is_file($imageUrl)) { + throw new \RuntimeException('Image does not exist in the configured storage directory.'); + } + + $resolvedImage = realpath($imageUrl); + $rootPrefix = rtrim($imageRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $comparisonPath = PHP_OS_FAMILY === 'Windows' ? strtolower((string)$resolvedImage) : $resolvedImage; + $comparisonRoot = PHP_OS_FAMILY === 'Windows' ? strtolower($rootPrefix) : $rootPrefix; + + if ($resolvedImage === false || !str_starts_with($comparisonPath, $comparisonRoot)) { + throw new \RuntimeException('Image path escapes the configured storage directory.'); + } + + return $resolvedImage; } } diff --git a/src/plugin/media/app/controller/Image.php b/src/plugin/media/app/controller/Image.php index c469f50..370aec6 100644 --- a/src/plugin/media/app/controller/Image.php +++ b/src/plugin/media/app/controller/Image.php @@ -1,4 +1,9 @@ + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + namespace plugin\media\app\controller; use support\Request; @@ -8,18 +16,13 @@ class Index { public function index(Request $request) { - $request->get('token'); + $response = view("index"); + $token = $request->get('token'); - if (!empty($request->get('token'))) { - /** - * Almost endless cookie lifetime is a max integer value - * 2147483647 = 2^31 - 1 - */ - $cookie = $request->get('token'); - } else { - $cookie = 'f36ac63b-7345-4b94-b9d4-c150824ef684'; + if (!is_string($token) || !preg_match('/\A[a-zA-Z0-9_-]{1,128}\z/D', $token)) { + return $response; } - return view("index")->cookie('token', $cookie, 2147483647); + return $response->cookie('token', $token, 604800, '/', '', $request->isSecure(), false, 'Lax'); } } diff --git a/src/plugin/media/app/controller/Processing.php b/src/plugin/media/app/controller/Processing.php index a485be4..b0737d9 100644 --- a/src/plugin/media/app/controller/Processing.php +++ b/src/plugin/media/app/controller/Processing.php @@ -1,5 +1,13 @@ + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + namespace plugin\media\app\controller; use support\Request; @@ -41,10 +49,16 @@ public function index(Request $request, $requestUri) storage()->set($requestUri, $imageData); } - return responseBlob($imageData); + $contentType = (string)config('plugin.triangle.media.app.target_type', 'image/png'); + return responseBlob($imageData, $contentType); } protected function returnImage($requestUri) + { + return ImageProcessing::withResourceLimits(fn() => $this->processImage($requestUri)); + } + + private function processImage($requestUri) { $dispatcher = new UriDispatcher($requestUri, self::FILTERS); $imageId = $dispatcher->id; diff --git a/src/plugin/media/app/controller/Project.php b/src/plugin/media/app/controller/Project.php index e232fc9..44aaf8d 100644 --- a/src/plugin/media/app/controller/Project.php +++ b/src/plugin/media/app/controller/Project.php @@ -1,27 +1,68 @@ + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + namespace plugin\media\app\controller; use support\Request; +use Triangle\Media\RateLimiter; class Project { public function index(Request $request) { - if (strtoupper($request->method()) != 'POST') { + if (!config('plugin.triangle.media.app.project_registration', false)) { + return response('Project registration is disabled', 403); + } + + $method = strtoupper($request->method()); + if ($method === 'GET') { return view("form"); } - /* @todo validate data */ + if ($method !== 'POST') { + return response('Method not allowed', 405); + } + + if (RateLimiter::instance()->isEnabled()) { + $key = 'MEDIA_PROJECT_REGISTER_' . ($request->getRequestIp() ?? 'unknown'); + if (!RateLimiter::instance()->check($key)) { + return response(RateLimiter::instance()->errorMessage(), 429); + } + } + + $name = $request->post('name'); + $description = $request->post('description', ''); + $email = $request->post('email', ''); + + if (!is_string($name) || !is_string($description) || !is_string($email)) { + return response('Invalid project data', 422); + } + + $name = trim($name); + $description = trim($description); + $email = trim($email); + + if ($name === '' || strlen($name) > 120 || strlen($description) > 2000 + || strlen($email) > 254 + || ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false)) { + return response('Invalid project data', 422); + } /** Generate project's token */ $token = generateId(); /** Compose project's data */ $projectData = [ - 'name' => (string) $request->post('name'), - 'description' => (string) $request->post('description'), - 'email' => (string) $request->post('email'), + 'name' => $name, + 'description' => $description, + 'email' => $email, 'token' => (string) $token, ]; diff --git a/src/plugin/media/app/controller/Upload.php b/src/plugin/media/app/controller/Upload.php index cc405a2..76fae4e 100644 --- a/src/plugin/media/app/controller/Upload.php +++ b/src/plugin/media/app/controller/Upload.php @@ -1,9 +1,14 @@ checkRateLimits(); + $rate = $this->checkRateLimits($request); if ($rate !== true) { return $rate; }; /** Check project's token */ - $projectId = $this->tryToFindProjectIdByToken(); + $projectId = $this->tryToFindProjectIdByToken($request); if ($projectId === false) { return response("Некорректный токен проекта", 403); } /** Process form data */ - if (!empty($request->file())) { - return $this->uploadFile($projectId); - } elseif (!empty($request->post('link'))) { - return $this->uploadLink($projectId); + $file = $request->file('file'); + if ($file !== null) { + return $this->uploadFile($request, $projectId, $file); + } + + $link = $request->post('link'); + if (is_string($link) && trim($link) !== '') { + return $this->uploadLink($request, $projectId, trim($link)); } else { return response("Некорректный запрос", 400); } @@ -39,39 +48,31 @@ public function index(Request $request) /** * Function processed uploading file * - * @param string $projectId - source project for image + * @param string $projectId Source project for image. */ - protected function uploadFile($projectId) + protected function uploadFile(Request $request, string $projectId, mixed $file) { - /** This way we have $_FILES['files'] as a one file or array with files */ - - if (empty(request()->file('file')->getUploadName())) { + if (!$file instanceof File || !$file->isValid() || trim((string)$file->getUploadName()) === '') { return response("Некорректный файл", 400); - } else { - $uploader = new Uploader($projectId); + } - $imageData = $uploader->uploadFile(request()->file('file')); + $uploader = new Uploader($projectId, $request->getRequestIp()); + $imageData = $uploader->uploadFile($file); - return $this->returnImageData($imageData); - } + return $this->returnImageData($imageData); } /** * Function processed uploading by link * - * @param string $projectId - source project for image + * @param string $projectId Source project for image. */ - protected function uploadLink($projectId) + protected function uploadLink(Request $request, string $projectId, string $link) { - if (empty(request()->post('link'))) { - return response("Некорректная ссылка", 400); - } else { - $uploader = new Uploader($projectId); + $uploader = new Uploader($projectId, $request->getRequestIp()); + $imageData = $uploader->uploadLink($link); - $imageData = $uploader->uploadLink((string) request()->post('link')); - - return $this->returnImageData($imageData); - } + return $this->returnImageData($imageData); } /** @@ -99,10 +100,10 @@ protected function returnImageData($imageData) /** * Check if client has allowed to upload image */ - private function checkRateLimits() + private function checkRateLimits(Request $request) { if (RateLimiter::instance()->isEnabled()) { - $ip = getRequestIp(); + $ip = $request->getRequestIp() ?? 'unknown'; $key = 'RATELIMITER_CLIENT_' . $ip; $requestAllowed = RateLimiter::instance()->check($key); @@ -120,11 +121,11 @@ private function checkRateLimits() * * @return string project's _id from MongoDB */ - private function tryToFindProjectIdByToken() + private function tryToFindProjectIdByToken(Request $request) { - $token = !empty(request()->post('token')) ? (string) request()->post('token') : ''; + $token = $request->post('token'); - if ($token) { + if (is_string($token) && $token !== '') { $mongoResponse = db()->where('token', $token)->getOne(config('plugin.triangle.media.app.database.projects')); if (!empty($mongoResponse['id'])) { diff --git a/tests/image_paths_and_limits.php b/tests/image_paths_and_limits.php new file mode 100644 index 0000000..472f928 --- /dev/null +++ b/tests/image_paths_and_limits.php @@ -0,0 +1,83 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace { + function config(string $key, mixed $default = null): mixed + { + return match ($key) { + 'plugin.triangle.media.app.target_ext' => 'png', + 'plugin.triangle.media.app.image_path' => $GLOBALS['media_test_directory'], + 'plugin.triangle.media.app.max_image_pixels' => 40000000, + 'plugin.triangle.media.app.max_image_frames' => 50, + default => $default, + }; + } + + function expect(bool $condition, string $message): void + { + if (!$condition) { + throw new RuntimeException($message); + } + } + + require dirname(__DIR__) . '/src/Util.php'; + require dirname(__DIR__) . '/src/ImageProcessing.php'; + + $GLOBALS['media_test_directory'] = sys_get_temp_dir() . '/triangle-media-path-' . bin2hex(random_bytes(6)); + $outsidePath = $GLOBALS['media_test_directory'] . '-outside.png'; + mkdir($GLOBALS['media_test_directory'], 0700); + file_put_contents($outsidePath, 'outside'); + + expect(\Triangle\Media\Util::imageNameToId('image-id.png') === 'image-id', 'PNG filename should resolve to its identifier.'); + expect(\Triangle\Media\Util::imageNameToId('../image-id.png') === '../image-id.png', 'A path must not be reduced to an identifier.'); + + foreach (['../outside', '..\\..\\outside', 'nested/image', 'nested\\image'] as $invalidId) { + try { + \Triangle\Media\Util::getPathToImageSource($invalidId); + } catch (InvalidArgumentException) { + continue; + } + + throw new RuntimeException("Expected unsafe image identifier to be rejected: $invalidId"); + } + + if (function_exists('symlink') && @symlink($outsidePath, $GLOBALS['media_test_directory'] . '/linked.png')) { + $symlinkRejected = false; + try { + \Triangle\Media\Util::getPathToImageSource('linked'); + } catch (RuntimeException) { + $symlinkRejected = true; + } + + @unlink($GLOBALS['media_test_directory'] . '/linked.png'); + expect($symlinkRejected, 'Image storage must reject symlinks that leave the configured directory.'); + } + + @unlink($outsidePath); + @rmdir($GLOBALS['media_test_directory']); + + \Triangle\Media\ImageProcessing::assertDimensionsWithinLimit(2000, 2000); + \Triangle\Media\ImageProcessing::assertFrameCountWithinLimit(50); + + try { + \Triangle\Media\ImageProcessing::assertDimensionsWithinLimit(7000, 7000); + } catch (\Exception) { + try { + \Triangle\Media\ImageProcessing::assertFrameCountWithinLimit(51); + } catch (\Exception) { + echo "Image path and processing limit checks passed.\n"; + exit(0); + } + + throw new RuntimeException('Image processing must reject frame counts above the configured limit.'); + } + + throw new RuntimeException('Image processing must reject dimensions above the configured pixel limit.'); +} diff --git a/tests/image_processing_limits.php b/tests/image_processing_limits.php new file mode 100644 index 0000000..d7477ec --- /dev/null +++ b/tests/image_processing_limits.php @@ -0,0 +1,121 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace { + $GLOBALS['max_image_pixels'] = 40000000; + $GLOBALS['max_image_frames'] = 50; + + function config(string $key, mixed $default = null): mixed + { + return match ($key) { + 'plugin.triangle.media.app.max_image_pixels' => $GLOBALS['max_image_pixels'], + 'plugin.triangle.media.app.max_image_frames' => $GLOBALS['max_image_frames'], + 'plugin.triangle.media.app.max_image_memory' => 268435456, + 'plugin.triangle.media.app.max_image_disk' => 536870912, + 'plugin.triangle.media.app.max_image_time' => 10, + 'plugin.triangle.media.app.exts' => ['png', 'gif'], + default => $default, + }; + } + + require dirname(__DIR__) . '/src/ImageProcessing.php'; + + if (!extension_loaded('imagick')) { + echo "ImageMagick integration checks skipped: ext-imagick is unavailable.\n"; + exit(0); + } + + $imagePath = tempnam(sys_get_temp_dir(), 'triangle-media-test-'); + if ($imagePath === false) { + throw new RuntimeException('Unable to create a temporary test image.'); + } + + try { + $png = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', true); + if (!is_string($png) || file_put_contents($imagePath, $png) === false) { + throw new RuntimeException('Unable to write a temporary test image.'); + } + + $image = new \Triangle\Media\ImageProcessing($imagePath); + + foreach ([ + static fn() => $image->resizeImage(7000), + static fn() => $image->cropImage(7000, 1), + ] as $operation) { + try { + $operation(); + } catch (\Exception) { + continue; + } + + throw new RuntimeException('Image processing must reject operations above the configured pixel limit.'); + } + + $animatedPath = tempnam(sys_get_temp_dir(), 'triangle-media-animated-'); + if ($animatedPath === false) { + throw new RuntimeException('Unable to create a temporary animated image path.'); + } + + try { + $animation = new \Imagick(); + $animation->newImage(1, 1, new \ImagickPixel('white')); + $animation->setImageFormat('gif'); + + $secondFrame = new \Imagick(); + $secondFrame->newImage(1, 1, new \ImagickPixel('black')); + $secondFrame->setImageFormat('gif'); + $animation->addImage($secondFrame); + $animation->writeImages($animatedPath, true); + $animation->clear(); + $secondFrame->clear(); + + $animationCheck = new \Imagick($animatedPath); + $frameCount = $animationCheck->getNumberImages(); + $animationCheck->clear(); + if ($frameCount < 2) { + throw new RuntimeException('Unable to create a two-frame test image.'); + } + + $GLOBALS['max_image_frames'] = 1; + $frameLimitRejected = false; + try { + new \Triangle\Media\ImageProcessing($animatedPath); + } catch (\Exception) { + $frameLimitRejected = true; + } + + if (!$frameLimitRejected) { + throw new RuntimeException('Processing must enforce the frame limit on existing images.'); + } + } finally { + $GLOBALS['max_image_frames'] = 50; + @unlink($animatedPath); + } + + $previousMemoryLimit = \Imagick::getResourceLimit(\Imagick::RESOURCETYPE_MEMORY); + try { + \Triangle\Media\ImageProcessing::withResourceLimits(static function (): void { + throw new RuntimeException('Exercise resource restoration.'); + }); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'Exercise resource restoration.') { + throw $exception; + } + } + + if (\Imagick::getResourceLimit(\Imagick::RESOURCETYPE_MEMORY) !== $previousMemoryLimit) { + throw new RuntimeException('ImageMagick limits must be restored after processing.'); + } + + echo "Image processing resource checks passed.\n"; + } finally { + @unlink($imagePath); + } +} diff --git a/tests/processing_response_type.php b/tests/processing_response_type.php new file mode 100644 index 0000000..b6c6417 --- /dev/null +++ b/tests/processing_response_type.php @@ -0,0 +1,54 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace support { + final class Request {} +} + +namespace { + final class TestResponse + { + public function __construct(public string $body, public string $contentType) {} + } + + final class TestStorage + { + public function get(string $key): string + { + return 'cached-image-bytes'; + } + + public function set(string $key, mixed $value): void {} + } + + function config(string $key, mixed $default = null): mixed + { + return $key === 'plugin.triangle.media.app.target_type' ? 'image/png' : $default; + } + + function storage(): TestStorage + { + return new TestStorage(); + } + + function responseBlob(string $blob, string $type = 'text/plain'): TestResponse + { + return new TestResponse($blob, $type); + } + + require dirname(__DIR__) . '/src/plugin/media/app/controller/Processing.php'; + + $response = (new \plugin\media\app\controller\Processing())->index(new \support\Request(), 'image-id'); + if (!$response instanceof TestResponse || $response->contentType !== 'image/png') { + throw new RuntimeException('Processed image responses must use the configured image content type.'); + } + + echo "Processing response content-type checks passed.\n"; +} diff --git a/tests/project_registration.php b/tests/project_registration.php new file mode 100644 index 0000000..10ca696 --- /dev/null +++ b/tests/project_registration.php @@ -0,0 +1,145 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace support { + final class Request + { + public function __construct( + private string $requestMethod, + private array $formData = [], + private ?string $requestIp = '203.0.113.10', + ) {} + + public function method(): string + { + return $this->requestMethod; + } + + public function post(string $name, mixed $default = null): mixed + { + return $this->formData[$name] ?? $default; + } + + public function getRequestIp(): ?string + { + return $this->requestIp; + } + } +} + +namespace Triangle\Media { + final class RateLimiter + { + public static bool $enabled = false; + public static array $keys = []; + + public static function instance(): self + { + return new self(); + } + + public function isEnabled(): bool + { + return self::$enabled; + } + + public function check(string $key): bool + { + self::$keys[] = $key; + return true; + } + + public function errorMessage(): string + { + return 'rate limited'; + } + } +} + +namespace { + final class TestResponse + { + public function __construct(public mixed $data, public int $status) {} + } + + final class TestDatabase + { + public array $inserted = []; + + public function insert(string $table, array $data): void + { + $this->inserted[] = [$table, $data]; + } + } + + $GLOBALS['project_registration_enabled'] = false; + $GLOBALS['test_database'] = new TestDatabase(); + + function config(string $key, mixed $default = null): mixed + { + return match ($key) { + 'plugin.triangle.media.app.project_registration' => $GLOBALS['project_registration_enabled'], + 'plugin.triangle.media.app.database.projects' => 'Media_Projects', + default => $default, + }; + } + + function response(mixed $data = '', int $status = 200): TestResponse + { + return new TestResponse($data, $status); + } + + function view(string $name): string + { + return $name; + } + + function generateId(): string + { + return 'test-project-token'; + } + + function db(): TestDatabase + { + return $GLOBALS['test_database']; + } + + function expect(bool $condition, string $message): void + { + if (!$condition) { + throw new RuntimeException($message); + } + } + + require dirname(__DIR__) . '/src/plugin/media/app/controller/Project.php'; + + $controller = new \plugin\media\app\controller\Project(); + $disabled = $controller->index(new \support\Request('POST', ['name' => 'blocked'])); + expect($disabled instanceof TestResponse && $disabled->status === 403, 'Disabled registration must reject requests.'); + expect($GLOBALS['test_database']->inserted === [], 'Disabled registration must not create a project.'); + + $GLOBALS['project_registration_enabled'] = true; + \Triangle\Media\RateLimiter::$enabled = true; + $invalid = $controller->index(new \support\Request('POST', ['name' => str_repeat('x', 121)])); + expect($invalid instanceof TestResponse && $invalid->status === 422, 'Invalid registration data must be rejected.'); + expect($GLOBALS['test_database']->inserted === [], 'Invalid registration data must not create a project.'); + expect(\Triangle\Media\RateLimiter::$keys === ['MEDIA_PROJECT_REGISTER_203.0.113.10'], 'Registration rate limits must use the Engine request IP.'); + + $valid = $controller->index(new \support\Request('POST', [ + 'name' => ' Example project ', + 'description' => 'Image uploads', + 'email' => 'owner@example.test', + ])); + expect($valid instanceof TestResponse && $valid->status === 200, 'Valid registration must succeed.'); + expect($valid->data === ['token' => 'test-project-token'], 'Registration must return the generated token.'); + expect($GLOBALS['test_database']->inserted[0][1]['name'] === 'Example project', 'Project names must be trimmed.'); + + echo "Project registration checks passed.\n"; +} diff --git a/tests/remote_image_downloader.php b/tests/remote_image_downloader.php index 4b4e4a6..2a0615a 100644 --- a/tests/remote_image_downloader.php +++ b/tests/remote_image_downloader.php @@ -1,4 +1,9 @@ + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace Triangle\Engine { + final class File + { + public function __construct(private string $name, private bool $valid = true) {} + + public function getUploadName(): string + { + return $this->name; + } + + public function isValid(): bool + { + return $this->valid; + } + } +} + +namespace support { + final class Request + { + public function __construct( + private string $requestMethod, + private array $formData = [], + private ?\Triangle\Engine\File $uploadedFile = null, + private ?string $requestIp = '203.0.113.12', + ) {} + + public function method(): string + { + return $this->requestMethod; + } + + public function file(?string $name = null): array|\Triangle\Engine\File|null + { + return $name === 'file' ? $this->uploadedFile : []; + } + + public function post(string $name, mixed $default = null): mixed + { + return $this->formData[$name] ?? $default; + } + + public function getRequestIp(): ?string + { + return $this->requestIp; + } + } +} + +namespace Triangle\Media { + final class RateLimiter + { + public static bool $enabled = false; + public static array $keys = []; + + public static function instance(): self + { + return new self(); + } + + public function isEnabled(): bool + { + return self::$enabled; + } + + public function check(string $key): bool + { + self::$keys[] = $key; + return true; + } + + public function errorMessage(): string + { + return 'rate limited'; + } + } + + final class Uploader + { + public static array $calls = []; + + public function __construct(public string $projectId, public ?string $authorIp = null) {} + + public function uploadFile(\Triangle\Engine\File $file): array + { + self::$calls[] = ['file', $this->projectId, $this->authorIp, $file]; + return [ + 'link' => 'https://media.example.test/image.png', + 'mime' => 'image/png', + 'width' => 10, + 'height' => 20, + 'color' => '#ffffff', + 'size' => 100, + ]; + } + + public function uploadLink(string $link): array + { + self::$calls[] = ['link', $this->projectId, $this->authorIp, $link]; + return [ + 'link' => 'https://media.example.test/image.png', + 'mime' => 'image/png', + 'width' => 10, + 'height' => 20, + 'color' => '#ffffff', + 'size' => 100, + ]; + } + } +} + +namespace { + final class TestResponse + { + public function __construct(public mixed $data, public int $status) {} + } + + final class TestDatabase + { + public function where(string $field, string $value): self + { + return $this; + } + + public function getOne(string $table): array + { + return ['id' => 'project-123']; + } + } + + function config(string $key, mixed $default = null): mixed + { + return $key === 'plugin.triangle.media.app.database.projects' ? 'Media_Projects' : $default; + } + + function response(mixed $data = '', int $status = 200): TestResponse + { + return new TestResponse($data, $status); + } + + function db(): TestDatabase + { + return new TestDatabase(); + } + + function expect(bool $condition, string $message): void + { + if (!$condition) { + throw new RuntimeException($message); + } + } + + require dirname(__DIR__) . '/src/plugin/media/app/controller/Upload.php'; + + $controller = new \plugin\media\app\controller\Upload(); + $file = new \Triangle\Engine\File('upload.png'); + \Triangle\Media\RateLimiter::$enabled = true; + + $response = $controller->index(new \support\Request('POST', ['token' => 'project-token'], $file)); + expect($response instanceof TestResponse && $response->status === 200, 'A valid request file should be accepted.'); + expect(\Triangle\Media\Uploader::$calls[0] === ['file', 'project-123', '203.0.113.12', $file], 'The controller must pass the request file and resolved IP to the uploader.'); + expect(\Triangle\Media\RateLimiter::$keys === ['RATELIMITER_CLIENT_203.0.113.12'], 'Upload rate limits must use the Engine request IP.'); + + $invalidFile = new \Triangle\Engine\File('upload.png', false); + $invalid = $controller->index(new \support\Request('POST', ['token' => 'project-token'], $invalidFile)); + expect($invalid instanceof TestResponse && $invalid->status === 400, 'Invalid uploads must be rejected before processing.'); + expect(count(\Triangle\Media\Uploader::$calls) === 1, 'Invalid uploads must not reach the uploader.'); + + $linkResponse = $controller->index(new \support\Request('POST', [ + 'token' => 'project-token', + 'link' => ' https://images.example.test/photo.png ', + ])); + expect($linkResponse instanceof TestResponse && $linkResponse->status === 200, 'A valid image link should be accepted.'); + expect(\Triangle\Media\Uploader::$calls[1] === ['link', 'project-123', '203.0.113.12', 'https://images.example.test/photo.png'], 'The link and request IP must come from the current request.'); + + echo "Upload request contract checks passed.\n"; +} diff --git a/tests/uploader_file_validation.php b/tests/uploader_file_validation.php new file mode 100644 index 0000000..11ecbc7 --- /dev/null +++ b/tests/uploader_file_validation.php @@ -0,0 +1,53 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace Triangle\Engine { + final class File + { + public function __construct(private bool $valid) {} + + public function isValid(): bool + { + return $this->valid; + } + } +} + +namespace { + function config(string $key, mixed $default = null): mixed + { + return $key === 'plugin.triangle.media.app.image_path' ? $GLOBALS['media_test_directory'] : $default; + } + + $GLOBALS['media_test_directory'] = sys_get_temp_dir() . '/triangle-media-uploader-' . bin2hex(random_bytes(6)); + if (!mkdir($GLOBALS['media_test_directory'], 0700)) { + throw new RuntimeException('Unable to create a temporary upload directory.'); + } + + require dirname(__DIR__) . '/src/Uploader.php'; + + try { + $uploader = new \Triangle\Media\Uploader('project-123'); + + foreach ([new \stdClass(), new \Triangle\Engine\File(false)] as $invalidFile) { + try { + $uploader->uploadFile($invalidFile); + } catch (InvalidArgumentException) { + continue; + } + + throw new RuntimeException('The uploader must reject invalid file inputs before reading paths.'); + } + } finally { + @rmdir($GLOBALS['media_test_directory']); + } + + echo "Uploader file validation checks passed.\n"; +}