Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
140 commits
Select commit Hold shift + click to select a range
05a0fc5
fix(schedules): restore jobs before accepting requests
imrja8 Nov 4, 2026
7c8806a
fix(terminal): close SSH sessions when the terminal WebSocket closes
imrja8 Nov 4, 2026
01dbf5d
fix(terminal): connect in dev StrictMode, test exit paths, quiet canc…
imrja8 Nov 4, 2026
4dae09a
fix(traefik): harden the Traefik update and rollback
imrja8 Nov 5, 2026
0104c2c
fix(traefik): recover an update interrupted after Traefik stops
imrja8 Nov 5, 2026
9b0db9a
fix(access-log): rewrite access.log in place on cleanup
narcisonunez Nov 5, 2026
190d2c9
fix(onboarding): let users continue past plan step after starting a t…
Siumauricio Nov 5, 2026
3dd3eed
Merge pull request #5885 from Dokploy/fix/templates-1274-access-log-i…
narcisonunez Nov 6, 2026
a4c95dd
Merge pull request #5542 from imrja8/fix/schedule-cloud-update-orphan…
imrja8 Nov 6, 2026
d736506
Merge pull request #5874 from Dokploy/fix/5217-terminal-ssh-leak
imrja8 Nov 6, 2026
4b58285
fix(security): enforce org/role boundaries across routers, webhooks a…
Siumauricio Nov 6, 2026
934de3d
Update README.md
Siumauricio Nov 7, 2026
40e818b
fix(security): address review findings on org/server boundaries
Siumauricio Nov 7, 2026
3f63e0d
Merge remote-tracking branch 'origin/canary' into fix/security-audit-…
Siumauricio Nov 7, 2026
291ddaa
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 7, 2026
5ca96f9
fix(security): allow restoring named compose volumes and dotted backu…
Siumauricio Nov 7, 2026
fd9bac4
fix(security): update server mock to include remote docker instance r…
Siumauricio Nov 7, 2026
3c6d5f6
Merge pull request #5899 from Dokploy/fix/security-audit-run-1
Siumauricio Nov 7, 2026
0fa3101
fix(security): stop client-controlled schedule appName reaching the s…
Siumauricio Nov 7, 2026
861a1fb
fix(security): delete local file mounts without a shell
Siumauricio Nov 7, 2026
549cdad
fix(security): quote backup prefix, bucket and compose serviceName
Siumauricio Nov 7, 2026
ad98bf0
fix(security): validate and quote volume backup prefix/serviceName/ap…
Siumauricio Nov 7, 2026
accc2ff
fix(security): shell-quote database changePassword commands
Siumauricio Nov 7, 2026
2cd86b2
fix(security): validate application build path, stage and version fields
Siumauricio Nov 7, 2026
45abd00
fix(security): validate composePath and quote it in compose shell com…
Siumauricio Nov 7, 2026
e9910d7
fix(security): stop returning the web server SSH key from getWebServe…
Siumauricio Nov 7, 2026
4e7c280
fix(security): restrict user.update to profile fields
Siumauricio Nov 7, 2026
4db8c9b
fix(security): block moving projects, environments and services acros…
Siumauricio Nov 7, 2026
8db4cc5
fix(security): only allow attaching SSH keys from the caller's organi…
Siumauricio Nov 7, 2026
257cf1a
fix(security): authorize every deployment type in deployment router a…
Siumauricio Nov 7, 2026
f83c771
fix(security): validate domain path and internalPath
Siumauricio Nov 7, 2026
55b109d
fix(security): only owners and admins can create or edit bind mounts
Siumauricio Nov 7, 2026
0f31dcc
fix(security): stop mounts.update from re-pointing a mount at another…
Siumauricio Nov 7, 2026
1959dac
fix(security): stop returning SSH private keys from sshKey.all, and f…
Siumauricio Nov 7, 2026
29c6cb9
fix(security): do not return rollback fullContext in deployment lists
Siumauricio Nov 7, 2026
c6db584
fix(security): hide docker registry password and webhook token from r…
Siumauricio Nov 7, 2026
3d0c60e
fix(security): check notification organization on every update, not o…
Siumauricio Nov 7, 2026
2b40ff0
fix(security): require re-entering vault credentials when connection …
Siumauricio Nov 7, 2026
f2c2e34
fix(security): verify git provider, SSH key and registry ids belong t…
Siumauricio Nov 7, 2026
f0f26c7
fix(security): validate appName on the docker stats websocket
Siumauricio Nov 7, 2026
fb140a9
fix(security): require volume backups to target a volume owned by the…
Siumauricio Nov 7, 2026
7037e45
test: mock assertVolumeBelongsToService in volume backup destination …
Siumauricio Nov 7, 2026
30dd596
fix(security): escape every '<' in whitelabeling customCss
Siumauricio Nov 7, 2026
968034f
Merge pull request #5925 from Dokploy/fix/notification-org-check
narcisonunez Nov 9, 2026
58eca7a
Merge pull request #5924 from Dokploy/fix/application-secrets-read-only
narcisonunez Nov 9, 2026
086538c
Merge pull request #5923 from Dokploy/fix/rollback-context-leak
narcisonunez Nov 9, 2026
0e00216
Merge pull request #5920 from Dokploy/fix/mount-update-rebind
narcisonunez Nov 9, 2026
6d1dc17
Merge pull request #5917 from Dokploy/fix/deployment-ownership
narcisonunez Nov 9, 2026
fd61ce9
Merge pull request #5916 from Dokploy/fix/server-ssh-key-cross-org
narcisonunez Nov 9, 2026
1e21508
Merge pull request #5915 from Dokploy/fix/cross-org-project-move
narcisonunez Nov 9, 2026
c819a33
Merge pull request #5914 from Dokploy/fix/user-update-mass-assignment
narcisonunez Nov 9, 2026
82be64a
Merge pull request #5913 from Dokploy/fix/web-server-settings-leak
narcisonunez Nov 9, 2026
1c862c9
Merge pull request #5910 from Dokploy/fix/db-change-password-injection
narcisonunez Nov 9, 2026
903b4ee
Merge pull request #5907 from Dokploy/fix/mount-delete-injection
narcisonunez Nov 9, 2026
5800911
Merge pull request #5905 from Dokploy/Siumauricio-patch-1
narcisonunez Nov 9, 2026
fad5039
Merge pull request #5887 from Dokploy/fix/onboarding-plan-step-back-n…
narcisonunez Nov 9, 2026
1048bcb
Merge pull request #5881 from Dokploy/fix/traefik-update-rename-stopped
imrja8 Nov 9, 2026
fe93c7f
fix(security): enforce the Access to API permission when creating API…
Siumauricio Nov 11, 2026
736b00e
fix(security): send notification webhooks through providerFetch
Siumauricio Nov 11, 2026
ecb2956
fix(security): require service:create to fetch templates from a custo…
Siumauricio Nov 11, 2026
b4cc3db
fix(security): require Docker access to manage networks
Siumauricio Nov 11, 2026
c5b5c6a
fix(security): quote stored logPath when cleaning up deployments
Siumauricio Nov 11, 2026
e3f907f
fix(security): quote stored volume backup appName/serviceName everywh…
Siumauricio Nov 11, 2026
32c9977
fix(security): validate stored build fields before building and cover…
Siumauricio Nov 11, 2026
c33fd53
Merge pull request #5964 from Dokploy/fix/api-key-permission
Siumauricio Nov 11, 2026
c972e00
Merge pull request #5966 from Dokploy/fix/template-base-url
Siumauricio Nov 11, 2026
ffa6800
Merge pull request #5930 from Dokploy/fix/whitelabel-css-xss
Siumauricio Nov 11, 2026
5f954d0
Merge pull request #5967 from Dokploy/fix/network-rbac
Siumauricio Nov 11, 2026
f508e89
fix(security): keep stored composePath inside the service directory a…
Siumauricio Nov 11, 2026
f30f8da
fix(security): reject '$' in domain paths so compose cannot interpola…
Siumauricio Nov 11, 2026
06c2385
fix: validate SSH key edits with the update schema so the hidden priv…
Siumauricio Nov 11, 2026
cdaf192
fix(security): reject volume backups that target more than one service
Siumauricio Nov 11, 2026
68c8730
Merge pull request #5906 from Dokploy/fix/schedule-appname-injection
narcisonunez Nov 11, 2026
1c2c7e4
Merge pull request #5912 from Dokploy/fix/compose-path-injection
narcisonunez Nov 11, 2026
0022b72
Merge pull request #5918 from Dokploy/fix/domain-path-traefik-rule
narcisonunez Nov 11, 2026
f2b31b1
Merge pull request #5928 from Dokploy/fix/stats-ws-appname
narcisonunez Nov 11, 2026
4b4a155
Merge pull request #5965 from Dokploy/fix/notification-ssrf
narcisonunez Nov 11, 2026
e2eefdf
Merge pull request #5911 from Dokploy/fix/application-build-field-inj…
narcisonunez Nov 11, 2026
5aaa1f1
Merge pull request #5929 from Dokploy/fix/volume-backup-ownership
Siumauricio Nov 11, 2026
21413f8
fix(profile): enforce minimum password length on profile update
DevChiniwala Nov 11, 2026
c99409f
Merge pull request #5969 from DevChiniwala/fix/profile-password-min-l…
Siumauricio Nov 11, 2026
e431fcf
fix(security): let members use bind mounts except on sensitive host p…
Siumauricio Nov 11, 2026
c35669b
Merge remote-tracking branch 'origin/canary' into fix/bind-mount-member
Siumauricio Nov 11, 2026
6e0d38a
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 11, 2026
5381a29
Merge pull request #5927 from Dokploy/fix/service-credential-ids-cros…
narcisonunez Nov 11, 2026
0b93b93
Merge pull request #5926 from Dokploy/fix/vault-mask-endpoint
narcisonunez Nov 11, 2026
5f34d05
Merge pull request #5922 from Dokploy/fix/ssh-key-private-key-leak
narcisonunez Nov 11, 2026
80d1994
Merge pull request #5909 from Dokploy/fix/volume-backup-injection
narcisonunez Nov 11, 2026
b24006e
Merge pull request #5908 from Dokploy/fix/backup-command-injection
narcisonunez Nov 11, 2026
e68a211
bump version to v0.31.1 in package.json
Siumauricio Nov 12, 2026
e64bbdb
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 12, 2026
3ca092b
remove unused import of shell-quote from deployment.ts
Siumauricio Nov 12, 2026
a6c40ce
fix(server): remove duplicate shell-quote import in deployment service
EgerDev Nov 12, 2026
9645c15
Merge pull request #5971 from EgerDev/fix/deployment-duplicate-quote-…
Siumauricio Nov 12, 2026
0f93883
fix(security): disable better-auth's native api-key create/update end…
Siumauricio Nov 12, 2026
8f71360
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 12, 2026
3068240
Merge pull request #5972 from Dokploy/fix/api-key-native-endpoints
Siumauricio Nov 12, 2026
8cc0795
Merge pull request #5970 from Dokploy/feat/new-version
Siumauricio Nov 12, 2026
1be177a
fix(security): only fetch metrics from the organization's monitoring …
Siumauricio Nov 12, 2026
93969ff
fix(security): guard AI provider requests against SSRF
Siumauricio Nov 12, 2026
2fcd7a9
fix(security): refuse file mount and patch writes that escape through…
Siumauricio Nov 12, 2026
d4dc6f8
fix(security): restrict GitLab/Gitea OAuth connect to provider editor…
Siumauricio Nov 12, 2026
cf88d45
fix: pass a typed session to canViewGitProviderSecrets
Siumauricio Nov 12, 2026
00c22e3
fix(security): require service access to read application monitoring …
Siumauricio Nov 12, 2026
196aa84
fix(security): scope host schedule reads and the deployment queue to …
Siumauricio Nov 12, 2026
cb17f1a
fix(security): refuse changing the profile email to one with a pendin…
Siumauricio Nov 12, 2026
74ea4f7
Merge canary
Siumauricio Nov 12, 2026
c43a628
fix(security): members can't attach a Docker volume that already exis…
Siumauricio Nov 12, 2026
9e9552d
fix: send Gitea connect through the authorize route and bind OAuth st…
Siumauricio Nov 12, 2026
c18c08a
fix: surface the blocked-endpoint error from guardedFetch
Siumauricio Nov 12, 2026
e326466
fix: check for symlink escapes before creating directories
Siumauricio Nov 12, 2026
4ccb8f5
fix: match monitoring containers by ownership instead of name prefix
Siumauricio Nov 12, 2026
ecd43c4
fix: ignore expired invitations when checking an email change
Siumauricio Nov 12, 2026
283f5d5
fix: start the GitLab OAuth flow from a server route that sets the st…
Siumauricio Nov 12, 2026
83ee8ea
Merge pull request #5980 from Dokploy/fix/host-schedule-read-access
Siumauricio Nov 12, 2026
c021cf4
Merge pull request #5977 from Dokploy/fix/symlink-escape
Siumauricio Nov 12, 2026
dcac780
Merge pull request #5978 from Dokploy/fix/git-oauth-callback-access
Siumauricio Nov 12, 2026
9184861
Merge pull request #5979 from Dokploy/fix/app-monitoring-access
Siumauricio Nov 12, 2026
24e0689
Merge pull request #5976 from Dokploy/fix/ai-sdk-ssrf
Siumauricio Nov 12, 2026
1f86abd
Merge pull request #5975 from Dokploy/fix/metrics-ssrf
Siumauricio Nov 12, 2026
a62f29a
Merge pull request #5981 from Dokploy/fix/email-change-pending-invita…
Siumauricio Nov 12, 2026
310c163
Merge pull request #5982 from Dokploy/fix/member-existing-volume-mount
Siumauricio Nov 12, 2026
68dd5fa
Merge pull request #5973 from Dokploy/canary
Siumauricio Nov 12, 2026
b572ec9
feat(servers): connect a server by running one command
narcisonunez Nov 12, 2026
d00ac8a
fix(servers): drop cancelConnectCommand
narcisonunez Nov 12, 2026
64d5a1f
feat: export and import projects between Dokploy instances (#5690)
narcisonunez Nov 12, 2026
d83c7d7
fix(deps): bump fast-xml-parser to 5.12.0
narcisonunez Nov 12, 2026
29477c2
fix(deps): bump fast-xml-parser to 5.12.0 (#5993)
narcisonunez Nov 12, 2026
e193834
feat(servers): connect a server by running one command (#5989)
narcisonunez Nov 12, 2026
879d5c7
fix(previews): limit application columns when closing a PR to avoid p…
Siumauricio Nov 12, 2026
f4bf120
Merge pull request #5995 from Dokploy/fix/preview-close-100-arg-limit
narcisonunez Nov 12, 2026
a9e14cd
fix(auth): add impersonation check for admin users
Siumauricio Nov 12, 2026
9157961
fix: bump version to v0.31.2
Siumauricio Nov 12, 2026
f403682
feat(api-keys): enforce a default rate limit on cloud API keys
Siumauricio Nov 12, 2026
6fab064
fix(auth): enhance rate limiting logic and improve admin user checks
Siumauricio Nov 12, 2026
656c00a
Merge pull request #5998 from Dokploy/fix/impersonation-admin-takeover
narcisonunez Nov 12, 2026
a16cf89
Merge pull request #5999 from Dokploy/canary
narcisonunez Nov 12, 2026
1862048
chore: merge upstream Dokploy v0.31.2
agentHits Nov 16, 2026
b91d8b7
fix(sync): lint, lockfile and destination test after the v0.31.2 merge
agentHits Nov 16, 2026
119c00c
test(sync): adapt tests to the v0.31.2 merge
agentHits Nov 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Build commands in `services/application.ts` and `services/compose.ts` go through

## Deployment logs

A deployment's log stays where it was written. Reads and single removals find that place through `getDeploymentLogServerId` (`packages/server/src/utils/deployments/log-server.ts`): the row's build server, otherwise the owning service's server, otherwise the panel. `deployment.serverId` is the exception: it marks a server's setup or hardening run, whose log the panel keeps on its own disk, so nothing connects to that server for it and `getAccessibleServerIds` is the only organization check on reading it. Deleting an application cascades to its deployment rows before `removeDeployments` runs, so past build servers come from the rows loaded with the application. `removeDeployment` keeps the row when the log could not be removed, so the removal can be repeated. The rotation of old deployments drops the row anyway and opens one connection per server, so a dead server neither stops a new deployment nor delays later ones again.
A deployment's log stays where it was written. Reads and single removals find that place through `getDeploymentLogServerId` (`packages/server/src/utils/deployments/log-server.ts`): the row's build server, otherwise the owning service's server, otherwise the panel. `deployment.serverId` is the exception: it marks a server's setup or hardening run, whose log the panel keeps on its own disk, so nothing connects to that server for it. Reading, killing or removing a deployment that belongs to no service (such a run, or a run of a host schedule) needs an owner or admin, besides `getAccessibleServerIds` (taken from upstream v0.31.1). Deleting an application cascades to its deployment rows before `removeDeployments` runs, so past build servers come from the rows loaded with the application. `removeDeployment` keeps the row when the log could not be removed, so the removal can be repeated. The rotation of old deployments drops the row anyway and opens one connection per server, so a dead server neither stops a new deployment nor delays later ones again.

## libSQL replicas

Expand Down Expand Up @@ -48,6 +48,8 @@ The panel's password change (`changeRedisPassword`, `utils/databases/redis-passw

The Server Security dialog (`routers/server-security.ts`, `services/server-security.ts`) runs root commands over SSH on remote servers, and its writes need `server:create`; the fork's Apply hardening button lives in that dialog now. `banFail2banIp` refuses the panel's address only when `webServerSettings.serverIp` is set and matches, so a panel that reaches the server from another address can still ban itself. `togglePanelPort` publishes or removes port 3000 on the panel's service, and the fork's update path has not been checked against a removed port. PostHog code stays, but `getPostHogKey` returns null unless `IS_CLOUD`, so a self-hosted panel contacts nobody. Upstream's Bitbucket watch paths are reachable only with a service Deploy Webhook Secret: `isProviderDeployWebhookAuthenticated` refuses every Bitbucket webhook without one, so upstream's `bitbucket-watch-paths.test.ts` is left out. Upstream's 3 s task loop in `mechanizeDockerContainer` is left out too, because `waitForApplicationRollout` covers it with a limit on each read.

Two features came with v0.31.2. Project export and import (`routers/project-export-import.ts`, `services/project-export-import/`) is open to owners and admins; the bundle holds every secret of the project, encrypted with a passphrase the caller picks, so `api-key-output-guard.ts` refuses `projectExportImport.export` to API keys like the reveal procedures, or a key's holder could decrypt the bundle offline. Connecting a server by one command (`services/server-connect.ts`, `pages/api/connect/[token].ts`) hands out `curl .../api/connect/<token> | sudo bash`: the token is an HMAC keyed with the SSH key's private key and lives one hour, and the script adds the panel's public key to root's `authorized_keys` and registers the address the request came from. A panel behind an IP allowlist answers the new server only if that server's address is allowed.

Deploy webhooks (`pages/api/deploy/[refreshToken].ts`, `compose/[refreshToken].ts`) turn Next's body parser off and read the body themselves (`readDeployWebhookBody`), so a signature is checked against the bytes the provider signed: Gitea marshals its JSON in Go, and `JSON.stringify` of the parsed body is a different text. A request with a provider event header must carry that provider's proof: GitHub `X-Hub-Signature-256` with the GitHub App's webhook secret, GitLab `X-Gitlab-Token` equal to the provider's Deploy Webhook Secret (`webhookSecret`; the OAuth `secret` is accepted only while no webhook secret is set, as before), Gitea `X-Gitea-Signature` (HMAC-SHA256 hex of the raw body) with the new Deploy Webhook Secret of the Gitea provider (`gitea.webhook_secret`, migration 0217, set in the provider dialog and the Secret field of the Gitea webhook). Applications and composes of source type Custom Git have no provider row, and Bitbucket and Soft Serve have no panel-side credentials, so they use the service's own Deploy Webhook Secret (`webhookSecret` on `application` and `compose`, `encryptedText`, migration 0218, generated in the Deployments tab next to the webhook URL): without one their provider-header requests stay refused with 401, which was a deliberate part of the hardening (a token holder could otherwise forge a branch with headers). With one, `isServiceSecretValid` checks the proof of the provider the event header names: Bitbucket Cloud and Data Center `X-Hub-Signature` = `sha256=<hex HMAC of the raw body>` (Data Center event `repo:refs_changed`, branch from `changes[].ref.displayId`; Cloud `repo:push`, `push.changes[].new.name`), Soft Serve `X-SoftServe-Signature` = `sha256=<hex HMAC>` (header and algorithm read from soft-serve's `pkg/webhook`), and for Custom Git also GitHub-style `X-Hub-Signature-256`, GitLab-style `X-Gitlab-Token` equal to the secret, Gitea/Forgejo `X-Gitea-Signature` (or their GitHub-compatible `X-Hub-Signature-256`), so mirrors on self-hosted GitHub/GitLab/Gitea/Forgejo work. A source of type Bitbucket uses the service secret as well; GitHub, GitLab and Gitea sources keep their provider secrets. The secret is read like the webhook token: `application.revealWebhookSecret` / `compose.revealWebhookSecret` (browser session only, `deployment: create`, audit `reveal`), `regenerateWebhookSecret` (browser session, `service: create`, returns the new value once) and `removeWebhookSecret`; `application.one` / `compose.one` answer it redacted, update schemas omit it and duplicating a project does not copy it. `__test__/deploy/service-webhook-secret.test.ts` covers it. A real Soft Serve (`ghcr.io/charmbracelet/soft-serve`, same image as `charmbracelet/soft-serve`) pushing to the real handler under Bun was checked on 2026-11-08: `ssh <host> repo webhook create <repo> <url> -e push -s <secret>`; Soft Serve refuses webhook URLs on private, loopback and TEST-NET addresses (`pkg/ssrf`), so a local test needs a public-range address assigned to the test box's `lo`. Bitbucket has only been checked with payloads and signatures built per Atlassian's docs. Gitea and Forgejo also send `X-GitHub-Event` and `X-Hub-Signature-256` for GitHub compatibility, so `getProviderByHeader` checks GitHub's header last; with it first, every real Gitea push was read as GitHub and refused with 401 (found with a real Gitea 1.24 on 2026-11-08). A request with no provider header skips the check as before, and for Git sources it ends in 301 "Branch Not Match: the request has no Git provider event header", since the branch is read from the header. `__test__/deploy/gitea-webhook-signature.test.ts` covers it.

`application.one` and `compose.one` return `refreshToken` as `__DOKPLOY_REDACTED_SECRET__`, so the Deployments tab showed and copied `/api/deploy/__DOKPLOY_REDACTED_SECRET__` (found 2026-11-08). It now shows the URL with dots and, on the first click (copy), calls `application.revealWebhookToken` or `compose.revealWebhookToken`: browser session only (`api-key-output-guard.ts` refuses API keys), the `deployment: create` permission on that service, and a `reveal` audit entry. Regenerating the token forgets the answer. `__test__/components/webhook-url-reveal.test.ts` guards it.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ Dokploy includes multiple features to make your life easier.
- **Backups**: Automate backups for databases to an external storage destination.
- **Docker Compose**: Native support for Docker Compose to manage complex applications.
- **Multi Node**: Scale applications to multiple nodes using Docker Swarm to manage the cluster.
- **Templates**: Deploy open-source templates (Plausible, Pocketbase, Calcom, etc.) with a single click.
- **Templates**: Deploy open-source templates (Plausible, Pocketbase, Calcom, etc.) with a single click +600 Templates.
- **Traefik Integration**: Automatically integrates with Traefik for routing and load balancing.
- **Real-time Monitoring**: Monitor CPU, memory, storage, and network usage for every resource.
- **Logs & Metrics**: Ship container logs and host/container metrics to Grafana (Loki, Prometheus/Mimir), Datadog, New Relic, InfluxDB, VictoriaMetrics, Better Stack, Elasticsearch/OpenSearch, Splunk, or AWS CloudWatch, tagged by project/environment/application.
Expand Down
11 changes: 10 additions & 1 deletion apps/api/src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { timingSafeEqual } from "node:crypto";

export const isValidApiKey = (
configuredKey: string | undefined,
authHeader: string | undefined,
Expand All @@ -6,6 +8,13 @@ export const isValidApiKey = (
typeof configuredKey === "string" && configuredKey.trim().length > 0;
const hasAuthHeader =
typeof authHeader === "string" && authHeader.trim().length > 0;
if (!hasConfiguredKey || !hasAuthHeader) {
return false;
}

return hasConfiguredKey && hasAuthHeader && configuredKey === authHeader;
const expected = Buffer.from(configuredKey);
const received = Buffer.from(authHeader);
return (
expected.length === received.length && timingSafeEqual(expected, received)
);
};
6 changes: 6 additions & 0 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,12 @@ export const deploymentFunction = inngest.createFunction(
},
);

if (!process.env.API_KEY) {
console.error(
"API_KEY is not set; all authenticated routes will be rejected",
);
}

app.use(async (c, next) => {
if (c.req.path === "/health" || c.req.path === "/api/inngest") {
return next();
Expand Down
1 change: 1 addition & 0 deletions apps/dokploy/__test__/application/provider-status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ vi.mock("@dokploy/server/index", async (importOriginal) => {
IS_CLOUD: true,
hasValidLicense: vi.fn(async () => false),
updateApplication: mockUpdateApplication,
assertServiceCredentialAccess: vi.fn(async () => {}),
findApplicationById: vi.fn(async () => ({
applicationId: "app-1",
appName: "example-app",
Expand Down
52 changes: 39 additions & 13 deletions apps/dokploy/__test__/auth/api-key-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,14 @@ const { organization } = await import("better-auth/plugins");
const drizzleAdapterOptions = vi.mocked(drizzleAdapter).mock.calls[0]?.[1];
const organizationOptions = vi.mocked(organization).mock.calls[0]?.[0];

const apiKeyRequest = {
headers: {
"x-api-key": "dokploy-test-key",
},
} as unknown as IncomingMessage;
// validateRequest keeps its answer per request object, so every case needs
// its own request.
const apiKeyRequest = () =>
({
headers: {
"x-api-key": "dokploy-test-key",
},
}) as unknown as IncomingMessage;

const userRecord = {
id: "user-1",
Expand Down Expand Up @@ -180,7 +183,7 @@ describe("validateRequest API key sessions", () => {
});
mocks.checkPermission.mockRejectedValue(new Error("Permission denied"));

await expect(validateRequest(apiKeyRequest)).resolves.toEqual({
await expect(validateRequest(apiKeyRequest())).resolves.toEqual({
session: null,
user: null,
});
Expand All @@ -189,7 +192,7 @@ describe("validateRequest API key sessions", () => {
it("rejects API key metadata for an organization the key owner is not a member of", async () => {
mocks.memberFindFirst.mockResolvedValue(undefined);

await expect(validateRequest(apiKeyRequest)).resolves.toEqual({
await expect(validateRequest(apiKeyRequest())).resolves.toEqual({
session: null,
user: null,
});
Expand All @@ -203,7 +206,7 @@ describe("validateRequest API key sessions", () => {
},
});

await expect(validateRequest(apiKeyRequest)).resolves.toMatchObject({
await expect(validateRequest(apiKeyRequest())).resolves.toMatchObject({
session: {
userId: "user-1",
activeOrganizationId: "org-1",
Expand All @@ -222,12 +225,35 @@ describe("validateRequest API key sessions", () => {
{ api: ["read"] },
);
});

it("verifies the API key once when the same request is validated twice", async () => {
mocks.memberFindFirst.mockResolvedValue({
role: "owner",
organization: {
ownerId: "user-1",
},
});
const request = apiKeyRequest();

const first = await validateRequest(request);
const second = await validateRequest(request);

expect(second).toBe(first);
expect(first).toMatchObject({
session: { userId: "user-1", activeOrganizationId: "org-1" },
});
expect(mocks.verifyApiKey).toHaveBeenCalledTimes(1);

await validateRequest(apiKeyRequest());
expect(mocks.verifyApiKey).toHaveBeenCalledTimes(2);
});
});

describe("validateRequest cookie sessions", () => {
const cookieRequest = {
headers: { cookie: "better-auth.session_token=token" },
} as unknown as IncomingMessage;
const cookieRequest = () =>
({
headers: { cookie: "better-auth.session_token=token" },
}) as unknown as IncomingMessage;

beforeEach(() => {
vi.clearAllMocks();
Expand All @@ -248,7 +274,7 @@ describe("validateRequest cookie sessions", () => {
user: { enableEnterpriseFeatures: true, isValidEnterpriseLicense: true },
});

await expect(validateRequest(cookieRequest)).resolves.toMatchObject({
await expect(validateRequest(cookieRequest())).resolves.toMatchObject({
session: { id: "session-1", activeOrganizationId: "org-1" },
user: {
id: "user-1",
Expand All @@ -263,7 +289,7 @@ describe("validateRequest cookie sessions", () => {
it("falls back to the user itself when there is no membership", async () => {
mocks.memberFindFirst.mockResolvedValue(undefined);

await expect(validateRequest(cookieRequest)).resolves.toMatchObject({
await expect(validateRequest(cookieRequest())).resolves.toMatchObject({
session: { activeOrganizationId: "" },
user: {
id: "user-1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ const caller = backupRouter.createCaller({
user: { id: "user-1", email: "user@example.com", role: "owner" },
} as Parameters<typeof backupRouter.createCaller>[0]);

const callerAs = (role: string) =>
backupRouter.createCaller({
session: { activeOrganizationId: "org-a" },
user: { id: "user-1", email: "user@example.com", role },
} as Parameters<typeof backupRouter.createCaller>[0]);

const ownDestination = { destinationId: "dest-a", organizationId: "org-a" };
const foreignDestination = { destinationId: "dest-b", organizationId: "org-b" };

Expand Down Expand Up @@ -113,6 +119,13 @@ const restoreInput = {
backupFile: "app/2024.sql.gz",
};

const postgresSchedule = {
appName: "app",
prefix: "/",
postgres: { appName: "app" },
};
const webServerSchedule = { appName: "panel", prefix: "/" };

const drain = async (stream: unknown) => {
for await (const _ of stream as AsyncIterable<string>) {
}
Expand All @@ -130,11 +143,12 @@ describe("backup endpoints scope destinations to the active organization", () =>
databaseType: "postgres",
backupType: "database",
});
mocks.findPostgresById.mockResolvedValue({ postgresId: "pg-1" });
mocks.findPostgresById.mockResolvedValue({
postgresId: "pg-1",
appName: "app",
});
// The fork only restores objects under a schedule of the same database.
mocks.findRestoreBackups.mockResolvedValue([
{ appName: "app", prefix: "/", postgres: { appName: "app" } },
]);
mocks.findRestoreBackups.mockResolvedValue([postgresSchedule]);
});

it("rejects creating a backup on a destination from another organization", async () => {
Expand Down Expand Up @@ -193,9 +207,7 @@ describe("backup endpoints scope destinations to the active organization", () =>
expect(mocks.restorePostgresBackup).toHaveBeenCalledTimes(1);
});

// Upstream leaves service-less web-server schedules unscoped; the fork
// scopes their destination like every other schedule.
it("rejects web-server schedules on a destination from another organization", async () => {
it("rejects a service-less web-server schedule on a foreign destination", async () => {
mocks.findDestinationRow.mockResolvedValue(foreignDestination);

await expect(
Expand All @@ -211,3 +223,74 @@ describe("backup endpoints scope destinations to the active organization", () =>
expect(mocks.createBackup).not.toHaveBeenCalled();
});
});

describe("restore access by role", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.findPostgresById.mockResolvedValue({
postgresId: "pg-1",
appName: "app",
});
});

// Web-server backups live under the schedule's appName folder, and the fork
// restores only objects under a schedule on that destination.
const webServerRestore = {
databaseId: "",
databaseType: "web-server" as const,
backupType: "database" as const,
databaseName: "panel",
backupFile: "panel/panel.zip",
destinationId: "dest-a",
};

for (const role of ["owner", "admin"]) {
it(`${role} can run a web-server restore`, async () => {
mocks.findDestinationRow.mockResolvedValue(ownDestination);
mocks.findRestoreBackups.mockResolvedValue([webServerSchedule]);
const stream =
await callerAs(role).restoreBackupWithLogs(webServerRestore);
await drain(stream);
expect(mocks.restoreWebServerBackup).toHaveBeenCalledTimes(1);
});
}

it("a member cannot run a web-server restore (panel wipe)", async () => {
mocks.findDestinationRow.mockResolvedValue(ownDestination);
mocks.findRestoreBackups.mockResolvedValue([webServerSchedule]);
const stream =
await callerAs("member").restoreBackupWithLogs(webServerRestore);
await expect(drain(stream)).rejects.toMatchObject({ code: "UNAUTHORIZED" });
expect(mocks.restoreWebServerBackup).not.toHaveBeenCalled();
});

it("a member with service access can still restore its own database", async () => {
mocks.findDestinationRow.mockResolvedValue(ownDestination);
mocks.findRestoreBackups.mockResolvedValue([postgresSchedule]);
const stream = await callerAs("member").restoreBackupWithLogs({
...restoreInput,
destinationId: "dest-a",
});
await drain(stream);
expect(mocks.restorePostgresBackup).toHaveBeenCalledTimes(1);
});

it("refuses a backup file outside the target service's folder", async () => {
mocks.findDestinationRow.mockResolvedValue(ownDestination);
mocks.findRestoreBackups.mockResolvedValue([postgresSchedule]);
mocks.findPostgresById.mockResolvedValue({
postgresId: "pg-1",
appName: "other",
});
const stream = await callerAs("member").restoreBackupWithLogs({
...restoreInput,
destinationId: "dest-a",
});
await expect(drain(stream)).rejects.toMatchObject({
message: expect.stringContaining(
"Backup file does not belong to this service",
),
});
expect(mocks.restorePostgresBackup).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ vi.mock("@dokploy/server", async (importOriginal) => ({
removeVolumeBackup: vi.fn(),
restoreVolume: vi.fn(),
runVolumeBackup: vi.fn(),
assertVolumeBelongsToService: vi.fn(async () => {}),
}));

vi.mock("@dokploy/server/lib/auth", () => ({
Expand Down
Loading
Loading