Dify security hardening

Hardening a self-hosted Dify means deciding where secrets live, how outbound requests and code execution are contained, and how model credentials and backups are handled. This page sets out those decisions, the build order and how to verify the result.

On this page

Why Dify security hardening starts before the first user signs in

Hardening a self-hosted Dify is a set of configuration decisions made at deployment, followed by verification and operations after go-live. A security or platform team asked to put Dify in front of staff or customers should treat the first deployment as the point where secrets, outbound calls and code execution are fixed in place, because changing some of them later is disruptive. Hardening is not a checklist you finish once the containers start.

The difficulty comes from how much sits in one stack. Dify combines a web console, workflow nodes that run code, outbound calls to model providers and external tools, and stored credentials for those providers, all reachable through the same administrative interface. A single misconfigured key, an unrestricted outbound path or a weak console account can expose more than one component. The Community edition is limited to a single workspace, and several controls such as SSO, multiple workspaces and advanced security depend on the edition you run. Confirm which features apply to your edition against the current Dify environment variable reference and the pricing page before you design around them.

The Docker Compose stack includes Nginx, a code sandbox and an SSRF proxy, which address real risks. Those defaults still need to be checked, not assumed. Confirm that the sandbox and proxy are running and wired in as you expect, that outbound requests are routed as intended, that SECRET_KEY was set to a value you generated rather than an example, and that the console is not exposed without TLS. Record each check so the next upgrade or infrastructure change can be tested against the same list.

Which Dify components hold secrets or reach outward

A self-hosted Dify stack holds credentials, signs sessions and makes outbound calls on behalf of workflows and agents. Each component below protects a different boundary, so each needs its own configuration check before go-live.

SECRET_KEY

The SECRET_KEY signs session cookies and JWTs and encrypts OAuth credentials stored by Dify. Generate it once, store it in your secrets manager, and keep it out of shared configuration files. Changing it after deployment logs out every user, so plan the value before the first users sign in. If it leaks, anyone holding it can forge sessions, so confirm who can read the .env file on each host.

Environment variable reference

Code execution sandbox

The code execution sandbox runs code nodes in workflows and renders Jinja2 templates in a restricted environment. It is the component that turns user-supplied or workflow-authored code into running code, so treat any change to its settings as a security change. Confirm that the sandbox container is running in the Compose stack, that workflow editors are limited to trusted builders, and that the 1.16.1 sandboxed Jinja2 rendering is present in your version.

SSRF proxy

The SSRF proxy routes outbound HTTP requests from Dify through a proxy that blocks internal and private IP ranges, which limits how a workflow or tool can be pointed at your internal services or cloud metadata endpoints. Set the SSRF_PROXY settings deliberately and test them with a request to a private address. A disabled or bypassed proxy lets any HTTP node reach hosts on your internal network.

Agent sandbox network isolation

Release 1.16.1 added network isolation for the agent sandbox through a Squid proxy, which controls where agent-run code can connect. Without it, an agent that is manipulated through prompt injection could reach internal systems or send data to external hosts. Verify the proxy is active after each upgrade, then test whether an agent can reach an internal address or an unapproved external domain.

Dify releases on GitHub

Workspace encryption keys

Workspace encryption keys protect data that Dify encrypts per workspace, and they can be stored on the local host or in Azure Key Vault. Local storage ties key custody to the same host as the database, so a copy of the host can expose both. Ask who owns the Key Vault, how access is granted and audited, and how keys are rotated and recovered if the vault becomes unavailable.

Model provider credentials and Nginx TLS

Model provider API keys are stored in Dify and are the most valuable secrets it holds, since they bill your account and can expose prompts sent to hosted models. Export and backup files do not include third-party API keys, so each restored environment needs keys re-entered and rotated. Nginx is the public entry point, so terminate TLS there with a certificate you manage and confirm that plain HTTP is redirected or closed.

Which hardening choices fit your environment and what each one costs you

This table compares four hardening decisions for a self-hosted Dify, showing when each option fits and what it asks of your operations team. Read each row as a trade-off: the stricter option usually buys tighter control at the price of ongoing maintenance and a new dependency.

DecisionWhen it fitsWhat it costs operationally
Workspace encryption keys stored locallyTeams without an existing Azure key management process, or deployments outside Azure where Key Vault is not an optionKeys sit alongside the application host, so host access controls, backup handling and key recovery procedures must be documented and tested by your team
Workspace encryption keys stored in Azure Key VaultTeams that already run Azure key management and want key access governed by the same policies and reviewsIdentity setup for the Dify service, access policy design, and a dependency on Key Vault availability that your runbooks must cover
Outbound traffic through the SSRF proxy onlyDeployments where model endpoints and tools are few, stable and reachable through the proxy's default rulesLower upkeep, but the proxy blocks internal and private IP ranges, so integrations on private addresses need a deliberate exception path
Specific destinations added to an allow-list by your teamDeployments with many model endpoints, internal APIs or tools that must be reached on a defined scheduleA maintained list of destinations that needs an owner, change review and periodic removal of endpoints no longer in use
Agent code execution and outbound access kept inside the Squid-proxied sandboxTeams that need workflow code nodes and agent tools and can accept proxy-mediated network pathsSandbox behavior must be tested after each upgrade, and failed tool calls often trace back to proxy rules that need review
Agent features that need sandbox or outbound access disabledUse cases that do not need code execution or external tool calls, and where risk tolerance is lowReduced functionality for app builders, plus a policy decision on which features are switched off and who can request exceptions
Model credentials managed in the Dify consoleSmall teams with few providers and a clear admin group that can access the consoleCredentials live in the application database, so access reviews, rotation and backup scope must be part of your operating procedures
Model credentials injected from an external secret store at deploymentOrganizations with an existing secret manager and a requirement to keep third-party keys out of the applicationDeployment pipelines must handle injection and rotation, and exports exclude third-party API keys, so re-entry steps must be planned

How to build a hardened Dify deployment in sequence

This sequence takes a self-hosted Dify from a first start with a unique secret and a locked-down network path to a deployment with verified outbound controls, TLS, key handling, credential hygiene and tested backups. Each step ends with a check you can record as evidence.

  1. Generate and store SECRET_KEY outside the repository

    Before the first start, generate a unique SECRET_KEY for this installation and place it in the deployment's environment file or secret store, not in the code or in any copied sample value. SECRET_KEY signs session cookies and JWTs and encrypts OAuth credentials, and changing it after deployment logs out all users, so record where it is kept and who can read it. Confirm the value is excluded from version control by checking the repository's ignore rules and searching the committed history for the key. The step is complete when the search returns no match and the key is held in your approved secret location.

  2. Review .env settings against .env.example

    Compare your working environment file with the .env.example shipped for the exact release you are deploying, not with an older copy. Remove or replace any default passwords for PostgreSQL, Redis and other services, and note every variable that is new or changed since your last version. The Dify Docker Compose documentation advises checking .env.example after upgrades, so keep this comparison in the change record. The check is a written list of each changed setting with its owner, and a scan showing no default credentials remain.

  3. Configure SSRF proxy and test private address blocking

    Set the SSRF_PROXY settings so outbound requests from Dify pass through the bundled proxy, which blocks internal and private IP ranges. From the api or worker container, attempt a request to an internal address such as a private RFC 1918 host and a loopback address, using an HTTP tool node or equivalent test. Repeat with a public test endpoint you control to confirm legitimate egress still works. The step closes when the private address requests fail at the proxy and the public request succeeds, and both results are saved with the release version.

  4. Confirm sandbox and agent network isolation on your version

    Verify that the code execution sandbox is running and that agent network isolation is active. The Dify 1.16.1 release notes describe agent sandbox network isolation through a Squid proxy, token-based authentication between services and sandboxed Jinja2 template rendering, so confirm these changes are present in the version you run and check the release notes for any later changes. Run a test code node that attempts an outbound connection and a file read outside its working area, and confirm both are refused. Record the version, the test code and the results. Ask your vendor or DeployOpen to confirm any sandbox behavior not covered by these release notes.

  5. Place Nginx behind TLS and close plain HTTP

    Terminate TLS at Nginx using certificates issued and renewed through your standard certificate process, and keep private keys in the location your policy requires. Configure the HTTP listener to redirect to HTTPS or to refuse connections, and make sure the web and API routes are served only over the encrypted listener. Confirm the TLS configuration with an external scanner approved by your security team. The check is a plain HTTP request that returns a redirect or no response, and a TLS test that shows the expected certificate chain and protocol versions.

  6. Decide workspace encryption key location and access

    Choose where workspace encryption keys are stored: locally on the host or in Azure Key Vault. Local storage keeps the key with the deployment and places the burden of host protection and backup on your team. Azure Key Vault moves key custody to a managed service, but requires that the service identity used by Dify has the access policies it needs and no broader rights. If Azure Key Vault is chosen, confirm the identity can read and use the key and that other identities cannot. The step closes when a test read from the approved identity succeeds, a read from any other identity is denied, and the decision is documented with its owner.

  7. Load model credentials and verify DSL exports exclude them

    Enter model provider credentials through the method your policy approves, such as environment-level configuration or the console with restricted access, and avoid pasting keys into prompts or workflow notes. Export a test app as YAML DSL and open the file to confirm it contains no third-party API keys. Dify documents that exports include app configuration, workflow nodes, model parameters, prompts and knowledge base connections, but not third-party API keys. The check is a DSL file with no key strings, which you should also confirm with a text search for the key prefix used by each provider.

  8. Restrict console access and test backups before go-live

    Limit console and administrator accounts to named people with the minimum roles needed, remove unused accounts, and place the console behind your identity controls or network restrictions. Then back up the metadata database and file storage, and perform a test restore into a separate environment to confirm the data and the SECRET_KEY needed to read encrypted values are both recoverable. Dify recommends a backup before every upgrade, so schedule backups with the same discipline. The step closes when the restored environment starts, a test user can sign in with a restricted role, and the restore is recorded with its date and version.

How hardening differs between Compose and Enterprise Kubernetes

The Community edition runs as a Docker Compose stack on a single host, with the api, worker, web, plugin daemon, PostgreSQL, Redis, Weaviate, Nginx, a code sandbox and an SSRF proxy defined in one project. Most hardening settings live in the .env file that accompanies the stack, so your team edits configuration values and restarts services rather than configuring a platform layer. Responsibility for TLS, host firewalling and backups sits with your operators.

  • SECRET_KEY handling: Generate a strong value before first start and store it in your secrets process, since changing it after deployment logs out all users.
  • Proxy and egress rules: Confirm the SSRF_PROXY settings are in place and add host firewall rules so only the model endpoints you approve are reachable.
  • TLS at the host: Terminate TLS in front of the Nginx container, with certificates and renewal managed by your team.
  • Backups: Back up PostgreSQL, the storage volumes and the .env file on a schedule you control, and test restores.
  • Upgrade discipline: Take a backup before each upgrade and compare your .env against .env.example for new variables.

Before go-live, check the current stack and variables against the Compose deployment guide and the environment variable reference, since defaults and variable names change between releases.

What breaks when SECRET_KEY or encryption keys change or go missing

SECRET_KEY is not a password to rotate casually. In a self-hosted Dify, it signs session cookies and JWTs and encrypts OAuth credentials. The environment variable reference says that changing it after deployment logs out all users, so a change made on a whim becomes an outage for every builder and end user at once. Treat the value as set-once for the life of the instance. Before any change, confirm with the current environment variable reference what happens to credentials that are already encrypted under the old value, because that behavior determines whether a rotation is a logout event or a data recovery event. Record the value in your secrets manager with an owner and a creation date, and make sure every environment that restores this instance from backup uses the same value.

The workspace encryption key carries a different risk. The reference says workspace encryption keys can be stored locally or in Azure Key Vault. Moving the key store between those two locations, or restoring a database into an environment that points at a different store, can leave encrypted model provider credentials and other secrets unreadable even though the rows themselves restored cleanly. The failure is quiet: the application starts, but the model connections that depend on those credentials stop working. For that reason, the key material and its backup must be recorded together with the PostgreSQL backup, with the same restore point, so that a database snapshot is never separated from the key that opens it.

Put the procedure in writing and test it before you need it. A rotation or recovery runbook should name the owner, list the variables and key store entries involved, state the order of operations, and define how to verify success, such as signing in as a test user and confirming that a saved model credential still runs a request. Rehearse the full sequence, including a restore of the database and key material, in a non-production copy built from the same .env and backups. Record what the rehearsal found, and repeat it after any upgrade that touches the .env file, since the upgrade guide may add variables that interact with these keys.

What drives hardening effort and how to keep each part small

This table lists the factors that change how much work a Dify hardening project takes, why each one adds effort, and how to keep it contained. Read it as a checklist for scoping: each driver maps to a line item a partner should price in a fixed-scope quote. The main takeaway is that egress destinations, code execution paths and environment count multiply work, so fixing them early keeps the project small.

DriverWhy it adds effortHow to reduce it
Model providers and tool endpoints needing egressEach new external destination needs an SSRF proxy allow-list entry, a connectivity test and a record of why it is permitted.Limit providers to those the business approves, group tools behind one internal gateway, and document each destination in one list.
Agents and sandboxed code nodesEvery agent tool and code node is an execution path that needs review of its permissions, network reach and file access.Start with a small set of approved agents, reuse vetted workflow templates, and review new code nodes before they reach production.
Identity and key management integrationConnecting Azure Key Vault or an identity provider adds access policies, managed identity setup and rotation procedures to test.Use one key vault per environment with least-privilege roles, and agree naming and rotation rules before configuration starts.
Compliance evidence requestsAssessors often ask for documented configuration, test results and change records, which take time to collect and keep current.Ask early which controls the evidence must cover, keep configuration in version-controlled files, and capture test output as each change is made.
Number of environmentsDevelopment, test and production each need the same security settings, separate secrets such as SECRET_KEY, and their own keys and access rules.Build one parameterized configuration and promote it between environments, so differences are limited to values stored outside the code.
Size of the data set to back up and restoreA restore test must cover the metadata database, uploaded files and vector store, and larger data sets take longer to copy and verify.Scope the restore test to a representative sample, record restore time, and agree with the partner which data stores the test must include.

How to prove the controls work and that they fail safely

Each control in this hardening plan needs a test that tries to break it, not only a configuration review. Start with the outbound path. From a code node or a workflow HTTP request in the sandbox, attempt requests to loopback, RFC 1918 private ranges, link-local metadata addresses and internal service names such as the database or Redis hosts. Confirm each request is refused through the SSRF proxy, and confirm the same attempts fail from an agent tool call. Repeat the test after every upgrade, because the proxy and sandbox settings are part of the .env file that new releases can change. Also confirm that agent or code nodes cannot reach arbitrary public hosts, since the Dify 1.16.1 release notes describe sandbox network isolation through a Squid proxy and your own egress policy should match what that proxy permits.

Next, test data leaving the platform. Export a representative app as a YAML DSL file and search it for third-party API keys, tokens and connection strings. The Dify docs say exports exclude third-party API keys, knowledge base content and usage logs, so a match means something in a prompt, tool setting or variable was stored in plain text and must be moved into the credential store. Then test the edges: confirm that plain HTTP is not served on the public address, that the Nginx listener redirects or refuses port 80 traffic, and that TLS settings reject weak protocol versions. Run these checks from outside your network, not only from the host.

Finally, test recovery and failure. Restore a recent backup of the database and file storage into a separate environment with its own SECRET_KEY handling, then confirm that a sample app runs, a knowledge base returns retrieval results and a stored model credential works. Changing SECRET_KEY logs users out, so confirm the restore uses the original value or that you accept re-authentication. For key storage, simulate an unreachable Azure Key Vault or a denied lookup and confirm the service refuses to start or refuses the affected operation rather than falling back to a locally generated key. Record the results, and ask an independent security testing provider to test the Dify application and its agents against these results. DeployOpen performs that testing and documents findings, but it does not issue certifications or audit reports.

What to monitor, back up, upgrade and document after go-live

Hardening is not finished at go-live. Dify's configuration, sandbox and proxy settings, and its release cadence all change over time, so the controls need an owner, a schedule and a record. The cards below cover what the team must keep doing once the instance is running.

Back up every data store

Back up the metadata database (PostgreSQL by default), the file storage configured for uploads and knowledge base documents, and the workspace encryption key store, including any local key material or Azure Key Vault references. Restore a copy to a separate environment at least once to confirm it works. The platform team owns the schedule, and the security team should verify that the key store backup is protected as strictly as the database. Take a backup before every upgrade, as the Compose docs advise.

Compose upgrade docs

Follow each upgrade guide

Read the upgrade guide for each target version on the GitHub releases page before changing the running stack. After upgrading, compare your .env file with .env.example for new variables, since new settings may carry security defaults you need to set explicitly. Minor releases have arrived roughly monthly, so the owner should plan a recurring review rather than an occasional one.

Minor release pace
Monthly
Dify releases

Review proxy and sandbox logs

Review logs from the SSRF proxy and the code sandbox for blocked outbound requests. Repeated blocks from an agent or workflow can point to a prompt injection attempt, a misconfigured tool, or an app trying to reach internal addresses. The security operations team should set an alert threshold and decide who triages it, and confirm that log retention meets your policy.

Track admin and access changes

Record changes to workspace members, roles, model provider credentials, and app publication settings. Review who can edit apps that call external APIs or hold credentials. Compare the current list against the identity provider each quarter, and remove accounts for people who have left. The workspace administrator owns the review, and the security team should approve the list.

Log every secret rotation

Record each change to SECRET_KEY or the workspace key store with the date, the reason, the people involved, and the procedure followed. Changing SECRET_KEY after deployment logs out all users, so schedule rotations and tell users in advance. The platform owner keeps this log, and the auditor should be able to match each rotation to an approved change ticket.

Keep audit-ready records

Maintain a configuration baseline covering the deployed version, environment variables, network rules, TLS setup, and model providers. Store test results and change records with it. DeployOpen prepares these systems, controls and evidence, but independent auditors and certification bodies decide whether they meet a given standard. The compliance lead owns the file and should refresh it after each upgrade.

Questions teams ask before hardening Dify themselves or hiring help

Can our own team harden Dify without a partner?

Yes, if your team already has solid container, network and key management skills and time to test each control. The answer depends on how many controls and environments are in scope. Hardening a single Docker Compose instance touches the SECRET_KEY setting, the sandbox and SSRF proxy configuration, TLS termination, backup routines and model credential handling. Each of these needs a verification step, not just a configuration change. Multiply that by staging and production, plus any Azure Key Vault integration or network isolation for agents, and the workload grows quickly. Review the Dify environment variable reference before deciding who does the work, and make sure at least one person owns the result after go-live.

How long does a Dify hardening project take?

The duration is driven by scope, not by the Dify version. The main drivers are the number of environments, whether you use local or Azure Key Vault workspace encryption keys, how many model providers and outbound endpoints must be allowed through the proxy, how much identity and TLS work is required, and how many restore tests you need to run. Your team's access approvals and change windows also add time. We cannot give a reliable figure without knowing these inputs, so ask for a timeline in a written scope that lists each control, the environment it applies to and the acceptance test for it.

What does Dify hardening cost?

Most of the cost is people time: design, build, testing, documentation and handover. A fixed-scope engagement is priced from the written scope, so the same inputs above set the price. Ask for each cost line separately, including who performs each task. Some costs recur, such as monitoring, patching, upgrades and retesting after new releases. If you plan to run the Enterprise edition, licensing is an additional cost that is custom priced according to the Dify pricing page. Request a written quote that separates one-time work from recurring support so you can compare it with your internal estimate.

What do we need to provide before hardening starts?

You need to provide several inputs before work begins:

  • Access to the hosting account, data center host or Kubernetes cluster, with rights to change the Compose stack or Helm values.
  • Named administrators for your identity provider and for Azure Key Vault, if you use it for workspace encryption keys.
  • The list of model endpoints and outbound domains that Dify must reach, so the proxy rules can allow them without opening internal ranges.
  • Decisions on where keys live, who can rotate SECRET_KEY, and how backups are stored and restored.
  • Test accounts and a staging environment where changes can be checked before production.
Does the Community edition support the controls we need?

Confirm each control feature by feature before you assume it is available. The Community edition is free and limited to a single workspace, according to the Dify pricing page, so any requirement for multiple workspaces needs the Enterprise edition. Enterprise adds SSO, multi-workspace management and advanced security features. Check the Dify self-hosting documentation for each control you need, such as sandbox isolation, SSRF proxy behavior, TLS and backup guidance. Where the docs do not state a capability clearly, ask the Dify team or test the behavior in staging instead of relying on assumptions.

Will hardening block future Dify upgrades?

Hardening does not block upgrades, but it adds steps to each one. Dify recommends a backup before every upgrade and advises checking .env.example for new variables after upgrading. Your hardened settings, such as proxy rules, sandbox options and key storage values, may need to be reviewed against the new version. Dify ships minor releases roughly monthly, so plan for regular review. Record every custom setting in version control, test upgrades in staging first, and include a retest of the proxy and sandbox controls in each upgrade checklist.

How DeployOpen scopes, hardens, tests and hands over Dify security hardening

DeployOpen plans, implements, hardens, backs up, documents and supports self-hosted Dify inside your own cloud accounts, data centers or air-gapped networks. For security hardening, we start from your threat model and deployment shape, change the settings that matter, test the result and leave your team with evidence and runbooks they can review.

How we scope

  • We review your Dify deployment target, whether Docker Compose or Kubernetes, and which model providers and data sources are in use.
  • We agree the hardening items in writing, including SECRET_KEY handling, sandbox and SSRF proxy settings, key storage and TLS.
  • Engagements are fixed-scope, so deliverables and timelines are agreed before any configuration work starts.

How we build

  • We configure the code execution sandbox, SSRF proxy and agent network isolation, then verify outbound paths reach only approved destinations.
  • We move workspace encryption keys to your chosen store, such as Azure Key Vault, and document how rotation and access are controlled.
  • We set up TLS termination, network segmentation and tested backups of the metadata database, file storage and vector store.

How we hand over

  • You receive a written configuration baseline listing each environment variable, its value source and the reason for the setting.
  • You receive test results, a findings list with fixes applied, and a retest record showing which items now pass.
  • You receive runbooks for backup restore, secret rotation, upgrades and the checks to repeat before each Dify release.

How we support

  • Ongoing support, upgrades and continuous security testing are available as retainers after go-live.
  • We review each Dify upgrade and new .env variables against the hardening baseline before they reach production.
  • We prepare evidence for your compliance and security reviewers, but independent auditors and certification bodies issue any formal assessment.

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.