Skip to content

chore: merge upstream Dokploy v0.31.2 - #281

Merged
agentHits merged 140 commits into
AgentHits-Devfrom
chore/upstream-sync-20261116
Nov 16, 2026
Merged

agentHits merged 140 commits into
AgentHits-Devfrom
chore/upstream-sync-20261116

Conversation

@agentHits

Copy link
Copy Markdown
Collaborator

Зачем

Форк брал upstream последний раз 5 ноября (v0.31.0, #186). С тех пор вышли v0.31.1 и v0.31.2: 82 коммита, почти все — исправления безопасности. Этот PR вливает тег v0.31.2 коммитом слияния: второй родитель — сам тег, поэтому git merge-base для следующей синхронизации останется верным. Вливать нужно merge-коммитом, не squash, иначе база снова «соврёт».

Что приходит из upstream

  • Границы организаций и ролей во всех роутерах, вебхуках и авторизации: перенос проектов, окружений и сервисов между организациями запрещён; SSH-ключи, git-провайдеры и реестры проверяются на принадлежность организации; user.update меняет только поля профиля; создание API-ключа требует права «Access to API»; встроенные эндпоинты better-auth для ключей и смены ролей выключены; вход под другим пользователем требует его согласия.
  • Экранирование и проверка ввода: команды смены пароля баз, префиксы и имена бэкапов, имена в бэкапах томов, composePath, путь сборки, стадия и версии сборщиков, путь домена (без $), путь логов, appName расписаний; удаление файла монтирования без shell; выход по симлинку при записи файлов монтирования и патчей.
  • SSRF: запросы AI-провайдеров, логотипы шаблонов и вебхуки уведомлений идут через защищённый fetch; шаблоны с чужого адреса — только с правом service:create.
  • Секреты: закрытый ключ веб-сервера и SSH-ключи больше не отдаются, пароль реестра и токен вебхука скрыты от ролей без права пользоваться ими, fullContext откатов не попадает в списки деплоев.
  • Доступ к логам и метрикам: деплой любого типа проверяется в роутере деплоев, compose.readLogs привязан к сервису; деплои без сервиса (настройка сервера, задачи хоста) читает, останавливает и удаляет только владелец или админ; метрики — только с эндпоинтов своей организации.
  • Обновление Traefik: новый контейнер создаётся первым, прерванное обновление восстанавливается через ту же очередь.
  • Две функции: экспорт и импорт проектов между панелями, подключение сервера одной командой.

Как разрешены конфликты

Конфликтовало 88 файлов. Где обе стороны чинили одно и то же, остался механизм форка, а проверки upstream добавлены сверху; ничего из проверок обеих сторон не выброшено (отдельно сверено: все удалённые строки с проверками доступа, экранированием и маскировкой заменены эквивалентом). Остались механизмы форка: маскировка секретов для всех ролей и reveal*-процедуры, quoteShellArg, ключи rclone в окружении, подписанное состояние OAuth GitLab/Gitea с привязкой к сессии, смена паролей баз через спецификацию сервиса, ожидание сходимости Swarm, исходящие запросы через utils/undici на Bun, никакого порта 80.

Не взяты, потому что в форке строже: cookie-состояние OAuth upstream, команды смены пароля upstream, назначение админа админом (в форке — только владелец), обход assertMonitoringAccess для любого, у кого есть чтение Docker. Не взяты ослабления upstream (вынесены на решение отдельно): бэкап томов compose, объявленных только в compose-файле, и имена сервисов compose с . или - в начале.

Добавлено поверх upstream

  • projectExportImport.export недоступен ключам API: архив содержит все секреты проекта, зашифрованные паролем, который выбирает вызывающий, так что владелец ключа расшифровал бы его у себя.
  • Сервер, подключённый командой, проходит assertServerDestinationAllowed: его адрес берётся из заголовков пересылки.
  • Ключ API сервисов apps/api и apps/schedules сравнивается за постоянное время.
  • destination.testConnection: "none" из выбора сервера снова означает «без сервера».
  • CLAUDE.md: новые функции и правило доступа к логам деплоев без сервиса.

Миграций нет. Зависимости не менялись, кроме нижней границы fast-xml-parser (5.12) в overrides.

Проверки

Linux, Bun 1.4.4, Node 26.13.0 (VM):

  • bun install --frozen-lockfile, bun audit --audit-level=moderate, biome ci . (0 ошибок), bun run server:build, bun run typecheck проходят.
  • Unit-тесты: 6369 прошли, 1 упал — backup-files > getBackupServerId, известный таймаут 5 с под нагрузкой всего набора (отдельно проходит).
  • Тесты форка переведены на более строгие правила upstream, у каждого нового запрета есть свой случай; тесты upstream, рассчитанные на другие моки или на другое поведение терминалов, переписаны под форк. Новые тесты Traefik и терминалов проверены на сломанном нарочно коде: падают.

Что проверить на панели

  • Вход, выход, 2FA, вызов API по ключу.
  • Логи и терминал контейнера, Docker-страница, обновление Traefik из компонентов.
  • Создание назначения и проверка подключения к S3, бэкап панели.

🤖 Generated with Claude Code

imrja8 and others added 30 commits November 4, 2026 19:01
mv swapped the inode, leaving containers that bind-mount the file
(e.g. CrowdSec template) reading a stale/deleted file.
…rial

Going back to the plan step after starting a trial only offered
"Start trial", which failed with "already have an active plan or trial",
leaving users stuck. Show the active plan/trial with a Continue button,
and hide the trial button once the trial has been used.
…-orphan-job

fix(schedules): prevent cron jobs from being lost on cloud
fix(terminal): close SSH sessions when the terminal WebSocket closes
…nd auth

Hardens authorization and input containment found in a source audit.

- shared assertServerAccess guard (org + accessedServers; rejects the local
  control-plane host on Cloud) applied to network, destination, registry,
  certificate, ai.deploy, docker/volume/image, swarm, cluster and settings
- getRemoteDocker fails closed when the target server has no SSH key
- bind path inputs to their owner: unzipDrop (zip-slip), patch repo file/dir
  read, backup object key, and volume restore (+ strict backupFileName)
- domain.create authorizes every service id regardless of domainType
- git-provider update (github/gitlab/gitea/bitbucket) checks provider ownership
- notification update binds the channel sub-record id to the notification
- backup web-server restore and service-less backup ops are owner/admin and
  org-bound
- listen-deployment binds the requested logPath to an authorized deployment
- github webhook pull_request closed scopes preview removal to the verified
  provider
- gitea/gitlab OAuth callbacks require a session whose org owns the provider
- SSRF: metrics endpoints, compose template baseUrl and AI model fetch go
  through providerFetch
- apps/api and apps/schedules fail closed when API_KEY is unset
- better-auth: member role/invite only via tRPC (+ admin-role ceiling),
  API-key sessions fail closed without a membership row, and reset/verification
  links use the canonical host instead of the request Host header

Adds role-based regression tests (owner/admin/member/custom) covering both
preserved legitimate access and blocked escalation.
- git providers: update the stored provider, not the client-supplied id
- web-server backups: bind one/update/remove/manual run to the org's destination
- compose restore: accept the service backup folder, reject '..'
- listen-deployment: authorize backup, volume backup and schedule logs
- traefik settings and network actions: enforce accessed servers
- patch repo: read files from the git tree so symlinks can't reach host files
- volume restore: bind volume and server to the service, run tar without a shell string
- reset email origin: honor the https setting
…run-1

# Conflicts:
#	apps/schedules/src/index.ts
…p names

- volume restore also accepts volumes the service already backs up, covering
  compose volumes with an explicit or external name
- backup restore rejects '..' path segments instead of any two dots
fix(security): enforce org/role boundaries across routers, webhooks and auth
…hell

appName and organizationId are no longer accepted from schedule
create/update input, and the schedule paths used in rm/mkdir/script
writes are shell-quoted so rows stored before this fix stay harmless.
removeFileOrDirectory and removeDirectoryIfExistsContent ran an unquoted
rm -rf, so a file mount filePath like x$(cmd) executed on the host when
the mount was removed. Use fs.rm instead.
The rclone destination was double-quoted (still expands $(...)), the
retention path was unquoted and compose serviceName went raw into the
docker ps filter. Also block web-server backups on cloud, where the
retention cleanup ran on the shared host, and stop logging the backup
command (it carries DB passwords).
…pName

appName is no longer accepted from input, serviceName must be a valid
service name, and prefix/serviceName/paths are shell-quoted in the
backup, retention and cleanup commands.
The new password (backticks allowed by DATABASE_PASSWORD_REGEX) sat in
double quotes and databaseUser / stored credentials were unquoted or
single-quoted. Pass every docker exec argument through quote().
dockerfile, build paths, dockerContextPath, publishDirectory and
dropBuildPath must be safe relative paths (no spaces, leading '-' or
'..'); dockerBuildStage, railpackVersion and herokuVersion are
restricted to [a-zA-Z0-9._-]. They were interpolated unquoted into the
builder shell commands.
…mands

composePath went unquoted into cat (remote), double-quoted into the
base64 write and, via the docker command, into the double-quoted log
banner echo. Restrict it to a safe relative path and quote those sinks.
…rSettings

Any authenticated user could read the host SSH private key and the
metrics token. The key is never returned now, and the metrics token is
only returned to owners and admins.
apiUpdateUser was the full partial insert schema, so a user could set
server-managed columns on their own row (stripeCustomerId,
serversQuantity, banned, role, ...). Only accept what the profile form
sends.
…s organizations

project.update accepted organizationId, environment.update accepted
projectId and the service update schemas accepted environmentId; move
never checked targetEnvironmentId; project.duplicate cloned any service
id. Narrow the update schemas, check the target environment's org (and
member access) in every move, and authorize each service before
duplicating it.
…zation to servers

server.create and server.update stored any sshKeyId without checking
which organization owns the key.
…nd bind compose.readLogs

killProcess, removeDeployment and readLogs only checked application and
compose deployments; backup, volume backup, preview and schedule
deployments had no check. Reuse the owner resolution from
listen-deployment (now a shared helper), require owner/admin for
serviceless deployments, only kill running deployments, and make
compose.readLogs verify the container belongs to the compose.
Siumauricio and others added 29 commits November 12, 2026 01:10
…ccess

fix(security): scope host schedule reads and the deployment queue
fix(security): refuse file mount and patch writes that escape through a symlink
…ccess

fix(security): restrict GitLab/Gitea OAuth connect to provider editors and add state
fix(security): require service access to read application monitoring stats
fix(security): guard AI provider requests against SSRF
fix(security): only fetch metrics from the organization's monitoring endpoints
…-invitation

fix(security): refuse changing the profile email to one with a pending invitation
…me-mount

fix(security): members can't attach an existing Docker volume that isn't their service's
Create Server gets a "Run a command" tab: Dokploy generates an SSH key and a
signed, single-use token; running the command on the VPS installs the key and
registers the server. Complete setup then opens the Setup Server modal.
Start over only clears the pending command; deleting keys from server.create
could remove unrelated SSH keys.
)

* feat(project-export-import): export and import projects between Dokploy instances
* feat(servers): connect a server by running one command
…g-limit

fix(previews): limit application columns when closing a PR to avoid postgres 100-arg limit
…takeover

fix(auth): require impersonation consent and rate limit cloud API keys
Merges upstream tags v0.31.1 and v0.31.2 (82 commits since v0.31.0, the
base of the previous sync). Most are security fixes: organization and role
boundaries across routers, webhooks and auth; shell quoting of database
password changes, backup prefixes, volume backup names, compose paths, log
paths and schedule app names; validation of build fields, domain paths and
composePath; symlink escapes in file mounts and patches; SSRF guards for AI
providers, templates and notification webhooks; SSH keys, registry
passwords, webhook tokens and rollback contexts no longer returned to roles
that cannot use them; API key creation bound to the "Access to API"
permission; impersonation consent. Two features come along: project export
and import between instances, and connecting a server with one command.

88 files conflicted. Where both sides fixed the same thing, the fork's
mechanism stays (its redaction of secrets for every role, quoting through
quoteShellArg, rclone credentials in env, signed OAuth state bound to the
session, password changes through the service spec, Swarm convergence
waits, outbound requests through utils/undici on Bun) and upstream's extra
checks are added on top. Fork changes on top of upstream:
- projectExportImport.export is refused to API keys: the bundle holds every
  secret of the project, encrypted with a passphrase the caller picks.
- A server connected by command goes through assertServerDestinationAllowed,
  since its address comes from forwarding headers.
- The sidecar API key checks compare in constant time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Biome import order in the server router and connect-server.
- bun.lock: the fast-xml-parser override floor from upstream.
- destination.testConnection: "none" from the cloud form's server picker
  means no server again; since the merge the server check runs in every
  mode, and an API client that sent "none" to a self-hosted panel got
  UNAUTHORIZED.
- ssh-key test: sshKey.all no longer loads the private key column at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fork tests follow the rules the merge brought in, and upstream's new tests
follow the fork's design:
- API key sessions: validateRequest caches its answer per request, so each
  case builds its own request; a request validated twice verifies once.
- Deployments that belong to no service (server setup, host schedule runs)
  need owner or admin to read, kill or remove; members get cases that prove
  the refusal and the filtered queue.
- Profile email: a pending, unexpired invitation blocks the change, an
  expired one does not.
- Vault: with a kept token, changing the URL or the mount is refused.
- member-role-ceiling (upstream): only the owner grants admin in the fork.
- Traefik recreate: the new order (create, stop, rename, start), still
  without a sleep and never binding port 80; a restore waits for a running
  update in the same queue.
- terminal-ssh-lifecycle (upstream): rewritten to the fork's terminals (the
  server terminal destroys a pending connection after 3 s, the container
  terminal keeps its connection for the hangup scans).
- Mocks for assertServerAccess, providerFetch, assertHostScheduleAccess and
  the version read from package.json instead of a hard-coded one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@agentHits
agentHits merged commit d0e828f into AgentHits-Dev Nov 16, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants