Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

4.0 KB
Raw Blame
import { describe, test, expect, beforeAll, afterAll } from 'vitest'
import { writeFile, mkdtemp, rm } from 'fs/promises'
import { join } from 'path'
import { tmpdir } from 'os'
import { createServer, type IncomingMessage, type Server } from 'http'
import { AddressInfo } from 'net'
import { uploadFile } from '../../src/template/buildApi'

// Regression test for e2b-dev/e2b#1243 — uploadFile used to pass a Node
// Readable directly to fetch, which made undici fall back to
// Transfer-Encoding: chunked. S3 presigned PUT URLs reject that with 501
// NotImplemented. The fix spools the archive to a temporary file and streams
// it from disk with an explicit Content-Length via undici's fetch, which
// honors the header on stream bodies on every runtime (Deno's native fetch
// ignores it and chunks). This suite runs under both Node and Deno.
describe('uploadFile transfer encoding', () => {
  let testDir: string
  let server: Server
  let baseUrl: string
  let capturedHeaders: IncomingMessage['headers'] = {}
  let capturedBodyLength = 0

  beforeAll(async () => {
    testDir = await mkdtemp(join(tmpdir(), 'uploadFile-test-'))
    await writeFile(join(testDir, 'hello.txt'), 'hello world')

    server = createServer((req, res) => {
      capturedHeaders = req.headers
      let bytes = 0
      req.on('data', (chunk: Buffer) => {
        bytes += chunk.length
      })
      req.on('end', () => {
        capturedBodyLength = bytes
        res.writeHead(200)
        res.end()
      })
    })
    await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
    const { port } = server.address() as AddressInfo
    baseUrl = `http://127.0.0.1:${port}/upload`
  })

  afterAll(async () => {
    await new Promise<void>((resolve) => server.close(() => resolve()))
    await rm(testDir, { recursive: true, force: true })
  })

  test('sets Content-Length and does not use chunked transfer encoding', async () => {
    await uploadFile(
      {
        fileName: '*.txt',
        fileContextPath: testDir,
        url: baseUrl,
        ignorePatterns: [],
        resolveSymlinks: false,
        gzip: true,
      },
      undefined
    )

    expect(capturedHeaders['content-length']).toBeDefined()
    const contentLength = Number(capturedHeaders['content-length'])
    expect(contentLength).toBeGreaterThan(0)
    expect(contentLength).toBe(capturedBodyLength)

    const transferEncoding = capturedHeaders['transfer-encoding']
    if (transferEncoding !== undefined) {
      expect(transferEncoding.toLowerCase()).not.toContain('chunked')
    }

    // Presigned upload URLs sign the request headers, so an implicit
    // Content-Type (e.g. inferred from the archive's file extension) makes
    // the storage backend reject the upload with 403 Forbidden.
    expect(capturedHeaders['content-type']).toBeUndefined()

    // S3/GCS presigned PUTs sign the header set — the upload must add nothing the API did not ask for.
    expect(capturedHeaders['x-ms-blob-type']).toBeUndefined()
  })

  test('sends the headers the API returned with the upload link', async () => {
    await uploadFile(
      {
        fileName: '*.txt',
        fileContextPath: testDir,
        url: baseUrl,
        headers: { 'x-ms-blob-type': 'BlockBlob' },
        ignorePatterns: [],
        resolveSymlinks: false,
        gzip: true,
      },
      undefined
    )

    // Azure's Put Blob needs a request header a SAS cannot carry, so the API hands it back instead.
    expect(capturedHeaders['x-ms-blob-type']).toBe('BlockBlob')
  })

  test('keeps its own Content-Length when the API returns one', async () => {
    await uploadFile(
      {
        fileName: '*.txt',
        fileContextPath: testDir,
        url: baseUrl,
        // lowercase on purpose: header names are case-insensitive, object keys are not
        headers: { 'content-length': '1' },
        ignorePatterns: [],
        resolveSymlinks: false,
        gzip: true,
      },
      undefined
    )

    expect(Number(capturedHeaders['content-length'])).toBe(capturedBodyLength)
  })
})