更新
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\logic\tcm\DiagnosisAiLogic;
|
||||
use app\adminapi\service\AiRequiredSource;
|
||||
use app\adminapi\service\AssistantSseProtocol;
|
||||
use app\adminapi\controller\tcm\DiagnosisController;
|
||||
|
||||
function errorReceiptExpect(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
|
||||
$format = new ReflectionMethod(DiagnosisAiLogic::class, 'formatAssistantResult');
|
||||
$sections = AiRequiredSource::manifest([]);
|
||||
foreach ($sections as &$section) { $section['status'] = 'failed'; $section['label'] = '不得回传的姓名'; }
|
||||
unset($section);
|
||||
$result = ['ok' => false, 'error_code' => 'REQUIRED_FILES_REJECTED', 'error' => '合成附件失败',
|
||||
'required_sections' => $sections, 'source_summary' => ['patient_name' => '不得回传的姓名', 'url' => 'https://private.invalid', 'required_sections' => $sections],
|
||||
'items' => [['kind' => 'image', 'status' => 'failed', 'label' => '不得回传的姓名', 'url' => 'https://private.invalid/image.png', 'upload_file_id' => 'private-id'],
|
||||
['kind' => 'video', 'status' => 'submitted', 'label' => 'private-video']],
|
||||
'attachment_count' => 1, 'attachment_transfer' => 'uploaded_files', 'transfer_manifest_final' => true,
|
||||
'upstream_http_status' => 400, 'upstream_message' => 'provider private message', 'api_key' => 'private-api-key'];
|
||||
errorReceiptExpect($format->invoke(null, [], $result) === null, 'real formatter retains failure');
|
||||
$meta = DiagnosisAiLogic::getAssistantErrorMeta();
|
||||
errorReceiptExpect(count($meta['required_sections']) === 13 && $meta['items'][0]['status'] === 'failed'
|
||||
&& count($meta['items']) === 1 && $meta['attachment_transfer'] === 'uploaded_files', 'safe complete final receipt survives failure');
|
||||
$encoded = json_encode($meta, JSON_UNESCAPED_UNICODE);
|
||||
foreach (['不得回传的姓名', 'private.invalid', 'private-id', 'private-api-key', 'provider private message', 'private-video'] as $private) {
|
||||
errorReceiptExpect(!str_contains($encoded, $private), 'error metadata excludes private fields');
|
||||
}
|
||||
$protocol = new AssistantSseProtocol(); $protocol->encode('start', []);
|
||||
$frames = [];
|
||||
$emit = static function (string $event, array $payload) use ($protocol, &$frames): bool {
|
||||
$frames[] = $protocol->encode($event, $payload); return true;
|
||||
};
|
||||
$controller = (new ReflectionClass(DiagnosisController::class))->newInstanceWithoutConstructor();
|
||||
$finish = new ReflectionMethod(DiagnosisController::class, 'finishAssistantError');
|
||||
$finish->invoke($controller, $emit, null, false);
|
||||
$frame = end($frames);
|
||||
errorReceiptExpect(str_contains($frame, 'REQUIRED_FILES_REJECTED') && str_contains($frame, '"transfer_manifest_final":true')
|
||||
&& str_contains($frame, '"status":"failed"'), 'real controller SSE error carries authoritative failure receipt');
|
||||
$frames = []; $cancelProtocol = new AssistantSseProtocol(); $cancelProtocol->encode('start', []);
|
||||
$cancelEmit = static function (string $event, array $payload) use ($cancelProtocol, &$frames): bool {
|
||||
$frames[] = $cancelProtocol->encode($event, $payload); return true;
|
||||
};
|
||||
$finish->invoke($controller, $cancelEmit, null, true);
|
||||
errorReceiptExpect(!str_contains(end($frames), 'required_sections') && str_contains(end($frames), 'AI_ASSISTANT_CANCELLED'),
|
||||
'cancel terminal does not reuse unrelated failed receipt');
|
||||
$format->invoke(null, [], ['ok' => true, 'content' => '合成回复']);
|
||||
errorReceiptExpect(DiagnosisAiLogic::getAssistantErrorMeta() === [], 'success clears stale error metadata');
|
||||
echo "Assistant final error receipt / real controller SSE / private metadata filter / cancellation isolation: OK\n";
|
||||
@@ -0,0 +1,309 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service {
|
||||
/** Route synthetic public storage to loopback AFTER recording real security options. */
|
||||
function curl_setopt_array($handle, array $options): bool
|
||||
{
|
||||
$original = $options;
|
||||
$url = (string) ($options[CURLOPT_URL] ?? '');
|
||||
if (str_starts_with($url, 'https://storage.synthetic.test/')) {
|
||||
$options[CURLOPT_URL] = 'http://127.0.0.1:' . $GLOBALS['attachmentFixturePort'] . substr($url, strlen('https://storage.synthetic.test'));
|
||||
unset($options[CURLOPT_RESOLVE]);
|
||||
} elseif (!str_starts_with($url, 'http://127.0.0.1:' . $GLOBALS['attachmentFixturePort'] . '/')) {
|
||||
throw new \RuntimeException('The synthetic test forbids external connections');
|
||||
}
|
||||
$GLOBALS['attachmentCurlOptions'][] = $original;
|
||||
return \curl_setopt_array($handle, $options);
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
// This same file is a loopback-only fixture router. It never loads application config.
|
||||
if (PHP_SAPI === 'cli-server') {
|
||||
$root = (string) getenv('DIFY_ATTACHMENT_FIXTURE_ROOT');
|
||||
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
||||
$append = static function (array $entry) use ($root): void {
|
||||
file_put_contents($root . '/requests.jsonl', json_encode($entry) . "\n", FILE_APPEND | LOCK_EX);
|
||||
};
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST' && str_ends_with($path, '/files/upload')) {
|
||||
$upload = $_FILES['file'] ?? [];
|
||||
$temporary = $upload['tmp_name'] ?? '';
|
||||
$id = bin2hex(random_bytes(16));
|
||||
$append(['kind' => 'upload', 'user' => $_POST['user'] ?? '', 'name' => $upload['name'] ?? '',
|
||||
'mime' => $upload['type'] ?? '', 'size' => $upload['size'] ?? 0,
|
||||
'hash' => is_file($temporary) ? hash_file('sha256', $temporary) : '', 'id' => $id,
|
||||
'authorization' => $_SERVER['HTTP_AUTHORIZATION'] ?? '', 'path' => $path]);
|
||||
if (str_starts_with($path, '/slow-headers/')) usleep(1200000);
|
||||
if (str_starts_with($path, '/budget/')) usleep(650000);
|
||||
header('Content-Type: application/json');
|
||||
if (str_starts_with($path, '/fail/')) { http_response_code(422); echo '{"error":"fixture-private-path-url-key-body"}'; return; }
|
||||
if (str_starts_with($path, '/fail-second/')) {
|
||||
$entries = array_map(static fn (string $line): array => json_decode($line, true), file($root . '/requests.jsonl', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
|
||||
$uploads = array_filter($entries, static fn (array $entry): bool => ($entry['kind'] ?? '') === 'upload');
|
||||
if (count($uploads) === 2) { http_response_code(422); echo '{"error":"fixture-private-path-url-key-body"}'; return; }
|
||||
}
|
||||
if (str_starts_with($path, '/bad-id/')) { http_response_code(201); echo '{"id":"invalid/id"}'; return; }
|
||||
if (str_starts_with($path, '/large-response/')) { http_response_code(201); echo str_repeat('x', 300000); return; }
|
||||
http_response_code(201);
|
||||
if (str_starts_with($path, '/slow-body/')) { echo '{"id":"'; flush(); usleep(1200000); echo $id . '"}'; return; }
|
||||
echo json_encode(['id' => $id]);
|
||||
return;
|
||||
}
|
||||
$append(['kind' => 'download', 'path' => $path, 'authorization' => $_SERVER['HTTP_AUTHORIZATION'] ?? '']);
|
||||
if ($path === '/redirect') { header('Location: http://169.254.169.254/latest/meta-data/'); http_response_code(302); echo 'redirect'; return; }
|
||||
if ($path === '/oversize-header') { header('Content-Length: 2000000'); echo 'x'; return; }
|
||||
if ($path === '/oversize-stream') { echo str_repeat('x', 30000); return; }
|
||||
if ($path === '/slow-download') usleep(1200000);
|
||||
if ($path === '/budget-download') usleep(650000);
|
||||
header('Content-Type: image/png');
|
||||
readfile($root . '/public/uploads/first.png');
|
||||
return;
|
||||
}
|
||||
|
||||
require dirname(__DIR__) . '/app/common/service/DifyRequiredAttachmentUpload.php';
|
||||
use app\common\service\DifyRequiredAttachmentUpload;
|
||||
|
||||
function attachmentExpect(bool $ok, string $message): void
|
||||
{
|
||||
if (!$ok) throw new RuntimeException($message);
|
||||
}
|
||||
function attachmentError(array $result, string $code, string $message): void
|
||||
{
|
||||
attachmentExpect(empty($result['ok']) && ($result['error_code'] ?? '') === $code && !isset($result['files']),
|
||||
$message . ' (' . ($result['error_code'] ?? 'no error') . ')');
|
||||
attachmentExpect(!str_contains(json_encode($result), 'fixture-private-path-url-key-body'), 'upstream body never escapes');
|
||||
}
|
||||
function attachmentRemoveTree(string $path, string $workspace): void
|
||||
{
|
||||
$resolved = realpath($path); $root = realpath($workspace);
|
||||
if ($resolved === false || $root === false || ($resolved !== $root && !str_starts_with(str_replace('\\', '/', $resolved), str_replace('\\', '/', $root) . '/'))) {
|
||||
throw new RuntimeException('Refusing to clean outside synthetic test workspace');
|
||||
}
|
||||
foreach (new DirectoryIterator($resolved) as $item) {
|
||||
if ($item->isDot()) continue;
|
||||
if ($item->isDir() && !$item->isLink()) attachmentRemoveTree($item->getPathname(), $workspace);
|
||||
else unlink($item->getPathname());
|
||||
}
|
||||
rmdir($resolved);
|
||||
}
|
||||
|
||||
$root = sys_get_temp_dir() . '/dify-required-synthetic-' . bin2hex(random_bytes(8));
|
||||
mkdir($root . '/public/uploads/nested', 0700, true);
|
||||
mkdir($root . '/private', 0700);
|
||||
mkdir($root . '/public/uploads-evil', 0700);
|
||||
$image = imagecreatetruecolor(64, 64);
|
||||
imagefill($image, 0, 0, imagecolorallocate($image, 50, 130, 180));
|
||||
imagepng($image, $root . '/public/uploads/first.png');
|
||||
imagefill($image, 0, 0, imagecolorallocate($image, 180, 130, 50));
|
||||
imagepng($image, $root . '/public/uploads/nested/second.png');
|
||||
imagedestroy($image);
|
||||
file_put_contents($root . '/public/uploads/report.pdf', "%PDF-1.4\n1 0 obj<</Type/Catalog>>endobj\n%%EOF\n");
|
||||
file_put_contents($root . '/public/uploads/audio.wav', 'RIFF' . pack('V', 38) . 'WAVEfmt ' . pack('VvvVVvv', 16, 1, 1, 8000, 16000, 2, 16) . 'data' . pack('V', 2) . "\0\0");
|
||||
file_put_contents($root . '/public/uploads/large.txt', str_repeat('x', 30000));
|
||||
file_put_contents($root . '/private/do-not-read.txt', 'synthetic-private-file');
|
||||
file_put_contents($root . '/public/uploads-evil/escape.txt', 'synthetic-private-file');
|
||||
$socket = stream_socket_server('tcp://127.0.0.1:0', $errno, $error);
|
||||
attachmentExpect(is_resource($socket), 'allocate loopback fixture port');
|
||||
$address = stream_socket_get_name($socket, false);
|
||||
fclose($socket);
|
||||
$port = (int) substr($address, strrpos($address, ':') + 1);
|
||||
$attachmentFixturePort = $port;
|
||||
$attachmentCurlOptions = [];
|
||||
$process = proc_open([PHP_BINARY, '-S', '127.0.0.1:' . $port, __FILE__],
|
||||
[['pipe', 'r'], ['file', $root . '/fixture-output.log', 'ab'], ['file', $root . '/fixture-error.log', 'ab']],
|
||||
$pipes, $root, ['DIFY_ATTACHMENT_FIXTURE_ROOT' => $root,
|
||||
'SystemRoot' => (string) getenv('SystemRoot'), 'TEMP' => (string) getenv('TEMP'), 'TMP' => (string) getenv('TMP')], ['bypass_shell' => true]);
|
||||
try {
|
||||
attachmentExpect(is_resource($process), 'start loopback fixture');
|
||||
if (isset($pipes[0]) && is_resource($pipes[0])) fclose($pipes[0]);
|
||||
$ready = false;
|
||||
for ($attempt = 0; $attempt < 150; ++$attempt) {
|
||||
$probe = @fsockopen('127.0.0.1', $port, $errno, $error, 0.02);
|
||||
if (is_resource($probe)) { fclose($probe); $ready = true; break; }
|
||||
usleep(20000);
|
||||
}
|
||||
attachmentExpect($ready, 'loopback fixture becomes ready');
|
||||
$endpoint = 'http://127.0.0.1:' . $port . '/v1/chat-messages';
|
||||
$options = ['local_origins' => ['https://site.synthetic.test', 'https://admin.synthetic.test'],
|
||||
'storage_origins' => ['https://storage.synthetic.test'], 'public_root' => $root . '/public',
|
||||
'temp_root' => $root . '/private/uploads', 'max_file_bytes' => 20000,
|
||||
'resolve_host' => static fn (string $host): array => ['8.8.8.8', '2606:4700:4700::1111']];
|
||||
$files = [
|
||||
['type' => 'image', 'transfer_method' => 'remote_url', 'url' => 'https://site.synthetic.test/uploads/first.png'],
|
||||
['type' => 'image', 'url' => 'https://admin.synthetic.test/uploads/nested/second.png'],
|
||||
['type' => 'document', 'url' => 'https://site.synthetic.test/uploads/report.pdf'],
|
||||
];
|
||||
$requests = static function () use ($root): array {
|
||||
if (!is_file($root . '/requests.jsonl')) return [];
|
||||
return array_map(static fn (string $line): array => json_decode($line, true), file($root . '/requests.jsonl', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
|
||||
};
|
||||
$clear = static function () use ($root, &$attachmentCurlOptions): void {
|
||||
file_put_contents($root . '/requests.jsonl', ''); $attachmentCurlOptions = [];
|
||||
};
|
||||
$clean = static function () use ($root): void {
|
||||
attachmentExpect((glob($root . '/private/uploads/required-*') ?: []) === [], 'temporary files are removed after every terminal outcome');
|
||||
};
|
||||
$run = static function (array $input, array $extra = [], ?callable $abort = null, string $user = 'synthetic-user', ?string $target = null, int $timeout = 5) use ($endpoint, $options): array {
|
||||
return DifyRequiredAttachmentUpload::prepare($target ?? $endpoint, 'fixture-only-key', $user, $input, $timeout, $abort, array_replace($options, $extra));
|
||||
};
|
||||
|
||||
$clear(); $events = [];
|
||||
$result = $run(array_merge($files, [
|
||||
['type' => 'video', 'url' => 'https://untrusted.invalid/record.mp4'],
|
||||
['type' => 'document', 'url' => 'https://untrusted.invalid/record.MOV'],
|
||||
['type' => 'image', 'url' => 'https://untrusted.invalid/opaque', 'mime_type' => 'video/webm'],
|
||||
]), ['on_upload' => static function (array $event) use (&$events): void { $events[] = $event; }]);
|
||||
attachmentExpect(!empty($result['ok']) && count($result['files']) === 3 && $result['attachment_transport'] === 'uploaded_files', 'two images and PDF all become local_file references');
|
||||
attachmentExpect(array_column($result['files'], 'type') === ['image', 'image', 'document']
|
||||
&& array_unique(array_column($result['files'], 'transfer_method')) === ['local_file'], 'types and attachment order preserved');
|
||||
attachmentExpect(count($requests()) === 3 && array_unique(array_column($requests(), 'user')) === ['synthetic-user'], 'every multipart upload has the exact chat user');
|
||||
attachmentExpect(array_column($requests(), 'hash') === [hash_file('sha256', $root . '/public/uploads/first.png'),
|
||||
hash_file('sha256', $root . '/public/uploads/nested/second.png'), hash_file('sha256', $root . '/public/uploads/report.pdf')], 'multipart contains complete binary bytes');
|
||||
attachmentExpect(count($events) === 6 && array_column($events, 'status') === ['uploading', 'uploaded', 'uploading', 'uploaded', 'uploading', 'uploaded'], 'safe one-based progress follows each actual upload');
|
||||
foreach ($events as $event) attachmentExpect(array_keys($event) === ['index', 'total', 'status'] && $event['total'] === 3, 'progress contains safe counts/status only');
|
||||
foreach ($attachmentCurlOptions as $curlOptions) {
|
||||
$temporary = $curlOptions[CURLOPT_POSTFIELDS]['file']->getFilename();
|
||||
attachmentExpect(str_starts_with(str_replace('\\', '/', $temporary), str_replace('\\', '/', $root) . '/private/uploads/') && !is_file($temporary), 'CURLFile uses cleaned nonpublic snapshot');
|
||||
attachmentExpect($curlOptions[CURLOPT_SSL_VERIFYPEER] === true && $curlOptions[CURLOPT_SSL_VERIFYHOST] === 2 && $curlOptions[CURLOPT_PROXY] === '', 'transport verifies TLS and ignores environment proxies');
|
||||
}
|
||||
$clean();
|
||||
|
||||
$clear();
|
||||
$duplicates = $run([$files[0], $files[0]]);
|
||||
attachmentExpect(!empty($duplicates['ok']) && count($duplicates['files']) === 2 && count($requests()) === 1
|
||||
&& $duplicates['files'][0]['upload_file_id'] === $duplicates['files'][1]['upload_file_id'], 'same request reuses ID while preserving both references');
|
||||
$otherUser = $run([$files[0]], [], null, 'another-synthetic-user');
|
||||
attachmentExpect(!empty($otherUser['ok']) && count($requests()) === 2
|
||||
&& $otherUser['files'][0]['upload_file_id'] !== $duplicates['files'][0]['upload_file_id']
|
||||
&& $requests()[1]['user'] === 'another-synthetic-user', 'no upload IDs or cache cross user boundaries');
|
||||
$sameUserNextRequest = $run([$files[0]]);
|
||||
attachmentExpect(!empty($sameUserNextRequest['ok']) && count($requests()) === 3
|
||||
&& $sameUserNextRequest['files'][0]['upload_file_id'] !== $duplicates['files'][0]['upload_file_id'], 'even same-user requests have no global ID cache');
|
||||
$clean();
|
||||
$clear();
|
||||
$audio = $run([['type' => 'audio', 'url' => 'https://site.synthetic.test/uploads/audio.wav']]);
|
||||
attachmentExpect(!empty($audio['ok']) && $audio['files'][0]['type'] === 'audio' && $requests()[0]['mime'] === 'audio/x-wav', 'audio bytes retain audio type');
|
||||
$clean();
|
||||
|
||||
$clear();
|
||||
$source = static fn (string $url): array => [['type' => 'document', 'url' => $url]];
|
||||
foreach ([
|
||||
'https://evil.synthetic.test/uploads/first.png',
|
||||
'https://site.synthetic.test.evil.invalid/uploads/first.png',
|
||||
'http://site.synthetic.test/uploads/first.png',
|
||||
'https://site.synthetic.test:444/uploads/first.png',
|
||||
] as $url) attachmentError($run($source($url)), 'REQUIRED_FILES_SOURCE_UNTRUSTED', 'exact origin prevents alias/scheme/port bypass');
|
||||
foreach ([
|
||||
'https://site.synthetic.test/uploads/../private/do-not-read.txt',
|
||||
'https://site.synthetic.test/uploads/%2e%2e/private/do-not-read.txt',
|
||||
'https://site.synthetic.test/uploads/%252e%252e/private/do-not-read.txt',
|
||||
'https://site.synthetic.test/uploads/nested%2fsecond.png',
|
||||
'https://site.synthetic.test/uploads/nested%5csecond.png',
|
||||
'https://site.synthetic.test/uploads//first.png',
|
||||
'https://site.synthetic.test/uploads/first.png::$DATA',
|
||||
'https://site.synthetic.test/uploads/first.png.',
|
||||
'https://site.synthetic.test/uploads-evil/escape.txt',
|
||||
'https://site.synthetic.test/private/do-not-read.txt',
|
||||
'https://site.synthetic.test@evil.invalid/uploads/first.png',
|
||||
'https://site.synthetic.test/uploads/first.png#fragment',
|
||||
'file:///private/do-not-read.txt',
|
||||
'/uploads/first.png',
|
||||
] as $url) attachmentError($run($source($url)), 'REQUIRED_FILES_INVALID', 'local path/URL bypass rejected before network');
|
||||
attachmentError($run($source('https://site.synthetic.test/uploads/missing.png')), 'REQUIRED_FILES_SOURCE_UNAVAILABLE', 'missing local files do not trigger network fallback');
|
||||
attachmentExpect($requests() === [], 'origin/path failures never upload or download');
|
||||
if (@symlink($root . '/private/do-not-read.txt', $root . '/public/uploads/link.txt')) {
|
||||
attachmentError($run($source('https://site.synthetic.test/uploads/link.txt')), 'REQUIRED_FILES_SOURCE_UNAVAILABLE', 'realpath rejects symlink escape');
|
||||
}
|
||||
$clean();
|
||||
|
||||
$clear();
|
||||
$remote = [['type' => 'image', 'url' => 'https://storage.synthetic.test/download.png']];
|
||||
$downloaded = $run($remote);
|
||||
attachmentExpect(!empty($downloaded['ok']) && count($requests()) === 2 && $requests()[0]['kind'] === 'download'
|
||||
&& $requests()[0]['authorization'] === '' && $requests()[1]['authorization'] === 'Bearer fixture-only-key', 'remote bytes upload without sharing Dify key with storage');
|
||||
attachmentExpect($attachmentCurlOptions[0][CURLOPT_RESOLVE] === ['storage.synthetic.test:443:8.8.8.8']
|
||||
&& $attachmentCurlOptions[0][CURLOPT_FOLLOWLOCATION] === false, 'validated DNS address is pinned and redirect following disabled');
|
||||
$clear(); $dnsCalls = 0;
|
||||
$rebound = $run($remote, ['resolve_host' => static function () use (&$dnsCalls): array { return [++$dnsCalls === 1 ? '8.8.8.8' : '127.0.0.1']; }]);
|
||||
attachmentExpect(!empty($rebound['ok']) && $dnsCalls === 1
|
||||
&& $attachmentCurlOptions[0][CURLOPT_RESOLVE] === ['storage.synthetic.test:443:8.8.8.8'], 'a rebound DNS answer cannot replace the pinned validated address');
|
||||
$clean();
|
||||
|
||||
foreach (['127.0.0.1', '10.0.0.1', '172.16.0.1', '192.168.1.1', '169.254.169.254', '100.100.100.200',
|
||||
'0.0.0.0', '224.0.0.1', '::1', 'fc00::1', 'fe80::1', '::ffff:127.0.0.1', '64:ff9b::7f00:1', '2002:7f00:1::', '2001:db8::1'] as $ip) {
|
||||
$clear();
|
||||
attachmentError($run($remote, ['resolve_host' => static fn (): array => [$ip]]), 'REQUIRED_FILES_SOURCE_UNTRUSTED', 'private/metadata/transition DNS addresses rejected');
|
||||
attachmentExpect($requests() === [] && $attachmentCurlOptions === [], 'unsafe DNS never opens a connection');
|
||||
}
|
||||
$clear();
|
||||
attachmentError($run($remote, ['resolve_host' => static fn (): array => ['8.8.8.8', '127.0.0.1']]), 'REQUIRED_FILES_SOURCE_UNTRUSTED', 'mixed public/private DNS is rejected in full');
|
||||
attachmentError($run($remote, ['resolve_host' => static fn (): array => []]), 'REQUIRED_FILES_DOWNLOAD_FAILED', 'unresolvable storage fails explicitly');
|
||||
foreach (['https://storage.synthetic.test/redirect', 'https://storage.synthetic.test/oversize-header', 'https://storage.synthetic.test/oversize-stream'] as $url) {
|
||||
$clear();
|
||||
attachmentError($run($source($url)), str_ends_with($url, '/redirect') ? 'REQUIRED_FILES_DOWNLOAD_FAILED' : 'REQUIRED_FILES_TOO_LARGE', 'redirect/oversize downloads fail without dropping mandatory file');
|
||||
attachmentExpect(count($requests()) === 1 && $requests()[0]['kind'] === 'download', 'redirect is never followed and bad download is never uploaded');
|
||||
$clean();
|
||||
}
|
||||
$clear();
|
||||
attachmentError($run($source('https://site.synthetic.test/uploads/large.txt')), 'REQUIRED_FILES_TOO_LARGE', 'local file copy has the same byte limit');
|
||||
attachmentExpect($requests() === [], 'oversize local file never uploads');
|
||||
$clean();
|
||||
|
||||
foreach (['fail', 'bad-id', 'large-response'] as $mode) {
|
||||
$clear(); $failedEvents = [];
|
||||
$failed = $run($files, ['on_upload' => static function (array $event) use (&$failedEvents): void { $failedEvents[] = $event; }], null, 'synthetic-user',
|
||||
'http://127.0.0.1:' . $port . '/' . $mode . '/v1/chat-messages');
|
||||
attachmentError($failed, 'REQUIRED_FILES_UPLOAD_FAILED', 'provider upload error never returns a partial attachment list');
|
||||
attachmentExpect(count($requests()) === 1 && $failedEvents[count($failedEvents) - 1]['status'] === 'failed', 'upload failure stops before a model request and marks safe progress failed');
|
||||
$clean();
|
||||
}
|
||||
$clear();
|
||||
$midway = $run($files, [], null, 'synthetic-user', 'http://127.0.0.1:' . $port . '/fail-second/v1/chat-messages');
|
||||
attachmentError($midway, 'REQUIRED_FILES_UPLOAD_FAILED', 'failure after a successful upload still returns no partial files');
|
||||
attachmentExpect(count($requests()) === 2 && $midway['failed_index'] === 2 && $midway['attachment_count'] === 3, 'failure identifies safe index and never skips ahead to remaining attachment');
|
||||
$clean();
|
||||
$clear();
|
||||
attachmentError($run($files, [], static fn (): bool => true), 'AI_ASSISTANT_CANCELLED', 'cancellation before preparation opens no transport');
|
||||
attachmentExpect($requests() === [], 'early cancellation has no network side effects');
|
||||
$cancelDuringCopy = false;
|
||||
attachmentError($run([$files[0]], ['on_upload' => static function () use (&$cancelDuringCopy): void { $cancelDuringCopy = true; }],
|
||||
static function () use (&$cancelDuringCopy): bool { return $cancelDuringCopy; }), 'AI_ASSISTANT_CANCELLED', 'cancellation during local copy cleans its new temporary file');
|
||||
attachmentExpect($requests() === [], 'cancelled local preparation never uploads');
|
||||
$clean();
|
||||
foreach (['slow-headers', 'slow-body'] as $mode) {
|
||||
$clear(); $start = microtime(true);
|
||||
$cancelled = $run([$files[0]], [], static fn (): bool => microtime(true) - $start > 0.15, 'synthetic-user',
|
||||
'http://127.0.0.1:' . $port . '/' . $mode . '/v1/chat-messages');
|
||||
attachmentError($cancelled, 'AI_ASSISTANT_CANCELLED', 'cancellation interrupts upload response ' . $mode);
|
||||
attachmentExpect(microtime(true) - $start < 0.7, 'curl_multi observes cancellation while waiting for headers/body');
|
||||
$clean(); usleep(1250000);
|
||||
}
|
||||
$clear(); $start = microtime(true);
|
||||
attachmentError($run($source('https://storage.synthetic.test/slow-download'), [], static fn (): bool => microtime(true) - $start > 0.15),
|
||||
'AI_ASSISTANT_CANCELLED', 'cancellation interrupts remote download header wait');
|
||||
attachmentExpect(microtime(true) - $start < 0.7, 'download cancellation does not wait for its full timeout');
|
||||
$clean(); usleep(1250000);
|
||||
$clear(); $start = microtime(true);
|
||||
$budget = $run(array_slice($files, 0, 2), [], null, 'synthetic-user', 'http://127.0.0.1:' . $port . '/budget/v1/chat-messages', 1);
|
||||
attachmentError($budget, 'REQUIRED_FILES_TIMEOUT', 'multiple uploads share one deadline');
|
||||
attachmentExpect(microtime(true) - $start < 1.4 && count($requests()) === 2, 'second upload receives only remaining request budget');
|
||||
$clean(); usleep(700000);
|
||||
$clear(); $start = microtime(true);
|
||||
$combinedBudget = $run($source('https://storage.synthetic.test/budget-download'), [], null, 'synthetic-user',
|
||||
'http://127.0.0.1:' . $port . '/budget/v1/chat-messages', 1);
|
||||
attachmentError($combinedBudget, 'REQUIRED_FILES_TIMEOUT', 'download and subsequent upload consume the same deadline');
|
||||
attachmentExpect(microtime(true) - $start < 1.4 && count($requests()) === 2, 'upload does not receive a fresh budget after downloading');
|
||||
$clean(); usleep(700000);
|
||||
$clear();
|
||||
attachmentError($run([$files[0]], ['temp_root' => $root . '/public/unsafe-temp']), 'CONFIG_INVALID', 'temporary files cannot be created in public');
|
||||
attachmentExpect($requests() === [], 'unsafe temp configuration opens no connection');
|
||||
attachmentError($run([['type' => 'image', 'transfer_method' => 'local_file', 'url' => $files[0]['url']]]), 'REQUIRED_FILES_INVALID', 'callers cannot inject upload IDs from other requests');
|
||||
$clean();
|
||||
echo "Dify required attachment upload: binary multipart, all sources, origins/paths/DNS/pinning/redirects/limits, isolation, cancellation/deadline, cleanup: OK\n";
|
||||
} finally {
|
||||
if (is_resource($process)) { proc_terminate($process); proc_close($process); }
|
||||
attachmentRemoveTree($root, $root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// No application bootstrap, Composer, .env, network, database or reference files.
|
||||
namespace think\facade {
|
||||
class Log {
|
||||
public static function warning(string $message): void { $GLOBALS['classificationLogs'][] = $message; }
|
||||
public static function write(string $message, string $level): void {
|
||||
if (!empty($GLOBALS['classificationThrowLog'])) throw new \RuntimeException('Synthetic log unavailable');
|
||||
$GLOBALS['classificationLogs'][] = $message;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace app\common\service {
|
||||
require __DIR__ . '/fixtures/CancellableCurlMultiStub.php';
|
||||
class NihaixiaClinicalSkill {
|
||||
public static function knowledgeSource(): array { return ['title' => 'synthetic']; }
|
||||
}
|
||||
function config(string $name): array { return $GLOBALS['classificationConfig']; }
|
||||
function curl_init(): \stdClass { return (object) ['errno' => 0]; }
|
||||
function curl_setopt_array(\stdClass $handle, array $options): bool {
|
||||
$handle->options = $options;
|
||||
$handle->payload = json_decode($options[CURLOPT_POSTFIELDS], true);
|
||||
return true;
|
||||
}
|
||||
function curl_exec(\stdClass $handle): string|bool {
|
||||
$options = $handle->options;
|
||||
$payload = $handle->payload;
|
||||
$streaming = ($payload['response_mode'] ?? '') === 'streaming' || !empty($payload['stream']);
|
||||
$GLOBALS['classificationRequests'][] = [
|
||||
'mode' => $streaming ? 'streaming' : 'blocking', 'payload' => $payload,
|
||||
'raw' => $options[CURLOPT_POSTFIELDS], 'timeout' => $options[CURLOPT_TIMEOUT],
|
||||
];
|
||||
$fixture = array_shift($GLOBALS['classificationFixtures']);
|
||||
if (!is_array($fixture)) throw new \RuntimeException('Unexpected extra upstream request');
|
||||
$handle->code = $fixture['http'] ?? 200;
|
||||
$handle->errno = $fixture['errno'] ?? 0;
|
||||
if (!empty($fixture['delay_us'])) usleep($fixture['delay_us']);
|
||||
if (!empty($fixture['cancel'])) $GLOBALS['classificationCancelled'] = true;
|
||||
if (isset($options[CURLOPT_HEADERFUNCTION])) {
|
||||
$options[CURLOPT_HEADERFUNCTION]($handle, 'HTTP/1.1 ' . $handle->code . " Synthetic\r\n");
|
||||
}
|
||||
$progress = $options[defined('CURLOPT_XFERINFOFUNCTION') ? CURLOPT_XFERINFOFUNCTION : CURLOPT_PROGRESSFUNCTION] ?? null;
|
||||
if (is_callable($progress) && $progress($handle, 0, 0, 100, 100)) {
|
||||
$handle->errno = CURLE_ABORTED_BY_CALLBACK;
|
||||
return false;
|
||||
}
|
||||
if (isset($fixture['body'])) {
|
||||
$body = $fixture['body'];
|
||||
} elseif (isset($fixture['error'])) {
|
||||
$body = $streaming && $handle->code === 200
|
||||
? 'data: ' . json_encode(['event' => 'error'] + $fixture['error']) . "\n\n"
|
||||
: json_encode($fixture['error']);
|
||||
} else {
|
||||
$body = !$streaming ? '{"answer":"synthetic answer"}'
|
||||
: (isset($payload['messages'])
|
||||
? "data: {\"choices\":[{\"delta\":{\"content\":\"synthetic answer\"}}]}\n\ndata: [DONE]\n\n"
|
||||
: "data: {\"event\":\"message\",\"answer\":\"synthetic answer\"}\n\ndata: {\"event\":\"message_end\"}\n\n");
|
||||
}
|
||||
if (!$streaming) return $body;
|
||||
// Exercise bounded HTTP error parsing across arbitrary network chunks.
|
||||
$write = $options[CURLOPT_WRITEFUNCTION];
|
||||
foreach (str_split($body, 11) as $chunk) {
|
||||
if ($write($handle, $chunk) !== strlen($chunk)) { $handle->errno = CURLE_WRITE_ERROR; break; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function curl_errno(\stdClass $handle): int { return $handle->errno; }
|
||||
function curl_getinfo(\stdClass $handle, int $option): int { return $handle->code ?? 200; }
|
||||
function curl_close(\stdClass $handle): void { ++$GLOBALS['classificationClosed']; }
|
||||
}
|
||||
|
||||
namespace {
|
||||
$root = dirname(__DIR__, 2);
|
||||
require $root . '/server/app/common/logic/BaseLogic.php';
|
||||
require $root . '/server/app/common/service/DifyChatService.php';
|
||||
require $root . '/server/app/adminapi/service/AssistantSseTiming.php';
|
||||
require $root . '/server/app/adminapi/logic/tcm/DiagnosisAiLogic.php';
|
||||
use app\common\service\DifyChatService;
|
||||
use app\adminapi\logic\tcm\DiagnosisAiLogic;
|
||||
use app\adminapi\service\AssistantSseTiming;
|
||||
|
||||
function classificationExpect(bool $condition, string $message): void {
|
||||
if (!$condition) throw new RuntimeException($message);
|
||||
}
|
||||
$classificationConfig = ['enable' => true, 'base_url' => 'https://synthetic.invalid/v1/chat-messages',
|
||||
'timeout' => 5, 'max_files' => 3,
|
||||
'models' => ['qwen' => ['name' => 'synthetic', 'api_key' => 'synthetic-only']]];
|
||||
$files = array_map(static fn (int $id): array => ['type' => 'image', 'url' => 'https://synthetic.invalid/' . $id . '.png'], [1, 2]);
|
||||
$sections = array_map(static fn (int $id): array => ['key' => 'source_' . $id, 'label' => 'synthetic',
|
||||
'count' => $id === 13 ? 0 : 1, 'availability' => $id === 13 ? 'empty' : 'present'], range(1, 13));
|
||||
$options = ['required_files' => true, 'knowledge_mode' => 'evidence', 'required_sections' => $sections];
|
||||
$reset = static function (array $fixtures): void {
|
||||
$GLOBALS['classificationFixtures'] = $fixtures;
|
||||
$GLOBALS['classificationRequests'] = [];
|
||||
$GLOBALS['classificationLogs'] = [];
|
||||
$GLOBALS['classificationCancelled'] = false;
|
||||
$GLOBALS['classificationClosed'] = 0;
|
||||
$GLOBALS['classificationThrowLog'] = false;
|
||||
};
|
||||
$call = static function (bool $streaming, array $inputs = [], array $extra = []) use ($files, $options): array {
|
||||
$selected = array_replace($options, $extra);
|
||||
return $streaming
|
||||
? DifyChatService::streamChat('qwen', $inputs, 'synthetic query', 'synthetic-user', static fn (): bool => true, null, $files, $selected)
|
||||
: DifyChatService::chat('qwen', $inputs, 'synthetic query', 'synthetic-user', $files, $selected);
|
||||
};
|
||||
$private = static fn (string $method, array $args) => (new ReflectionClass(DifyChatService::class))->getMethod($method)->invokeArgs(null, $args);
|
||||
$inputError = ['http' => 400, 'error' => ['code' => 'invalid_param', 'message' => 'Unknown input variable: synthetic_field']];
|
||||
$fileError = ['http' => 400, 'error' => ['code' => 'invalid_param', 'message' => 'Number of files exceeds the limit.']];
|
||||
$secret = 'SYNTHETIC_PRIVATE_MARKER';
|
||||
|
||||
foreach ([false, true] as $streaming) {
|
||||
// Mere status codes/invalid_param do not identify a file or an inputs error.
|
||||
foreach ([400, 413, 415, 422] as $http) {
|
||||
$reset([['http' => $http, 'error' => ['code' => 'invalid_param', 'message' => $secret . ' https://synthetic.invalid/private.png']]]);
|
||||
$result = $call($streaming, ['synthetic_field' => 'value']);
|
||||
classificationExpect($result['error_code'] === 'UPSTREAM_REJECTED' && count($classificationRequests) === 1,
|
||||
'Generic validation does not invent attachment or inputs rejection');
|
||||
classificationExpect(!str_contains(json_encode([$result, $classificationLogs]), $secret), 'Provider messages never enter errors or logs');
|
||||
classificationExpect(count($classificationLogs) === 1
|
||||
&& str_contains($classificationLogs[0], '"upstream_code":"invalid_param"')
|
||||
&& !str_contains($classificationLogs[0], 'https://'), 'Safe failure code is logged immediately without hostnames or resource URLs');
|
||||
}
|
||||
foreach ([[401, 'CONFIG_INVALID'], [403, 'CONFIG_INVALID'], [429, 'UPSTREAM_BUSY'], [503, 'UPSTREAM_BUSY']] as [$http, $expected]) {
|
||||
$reset([$inputError, ['http' => $http, 'error' => ['code' => 'invalid_param', 'message' => 'file type not supported']]]);
|
||||
$result = $call($streaming, ['synthetic_field' => 'value']);
|
||||
classificationExpect($result['error_code'] === $expected && count($classificationRequests) === 2,
|
||||
'Latest auth/availability response is not overwritten by an earlier inputs rejection');
|
||||
classificationExpect(array_map(static fn (array $request): int => count($request['payload']['files']), $classificationRequests) === [2, 2],
|
||||
'Every compatibility request retains both mandatory files');
|
||||
}
|
||||
$reset([$inputError, []]);
|
||||
$result = $call($streaming, ['synthetic_field' => 'value']);
|
||||
classificationExpect(!empty($result['ok']) && count($classificationRequests) === 2
|
||||
&& $classificationRequests[1]['payload']['inputs'] === []
|
||||
&& str_contains($classificationRequests[1]['raw'], '"inputs":{}')
|
||||
&& $classificationRequests[0]['payload']['query'] === $classificationRequests[1]['payload']['query'],
|
||||
'Explicit inputs compatibility succeeds with identical query/files and object inputs');
|
||||
|
||||
foreach ([$fileError, ['http' => 413, 'error' => ['code' => 'file_too_large']],
|
||||
['http' => 415, 'error' => ['code' => 'unsupported_file_type']],
|
||||
['http' => 422, 'error' => ['code' => 'invalid_param', 'message' => 'File type is not supported.']]] as $fixture) {
|
||||
$reset([$fixture]); $events = [];
|
||||
$result = $call($streaming, ['synthetic_field' => 'value'],
|
||||
['on_progress' => static function (array $event) use (&$events): void { $events[] = $event; }]);
|
||||
classificationExpect($result['error_code'] === 'REQUIRED_FILES_REJECTED' && count($classificationRequests) === 1,
|
||||
'Affirmative file count/type/size failure never strips mandatory files or retries inputs');
|
||||
$last = $events[count($events) - 1];
|
||||
foreach ([$result, $last] as $manifest) {
|
||||
classificationExpect($manifest['transfer_manifest_final'] === true && $manifest['attachment_count'] === 2
|
||||
&& count($manifest['required_sections']) === 13
|
||||
&& array_unique(array_column($manifest['items'], 'status')) === ['failed']
|
||||
&& array_unique(array_column($manifest['required_sections'], 'status')) === ['failed']
|
||||
&& $manifest['required_sections'][12]['availability'] === 'empty', 'Failure results and progress carry a complete final failed manifest');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Business SSE errors may be reported under HTTP 200. An ambiguous base must
|
||||
// not re-submit quotas, credentials, cancellation or affirmative file failures.
|
||||
$classificationConfig['base_url'] = 'https://synthetic.invalid/v1';
|
||||
foreach ([['provider_quota_exceeded', 'UPSTREAM_BUSY'], ['invalid_api_key', 'CONFIG_INVALID'],
|
||||
['provider_unavailable', 'UPSTREAM_BUSY'], ['task_cancelled', 'AI_ASSISTANT_CANCELLED'],
|
||||
['file_download_failed', 'REQUIRED_FILES_REJECTED']] as [$code, $expected]) {
|
||||
$reset([['http' => 200, 'error' => ['code' => $code, 'message' => $secret]]]);
|
||||
$result = $call(true);
|
||||
classificationExpect($result['error_code'] === $expected && count($classificationRequests) === 1,
|
||||
'SSE business failure retains its diagnosis without cross-protocol replay');
|
||||
}
|
||||
$classificationConfig['base_url'] = 'https://synthetic.invalid/v1/chat-messages';
|
||||
$reset([['http' => 200, 'error' => ['code' => 'unknown_provider_error', 'message' => $secret]]]);
|
||||
classificationExpect($call(true)['error_code'] === 'UPSTREAM_REJECTED', 'Unknown SSE errors do not implicate files');
|
||||
|
||||
$modeError = ['http' => 400, 'delay_us' => 3000,
|
||||
'error' => ['code' => 'invalid_param', 'message' => 'response_mode must be blocking. ' . $secret]];
|
||||
$prepared = ['profile' => 'qwen', 'task' => 'summary', 'query' => 'synthetic query', 'user' => 'synthetic-user',
|
||||
'files' => $files, 'inputs' => ['synthetic_field' => 'value'], 'required_sections' => $sections, 'upstream_timeout' => 5];
|
||||
$reset([$modeError, []]);
|
||||
$answer = DiagnosisAiLogic::streamPreparedAssistant($prepared, static fn (): bool => true, null,
|
||||
new AssistantSseTiming(), ['knowledge_mode' => 'evidence']);
|
||||
classificationExpect(is_array($answer) && array_column($classificationRequests, 'mode') === ['streaming', 'blocking']
|
||||
&& count($classificationRequests[1]['payload']['files']) === 2
|
||||
&& $classificationRequests[0]['payload']['files'] === $classificationRequests[1]['payload']['files']
|
||||
&& $classificationRequests[0]['payload']['inputs'] === $classificationRequests[1]['payload']['inputs']
|
||||
&& $classificationRequests[1]['timeout'] <= 4, 'Actual assistant recovers response_mode with both files and the remaining shared budget');
|
||||
|
||||
// An emitted clinical delta prevents replay even if a later SSE error names inputs.
|
||||
$reset([['http' => 200, 'body' => "data: {\"event\":\"message\",\"answer\":\"synthetic partial\"}\n\ndata: {\"event\":\"error\",\"code\":\"invalid_inputs\"}\n\n"]]);
|
||||
$answer = DiagnosisAiLogic::streamPreparedAssistant($prepared, static fn (): bool => true, null,
|
||||
new AssistantSseTiming(), ['knowledge_mode' => 'evidence']);
|
||||
classificationExpect($answer === null && count($classificationRequests) === 1, 'No inputs or blocking replay after delivered text');
|
||||
|
||||
$reset([['http' => 400, 'cancel' => true, 'error' => ['code' => 'file_too_large']]]);
|
||||
$result = DifyChatService::chat('qwen', [], 'synthetic query', 'synthetic-user', $files,
|
||||
$options + ['should_abort' => static fn (): bool => $GLOBALS['classificationCancelled']]);
|
||||
classificationExpect($result['error_code'] === 'AI_ASSISTANT_CANCELLED' && count($classificationRequests) === 1
|
||||
&& $classificationClosed === 1, 'Cancellation closes transport and wins over apparent file errors');
|
||||
|
||||
// Optional-file and generic strict callers retain their existing distinction.
|
||||
$reset([['http' => 400], []]);
|
||||
$result = DifyChatService::chat('qwen', [], 'synthetic query', 'synthetic-user', $files, ['knowledge_mode' => 'evidence']);
|
||||
classificationExpect(!empty($result['ok']) && !isset($classificationRequests[1]['payload']['files']), 'Legacy optional files keep the explicit text fallback');
|
||||
$reset([['http' => 400]]);
|
||||
$result = DifyChatService::chat('qwen', [], 'synthetic query', 'synthetic-user', $files, ['knowledge_mode' => 'evidence', 'strict_files' => true]);
|
||||
classificationExpect($result['error_code'] === 'UPSTREAM_REJECTED' && count($classificationRequests) === 1, 'Legacy strict never drops mandatory batch data');
|
||||
|
||||
$reset([['http' => 400, 'error' => ['code' => 'invalid_param', 'message' => 'Failed to download image ' . $secret]]]);
|
||||
$transport = $private('sendStreamRequest', ['dify', 'https://synthetic.invalid/v1/chat-messages', ['response_mode' => 'streaming'], 'synthetic-only', 5, static fn (): bool => true, null]);
|
||||
classificationExpect($transport['upstream_code'] === 'invalid_param' && $transport['upstream_reason'] === 'file_access'
|
||||
&& !isset($transport['body']) && !str_contains(json_encode($transport), $secret), 'Split HTTP error JSON retains only a short code and fixed reason');
|
||||
$reset([['http' => 400, 'error' => ['code' => 'file_too_large', 'message' => str_repeat($secret, 1500)]]]);
|
||||
$transport = $private('sendStreamRequest', ['dify', 'https://synthetic.invalid/v1/chat-messages', ['response_mode' => 'streaming'], 'synthetic-only', 5, static fn (): bool => true, null]);
|
||||
classificationExpect($transport['upstream_code'] === '' && $transport['upstream_reason'] === '' && !isset($transport['body']), 'Oversized error bodies are discarded instead of retained or partially decoded');
|
||||
classificationExpect($private('upstreamErrorMetadata', [['error' => ['code' => 'insufficient_quota', 'message' => $secret]]])['upstream_reason'] === 'quota', 'Nested OpenAI JSON errors use the same safe classification');
|
||||
$reset([['http' => 503]]); $classificationThrowLog = true;
|
||||
classificationExpect($call(true)['error_code'] === 'UPSTREAM_BUSY', 'Logging failure cannot alter or throw away the upstream diagnosis');
|
||||
echo "Dify mandatory-file error classification / compatibility / final manifests / cancellation: OK\n";
|
||||
}
|
||||
@@ -40,7 +40,7 @@ namespace {
|
||||
$payload = json_decode($body, true);
|
||||
$stream = ($payload['response_mode'] ?? '') === 'streaming' || !empty($payload['stream']);
|
||||
$status = ($argv[2] ?? '') === 'reject' ? 413 : 200;
|
||||
$response = $status === 413 ? '{"code":"invalid_param"}'
|
||||
$response = $status === 413 ? '{"code":"invalid_param","message":"Number of files exceeds the limit."}'
|
||||
: ($stream ? "data: {\"event\":\"message\",\"answer\":\"synthetic-answer\"}\n\ndata: {\"event\":\"message_end\"}\n\n" : '{"answer":"synthetic-answer"}');
|
||||
fwrite($client, 'HTTP/1.1 ' . $status . " Synthetic\r\nContent-Type: " . ($stream ? 'text/event-stream' : 'application/json')
|
||||
. "\r\nContent-Length: " . strlen($response) . "\r\nConnection: close\r\n\r\n" . $response);
|
||||
|
||||
@@ -29,7 +29,16 @@ namespace app\common\service {
|
||||
if ($scenario === 'cancel') $GLOBALS['requiredCancelled'] = true;
|
||||
$progress = $handle->options[defined('CURLOPT_XFERINFOFUNCTION') ? CURLOPT_XFERINFOFUNCTION : CURLOPT_PROGRESSFUNCTION] ?? null;
|
||||
if (is_callable($progress) && $progress($handle, 0, 0, 100, 100)) return false;
|
||||
if ($handle->code !== 200) return $stream ? true : '{}';
|
||||
if ($handle->code !== 200) {
|
||||
$errorBody = json_encode(['code' => $scenario === 'fallback' ? 'not_found' : 'invalid_param',
|
||||
'message' => $scenario === 'reject' ? 'Number of files exceeds the limit.'
|
||||
: ($scenario === 'input_rejected' ? 'Unknown input variable: synthetic_undeclared' : 'Synthetic path not found')]);
|
||||
if ($stream) {
|
||||
($handle->options[CURLOPT_WRITEFUNCTION])($handle, $errorBody);
|
||||
return true;
|
||||
}
|
||||
return $errorBody;
|
||||
}
|
||||
if (!$stream) return json_encode(['answer' => '合成回答']);
|
||||
$write = $handle->options[CURLOPT_WRITEFUNCTION];
|
||||
if (str_ends_with($handle->url, '/chat-messages')) {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace think\facade {
|
||||
class Log { public static function warning(string $message): void {} public static function write(string $message, string $level): void {} }
|
||||
}
|
||||
namespace app\common\service {
|
||||
require __DIR__ . '/fixtures/CancellableCurlMultiStub.php';
|
||||
function config(string $name): array { return $GLOBALS['uploadTransportConfig']; }
|
||||
final class DifyRequiredAttachmentUpload {
|
||||
public static function prepare(string $endpoint, string $key, string $user, array $files, int $timeout,
|
||||
?callable $shouldAbort = null, array $options = []): array {
|
||||
$GLOBALS['uploadTransportStages'][] = compact('endpoint', 'user', 'files', 'timeout');
|
||||
if ($GLOBALS['uploadTransportScenario'] === 'cancel') return ['ok' => false, 'error_code' => 'AI_ASSISTANT_CANCELLED', 'error' => '合成取消'];
|
||||
if ($GLOBALS['uploadTransportScenario'] === 'upload-failed') return ['ok' => false, 'error_code' => 'REQUIRED_FILES_UPLOAD_FAILED', 'error' => '合成上传失败'];
|
||||
$result = [];
|
||||
foreach ($files as $index => $file) {
|
||||
foreach (['uploading', 'uploaded'] as $status) {
|
||||
if (is_callable($options['on_upload'] ?? null)) ($options['on_upload'])(['index' => $index + 1, 'total' => count($files), 'status' => $status]);
|
||||
}
|
||||
$result[] = ['type' => $file['type'], 'transfer_method' => 'local_file', 'upload_file_id' => 'fixture-upload-' . ($index + 1)];
|
||||
}
|
||||
return ['ok' => true, 'files' => $result, 'attachment_transport' => 'uploaded_files'];
|
||||
}
|
||||
}
|
||||
function curl_init(): \stdClass { return new \stdClass(); }
|
||||
function curl_setopt_array(\stdClass $handle, array $options): bool { $handle->options = $options; return true; }
|
||||
function curl_exec(\stdClass $handle): string|bool {
|
||||
$payload = json_decode($handle->options[CURLOPT_POSTFIELDS], true);
|
||||
$GLOBALS['uploadTransportRequests'][] = $payload;
|
||||
$stream = ($payload['response_mode'] ?? '') === 'streaming';
|
||||
$handle->code = $GLOBALS['uploadTransportScenario'] === 'inputs' && !empty($payload['inputs']) ? 400 : 200;
|
||||
($handle->options[CURLOPT_HEADERFUNCTION])($handle, 'HTTP/1.1 ' . $handle->code . " Synthetic\r\n");
|
||||
if ($handle->code !== 200) {
|
||||
$body = json_encode(['code' => 'invalid_param', 'message' => 'synthetic_undeclared_input input variable invalid']);
|
||||
if ($stream) { ($handle->options[CURLOPT_WRITEFUNCTION])($handle, $body); return true; }
|
||||
return $body;
|
||||
}
|
||||
if (!$stream) return json_encode(['answer' => '合成回答']);
|
||||
$write = $handle->options[CURLOPT_WRITEFUNCTION];
|
||||
$write($handle, 'data: ' . json_encode(['event' => 'message', 'answer' => '合成回答']) . "\n\n");
|
||||
$write($handle, "data: {\"event\":\"message_end\"}\n\n");
|
||||
return true;
|
||||
}
|
||||
function curl_errno(\stdClass $handle): int { return 0; }
|
||||
function curl_getinfo(\stdClass $handle, int $option): int { return $handle->code; }
|
||||
function curl_close(\stdClass $handle): void {}
|
||||
}
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
use app\common\service\DifyChatService;
|
||||
use app\adminapi\service\AiRequiredSource;
|
||||
function uploadTransportExpect(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
|
||||
$uploadTransportConfig = ['enable' => true, 'base_url' => 'https://synthetic.invalid/v1/chat-messages',
|
||||
'timeout' => 5, 'required_attachment_transport' => 'upload',
|
||||
'models' => ['qwen' => ['name' => 'synthetic', 'api_key' => 'fixture-only']]];
|
||||
$files = [['type' => 'image', 'url' => 'https://synthetic.invalid/one.png'],
|
||||
['type' => 'image', 'url' => 'https://synthetic.invalid/two.png'],
|
||||
['type' => 'document', 'url' => 'https://synthetic.invalid/three.pdf']];
|
||||
$options = ['required_files' => true, 'knowledge_mode' => 'evidence', 'required_sections' => AiRequiredSource::manifest([])];
|
||||
foreach ([false, true] as $stream) foreach (['success', 'inputs', 'upload-failed', 'cancel'] as $scenario) {
|
||||
$uploadTransportScenario = $scenario; $uploadTransportStages = []; $uploadTransportRequests = []; $events = [];
|
||||
$opts = $options + ['on_progress' => static function (array $event) use (&$events): void { $events[] = $event; }];
|
||||
$result = $stream ? DifyChatService::streamChat('qwen', ['synthetic_undeclared_input' => 'value'], '合成资料', 'fixture-same-user',
|
||||
static fn (string $text): bool => true, null, $files, $opts)
|
||||
: DifyChatService::chat('qwen', ['synthetic_undeclared_input' => 'value'], '合成资料', 'fixture-same-user', $files, $opts);
|
||||
uploadTransportExpect(count($uploadTransportStages) === 1, 'all required files are staged once per request');
|
||||
uploadTransportExpect($uploadTransportStages[0]['user'] === 'fixture-same-user' && count($uploadTransportStages[0]['files']) === 3,
|
||||
'upload and chat share end user and complete source set');
|
||||
if (in_array($scenario, ['upload-failed', 'cancel'], true)) {
|
||||
uploadTransportExpect(empty($result['ok']) && $uploadTransportRequests === [], 'failed or cancelled upload never starts model generation');
|
||||
uploadTransportExpect($result['error_code'] === ($scenario === 'cancel' ? 'AI_ASSISTANT_CANCELLED' : 'REQUIRED_FILES_UPLOAD_FAILED'),
|
||||
'upload failure retains actual cause');
|
||||
continue;
|
||||
}
|
||||
uploadTransportExpect(!empty($result['ok']) && $result['attachment_transfer'] === 'uploaded_files', 'final receipt identifies actual uploads');
|
||||
uploadTransportExpect(count($uploadTransportRequests) === ($scenario === 'inputs' ? 2 : 1), 'bounded input compatibility remains intact');
|
||||
foreach ($uploadTransportRequests as $payload) {
|
||||
uploadTransportExpect($payload['user'] === 'fixture-same-user' && count($payload['files']) === 3, 'every generation attempt retains all uploaded files');
|
||||
uploadTransportExpect(array_column($payload['files'], 'transfer_method') === ['local_file', 'local_file', 'local_file'], 'Dify gets upload IDs, not resource URLs');
|
||||
uploadTransportExpect(!array_key_exists('url', $payload['files'][0]) && $payload['files'][0]['upload_file_id'] === 'fixture-upload-1', 'original URL never leaks into uploaded wire files');
|
||||
}
|
||||
uploadTransportExpect(count(array_filter($events, static fn (array $event): bool => ($event['status'] ?? '') === 'uploading')) >= 3,
|
||||
'safe per-file upload progress reaches the desktop');
|
||||
}
|
||||
echo "Dify required upload transport / complete IDs / same user / input retry reuse / failure / cancel: OK\n";
|
||||
}
|
||||
@@ -288,11 +288,11 @@ $openAiInputSpec = ['protocol' => 'openai'];
|
||||
expectSame(
|
||||
true,
|
||||
callPrivate('isInputRejection', [
|
||||
['errno' => 0, 'http_code' => 400, 'body' => '{"code":"invalid_param"}'],
|
||||
['errno' => 0, 'http_code' => 400, 'body' => '{"code":"invalid_param","message":"Unknown input variable: prompt_version"}'],
|
||||
$difyInputSpec,
|
||||
['prompt_version' => 'v2'],
|
||||
]),
|
||||
'Dify invalid_param retries with query-only input'
|
||||
'an explicit undeclared Dify input retries with query-only input'
|
||||
);
|
||||
expectSame(
|
||||
false,
|
||||
@@ -329,12 +329,13 @@ expectSame(
|
||||
'http_code' => 200,
|
||||
'upstream_error' => true,
|
||||
'upstream_code' => 'invalid_param',
|
||||
'upstream_reason' => 'inputs_invalid',
|
||||
'emitted' => false,
|
||||
],
|
||||
$difyInputSpec,
|
||||
['prompt_version' => 'v2'],
|
||||
]),
|
||||
'a streaming invalid_param before any delta also retries without inputs'
|
||||
'an explicit streaming inputs error before any delta retries without inputs'
|
||||
);
|
||||
expectSame(
|
||||
false,
|
||||
@@ -344,6 +345,7 @@ expectSame(
|
||||
'http_code' => 200,
|
||||
'upstream_error' => true,
|
||||
'upstream_code' => 'invalid_param',
|
||||
'upstream_reason' => 'inputs_invalid',
|
||||
'emitted' => true,
|
||||
],
|
||||
$difyInputSpec,
|
||||
@@ -358,8 +360,8 @@ expectSame(false, callPrivate('shouldRetryWithoutFiles', [400, []]), 'a text-onl
|
||||
expectSame(false, callPrivate('shouldRetryWithoutFiles', [401, $capped['kept']]), 'a credential failure is not retried');
|
||||
expectSame(false, callPrivate('shouldRetryWithoutFiles', [500, $capped['kept']]), 'an upstream outage is not retried here');
|
||||
|
||||
// 协议回退会把最初的“附件被拒”换成另一协议的状态码(Dify 400 -> OpenAI 404),
|
||||
// 降级判断必须按每次响应累计,否则去掉附件的重试永远不会发生。
|
||||
// Optional legacy files retain their historic text fallback; required clinical
|
||||
// files use the affirmative-evidence flag tested by DifyRequiredFilesRejectionClassificationTest.
|
||||
expectSame(
|
||||
true,
|
||||
callPrivate('isFileRejection', [['errno' => 0, 'http_code' => 400], $capped['kept']]),
|
||||
|
||||
Reference in New Issue
Block a user