Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(e2e): share sandbox auth token across managed runtimes (#44164)

盐粒 Yanlibc00ebe1a085
diff --git a/e2e/.env.example b/e2e/.env.example
index a8df69a631a..cd14de2ed4c 100644
--- a/e2e/.env.example
+++ b/e2e/.env.example
@@ -24,8 +24,10 @@ E2E_MODEL_PROVIDER_CREDENTIALS_JSON='{"openai_api_key":"replace-with-real-key"}'
# Optional: start the standalone dify-agent backend for Agent V2 runtime scenarios.
# This is required for scenarios tagged @agent-backend-runtime. It is separate
# from @external-model because other external-model scenarios may not use dify-agent.
-# When enabled, the E2E runner also starts the shellctl local sandbox required by
-# dify-agent's dify.shell/config runtime layer.
+# When enabled, the E2E runner starts shellctl with a random token shared with
+# dify-agent for this run. E2E_SHELLCTL_AUTH_TOKEN overrides that token.
+# An explicit E2E_SHELLCTL_URL or Agent sandbox endpoint uses an existing sandbox
+# and requires its real token; the runner does not start shellctl.
# Use E2E_AGENT_BACKEND_URL only for an already-running backend; do not set it
# together with E2E_START_AGENT_BACKEND.
# E2E_START_AGENT_BACKEND=1
diff --git a/e2e/scripts/run-cucumber.ts b/e2e/scripts/run-cucumber.ts
index 4d41c262846..751ef4e6dc1 100644
--- a/e2e/scripts/run-cucumber.ts
+++ b/e2e/scripts/run-cucumber.ts
@@ -10,7 +10,12 @@ import { apiURL, baseURL, reuseExistingWebServer } from '../test-env.ts'
import { e2eDir, isMainModule, runCommand } from './common.ts'
import { parseRunOptions, shouldStartManagedAgentBackend } from './run-options.ts'
import { runSeed } from './seed-runner.ts'
-import { resetState, startMiddleware, stopMiddleware } from './setup.ts'
+import {
+ getManagedSandboxEnvironment,
+ resetState,
+ startMiddleware,
+ stopMiddleware,
+} from './setup.ts'
import './env-register.ts'
const hasCustomTags = (forwardArgs: string[]) =>
@@ -77,6 +82,7 @@ const waitForManagedProcess = async ({
export const runCucumber = async (argv: string[]) => {
const { downloadWebBuild, forwardArgs, full, headed, seed, seedOnly } = parseRunOptions(argv)
const startAgentBackendForRun = shouldStartManagedAgentBackend()
+ const sandboxEnvironment = startAgentBackendForRun ? getManagedSandboxEnvironment() : {}
const cucumberReportDir = path.join(e2eDir, 'cucumber-report')
const logDir = path.join(e2eDir, '.logs')
let apiProcess: ManagedProcess | undefined
@@ -135,11 +141,17 @@ export const runCucumber = async (argv: string[]) => {
await startMiddleware()
}
- if (startAgentBackendForRun) {
+ if (
+ startAgentBackendForRun &&
+ !process.env.DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT?.trim() &&
+ !process.env.DIFY_AGENT_SHELLCTL_ENTRYPOINT?.trim() &&
+ !process.env.E2E_SHELLCTL_URL?.trim()
+ ) {
shellctlProcess = await startLoggedProcess({
command: process.execPath,
args: ['./scripts/setup.ts', 'shellctl-sandbox'],
cwd: e2eDir,
+ env: sandboxEnvironment,
label: 'shellctl sandbox',
logFilePath: path.join(logDir, 'cucumber-shellctl-sandbox.log'),
})
@@ -149,12 +161,14 @@ export const runCucumber = async (argv: string[]) => {
managedProcess: shellctlProcess,
url: `http://127.0.0.1:${shellctlPort}/healthz`,
})
+ }
+ if (startAgentBackendForRun) {
difyAgentProcess = await startLoggedProcess({
command: process.execPath,
args: ['./scripts/setup.ts', 'agent-backend'],
cwd: e2eDir,
- env: { E2E_START_AGENT_BACKEND: '1' },
+ env: { ...sandboxEnvironment, E2E_START_AGENT_BACKEND: '1' },
label: 'agent backend',
logFilePath: path.join(logDir, 'cucumber-agent-backend.log'),
})
@@ -213,6 +227,7 @@ export const runCucumber = async (argv: string[]) => {
if (!seedOnly) {
const cucumberEnv: NodeJS.ProcessEnv = {
...process.env,
+ ...sandboxEnvironment,
CUCUMBER_HEADLESS: headed ? '0' : '1',
}
diff --git a/e2e/scripts/setup.ts b/e2e/scripts/setup.ts
index 39d282054fd..880f98a62a2 100644
--- a/e2e/scripts/setup.ts
+++ b/e2e/scripts/setup.ts
@@ -1,4 +1,4 @@
-import { createHash } from 'node:crypto'
+import { createHash, randomBytes } from 'node:crypto'
import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { waitForUrl } from '../support/process.ts'
@@ -106,9 +106,38 @@ function getAgentBackendBaseUrl() {
return undefined
}
+export const getManagedSandboxEnvironment = () => {
+ const externalSandbox =
+ process.env.DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT?.trim() ||
+ process.env.DIFY_AGENT_SHELLCTL_ENTRYPOINT?.trim() ||
+ process.env.E2E_SHELLCTL_URL?.trim()
+ const token =
+ process.env.E2E_SHELLCTL_AUTH_TOKEN ||
+ process.env.DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN ||
+ process.env.DIFY_AGENT_SHELLCTL_AUTH_TOKEN ||
+ (externalSandbox ? '' : randomBytes(32).toString('hex'))
+
+ if (!token.trim()) {
+ throw new Error(
+ 'A nonblank sandbox auth token (E2E_SHELLCTL_AUTH_TOKEN or the Agent sandbox token) is required for an existing sandbox or when explicitly configured.',
+ )
+ }
+
+ return {
+ E2E_SHELLCTL_AUTH_TOKEN: token,
+ DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN: token,
+ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: token,
+ }
+}
+
export const getAgentBackendEnvironment = async () => {
const apiEnv = await getApiEnvironment()
const redisPassword = process.env.REDIS_PASSWORD || apiEnv.REDIS_PASSWORD || 'difyai123456'
+ const sandboxToken =
+ process.env.E2E_SHELLCTL_AUTH_TOKEN ||
+ process.env.DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN ||
+ process.env.DIFY_AGENT_SHELLCTL_AUTH_TOKEN ||
+ ''
return {
DIFY_AGENT_INNER_API_KEY:
@@ -136,8 +165,8 @@ export const getAgentBackendEnvironment = async () => {
DIFY_AGENT_REDIS_PREFIX: process.env.DIFY_AGENT_REDIS_PREFIX || 'dify-agent-e2e',
DIFY_AGENT_REDIS_URL:
process.env.DIFY_AGENT_REDIS_URL || `redis://:${redisPassword}@127.0.0.1:6379/0`,
- DIFY_AGENT_SHELLCTL_AUTH_TOKEN:
- process.env.DIFY_AGENT_SHELLCTL_AUTH_TOKEN || process.env.E2E_SHELLCTL_AUTH_TOKEN || '',
+ DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN: sandboxToken,
+ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: sandboxToken,
DIFY_AGENT_SHELLCTL_ENTRYPOINT:
process.env.DIFY_AGENT_SHELLCTL_ENTRYPOINT || process.env.E2E_SHELLCTL_URL || shellctlUrl,
}
@@ -400,6 +429,8 @@ const ensureShellctlSandboxImage = async () => {
}
export const startShellctlSandbox = async () => {
+ const { E2E_SHELLCTL_AUTH_TOKEN: token } = getManagedSandboxEnvironment()
+
if (await isTcpPortReachable(shellctlHost, shellctlPort)) {
const listenerDescription = await getTcpPortListenerDescription(shellctlPort)
const listenerMessage = listenerDescription ? `\n\nPort listener:\n${listenerDescription}` : ''
@@ -428,12 +459,12 @@ export const startShellctlSandbox = async () => {
...(process.platform === 'linux' ? ['--add-host', 'host.docker.internal:host-gateway'] : []),
'-p',
`${shellctlHost}:${shellctlPort}:5004`,
- ...(process.env.E2E_SHELLCTL_AUTH_TOKEN
- ? ['-e', `SHELLCTL_AUTH_TOKEN=${process.env.E2E_SHELLCTL_AUTH_TOKEN}`]
- : []),
+ '-e',
+ 'SHELLCTL_AUTH_TOKEN',
shellctlImage,
],
cwd: rootDir,
+ env: { SHELLCTL_AUTH_TOKEN: token },
})
}
diff --git a/e2e/tests/managed-runtime-environment.test.ts b/e2e/tests/managed-runtime-environment.test.ts
index 30608d90ecd..c2a0c1242ff 100644
--- a/e2e/tests/managed-runtime-environment.test.ts
+++ b/e2e/tests/managed-runtime-environment.test.ts
@@ -1,7 +1,33 @@
-import { afterEach, describe, expect, it, vi } from 'vite-plus/test'
-import { getAgentBackendEnvironment } from '../scripts/setup.ts'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { isTcpPortReachable, runCommand, runForegroundProcess } from '../scripts/common.ts'
+import {
+ getAgentBackendEnvironment,
+ getManagedSandboxEnvironment,
+ startShellctlSandbox,
+} from '../scripts/setup.ts'
+
+vi.mock('../scripts/common.ts', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../scripts/common.ts')>()),
+ getTcpPortListenerDescription: vi.fn().mockResolvedValue(''),
+ isTcpPortReachable: vi.fn().mockResolvedValue(false),
+ runCommand: vi.fn().mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }),
+ runForegroundProcess: vi.fn(),
+}))
describe('managed runtime environment', () => {
+ beforeEach(() => {
+ for (const key of [
+ 'E2E_SHELLCTL_AUTH_TOKEN',
+ 'DIFY_AGENT_SHELLCTL_AUTH_TOKEN',
+ 'DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN',
+ 'DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT',
+ 'E2E_SHELLCTL_URL',
+ 'DIFY_AGENT_SHELLCTL_ENTRYPOINT',
+ ])
+ vi.stubEnv(key, '')
+ vi.clearAllMocks()
+ })
+
afterEach(() => {
vi.unstubAllEnvs()
})
@@ -23,4 +49,88 @@ describe('managed runtime environment', () => {
DIFY_AGENT_SANDBOX_FILES_BASE_URL: 'https://dify.example.test/base',
})
})
+
+ it('generates a fresh nonblank token for each self-managed lifecycle', () => {
+ const first = getManagedSandboxEnvironment()
+ const second = getManagedSandboxEnvironment()
+
+ expect(first.E2E_SHELLCTL_AUTH_TOKEN).toMatch(/^[\da-f]{64}$/)
+ expect(first.DIFY_AGENT_SHELLCTL_AUTH_TOKEN).toBe(first.E2E_SHELLCTL_AUTH_TOKEN)
+ expect(second.E2E_SHELLCTL_AUTH_TOKEN).not.toBe(first.E2E_SHELLCTL_AUTH_TOKEN)
+ expect(process.env.E2E_SHELLCTL_AUTH_TOKEN).toBe('')
+ })
+
+ it('preserves the explicit E2E token over a different Agent token', async () => {
+ vi.stubEnv('E2E_SHELLCTL_AUTH_TOKEN', ' explicit-token ')
+ vi.stubEnv('DIFY_AGENT_SHELLCTL_AUTH_TOKEN', 'other-token')
+ vi.stubEnv('DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN', 'canonical-other-token')
+
+ expect(getManagedSandboxEnvironment()).toEqual({
+ E2E_SHELLCTL_AUTH_TOKEN: ' explicit-token ',
+ DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN: ' explicit-token ',
+ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: ' explicit-token ',
+ })
+ await expect(getAgentBackendEnvironment()).resolves.toMatchObject({
+ DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN: ' explicit-token ',
+ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: ' explicit-token ',
+ })
+ })
+
+ it.each([
+ 'E2E_SHELLCTL_URL',
+ 'DIFY_AGENT_SHELLCTL_ENTRYPOINT',
+ 'DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT',
+ ])('requires and preserves real credentials for an existing sandbox via %s', (key) => {
+ vi.stubEnv(key, 'http://sandbox.example.test')
+ expect(() => getManagedSandboxEnvironment()).toThrow('required for an existing sandbox')
+
+ vi.stubEnv('DIFY_AGENT_SHELLCTL_AUTH_TOKEN', 'existing-token')
+ expect(getManagedSandboxEnvironment()).toEqual({
+ E2E_SHELLCTL_AUTH_TOKEN: 'existing-token',
+ DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN: 'existing-token',
+ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: 'existing-token',
+ })
+ })
+
+ it('rejects a whitespace-only token without including credentials in the error', () => {
+ vi.stubEnv('E2E_SHELLCTL_AUTH_TOKEN', ' \t ')
+ vi.stubEnv('DIFY_AGENT_SHELLCTL_AUTH_TOKEN', 'secret-do-not-log')
+ expect(() => getManagedSandboxEnvironment()).toThrow('nonblank')
+ expect(() => getManagedSandboxEnvironment()).not.toThrow('secret-do-not-log')
+ })
+
+ it('passes Docker the token through the environment rather than command arguments', async () => {
+ vi.stubEnv('E2E_SHELLCTL_AUTH_TOKEN', 'secret-do-not-log')
+ await startShellctlSandbox()
+
+ expect(runForegroundProcess).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: expect.arrayContaining(['-e', 'SHELLCTL_AUTH_TOKEN']),
+ env: { SHELLCTL_AUTH_TOKEN: 'secret-do-not-log' },
+ }),
+ )
+
+ expect(vi.mocked(runForegroundProcess).mock.calls[0]![0].args.join(' ')).not.toContain(
+ 'secret-do-not-log',
+ )
+ })
+
+ it('does not remove or replace a sandbox on an occupied port', async () => {
+ vi.mocked(isTcpPortReachable).mockResolvedValueOnce(true)
+ await expect(startShellctlSandbox()).rejects.toThrow('already in use')
+ expect(runCommand).not.toHaveBeenCalled()
+ expect(runForegroundProcess).not.toHaveBeenCalled()
+ })
+
+ it('uses the canonical Agent credential for an existing sandbox', async () => {
+ vi.stubEnv('DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT', 'http://sandbox.example.test')
+ vi.stubEnv('DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN', 'canonical-token')
+ vi.stubEnv('DIFY_AGENT_SHELLCTL_AUTH_TOKEN', 'legacy-token')
+
+ expect(getManagedSandboxEnvironment().E2E_SHELLCTL_AUTH_TOKEN).toBe('canonical-token')
+ await expect(getAgentBackendEnvironment()).resolves.toMatchObject({
+ DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN: 'canonical-token',
+ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: 'canonical-token',
+ })
+ })
})
diff --git a/e2e/tests/run-cucumber.test.ts b/e2e/tests/run-cucumber.test.ts
index e3e78d781da..304674d5bab 100644
--- a/e2e/tests/run-cucumber.test.ts
+++ b/e2e/tests/run-cucumber.test.ts
@@ -4,7 +4,12 @@ import { readFile } from 'node:fs/promises'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { runCommand } from '../scripts/common.ts'
import { runCucumber } from '../scripts/run-cucumber.ts'
-import { resetState, startMiddleware, stopMiddleware } from '../scripts/setup.ts'
+import {
+ getManagedSandboxEnvironment,
+ resetState,
+ startMiddleware,
+ stopMiddleware,
+} from '../scripts/setup.ts'
import { startLoggedProcess, stopManagedProcess, waitForUrl } from '../support/process.ts'
import { startWebBuildDownload } from '../support/web-build.ts'
import { startWebServer, stopWebServer } from '../support/web-server.ts'
@@ -18,6 +23,7 @@ vi.mock('../scripts/common.ts', () => ({
runCommand: vi.fn(),
}))
vi.mock('../scripts/setup.ts', () => ({
+ getManagedSandboxEnvironment: vi.fn(),
resetState: vi.fn(),
startMiddleware: vi.fn(),
stopMiddleware: vi.fn(),
@@ -46,6 +52,11 @@ describe('core E2E preparation', () => {
beforeEach(() => {
vi.resetAllMocks()
vi.stubEnv('E2E_START_AGENT_BACKEND', '')
+ vi.stubEnv('E2E_AGENT_BACKEND_URL', '')
+ vi.stubEnv('AGENT_BACKEND_BASE_URL', '')
+ vi.stubEnv('E2E_SHELLCTL_URL', '')
+ vi.stubEnv('DIFY_AGENT_SHELLCTL_ENTRYPOINT', '')
+ vi.stubEnv('DIFY_AGENT_LOCAL_SANDBOX_ENDPOINT', '')
vi.mocked(startLoggedProcess).mockImplementation(async () => managedProcess())
vi.mocked(readFile).mockResolvedValue('{"testCaseStarted":{}}')
vi.mocked(runCommand).mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' })
@@ -137,4 +148,62 @@ describe('core E2E preparation', () => {
vi.mocked(readFile).mockResolvedValue('')
await expect(runCucumber(['--full', '--download-web-build'])).rejects.toThrow('zero scenarios')
})
+
+ it('resolves one token and forwards it to both setup children and Cucumber', async () => {
+ vi.stubEnv('E2E_START_AGENT_BACKEND', '1')
+ const environment = {
+ E2E_SHELLCTL_AUTH_TOKEN: 'one-lifecycle-token',
+ DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN: 'one-lifecycle-token',
+ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: 'one-lifecycle-token',
+ }
+ vi.mocked(getManagedSandboxEnvironment).mockReturnValue(environment)
+
+ await runCucumber([])
+
+ expect(getManagedSandboxEnvironment).toHaveBeenCalledOnce()
+ for (const command of ['shellctl-sandbox', 'agent-backend']) {
+ expect(startLoggedProcess).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: ['./scripts/setup.ts', command],
+ env: expect.objectContaining(environment),
+ }),
+ )
+ }
+ expect(runCommand).toHaveBeenCalledWith(
+ expect.objectContaining({ env: expect.objectContaining(environment) }),
+ )
+ })
+
+ it('does not start or stop an independently managed sandbox', async () => {
+ vi.stubEnv('E2E_START_AGENT_BACKEND', '1')
+ vi.stubEnv('E2E_SHELLCTL_URL', 'http://existing.example.test')
+ vi.mocked(getManagedSandboxEnvironment).mockReturnValue({
+ E2E_SHELLCTL_AUTH_TOKEN: 'existing-token',
+ DIFY_AGENT_LOCAL_SANDBOX_AUTH_TOKEN: 'existing-token',
+ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: 'existing-token',
+ })
+
+ await runCucumber([])
+
+ expect(startLoggedProcess).not.toHaveBeenCalledWith(
+ expect.objectContaining({ args: ['./scripts/setup.ts', 'shellctl-sandbox'] }),
+ )
+ expect(startLoggedProcess).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: ['./scripts/setup.ts', 'agent-backend'],
+ env: expect.objectContaining({ DIFY_AGENT_SHELLCTL_AUTH_TOKEN: 'existing-token' }),
+ }),
+ )
+ })
+
+ it('fails before resetting or starting services when sandbox credentials are invalid', async () => {
+ vi.stubEnv('E2E_START_AGENT_BACKEND', '1')
+ vi.mocked(getManagedSandboxEnvironment).mockImplementation(() => {
+ throw new Error('sandbox credentials required')
+ })
+
+ await expect(runCucumber(['--full'])).rejects.toThrow('sandbox credentials required')
+ expect(resetState).not.toHaveBeenCalled()
+ expect(startLoggedProcess).not.toHaveBeenCalled()
+ })
})