Skip to content

armgit / E2B

Public Imported from GitHub
0

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

9.9 KB
Raw Blame
import { assert } from 'vitest'

import { sandboxTest, isDebug } from '../setup.js'
import { Sandbox, SandboxError } from '../../src'

const SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS = 120_000

sandboxTest.skipIf(isDebug)(
  'create a snapshot from sandbox',
  async ({ sandbox }) => {
    // Write a file to the sandbox
    await sandbox.files.write('/home/user/test.txt', 'snapshot test content')

    // Create a snapshot
    const snapshot = await sandbox.createSnapshot()

    assert.isString(snapshot.snapshotId)
    assert.isTrue(snapshot.snapshotId.length > 0)

    // Cleanup
    await Sandbox.deleteSnapshot(snapshot.snapshotId)
  }
)

sandboxTest.skipIf(isDebug)(
  'create sandbox from snapshot',
  async ({ sandbox, sandboxTestId }) => {
    const testContent = 'content from original sandbox'

    // Write a file to the sandbox
    await sandbox.files.write('/home/user/test.txt', testContent)

    // Create a snapshot
    const snapshot = await sandbox.createSnapshot()

    try {
      // Create a new sandbox from the snapshot
      const newSandbox = await Sandbox.create(snapshot.snapshotId, {
        metadata: { sandboxTestId: `${sandboxTestId}-from-snapshot` },
        requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
      })

      try {
        // Verify the file exists in the new sandbox
        const content = await newSandbox.files.read('/home/user/test.txt')
        assert.equal(content, testContent)
      } finally {
        await newSandbox.kill()
      }
    } finally {
      await Sandbox.deleteSnapshot(snapshot.snapshotId)
    }
  },
  180_000
)

sandboxTest.skipIf(isDebug)(
  'create multiple sandboxes from same snapshot',
  async ({ sandbox, sandboxTestId }) => {
    const testContent = 'shared snapshot content'

    await sandbox.files.write('/home/user/shared.txt', testContent)

    const snapshot = await sandbox.createSnapshot()

    let sandbox1: Sandbox | undefined
    let sandbox2: Sandbox | undefined
    try {
      // Create two sandboxes from the same snapshot
      sandbox1 = await Sandbox.create(snapshot.snapshotId, {
        metadata: { sandboxTestId: `${sandboxTestId}-branch-1` },
        requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
      })
      sandbox2 = await Sandbox.create(snapshot.snapshotId, {
        metadata: { sandboxTestId: `${sandboxTestId}-branch-2` },
        requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
      })

      // Both should have the same initial content
      const content1 = await sandbox1.files.read('/home/user/shared.txt')
      const content2 = await sandbox2.files.read('/home/user/shared.txt')

      assert.equal(content1, testContent)
      assert.equal(content2, testContent)

      // Modify one sandbox - should not affect the other
      await sandbox1.files.write(
        '/home/user/shared.txt',
        'modified in sandbox1'
      )

      const modifiedContent = await sandbox1.files.read('/home/user/shared.txt')
      const unchangedContent = await sandbox2.files.read(
        '/home/user/shared.txt'
      )

      assert.equal(modifiedContent, 'modified in sandbox1')
      assert.equal(unchangedContent, testContent)
    } finally {
      await Promise.all([
        sandbox1?.kill().catch(() => {}),
        sandbox2?.kill().catch(() => {}),
      ])
      await Sandbox.deleteSnapshot(snapshot.snapshotId)
    }
  },
  300_000
)

sandboxTest.skipIf(isDebug)('list snapshots', async ({ sandbox }) => {
  // Create a snapshot
  const snapshot = await sandbox.createSnapshot()

  try {
    // List all snapshots
    const paginator = Sandbox.listSnapshots()
    assert.isTrue(paginator.hasNext)

    const snapshots = await paginator.nextItems()
    assert.isArray(snapshots)

    // Find our snapshot in the list
    const found = snapshots.find((s) => s.snapshotId === snapshot.snapshotId)
    assert.isDefined(found)
  } finally {
    await Sandbox.deleteSnapshot(snapshot.snapshotId)
  }
})

sandboxTest.skipIf(isDebug)(
  'list snapshots for specific sandbox',
  async ({ sandbox }) => {
    // Create a snapshot
    const snapshot = await sandbox.createSnapshot()

    try {
      // List snapshots for this sandbox using instance method
      const paginator = sandbox.listSnapshots()
      const snapshots = await paginator.nextItems()

      // Should find our snapshot
      const found = snapshots.find((s) => s.snapshotId === snapshot.snapshotId)
      assert.isDefined(found)
    } finally {
      await Sandbox.deleteSnapshot(snapshot.snapshotId)
    }
  }
)

sandboxTest.skipIf(isDebug)(
  'create a named snapshot',
  async ({ sandbox, sandboxTestId }) => {
    const snapshotName = `snap-${sandboxTestId}`

    const snapshot = await sandbox.createSnapshot({ name: snapshotName })

    try {
      assert.isString(snapshot.snapshotId)
      assert.isArray(snapshot.names)
      assert.isTrue(snapshot.names.length > 0)
      assert.isTrue(snapshot.names.some((n) => n.includes(snapshotName)))
    } finally {
      await Sandbox.deleteSnapshot(snapshot.snapshotId)
    }
  }
)

sandboxTest.skipIf(isDebug)(
  'list snapshots filtered by name',
  async ({ sandbox, sandboxTestId }) => {
    const snapshotName = `snap-filter-${sandboxTestId}`

    const snapshot = await sandbox.createSnapshot({ name: snapshotName })

    try {
      // Filtering by the snapshot name should return the snapshot
      const paginator = Sandbox.listSnapshots({ name: snapshotName })
      const snapshots = await paginator.nextItems()

      const found = snapshots.find((s) => s.snapshotId === snapshot.snapshotId)
      assert.isDefined(found)

      // Filtering by an unknown name should return an empty list
      const emptyPaginator = Sandbox.listSnapshots({
        name: `${snapshotName}-does-not-exist`,
      })
      const emptySnapshots = await emptyPaginator.nextItems()
      assert.isArray(emptySnapshots)
      assert.equal(emptySnapshots.length, 0)
    } finally {
      await Sandbox.deleteSnapshot(snapshot.snapshotId)
    }
  }
)

sandboxTest.skipIf(isDebug)('delete snapshot', async ({ sandbox }) => {
  const snapshot = await sandbox.createSnapshot()

  // Delete should succeed
  const deleted = await Sandbox.deleteSnapshot(snapshot.snapshotId)
  assert.isTrue(deleted)

  // Second delete should return false (not found)
  const deletedAgain = await Sandbox.deleteSnapshot(snapshot.snapshotId)
  assert.isFalse(deletedAgain)
})

sandboxTest.skipIf(isDebug)(
  'snapshot preserves file system state',
  async ({ sandbox, sandboxTestId }) => {
    const appDir = '/home/user/app'
    const configPath = `${appDir}/config.json`
    const configContent = '{"env": "test"}'
    const dataPath = `${appDir}/data.txt`
    const dataContent = 'important data'

    await sandbox.files.makeDir(appDir)
    await sandbox.files.write(configPath, configContent)
    await sandbox.files.write(dataPath, dataContent)

    const snapshot = await sandbox.createSnapshot()

    try {
      const newSandbox = await Sandbox.create(snapshot.snapshotId, {
        metadata: { sandboxTestId: `${sandboxTestId}-fs-test` },
        requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
      })

      try {
        // Verify directory exists
        const dirExists = await newSandbox.files.exists(appDir)
        assert.isTrue(dirExists)

        // Verify files exist with correct content
        const config = await newSandbox.files.read(configPath)
        const data = await newSandbox.files.read(dataPath)

        assert.equal(config, configContent)
        assert.equal(data, dataContent)
      } finally {
        await newSandbox.kill()
      }
    } finally {
      await Sandbox.deleteSnapshot(snapshot.snapshotId)
    }
  },
  180_000
)

sandboxTest.skipIf(isDebug)(
  'create a filesystem-only snapshot',
  async ({ sandbox, sandboxTestId, skip }) => {
    const testContent = 'filesystem-only snapshot content'
    await sandbox.files.write('/home/user/fs-only.txt', testContent)

    // Kernel boot id: it changes only across a real (cold) boot. Read via a
    // command, not files.read: envd serves procfs files as an empty 200
    // because it sizes them by stat.
    const bootId = async (sbx: Sandbox) =>
      (
        await sbx.commands.run('cat /proc/sys/kernel/random/boot_id')
      ).stdout.trim()
    const sourceBoot = await bootId(sandbox)
    assert.isTrue(sourceBoot.length > 0)

    let snapshot
    try {
      snapshot = await sandbox.createSnapshot({ mode: 'filesystem' })
    } catch (error) {
      // The API answers 400 while filesystem-only snapshots are not enabled
      // for the team; there is nothing to prove in that environment.
      if (
        error instanceof SandboxError &&
        error.statusCode === 400 &&
        error.message.includes('not enabled for this team')
      ) {
        skip('filesystem-only snapshots are not enabled for this team')
      }
      throw error
    }
    assert.isString(snapshot.snapshotId)
    assert.isTrue(snapshot.snapshotId.length > 0)

    try {
      // The source sandbox keeps running and was not rebooted.
      assert.isTrue(await sandbox.isRunning())
      assert.equal(
        await sandbox.files.read('/home/user/fs-only.txt'),
        testContent
      )
      assert.equal(await bootId(sandbox), sourceBoot)

      // A sandbox created from it has the files and a fresh boot id: it
      // cold-booted instead of restoring memory. A memory snapshot would
      // carry the source's boot id over, so this is what tells them apart.
      const newSandbox = await Sandbox.create(snapshot.snapshotId, {
        metadata: { sandboxTestId: `${sandboxTestId}-fs-only` },
        requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
      })

      try {
        const content = await newSandbox.files.read('/home/user/fs-only.txt')
        assert.equal(content, testContent)
        const newBoot = await bootId(newSandbox)
        assert.isTrue(newBoot.length > 0)
        assert.notEqual(newBoot, sourceBoot)
      } finally {
        await newSandbox.kill()
      }
    } finally {
      await Sandbox.deleteSnapshot(snapshot.snapshotId)
    }
  },
  180_000
)