diff --git a/extensions/vscode/e2e/actions/NextEdit.actions.ts b/extensions/vscode/e2e/actions/NextEdit.actions.ts index 626626843..6a5d55b7d 100644 --- a/extensions/vscode/e2e/actions/NextEdit.actions.ts +++ b/extensions/vscode/e2e/actions/NextEdit.actions.ts @@ -50,7 +50,7 @@ export class NextEditActions { await new Workbench().executeCommand("Continue: Force Next Edit"); console.log("Executed 'Force Next Edit' command"); - + // console.log("Waiting for SVG decoration to appear..."); // await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.MD); // console.log("Wait completed, looking for decoration..."); diff --git a/extensions/vscode/e2e/selectors/NextEdit.selectors.ts b/extensions/vscode/e2e/selectors/NextEdit.selectors.ts index de5ff6e65..e3452f909 100644 --- a/extensions/vscode/e2e/selectors/NextEdit.selectors.ts +++ b/extensions/vscode/e2e/selectors/NextEdit.selectors.ts @@ -1,50 +1,37 @@ import { By, WebDriver } from "vscode-extension-tester"; - export class NextEditSelectors { /** * Get the SVG decoration element if present (for next edit). */ public static async getSvgDecoration(driver: WebDriver) { - console.log("===") + console.log("==="); // return SelectorUtils.getElementByClassName( // driver, // "TextEditorDecorationType", // ); - return Promise.any( - [ - await driver.findElement( - By.css("[class*='TextEditorDecorationType']") - ), - await driver.findElement( - By.css("[class*=TextEditorDecorationType]") - ), - await driver.findElement( - By.css("*[class*='TextEditorDecorationType']") - ), - await driver.findElement( - By.css("*[class*=TextEditorDecorationType]") - ), - await driver.findElement( - By.css("span[class*='TextEditorDecorationType']") - ), - await driver.findElement( - By.css("span[class*=TextEditorDecorationType]") - ), - await driver.findElement( - By.xpath(`//span[contains(@class, 'TextEditorDecorationType')]`) - ), - await driver.findElement( - By.xpath(`//span[contains(@class, TextEditorDecorationType)]`) - ), - await driver.findElement( - By.xpath(`//*[contains(@class, 'TextEditorDecorationType')]`) - ), - await driver.findElement( - By.xpath(`//*[contains(@class, TextEditorDecorationType)]`) - ), - ] - ) + return Promise.any([ + await driver.findElement(By.css("[class*='TextEditorDecorationType']")), + await driver.findElement(By.css("[class*=TextEditorDecorationType]")), + await driver.findElement(By.css("*[class*='TextEditorDecorationType']")), + await driver.findElement(By.css("*[class*=TextEditorDecorationType]")), + await driver.findElement( + By.css("span[class*='TextEditorDecorationType']"), + ), + await driver.findElement(By.css("span[class*=TextEditorDecorationType]")), + await driver.findElement( + By.xpath(`//span[contains(@class, 'TextEditorDecorationType')]`), + ), + await driver.findElement( + By.xpath(`//span[contains(@class, TextEditorDecorationType)]`), + ), + await driver.findElement( + By.xpath(`//*[contains(@class, 'TextEditorDecorationType')]`), + ), + await driver.findElement( + By.xpath(`//*[contains(@class, TextEditorDecorationType)]`), + ), + ]); // try { // const decorations = await driver.findElement( // // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]") @@ -72,7 +59,7 @@ export class NextEditSelectors { // } catch (e) { // console.log("No decoration elements found:", e.message); // } - + // const decorations = await driver.findElement( // By.css("[class*='TextEditorDecorationType']"), // ); diff --git a/extensions/vscode/e2e/selectors/SelectorUtils.ts b/extensions/vscode/e2e/selectors/SelectorUtils.ts index eef58e04e..f3d210198 100644 --- a/extensions/vscode/e2e/selectors/SelectorUtils.ts +++ b/extensions/vscode/e2e/selectors/SelectorUtils.ts @@ -29,7 +29,7 @@ export class SelectorUtils { public static getElementByClassName( driver: WebDriver, - className: string + className: string, ): Promise { return driver.findElement( // By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]") diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index 6f213d0cb..4123b4804 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -10,7 +10,7 @@ describe("Autocomplete", () => { before(async function () { process.env.NEXT_EDIT_TEST_ENABLED = "false"; - }) + }); beforeEach(async function () { this.timeout(DEFAULT_TIMEOUT.XL); diff --git a/packages/continue-sdk/package.json b/packages/continue-sdk/package.json index f67f86f95..ae682237e 100644 --- a/packages/continue-sdk/package.json +++ b/packages/continue-sdk/package.json @@ -22,4 +22,4 @@ "devDependencies": { "typescript": "^5.0.0" } -} \ No newline at end of file +} diff --git a/packages/fetch/src/fetch.e2e.test.ts b/packages/fetch/src/fetch.e2e.test.ts new file mode 100644 index 000000000..fa0a3c4fc --- /dev/null +++ b/packages/fetch/src/fetch.e2e.test.ts @@ -0,0 +1,518 @@ +import * as fs from "node:fs"; +import * as http from "node:http"; +import * as https from "node:https"; +import * as os from "node:os"; +import * as path from "node:path"; +import { execSync } from "node:child_process"; +import { afterEach, describe, expect, test } from "vitest"; +import { fetchwithRequestOptions } from "./fetch.js"; + +// Test server ports +const HTTP_PORT = 3001; +const HTTPS_PORT = 3002; + +// Track servers and temp dirs for cleanup +const serversToCleanup: Array = []; +const tempDirsToCleanup: string[] = []; + +afterEach(() => { + // Clean up all servers + serversToCleanup.forEach((server) => server.close()); + serversToCleanup.length = 0; + + // Clean up temp directories + tempDirsToCleanup.forEach((tempDir) => { + if (fs.existsSync(tempDir)) { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + tempDirsToCleanup.length = 0; +}); + +/** + * Create a temporary directory for test files + */ +function createTempDir(): string { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "fetch-e2e-test-")); + tempDirsToCleanup.push(tempDir); + return tempDir; +} + +/** + * Generate a self-signed certificate for testing + */ +async function generateCertificate( + tempDir: string, + name: string, + options: { cn: string; san: string[]; org: string }, +): Promise<{ certPath: string; keyPath: string; caCertPath: string }> { + const certPath = path.join(tempDir, `${name}.crt`); + const keyPath = path.join(tempDir, `${name}.key`); + const caCertPath = path.join(tempDir, `${name}-ca.crt`); + + try { + // Generate a private key + execSync(`openssl genrsa -out "${keyPath}" 2048`, { stdio: "pipe" }); + + // Create config file for certificate + const configPath = path.join(tempDir, `${name}.conf`); + const altNames = options.san + .map((san, i) => { + return san.match(/^\d+\.\d+\.\d+\.\d+$/) + ? `IP.${i + 1} = ${san}` + : `DNS.${i + 1} = ${san}`; + }) + .join("\n"); + + const configContent = ` +[req] +distinguished_name = req_distinguished_name +req_extensions = v3_req +prompt = no + +[req_distinguished_name] +C = US +ST = Test +L = Test +O = ${options.org} +CN = ${options.cn} + +[v3_req] +keyUsage = keyEncipherment, dataEncipherment +extendedKeyUsage = serverAuth +subjectAltName = @alt_names + +[alt_names] +${altNames} +`; + fs.writeFileSync(configPath, configContent); + + // Generate a self-signed certificate + execSync( + `openssl req -new -x509 -key "${keyPath}" -out "${certPath}" -days 365 -config "${configPath}" -extensions v3_req`, + { stdio: "pipe" }, + ); + + // Copy the certificate as CA (for testing custom CA scenarios) + fs.copyFileSync(certPath, caCertPath); + + return { certPath, keyPath, caCertPath }; + } catch (error) { + // Fallback: create minimal test certificates if OpenSSL not available + const key = `-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7VJTUt9Us8cKB +wEiOfniel+2jNcJjYUiUoq5YbVKk+xqt4bOMh5DNFJ3LnU1OaUHyG5sHlgNyKA== +-----END PRIVATE KEY-----`; + + const cert = `-----BEGIN CERTIFICATE----- +MIICljCCAX4CCQCKnW9qX7TlxzANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJV +UzAeFw0yNDAxMDEwMDAwMDBaFw0yNTAxMDEwMDAwMDBaMA0xCzAJBgNVBAYTAlVT +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1L7VLPHCQD1OvF4p +4td9ozXCY2FIlKKuWG1SpPsareGzjIeQzRSdy51NTmlB8hubB5YDcigN8= +-----END CERTIFICATE-----`; + + fs.writeFileSync(keyPath, key); + fs.writeFileSync(certPath, cert); + fs.writeFileSync(caCertPath, cert); + + return { certPath, keyPath, caCertPath }; + } +} + +/** + * Start a simple HTTP server for testing + */ +async function startHttpServer(): Promise { + const server = http.createServer((req, res) => { + const url = new URL(req.url!, `http://localhost:${HTTP_PORT}`); + + if (url.pathname === "/json") { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end( + JSON.stringify({ + message: "Hello from HTTP server", + method: req.method, + }), + ); + } else if (url.pathname === "/headers") { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ headers: req.headers })); + } else if (url.pathname === "/body") { + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); + req.on("end", () => { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ body, headers: req.headers })); + }); + } else if (url.pathname === "/status/404") { + res.writeHead(404, { "Content-Type": "text/plain" }); + res.end("Not Found"); + } else if (url.pathname === "/slow") { + setTimeout(() => { + res.writeHead(200, { "Content-Type": "text/plain" }); + res.end("Slow response"); + }, 100); + } else { + res.writeHead(404); + res.end("Not Found"); + } + }); + + await new Promise((resolve) => { + server.listen(HTTP_PORT, () => resolve()); + }); + + serversToCleanup.push(server); + return server; +} + +/** + * Start an HTTPS server with given certificates + */ +async function startHttpsServer( + certPath: string, + keyPath: string, +): Promise { + const server = https.createServer( + { + cert: fs.readFileSync(certPath), + key: fs.readFileSync(keyPath), + }, + (req, res) => { + const url = new URL(req.url!, `https://localhost:${HTTPS_PORT}`); + + if (url.pathname === "/secure") { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end( + JSON.stringify({ message: "Hello from HTTPS server", secure: true }), + ); + } else if (url.pathname === "/headers") { + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ headers: req.headers })); + } else { + res.writeHead(404); + res.end("Not Found"); + } + }, + ); + + await new Promise((resolve) => { + server.listen(HTTPS_PORT, () => resolve()); + }); + + serversToCleanup.push(server); + return server; +} + +describe("fetchwithRequestOptions E2E tests", () => { + describe("HTTP requests", () => { + test("should make basic HTTP GET request", async () => { + await startHttpServer(); + + const response = await fetchwithRequestOptions( + `http://localhost:${HTTP_PORT}/json`, + ); + + expect(response.status).toBe(200); + const data = (await response.json()) as { + message: string; + method: string; + }; + expect(data).toEqual({ + message: "Hello from HTTP server", + method: "GET", + }); + }); + + test("should make HTTP POST request with body", async () => { + await startHttpServer(); + + const response = await fetchwithRequestOptions( + `http://localhost:${HTTP_PORT}/json`, + { + method: "POST", + body: JSON.stringify({ test: "data" }), + headers: { "Content-Type": "application/json" }, + }, + ); + + expect(response.status).toBe(200); + const data = (await response.json()) as { + message: string; + method: string; + }; + expect(data.method).toBe("POST"); + }); + + test("should handle custom headers", async () => { + await startHttpServer(); + + const response = await fetchwithRequestOptions( + `http://localhost:${HTTP_PORT}/headers`, + { + headers: { "X-Custom-Header": "test-value" }, + }, + ); + + const data = (await response.json()) as { + headers: Record; + }; + expect(data.headers["x-custom-header"]).toBe("test-value"); + }); + + test("should handle error responses", async () => { + await startHttpServer(); + + const response = await fetchwithRequestOptions( + `http://localhost:${HTTP_PORT}/status/404`, + ); + + expect(response.status).toBe(404); + expect(response.ok).toBe(false); + }); + }); + + describe("Request options integration", () => { + test("should merge extra body properties", async () => { + await startHttpServer(); + + const response = await fetchwithRequestOptions( + `http://localhost:${HTTP_PORT}/body`, + { + method: "POST", + body: JSON.stringify({ original: "data" }), + headers: { "Content-Type": "application/json" }, + }, + { + extraBodyProperties: { extra: "property" }, + }, + ); + + expect(response.status).toBe(200); + const data = (await response.json()) as { + body: string; + headers: Record; + }; + const body = JSON.parse(data.body); + expect(body).toEqual({ original: "data", extra: "property" }); + }); + + test("should handle RequestOptions headers", async () => { + await startHttpServer(); + + const response = await fetchwithRequestOptions( + `http://localhost:${HTTP_PORT}/headers`, + {}, + { + headers: { "X-Request-Options-Header": "from-request-options" }, + }, + ); + + const data = (await response.json()) as { + headers: Record; + }; + expect(data.headers["x-request-options-header"]).toBe( + "from-request-options", + ); + }); + + test("should merge headers from init and requestOptions", async () => { + await startHttpServer(); + + const response = await fetchwithRequestOptions( + `http://localhost:${HTTP_PORT}/headers`, + { + headers: { "X-Init-Header": "from-init" }, + }, + { + headers: { "X-Request-Options-Header": "from-request-options" }, + }, + ); + + const data = (await response.json()) as { + headers: Record; + }; + expect(data.headers["x-init-header"]).toBe("from-init"); + expect(data.headers["x-request-options-header"]).toBe( + "from-request-options", + ); + }); + }); + + describe("Certificate handling - Enterprise scenarios", () => { + test("should REJECT self-signed certificates when SSL verification is enabled", async () => { + const tempDir = createTempDir(); + const serverCerts = await generateCertificate(tempDir, "server", { + cn: "localhost", + san: ["localhost", "127.0.0.1"], + org: "Test", + }); + + await startHttpsServer(serverCerts.certPath, serverCerts.keyPath); + + // This simulates the customer's "unable to get local issuer certificate" error + await expect( + fetchwithRequestOptions( + `https://localhost:${HTTPS_PORT}/secure`, + {}, + { verifySsl: true }, // No custom CA provided + ), + ).rejects.toThrow(); // Should fail with certificate error + }); + + test("should ACCEPT self-signed certificates when SSL verification is disabled", async () => { + const tempDir = createTempDir(); + const serverCerts = await generateCertificate(tempDir, "server", { + cn: "localhost", + san: ["localhost", "127.0.0.1"], + org: "Test", + }); + + await startHttpsServer(serverCerts.certPath, serverCerts.keyPath); + + const response = await fetchwithRequestOptions( + `https://localhost:${HTTPS_PORT}/secure`, + {}, + { verifySsl: false }, + ); + + expect(response.status).toBe(200); + const data = (await response.json()) as { + message: string; + secure: boolean; + }; + expect(data.secure).toBe(true); + }); + + test("should ACCEPT self-signed certificates with custom CA bundle", async () => { + const tempDir = createTempDir(); + const serverCerts = await generateCertificate(tempDir, "server", { + cn: "localhost", + san: ["localhost", "127.0.0.1"], + org: "Test", + }); + + await startHttpsServer(serverCerts.certPath, serverCerts.keyPath); + + const response = await fetchwithRequestOptions( + `https://localhost:${HTTPS_PORT}/secure`, + {}, + { + caBundlePath: serverCerts.caCertPath, // Our self-signed cert as CA + verifySsl: true, + }, + ); + + expect(response.status).toBe(200); + const data = (await response.json()) as { + message: string; + secure: boolean; + }; + expect(data.secure).toBe(true); + }); + + test("should REJECT certificates when provided WRONG CA bundle", async () => { + const tempDir = createTempDir(); + const serverCerts = await generateCertificate(tempDir, "server", { + cn: "localhost", + san: ["localhost", "127.0.0.1"], + org: "Test", + }); + + // Generate a different certificate as the "wrong" CA + const wrongCaCerts = await generateCertificate(tempDir, "wrong-ca", { + cn: "wrong-ca", + san: ["wrong-ca"], + org: "Wrong CA", + }); + + await startHttpsServer(serverCerts.certPath, serverCerts.keyPath); + + // This should fail because the wrong CA can't validate our server certificate + await expect( + fetchwithRequestOptions( + `https://localhost:${HTTPS_PORT}/secure`, + {}, + { + caBundlePath: wrongCaCerts.caCertPath, + verifySsl: true, + }, + ), + ).rejects.toThrow(); // Should fail with certificate validation error + }); + + test("should REJECT certificates when CA bundle file is corrupted", async () => { + const tempDir = createTempDir(); + const serverCerts = await generateCertificate(tempDir, "server", { + cn: "localhost", + san: ["localhost", "127.0.0.1"], + org: "Test", + }); + + // Create a corrupted/invalid certificate file + const corruptedCaPath = path.join(tempDir, "corrupted-ca.pem"); + const corruptedContent = `-----BEGIN CERTIFICATE----- +This is not a valid certificate content +Just some random text that looks like a cert +-----END CERTIFICATE-----`; + + fs.writeFileSync(corruptedCaPath, corruptedContent); + + await startHttpsServer(serverCerts.certPath, serverCerts.keyPath); + + // This should fail because the corrupted CA file can't be parsed + await expect( + fetchwithRequestOptions( + `https://localhost:${HTTPS_PORT}/secure`, + {}, + { + caBundlePath: corruptedCaPath, + verifySsl: true, + }, + ), + ).rejects.toThrow(); // Should fail with certificate parsing or validation error + }); + + test("should REJECT certificates when CA bundle file does not exist", async () => { + const tempDir = createTempDir(); + const serverCerts = await generateCertificate(tempDir, "server", { + cn: "localhost", + san: ["localhost", "127.0.0.1"], + org: "Test", + }); + + const nonExistentCaPath = path.join(tempDir, "does-not-exist.pem"); + + await startHttpsServer(serverCerts.certPath, serverCerts.keyPath); + + // This should handle the missing file gracefully but still fail cert validation + await expect( + fetchwithRequestOptions( + `https://localhost:${HTTPS_PORT}/secure`, + {}, + { + caBundlePath: nonExistentCaPath, + verifySsl: true, + }, + ), + ).rejects.toThrow(); // Should fail with certificate validation error + }); + }); + + describe("Error handling", () => { + test("should handle network errors gracefully", async () => { + // Try to connect to a non-existent server + await expect( + fetchwithRequestOptions("http://localhost:9999/nonexistent"), + ).rejects.toThrow(); + }); + + test("should handle malformed URLs", async () => { + await expect( + fetchwithRequestOptions("not-a-valid-url"), + ).rejects.toThrow(); + }); + }); +}); diff --git a/packages/fetch/src/ssl-certificate.test.ts b/packages/fetch/src/ssl-certificate.test.ts new file mode 100644 index 000000000..75a0b888c --- /dev/null +++ b/packages/fetch/src/ssl-certificate.test.ts @@ -0,0 +1,301 @@ +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { CertsCache, getCertificateContent } from "./certs.js"; +import { getAgentOptions } from "./getAgentOptions.js"; + +// Store original env +const originalEnv = process.env; + +// Temporary directory for test certificate files +let tempDir: string; + +beforeEach(() => { + // Create a temporary directory for test files + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "cert-troubleshoot-test-")); + process.env = { ...originalEnv }; +}); + +afterEach(() => { + process.env = originalEnv; + CertsCache.getInstance().clear(); + + // Clean up temporary directory + if (tempDir && fs.existsSync(tempDir)) { + fs.rmSync(tempDir, { recursive: true, force: true }); + } +}); + +describe("SSL certificate handling", () => { + describe("CA certificate handling", () => { + test("should handle custom CA bundle from file path", async () => { + const customCaCert = `-----BEGIN CERTIFICATE----- +MIIDXTCCAkWgAwIBAgIJAKoK/heBjcOuMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMTcwODI4MTkzNDA5WhcNMTgwODI4MTkzNDA5WjBF +-----END CERTIFICATE-----`; + + const caCertPath = path.join(tempDir, "ca-bundle.pem"); + fs.writeFileSync(caCertPath, customCaCert); + + const options = await getAgentOptions({ caBundlePath: caCertPath }); + + expect(options.ca).toBeDefined(); + expect(Array.isArray(options.ca)).toBe(true); + expect(options.ca).toContain(customCaCert); + }); + + test("should handle NODE_EXTRA_CA_CERTS environment variable", async () => { + const extraCaCert = `-----BEGIN CERTIFICATE----- +MIIDUzCCAjugAwIBAgIJALvxFjX5V+/vMA0GCSqGSIb3DQEBCwUAMDgxCzAJBgNV +BAYTAlVTMRAwDgYDVQQIDAdDb21wYW55MRcwFQYDVQQKDA5Db21wYW55IENvcnAw +-----END CERTIFICATE-----`; + + const extraCaPath = path.join(tempDir, "extra-ca.crt"); + fs.writeFileSync(extraCaPath, extraCaCert); + + process.env.NODE_EXTRA_CA_CERTS = extraCaPath; + + const options = await getAgentOptions(); + + expect(options.ca).toBeDefined(); + expect(Array.isArray(options.ca)).toBe(true); + expect(options.ca).toContain(extraCaCert); + }); + + test("should combine NODE_EXTRA_CA_CERTS with custom CA bundle", async () => { + const extraCaCert = `-----BEGIN CERTIFICATE----- +MIIDExtra1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE-----`; + + const customCaCert = `-----BEGIN CERTIFICATE----- +MIIDCustom1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE-----`; + + const extraCaPath = path.join(tempDir, "extra-ca.crt"); + const customCaPath = path.join(tempDir, "custom-ca.pem"); + + fs.writeFileSync(extraCaPath, extraCaCert); + fs.writeFileSync(customCaPath, customCaCert); + + process.env.NODE_EXTRA_CA_CERTS = extraCaPath; + + const options = await getAgentOptions({ caBundlePath: customCaPath }); + + expect(options.ca).toBeDefined(); + expect(Array.isArray(options.ca)).toBe(true); + expect(options.ca).toContain(extraCaCert); + expect(options.ca).toContain(customCaCert); + }); + }); + + describe("Data URI certificate handling", () => { + test("should handle base64 encoded data URI certificates", () => { + const originalCert = `-----BEGIN CERTIFICATE----- +MIIDUzCCAjugAwIBAgIJALvxFjX5V+/vMA0GCSqGSIb3DQEB +-----END CERTIFICATE-----`; + + const base64Data = Buffer.from(originalCert).toString("base64"); + const dataUri = `data:application/x-pem-file;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(originalCert); + }); + + test("should handle URL-encoded data URI certificates", () => { + const originalCert = + "certificate with spaces and special chars: !@#$%^&*()"; + const encodedData = encodeURIComponent(originalCert); + const dataUri = `data:text/plain,${encodedData}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(originalCert); + }); + }); + + describe("SSL/TLS configuration", () => { + test("should configure SSL verification correctly", async () => { + // Test with SSL verification enabled + let options = await getAgentOptions({ verifySsl: true }); + expect(options.rejectUnauthorized).toBe(true); + + // Test with SSL verification disabled + options = await getAgentOptions({ verifySsl: false }); + expect(options.rejectUnauthorized).toBe(false); + }); + + test("should configure timeout correctly", async () => { + const customTimeout = 60; // 1 minute in seconds + const options = await getAgentOptions({ timeout: customTimeout }); + + expect(options.timeout).toBe(customTimeout * 1000); // Should be converted to milliseconds + }); + + test("should handle client certificate authentication", async () => { + const clientCert = `-----BEGIN CERTIFICATE----- +MIIDClientCert1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE-----`; + + const clientKey = `-----BEGIN PRIVATE KEY----- +MIIEClientKey567890abcdefghijklmnopqrstuvwxyz +-----END PRIVATE KEY-----`; + + const clientCertPath = path.join(tempDir, "client.crt"); + const clientKeyPath = path.join(tempDir, "client.key"); + + fs.writeFileSync(clientCertPath, clientCert); + fs.writeFileSync(clientKeyPath, clientKey); + + const options = await getAgentOptions({ + clientCertificate: { + cert: clientCertPath, + key: clientKeyPath, + passphrase: "test-passphrase", + }, + }); + + expect(options.cert).toBe(clientCert); + expect(options.key).toBe(clientKey); + expect(options.passphrase).toBe("test-passphrase"); + }); + }); + + describe("Certificate caching behavior", () => { + test("should cache certificate content to avoid repeated file reads", async () => { + const certsCache = CertsCache.getInstance(); + const certPath = path.join(tempDir, "cached-cert.pem"); + const certContent = `-----BEGIN CERTIFICATE----- +MIIDCachedCert1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE-----`; + + fs.writeFileSync(certPath, certContent); + + // First call should read from file + const result1 = await certsCache.getCachedCustomCert(certPath); + expect(result1).toBe(certContent); + + // Modify the file on disk + const modifiedContent = certContent.replace("CachedCert", "ModifiedCert"); + fs.writeFileSync(certPath, modifiedContent); + + // Second call should return cached content, not the modified content + const result2 = await certsCache.getCachedCustomCert(certPath); + expect(result2).toBe(certContent); // Should still be the original cached content + }); + + test("should handle cache clearing", async () => { + const certsCache = CertsCache.getInstance(); + const certPath = path.join(tempDir, "clear-cache-cert.pem"); + const originalContent = `-----BEGIN CERTIFICATE----- +MIIDOriginalCert1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE-----`; + + fs.writeFileSync(certPath, originalContent); + + // Load into cache + await certsCache.getCachedCustomCert(certPath); + + // Clear cache + certsCache.clear(); + + // Modify file + const newContent = originalContent.replace("OriginalCert", "NewCert"); + fs.writeFileSync(certPath, newContent); + + // Should read new content after cache clear + const result2 = await certsCache.getCachedCustomCert(certPath); + expect(result2).toBe(newContent); + }); + }); + + describe("Error handling scenarios", () => { + test("should handle non-existent certificate files gracefully", async () => { + const nonExistentPath = path.join(tempDir, "does-not-exist.pem"); + + // Should not throw but should continue with system certificates only + const options = await getAgentOptions({ caBundlePath: nonExistentPath }); + + expect(options.ca).toBeDefined(); + expect(Array.isArray(options.ca)).toBe(true); + // Should only contain system certificates, not the missing custom one + expect(options.ca.length).toBeGreaterThan(0); + }); + + test("should handle empty certificate files", () => { + const emptyCertPath = path.join(tempDir, "empty-cert.pem"); + fs.writeFileSync(emptyCertPath, ""); + + const result = getCertificateContent(emptyCertPath); + expect(result).toBe(""); + }); + + test("should handle malformed data URIs", () => { + const validMalformedDataUris = ["data:invalid-format", "data:"]; + + validMalformedDataUris.forEach((uri) => { + // These should not throw but may return unexpected content + expect(() => getCertificateContent(uri)).not.toThrow(); + const result = getCertificateContent(uri); + expect(typeof result).toBe("string"); + }); + + // This one will be treated as a file path and should throw + expect(() => getCertificateContent("not-a-data-uri-at-all")).toThrow( + "ENOENT", + ); + }); + }); + + describe("Real-world scenarios", () => { + test("should handle certificate bundle with multiple certificates", () => { + const bundleContent = `-----BEGIN CERTIFICATE----- +MIIDRootCA1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDIntermediateCA1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE-----`; + + const bundlePath = path.join(tempDir, "ca-bundle.pem"); + fs.writeFileSync(bundlePath, bundleContent); + + const result = getCertificateContent(bundlePath); + expect(result).toBe(bundleContent); + expect(result).toContain("RootCA"); + expect(result).toContain("IntermediateCA"); + }); + + test("should work with common certificate file extensions", () => { + const certExtensions = [".pem", ".crt", ".cer"]; + const testCert = `-----BEGIN CERTIFICATE----- +MIIDTestCert1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE-----`; + + for (const ext of certExtensions) { + const certPath = path.join(tempDir, `test-cert${ext}`); + fs.writeFileSync(certPath, testCert); + + const result = getCertificateContent(certPath); + expect(result).toBe(testCert); + } + }); + + test("should handle proxy scenarios with custom certificates", async () => { + // Test that certificates work properly when proxy might be involved + const proxyCaCert = `-----BEGIN CERTIFICATE----- +MIIDProxyCA1234567890abcdefghijklmnopqrstuvwxyz +-----END CERTIFICATE-----`; + + const proxyCaPath = path.join(tempDir, "proxy-ca.pem"); + fs.writeFileSync(proxyCaPath, proxyCaCert); + + const options = await getAgentOptions({ caBundlePath: proxyCaPath }); + + expect(options.ca).toBeDefined(); + expect(options.ca).toContain(proxyCaCert); + expect(options.keepAlive).toBe(true); // Should work with keep-alive for proxy scenarios + }); + }); +}); diff --git a/packages/fetch/src/stream.test.ts b/packages/fetch/src/stream.test.ts index d52221954..084002ac5 100644 --- a/packages/fetch/src/stream.test.ts +++ b/packages/fetch/src/stream.test.ts @@ -90,6 +90,13 @@ describe("parseDataLine", () => { ); }); + test("parseDataLine should throw error when data contains error object with message", () => { + const line = 'data: {"error":{"message":"detailed error message"}}'; + expect(() => parseDataLine(line)).toThrow( + "Error streaming response: detailed error message", + ); + }); + test("parseDataLine should handle empty objects", () => { const line = "data: {}"; const result = parseDataLine(line); diff --git a/packages/fetch/vitest.config.ts b/packages/fetch/vitest.config.ts index 50f824200..d4dab2104 100644 --- a/packages/fetch/vitest.config.ts +++ b/packages/fetch/vitest.config.ts @@ -5,6 +5,7 @@ export default defineConfig({ environment: "node", timeout: 10000, globals: true, + include: ["**/*.{test,spec}.?(c|m)[jt]s?(x)"], }, resolve: { alias: { @@ -12,6 +13,8 @@ export default defineConfig({ "./getAgentOptions.js": "./getAgentOptions.ts", "./stream.js": "./stream.ts", "./util.js": "./util.ts", + "./certs.js": "./certs.ts", + "./fetch.js": "./fetch.ts", }, }, });