|
1 | 1 | // Provider fallback tests verify web_fetch normalizes third-party fetch output |
2 | 2 | // before exposing it to agents or cache entries. |
3 | 3 | import { rm } from "node:fs/promises"; |
| 4 | +import { createServer, type Server } from "node:http"; |
4 | 5 | import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
5 | 6 | import type { OpenClawConfig } from "../../config/config.js"; |
6 | 7 | import { setActiveDegradedSecretOwners } from "../../secrets/runtime-degraded-state.js"; |
7 | 8 | import { wrapExternalContent } from "../../security/external-content.js"; |
8 | 9 | import { withFetchPreconnect } from "../../test-utils/fetch-mock.js"; |
9 | 10 | import { createWebFetchTool } from "./web-fetch.js"; |
| 11 | +import * as webGuardedFetch from "./web-guarded-fetch.js"; |
10 | 12 |
|
11 | 13 | const { resolveWebFetchDefinitionMock } = vi.hoisted(() => ({ |
12 | 14 | resolveWebFetchDefinitionMock: vi.fn(), |
@@ -359,4 +361,291 @@ describe("web_fetch provider fallback normalization", () => { |
359 | 361 | expect(secondDetails.text).toContain("perplexity-fetch fallback body"); |
360 | 362 | expect(secondDetails.cached).toBeUndefined(); |
361 | 363 | }); |
| 364 | + |
| 365 | + it("cancels an unread non-OK response body when provider fallback succeeds", async () => { |
| 366 | + let cancelled = false; |
| 367 | + const stream = new ReadableStream<Uint8Array>({ |
| 368 | + pull(controller) { |
| 369 | + controller.enqueue(new TextEncoder().encode("upstream error body")); |
| 370 | + }, |
| 371 | + cancel() { |
| 372 | + cancelled = true; |
| 373 | + }, |
| 374 | + }); |
| 375 | + global.fetch = withFetchPreconnect( |
| 376 | + vi.fn( |
| 377 | + async () => |
| 378 | + new Response(stream, { |
| 379 | + status: 503, |
| 380 | + statusText: "Service Unavailable", |
| 381 | + headers: { "content-type": "text/plain" }, |
| 382 | + }), |
| 383 | + ), |
| 384 | + ); |
| 385 | + resolveWebFetchDefinitionMock.mockReturnValue({ |
| 386 | + provider: { id: "firecrawl" }, |
| 387 | + definition: { |
| 388 | + description: "firecrawl", |
| 389 | + parameters: {}, |
| 390 | + execute: async () => ({ |
| 391 | + text: "provider rescued body", |
| 392 | + status: 200, |
| 393 | + contentType: "text/plain", |
| 394 | + extractor: "custom-provider", |
| 395 | + }), |
| 396 | + }, |
| 397 | + }); |
| 398 | + |
| 399 | + const tool = createWebFetchTool({ |
| 400 | + config: {} as OpenClawConfig, |
| 401 | + sandboxed: false, |
| 402 | + }); |
| 403 | + const result = await tool?.execute?.("call-provider-fallback", { |
| 404 | + url: "https://example.com/non-ok-fallback", |
| 405 | + }); |
| 406 | + const details = result?.details as { text?: string; extractor?: string }; |
| 407 | + |
| 408 | + expect(details.extractor).toBe("custom-provider"); |
| 409 | + expect(details.text).toContain("provider rescued body"); |
| 410 | + expect(cancelled).toBe(true); |
| 411 | + console.log( |
| 412 | + `[web-fetch non-ok fallback cancel proof] cancelled=${cancelled} extractor=${details.extractor ?? "n/a"}`, |
| 413 | + ); |
| 414 | + }); |
| 415 | + |
| 416 | + it("cancels the response body when readability-disabled fallback succeeds", async () => { |
| 417 | + let cancelInvoked = false; |
| 418 | + global.fetch = withFetchPreconnect( |
| 419 | + vi.fn(async () => { |
| 420 | + const stream = new ReadableStream<Uint8Array>({ |
| 421 | + start(controller) { |
| 422 | + controller.enqueue( |
| 423 | + new TextEncoder().encode("<html><body><p>direct html</p></body></html>"), |
| 424 | + ); |
| 425 | + controller.close(); |
| 426 | + }, |
| 427 | + }); |
| 428 | + const response = new Response(stream, { |
| 429 | + status: 200, |
| 430 | + headers: { "content-type": "text/html" }, |
| 431 | + }); |
| 432 | + const body = response.body; |
| 433 | + if (!body) { |
| 434 | + throw new Error("expected response body"); |
| 435 | + } |
| 436 | + const originalCancel = body.cancel.bind(body); |
| 437 | + body.cancel = ((reason?: unknown) => { |
| 438 | + cancelInvoked = true; |
| 439 | + return originalCancel(reason); |
| 440 | + }) as typeof body.cancel; |
| 441 | + return response; |
| 442 | + }), |
| 443 | + ); |
| 444 | + resolveWebFetchDefinitionMock.mockReturnValue({ |
| 445 | + provider: { id: "firecrawl" }, |
| 446 | + definition: { |
| 447 | + description: "firecrawl", |
| 448 | + parameters: {}, |
| 449 | + execute: async () => ({ |
| 450 | + text: "provider html rescue", |
| 451 | + status: 200, |
| 452 | + contentType: "text/plain", |
| 453 | + extractor: "custom-provider", |
| 454 | + }), |
| 455 | + }, |
| 456 | + }); |
| 457 | + |
| 458 | + const tool = createWebFetchTool({ |
| 459 | + config: { |
| 460 | + tools: { web: { fetch: { readability: false } } }, |
| 461 | + } as OpenClawConfig, |
| 462 | + sandboxed: false, |
| 463 | + }); |
| 464 | + const result = await tool?.execute?.("call-provider-fallback", { |
| 465 | + url: "https://example.com/readability-off-fallback", |
| 466 | + }); |
| 467 | + const details = result?.details as { text?: string; extractor?: string }; |
| 468 | + |
| 469 | + expect(details.extractor).toBe("custom-provider"); |
| 470 | + expect(details.text).toContain("provider html rescue"); |
| 471 | + expect(cancelInvoked).toBe(true); |
| 472 | + console.log( |
| 473 | + `[web-fetch readability-off fallback cancel proof] cancel_invoked=${cancelInvoked} extractor=${details.extractor ?? "n/a"}`, |
| 474 | + ); |
| 475 | + }); |
| 476 | + |
| 477 | + it("does not block provider fallback when body cancel never settles", async () => { |
| 478 | + // cancel() must stay fire-and-forget; awaiting it can hang a successful fallback. |
| 479 | + global.fetch = withFetchPreconnect( |
| 480 | + vi.fn(async () => { |
| 481 | + const stream = new ReadableStream<Uint8Array>({ |
| 482 | + pull(controller) { |
| 483 | + controller.enqueue(new TextEncoder().encode("never-settling-cancel body")); |
| 484 | + }, |
| 485 | + cancel() { |
| 486 | + return new Promise(() => { |
| 487 | + // Intentionally never settles. |
| 488 | + }); |
| 489 | + }, |
| 490 | + }); |
| 491 | + return new Response(stream, { |
| 492 | + status: 503, |
| 493 | + statusText: "Service Unavailable", |
| 494 | + headers: { "content-type": "text/plain" }, |
| 495 | + }); |
| 496 | + }), |
| 497 | + ); |
| 498 | + resolveWebFetchDefinitionMock.mockReturnValue({ |
| 499 | + provider: { id: "firecrawl" }, |
| 500 | + definition: { |
| 501 | + description: "firecrawl", |
| 502 | + parameters: {}, |
| 503 | + execute: async () => ({ |
| 504 | + text: "provider rescued despite hung cancel", |
| 505 | + status: 200, |
| 506 | + contentType: "text/plain", |
| 507 | + extractor: "custom-provider", |
| 508 | + }), |
| 509 | + }, |
| 510 | + }); |
| 511 | + |
| 512 | + const tool = createWebFetchTool({ |
| 513 | + config: { |
| 514 | + tools: { web: { fetch: { cacheTtlMinutes: 0 } } }, |
| 515 | + } as OpenClawConfig, |
| 516 | + sandboxed: false, |
| 517 | + }); |
| 518 | + const started = Date.now(); |
| 519 | + const result = await Promise.race([ |
| 520 | + tool?.execute?.("call-provider-fallback", { |
| 521 | + url: "https://example.com/hung-cancel-fallback", |
| 522 | + }), |
| 523 | + new Promise((_, reject) => { |
| 524 | + setTimeout(() => reject(new Error("fallback blocked on never-settling cancel")), 1500); |
| 525 | + }), |
| 526 | + ]); |
| 527 | + const elapsedMs = Date.now() - started; |
| 528 | + const details = (result as { details?: { text?: string; extractor?: string } })?.details; |
| 529 | + |
| 530 | + expect(details?.extractor).toBe("custom-provider"); |
| 531 | + expect(details?.text).toContain("provider rescued despite hung cancel"); |
| 532 | + expect(elapsedMs).toBeLessThan(1500); |
| 533 | + console.log( |
| 534 | + `[web-fetch never-settling cancel proof] returned=true elapsed_ms=${elapsedMs} extractor=${details?.extractor ?? "n/a"}`, |
| 535 | + ); |
| 536 | + }); |
| 537 | + |
| 538 | + it("cancels unread non-OK body over real guarded HTTP when provider fallback succeeds", async () => { |
| 539 | + // Real node:http upstream + production guarded fetch path (private-network allow |
| 540 | + // only for this loopback proof). Provider fallback is configured; cancel must run |
| 541 | + // before the early return so the abandoned body is closed. |
| 542 | + const realGuarded = webGuardedFetch.fetchWithWebToolsNetworkGuard; |
| 543 | + const guardedSpy = vi |
| 544 | + .spyOn(webGuardedFetch, "fetchWithWebToolsNetworkGuard") |
| 545 | + .mockImplementation((params) => |
| 546 | + realGuarded({ |
| 547 | + ...params, |
| 548 | + policy: { |
| 549 | + ...params.policy, |
| 550 | + dangerouslyAllowPrivateNetwork: true, |
| 551 | + }, |
| 552 | + }), |
| 553 | + ); |
| 554 | + |
| 555 | + let cancelInvoked = 0; |
| 556 | + const originalCancel = ReadableStream.prototype.cancel; |
| 557 | + ReadableStream.prototype.cancel = function cancel( |
| 558 | + this: ReadableStream, |
| 559 | + reason?: unknown, |
| 560 | + ): Promise<void> { |
| 561 | + cancelInvoked += 1; |
| 562 | + return originalCancel.call(this, reason); |
| 563 | + }; |
| 564 | + |
| 565 | + let serverSawClose = false; |
| 566 | + let server: Server | undefined; |
| 567 | + try { |
| 568 | + server = createServer((req, res) => { |
| 569 | + res.writeHead(503, { |
| 570 | + "Content-Type": "text/plain; charset=utf-8", |
| 571 | + "Content-Length": "1048576", |
| 572 | + }); |
| 573 | + res.write("upstream-error-body-chunk\n"); |
| 574 | + const timer = setInterval(() => { |
| 575 | + try { |
| 576 | + res.write("x".repeat(2048)); |
| 577 | + } catch { |
| 578 | + clearInterval(timer); |
| 579 | + } |
| 580 | + }, 10); |
| 581 | + const markClosed = () => { |
| 582 | + serverSawClose = true; |
| 583 | + clearInterval(timer); |
| 584 | + try { |
| 585 | + res.end(); |
| 586 | + } catch { |
| 587 | + // already closed |
| 588 | + } |
| 589 | + }; |
| 590 | + req.on("aborted", markClosed); |
| 591 | + req.on("close", markClosed); |
| 592 | + res.on("close", markClosed); |
| 593 | + }); |
| 594 | + await new Promise<void>((resolve) => { |
| 595 | + server?.listen(0, "127.0.0.1", () => resolve()); |
| 596 | + }); |
| 597 | + const address = server.address(); |
| 598 | + if (!address || typeof address === "string") { |
| 599 | + throw new Error("expected TCP listen address"); |
| 600 | + } |
| 601 | + const url = `http://127.0.0.1:${address.port}/non-ok-fallback`; |
| 602 | + |
| 603 | + resolveWebFetchDefinitionMock.mockReturnValue({ |
| 604 | + provider: { id: "firecrawl" }, |
| 605 | + definition: { |
| 606 | + description: "firecrawl", |
| 607 | + parameters: {}, |
| 608 | + execute: async () => ({ |
| 609 | + text: "provider rescued from real upstream", |
| 610 | + status: 200, |
| 611 | + contentType: "text/plain", |
| 612 | + extractor: "custom-provider", |
| 613 | + }), |
| 614 | + }, |
| 615 | + }); |
| 616 | + |
| 617 | + const tool = createWebFetchTool({ |
| 618 | + config: { |
| 619 | + tools: { web: { fetch: { cacheTtlMinutes: 0 } } }, |
| 620 | + } as OpenClawConfig, |
| 621 | + sandboxed: false, |
| 622 | + }); |
| 623 | + const started = Date.now(); |
| 624 | + const result = await tool?.execute?.("call-provider-fallback", { url }); |
| 625 | + const elapsedMs = Date.now() - started; |
| 626 | + const details = result?.details as { text?: string; extractor?: string }; |
| 627 | + |
| 628 | + await new Promise<void>((resolve) => { |
| 629 | + setTimeout(resolve, 150); |
| 630 | + }); |
| 631 | + |
| 632 | + expect(details.extractor).toBe("custom-provider"); |
| 633 | + expect(details.text).toContain("provider rescued from real upstream"); |
| 634 | + expect(cancelInvoked).toBeGreaterThan(0); |
| 635 | + expect(serverSawClose).toBe(true); |
| 636 | + console.log( |
| 637 | + `[web-fetch live guarded HTTP cancel proof] url_host=127.0.0.1 cancel_invoked=${cancelInvoked} server_closed=${serverSawClose} extractor=${details.extractor ?? "n/a"} elapsed_ms=${elapsedMs}`, |
| 638 | + ); |
| 639 | + } finally { |
| 640 | + ReadableStream.prototype.cancel = originalCancel; |
| 641 | + guardedSpy.mockRestore(); |
| 642 | + await new Promise<void>((resolve) => { |
| 643 | + if (!server) { |
| 644 | + resolve(); |
| 645 | + return; |
| 646 | + } |
| 647 | + server.close(() => resolve()); |
| 648 | + }); |
| 649 | + } |
| 650 | + }); |
362 | 651 | }); |
0 commit comments