Skip to Content

AWS Lambda MicroVMs

Build the agent image and add the AWS key that lets Sandcovery run sandboxes in your own AWS account.

Sandcovery runs AWS Lambda MicroVMs in your AWS account, from an image you build once. AWS has no API that runs a command or moves a file inside a MicroVM, so the image holds a small agent that does both over the MicroVM's endpoint.

What runs

OptionSupport
Size2x4 only
EgressOpen egress only
LifetimeUp to 8 hours
Pause and resumeYes
Command timeoutUp to 300 seconds
RegionThe Region in the image ARN

Snapshots, port previews, custom images, environment variables set at create, and GPUs are not available on this provider.

Build the image

Save these two files in an empty folder.

agent.ts
import { spawn } from 'node:child_process'
import type { ChildProcessEventMap } from 'node:child_process'
import { createServer } from 'node:http'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { constants } from 'node:os'

import { Effect, MutableRef, Option, Predicate, Schema } from 'effect'
import { constVoid } from 'effect/Function'

const OK = 200

const PORT = 8080

const HOOK_PREFIX = '/aws/lambda-microvms/runtime/v1/'

const MAX_TIMEOUT_MS = 300_000

const SIGNAL_EXIT_BASE = 128

const BAD_REQUEST = 400

const NOT_FOUND = 404

const SERVER_ERROR = 500

const execSchema = Schema.Struct({
  argv: Schema.NonEmptyArray(Schema.String),
  stdin_base64: Schema.String.pipe(
    Schema.withDecodingDefaultKey(Effect.succeed(''))
  ),
  timeout_ms: Schema.Int.check(
    Schema.isBetween({ maximum: MAX_TIMEOUT_MS, minimum: 1 })
  ),
})

type Exec = typeof execSchema.Type

const run = async ({
  argv: [file, ...args],
  stdin_base64: stdin,
  timeout_ms: timeoutMs,
}: Exec) => {
  const { promise, reject, resolve } =
    Promise.withResolvers<ChildProcessEventMap['close']>()

  const child = spawn(file, args, { detached: true })
  const stdout = MutableRef.make<readonly Buffer[]>([])
  const stderr = MutableRef.make<readonly Buffer[]>([])
  const timedOut = MutableRef.make(false)

  const timer = setTimeout(() => {
    MutableRef.set(timedOut, true)

    Option.match(Option.fromUndefinedOr(child.pid), {
      onNone: constVoid,
      onSome: (pid) => {
        try {
          process.kill(-pid, 'SIGKILL')
        } catch (error) {
          if (
            !(
              error instanceof Error &&
              Predicate.hasProperty(error, 'code') &&
              error.code === 'ESRCH'
            )
          ) {
            throw error
          }
        }
      },
    })

    child.stdout.destroy()
    child.stderr.destroy()
  }, timeoutMs)

  child.stdout.on('data', (chunk: Buffer) => {
    MutableRef.update(stdout, (chunks) => [...chunks, chunk])
  })
  child.stderr.on('data', (chunk: Buffer) => {
    MutableRef.update(stderr, (chunks) => [...chunks, chunk])
  })
  child.stdin.on('error', constVoid)
  child.on('error', (error) => {
    clearTimeout(timer)
    reject(error)
  })
  child.on('close', (code, signal) => {
    clearTimeout(timer)
    resolve([code, signal])
  })
  child.stdin.end(Buffer.from(stdin, 'base64'))

  const [code, signal] = await promise

  const signalled = Option.match(Option.fromNullOr(signal), {
    onNone: () => 0,
    onSome: (name) => constants.signals[name],
  })

  return {
    exit_code: Option.getOrElse(
      Option.fromNullishOr(code),
      () => SIGNAL_EXIT_BASE + signalled
    ),
    stderr_base64: Buffer.concat(MutableRef.get(stderr)).toString('base64'),
    stdout_base64: Buffer.concat(MutableRef.get(stdout)).toString('base64'),
    timed_out: MutableRef.get(timedOut),
  }
}

const answer = async (incoming: IncomingMessage, outgoing: ServerResponse) => {
  const path = Option.match(
    Option.fromNullishOr(
      URL.parse(
        Option.getOrElse(Option.fromNullishOr(incoming.url), () => '/'),
        'https://agent'
      )
    ),
    { onNone: () => '', onSome: (parsed) => parsed.pathname }
  )

  const [body] = await Promise.allSettled([incoming.toArray()])

  if (body.status === 'rejected') {
    outgoing.destroy()

    return
  }

  if (path.startsWith(HOOK_PREFIX)) {
    outgoing.writeHead(OK).end()

    return
  }

  if (incoming.method !== 'POST' || path !== '/exec') {
    outgoing.writeHead(NOT_FOUND).end()

    return
  }

  const exec = Schema.decodeUnknownOption(Schema.fromJsonString(execSchema))(
    Buffer.concat(body.value).toString()
  )

  if (Option.isNone(exec)) {
    outgoing.writeHead(BAD_REQUEST, { 'content-type': 'application/json' }).end(
      JSON.stringify({
        message:
          'The body is a JSON object with argv, a non-empty array of strings, optional stdin_base64, and timeout_ms, a whole number from 1 to 300000.',
      })
    )

    return
  }

  const [ran] = await Promise.allSettled([run(exec.value)])

  if (ran.status === 'rejected') {
    outgoing
      .writeHead(SERVER_ERROR, { 'content-type': 'application/json' })
      .end(
        JSON.stringify({
          message:
            ran.reason instanceof Error
              ? ran.reason.message
              : 'the command did not start',
        })
      )

    return
  }

  outgoing
    .writeHead(OK, { 'content-type': 'application/json' })
    .end(JSON.stringify(ran.value))
}

if (import.meta.main) {
  createServer((incoming, outgoing) => {
    void answer(incoming, outgoing)
  }).listen(PORT)
}
Dockerfile
FROM scratch AS relay

COPY . /

FROM public.ecr.aws/docker/library/golang:1.27.4-alpine@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 AS relay-build

COPY --from=relay / /src

WORKDIR /src

RUN mkdir /relays \
  && if [ -f go.mod ]; then \
    version="$(printf '%s\n' go.mod go.sum *.go | LC_ALL=C sort | xargs sha256sum | sha256sum | cut -c 1-16)" \
    && CGO_ENABLED=0 GOTOOLCHAIN=local GOFLAGS=-mod=vendor GOPROXY=off go build -trimpath -ldflags=-s -o "/relays/sandcovery-relay-$version" .; \
  fi

FROM public.ecr.aws/lambda/microvms:al2023-minimal@sha256:3e45d46e969eb0d34ea954aff12747e15ca3f4a594788812c7218445777fa4bc

RUN dnf install -y findutils git gzip nodejs24 nodejs24-npm procps-ng tar \
  && dnf clean all

WORKDIR /opt/sandcovery

COPY agent.ts agent.ts

COPY --from=relay-build /relays/ /opt/sandcovery/

RUN npm-24 install --no-audit --no-fund --omit=dev --save-exact effect@4.1.5

ENV HOME=/root

WORKDIR /root

EXPOSE 8080

CMD ["node-24", "/opt/sandcovery/agent.ts"]

Zip them and upload the archive to an S3 bucket you own, in the Region that will run your sandboxes.

zip sandcovery-agent.zip agent.ts Dockerfile
aws s3 cp sandcovery-agent.zip s3://<bucket>/sandcovery-agent.zip

Create a build role that AWS Lambda can assume, with this trust policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "lambda.amazonaws.com" },
      "Action": ["sts:AssumeRole", "sts:TagSession"]
    }
  ]
}

Give the role this policy, so the build can read the archive and write its logs:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::<bucket>/*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:<region>:<account>:log-group:/aws/lambda-microvms/*"
    }
  ]
}

Build the image:

aws lambda-microvms create-microvm-image \
  --name sandcovery-agent \
  --code-artifact uri=s3://<bucket>/sandcovery-agent.zip \
  --base-image-arn arn:aws:lambda:<region>:aws:microvm-image:al2023-1 \
  --build-role-arn arn:aws:iam::<account>:role/<build role> \
  --cpu-configurations architecture=ARM_64 \
  --resources minimumMemoryInMiB=4096 \
  --egress-network-connectors arn:aws:lambda:<region>:aws:network-connector:aws-network-connector:INTERNET_EGRESS \
  --hooks '{"port":8080,"microvmImageHooks":{"ready":"ENABLED","readyTimeoutInSeconds":120,"validate":"ENABLED","validateTimeoutInSeconds":120}}'

The build is done when this command prints CREATED:

aws lambda-microvms get-microvm-image \
  --image-identifier arn:aws:lambda:<region>:<account>:microvm-image:sandcovery-agent \
  --query state --output text

Create the access key

Create an IAM user with this policy, then create an access key for it. The policy allows only the calls Sandcovery makes, on your image and on the two network connectors each sandbox uses.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "lambda:RunMicrovm",
        "lambda:GetMicrovm",
        "lambda:SuspendMicrovm",
        "lambda:ResumeMicrovm",
        "lambda:TerminateMicrovm",
        "lambda:CreateMicrovmAuthToken"
      ],
      "Resource": "arn:aws:lambda:<region>:<account>:microvm-image:sandcovery-agent"
    },
    {
      "Effect": "Allow",
      "Action": "lambda:PassNetworkConnector",
      "Resource": [
        "arn:aws:lambda:<region>:aws:network-connector:aws-network-connector:HTTP_INGRESS",
        "arn:aws:lambda:<region>:aws:network-connector:aws-network-connector:INTERNET_EGRESS"
      ]
    }
  ]
}

Add the credential

In Provider Credentials in the dashboard, add these three fields for AWS Lambda MicroVMs:

  • Access key ID
  • Secret access key
  • MicroVM image ARN

Costs

AWS bills MicroVM usage to your AWS account. Sandcovery's estimates and spend limits count the 2x4 baseline at the Arm list price for US West (Oregon).

A running sandbox can use up to 8 vCPUs and 16 GB of memory, and AWS bills active use above the baseline at the same unit prices. Snapshot storage, reads, and writes also appear on your AWS bill. Sandcovery's estimates count none of these.