Skip to content

armgit / E2B

Public Imported from GitHub
0

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

28.1 KB
Raw Blame
openapi: 3.0.0
info:
  title: envd
  version: 0.1.3
  description: API for managing files' content and controlling envd

tags:
  - name: files

# Operations marked `x-internal: true` are the orchestrator's control plane. The
# orchestrator reaches them over the host network, straight at the sandbox slot
# IP, so they are never a legitimate destination for traffic arriving through the
# public sandbox URL. The sandbox proxy generates its rejection list from this
# marker, so adding a control operation here is what closes it to the outside;
# see the orchestrator's `pkg/sandbox/envd` package.
paths:
  /health:
    get:
      summary: Check the health of the service
      responses:
        "204":
          description: The service is healthy

  /metrics:
    get:
      summary: Service stats
      security:
        - AccessTokenAuth: []
        - {}
      responses:
        "200":
          description: The resource usage metrics of the service
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Metrics"

  /init:
    post:
      summary: Set initial vars, ensure the time and metadata is synced with the host
      x-internal: true
      security:
        - AccessTokenAuth: []
        - {}
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                volumeMounts:
                  type: array
                  items:
                    $ref: "#/components/schemas/VolumeMount"
                hyperloopIP:
                  type: string
                  description: IP address of the hyperloop server to connect to
                lifecycleID:
                  type: string
                  description: Lifecycle ID of the sandbox
                envVars:
                  $ref: "#/components/schemas/EnvVars"
                accessToken:
                  type: string
                  description: Access token for secure access to envd service
                  x-go-type: SecureToken
                timestamp:
                  type: string
                  format: date-time
                  description: >-
                    The current timestamp in RFC3339 format. envd adds its own time from reading
                    the request body to its clock gates, reported on
                    X-Envd-Init-Clock-Correction, and applies its clock rules to the result.
                defaultUser:
                  type: string
                  description: The default user to use for operations
                defaultWorkdir:
                  type: string
                  description: The default working directory to use for operations
                caBundle:
                  type: string
                  description: PEM-encoded CA certificates to install into the system trust store (may contain multiple concatenated PEM blocks)
                cpuCount:
                  type: integer
                  minimum: 1
                  description: >-
                    Number of guest CPUs that should be online. envd attempts to bring
                    the set of requested CPUs online asynchronously; the outcome is
                    reported on the X-Envd-Cpus header and on /metrics.
                thaw:
                  type: string
                  enum: [inline, skip]
                  description: >-
                    Whether this call thaws the workload cgroups a pre-pause freeze left
                    frozen. Absent or "inline": it thaws them before it answers, as every envd
                    before this field did, unless a freeze came after the call entered, which
                    the call then leaves in place. "skip": it thaws nothing and answers X-Envd-Thaw:
                    skip, leaving the workload frozen; only for a resume whose VM is discarded
                    after the call, such as one that records which pages the resume touches. A
                    value this envd does not know reads as inline, the side on which a guest
                    is never left frozen.

      responses:
        "204":
          description: Env vars set, the time and metadata is synced with the host
          headers:
            X-Envd-Thaw:
              description: >-
                Present, with the value "skip", when the call carried thaw: "skip" and so
                thawed nothing; an authorized call that asked to skip and then failed carries
                it on its error response too. Absent on every other call, including one
                whose thaw a later freeze withheld, and on an envd predating the thaw field.
              schema:
                type: string
                enum: [skip]
            X-Envd-Init-Clock-Correction:
              description: >-
                The time, in whole milliseconds, truncated, that envd added to the request's
                timestamp: its own time from reading the request body to its clock gates.
                Present on every 204 to a request that carried a timestamp, whether or not the
                clock was then stepped; absent on an envd predating it.
              schema:
                type: integer
                minimum: 0
            X-Envd-Init-Unobserved:
              description: >-
                How many /init handlers ran their thaw and finished with their request
                context already done since the last 204 that carried this header or the last
                freeze, whichever came later: thaws that ran with no caller left to observe
                them. Present, zero included, on every 204 whose client was still connected
                when its headers were decided; absent on an error response and on an envd
                predating it. A handler that asked to skip the thaw, or whose thaw was
                withheld because a freeze came after it entered, is never counted.
              schema:
                type: integer
                minimum: 0

  /freeze:
    post:
      summary: Freeze user/pty cgroups before pause and wait for them to stop. Written directly by envd to avoid Process.Start / shell overhead under load.
      description: |
        Writing cgroup.freeze only requests a freeze; the kernel stops each task at its
        next signal-delivery point. This endpoint therefore polls cgroup.events until the
        cgroups read back frozen, and returns what it observed, so a caller can tell a
        freeze that took effect from one that was merely issued.

        cgroup.events reports STATE, not an acknowledgement of our write: a cgroup the
        guest froze itself reads frozen too. The counts below say what was observed, not
        what this call caused.

        Best-effort by design: a workload that will not quiesce within the budget is
        reported as unconfirmed rather than failing the call, cgroups that reject the write
        are counted in failed, and cgroups the guest removed while the sweep was working on
        them are counted in vanished. None of the three may block a pause, which is why all
        three are counts in the body rather than an error.

        Whether this endpoint waits is the caller's choice, expressed by supplying
        maxWaitMs: see that parameter.
      x-internal: true
      parameters:
        - name: mode
          in: query
          required: false
          description: |
            Which cgroups to freeze. "hierarchy" freezes the complement of envd's own
            ancestor chain, so cgroups the customer created anywhere in the tree are
            covered; "legacy" freezes only the user and pty cgroups envd itself creates.
            Omitted means legacy, which is what an orchestrator predating this parameter
            gets.

            The mode is chosen by the caller because the feature flag that selects it is
            evaluated there — envd has no access to it. FreezeResult echoes the mode back
            so the caller can confirm envd honoured the request rather than inferring it
            from the flag's value: an envd too old to know about modes reports legacy
            while the flag reads on.
          schema:
            type: string
            enum: [legacy, hierarchy]
        - name: maxCgroups
          in: query
          required: false
          description: |
            Bounds how many cgroups a hierarchy sweep may visit. A safety guard against a
            pathological or hostile hierarchy rather than a performance knob — the guest is
            the threat model. Omitted or non-positive means envd's own default. Ignored in
            legacy mode.
          schema:
            type: integer
        - name: maxWaitMs
          in: query
          required: false
          description: |
            How long to wait for the cgroups to read back frozen, in milliseconds. The
            caller owns this budget because it also owns the request timeout, and a wait
            longer than that timeout cannot be observed.

            Supplying it also selects the response: with it, the call waits and answers 200
            with a FreezeResult; omitted or non-positive, the call does not wait at all and
            answers 204, which is the contract callers older than this parameter expect.
          schema:
            type: integer
            format: int64
      security:
        - AccessTokenAuth: []
        - {}
      responses:
        "200":
          description: Freeze issued and the frozen state awaited (maxWaitMs was supplied); the body reports what was observed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/FreezeResult"
        "204":
          description: Freeze issued without waiting (maxWaitMs absent), for callers predating the structured result
        "500":
          $ref: "#/components/responses/InternalServerError"
        "503":
          description: Freeze lock is held by another operation

  /unfreeze:
    post:
      summary: Unfreeze user/pty cgroups. Intended for the orchestrator's pause-failure rollback path and the thaw after an in-place checkpoint; the normal resume thaw happens inside /init, not here.
      x-internal: true
      security:
        - AccessTokenAuth: []
        - {}
      responses:
        "204":
          description: Cgroups unfrozen
        "500":
          $ref: "#/components/responses/InternalServerError"
        "503":
          description: Freeze lock is held by another operation

  /collapse:
    post:
      summary: Collapse envd's own anonymous heap into 2 MiB transparent hugepages before pause, so on resume envd touches fewer distinct guest-physical frames (each a cold fault). Best-effort.
      x-internal: true
      security:
        - AccessTokenAuth: []
        - {}
      responses:
        "200":
          description: Heap collapsed
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CollapseResult"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /fsfreeze:
    post:
      summary: Freeze the guest rootfs (FIFREEZE) before a filesystem-only pause so it is flushed to a consistent on-disk state, closing the sync->pause race. Idempotent. On a successful filesystem-only pause the VM is rebooted, so no thaw is needed; the orchestrator thaws only on the pause-failure path.
      x-internal: true
      security:
        - AccessTokenAuth: []
        - {}
      responses:
        "204":
          description: Rootfs frozen
        "500":
          $ref: "#/components/responses/InternalServerError"
        "503":
          description: Freeze lock is held by another operation

  /fsthaw:
    post:
      summary: Thaw the guest rootfs (FITHAW). Intended ONLY for the orchestrator's pause-failure rollback path, so a frozen filesystem cannot leave the live VM deadlocked. Idempotent.
      x-internal: true
      security:
        - AccessTokenAuth: []
        - {}
      responses:
        "204":
          description: Rootfs thawed
        "500":
          $ref: "#/components/responses/InternalServerError"
        "503":
          description: Freeze lock is held by another operation

  /envs:
    get:
      summary: Environment variables
      security:
        - AccessTokenAuth: []
        - {}
      responses:
        "200":
          description: Environment variables
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/EnvVars"

  /files:
    get:
      summary: Download a file
      tags: [files]
      security:
        - AccessTokenAuth: []
        - {}
      parameters:
        - $ref: "#/components/parameters/FilePath"
        - $ref: "#/components/parameters/User"
        - $ref: "#/components/parameters/Signature"
        - $ref: "#/components/parameters/SignatureExpiration"
      responses:
        "200":
          $ref: "#/components/responses/DownloadSuccess"
        "400":
          $ref: "#/components/responses/InvalidPath"
        "401":
          $ref: "#/components/responses/InvalidUser"
        "404":
          $ref: "#/components/responses/FileNotFound"
        "406":
          $ref: "#/components/responses/NotAcceptable"
        "500":
          $ref: "#/components/responses/InternalServerError"
    post:
      summary: Upload a file and ensure the parent directories exist. If the file exists, it will be overwritten.
      description: |
        Any request header of the form `X-Metadata-<key>: <value>` is persisted
        as a user-defined extended attribute on the uploaded file. The
        `X-Metadata-` prefix is stripped and the remaining header name is
        lowercased to form the metadata key; the resulting map is returned on
        `EntryInfo` lookups (e.g. `Stat`, `ListDir`).

        Each upload replaces the file's metadata with the keys provided in
        that request: keys previously stored but absent from the new request
        are removed, and an upload that sends no `X-Metadata-*` header clears
        all existing metadata.

        Both keys and values must be printable US-ASCII (bytes `0x20`-`0x7E`)
        and are rejected with HTTP 400 otherwise. Each key is capped at 246
        bytes (the Linux VFS xattr-name limit minus the namespace prefix), and
        the combined size of all metadata on a file (keys plus values, with the
        namespace prefix counted per key) is capped at 4096 bytes to stay within
        the filesystem's per-inode xattr budget. Multiple files in a single
        multipart upload receive the same metadata. If the same
        `X-Metadata-<key>` header is sent more than once, only the first
        value is used.
      tags: [files]
      security:
        - AccessTokenAuth: []
        - {}
      parameters:
        - $ref: "#/components/parameters/FilePath"
        - $ref: "#/components/parameters/User"
        - $ref: "#/components/parameters/Signature"
        - $ref: "#/components/parameters/SignatureExpiration"
      requestBody:
        $ref: "#/components/requestBodies/File"
      responses:
        "200":
          $ref: "#/components/responses/UploadSuccess"
        "400":
          $ref: "#/components/responses/InvalidPath"
        "401":
          $ref: "#/components/responses/InvalidUser"
        "500":
          $ref: "#/components/responses/InternalServerError"
        "507":
          $ref: "#/components/responses/NotEnoughDiskSpace"

  /files/compose:
    post:
      summary: Compose multiple files into a single file using zero-copy concatenation. Source files are deleted after successful composition.
      tags: [files]
      security:
        - AccessTokenAuth: []
        - {}
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ComposeRequest"
      responses:
        "200":
          description: Files composed successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/EntryInfo"
        "400":
          $ref: "#/components/responses/InvalidPath"
        "401":
          $ref: "#/components/responses/InvalidUser"
        "404":
          $ref: "#/components/responses/FileNotFound"
        "500":
          $ref: "#/components/responses/InternalServerError"
        "507":
          $ref: "#/components/responses/NotEnoughDiskSpace"

components:
  securitySchemes:
    AccessTokenAuth:
      type: apiKey
      in: header
      name: X-Access-Token

  parameters:
    FilePath:
      name: path
      in: query
      required: false
      description: Path to the file, URL encoded. Can be relative to the user's home directory (e.g. "file.txt" resolves to ~/file.txt).
      schema:
        type: string
    User:
      name: username
      in: query
      required: false
      description: User for setting file ownership and resolving relative paths. Defaults to the sandbox's default user.
      schema:
        type: string
    Signature:
      name: signature
      in: query
      required: false
      description: Signature used for file access permission verification.
      schema:
        type: string
    SignatureExpiration:
      name: signature_expiration
      in: query
      required: false
      description: Unix timestamp (seconds) after which the signature expires. Only used with the signature parameter.
      schema:
        type: integer
  requestBodies:
    File:
      required: true
      content:
        multipart/form-data:
          schema:
            type: object
            properties:
              file:
                type: string
                format: binary
        application/octet-stream:
          schema:
            type: string
            format: binary
            description: Raw file content. The 'path' query parameter is required when using this content type.

  responses:
    UploadSuccess:
      description: The file was uploaded successfully.
      content:
        application/json:
          schema:
            type: array
            items:
              $ref: "#/components/schemas/EntryInfo"
          example:
            - path: "/home/user/hello.txt"
              name: "hello.txt"
              type: "file"

    DownloadSuccess:
      description: Entire file downloaded successfully.
      content:
        application/octet-stream:
          schema:
            type: string
            format: binary
            description: The raw file content
    NotAcceptable:
      description: Requested encoding is not supported
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            message: "no acceptable encoding found, supported: [identity, gzip]"
            code: 406
    InvalidPath:
      description: Invalid path
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            message: "path '/home/user/docs' is a directory"
            code: 400
    InternalServerError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            message: "error opening file '/home/user/file.txt': permission denied"
            code: 500
    FileNotFound:
      description: File not found
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            message: "path '/home/user/missing.txt' does not exist"
            code: 404
    InvalidUser:
      description: Invalid user
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            message: "error looking up user 'nonexistent': user: unknown user nonexistent"
            code: 401
    NotEnoughDiskSpace:
      description: Not enough disk space
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            message: "not enough disk space available"
            code: 507

  schemas:
    Error:
      required:
        - message
        - code
      properties:
        message:
          type: string
          description: Error message
        code:
          type: integer
          description: Error code
    EntryInfo:
      required:
        - path
        - name
        - type
      properties:
        path:
          type: string
          description: Path to the file
        name:
          type: string
          description: Name of the file
        type:
          type: string
          description: Type of the file
          enum:
            - file
        metadata:
          type: object
          description: User-defined metadata stored as extended attributes on the file.
          additionalProperties:
            type: string
    EnvVars:
      type: object
      description: Environment variables to set
      additionalProperties:
        type: string
    Metrics:
      type: object
      description: Resource usage metrics
      properties:
        ts:
          type: integer
          format: int64
          description: Unix timestamp in UTC for current sandbox time
        cpu_count:
          type: integer
          description: Number of CPU cores online
        cpu_possible:
          type: integer
          description: Number of CPUs the guest can bring online
        cpu_target:
          type: integer
          description: Online count last requested, 0 when none was
        cpu_target_attempts:
          type: integer
          description: Attempts at reaching cpu_target since it was set
        cpu_write_pending_ms:
          type: integer
          format: int64
          description: >-
            How long a CPU online or offline write has been running in the guest kernel,
            0 when none is. A value that keeps growing means CPU hotplug is stuck.
        cpu_used_pct:
          type: number
          format: float
          description: CPU usage percentage
        mem_total:
          type: integer
          description: Total virtual memory in bytes
        mem_used:
          type: integer
          description: Used virtual memory in bytes
        mem_cache:
          type: integer
          description: Cached memory (page cache) in bytes
        disk_used:
          type: integer
          description: Used disk space in bytes
        disk_total:
          type: integer
          description: Total disk space in bytes
        oom_kills:
          type: array
          description: The latest 32 out-of-memory kills since the guest booted, oldest first. Reading does not consume them. Empty when there are none. Omitted when not known (while envd is still reading the kernel log, when it can't be read or envd stopped reading it, and outside Firecracker).
          x-go-type-skip-optional-pointer: false
          items:
            $ref: "#/components/schemas/OOMKill"
    OOMKill:
      type: object
      description: A process the guest kernel killed for running out of memory
      required:
        - seq
        - process
      properties:
        seq:
          type: integer
          format: int64
          description: Kernel log sequence number of the kill record. It only grows, across pauses and envd restarts.
        process:
          type: string
          description: Name of the killed process, or Unknown if the record doesn't show it
    FreezeResult:
      type: object
      description: Per-call statistics from a pre-pause workload freeze
      properties:
        mode:
          type: string
          enum: [legacy, hierarchy]
          description: Which sweep actually ran. Echoed back rather than inferred from the flag, so a caller can tell that envd honoured what it asked for
        visited:
          type: integer
          description: Cgroups the walk examined, whether or not it froze them. The input for sizing the bound; meaningless in legacy mode
        allowlisted:
          type: integer
          description: Cgroups skipped because the resume path depends on them (systemd, journald, envd's port forwarding). Reported because the allowlist is expected to grow, and a distro that routes journald differently changes this count
        truncated:
          type: boolean
          description: True when the walk stopped because it hit the bound rather than because it ran out of tree, so coverage is incomplete
        preFrozen:
          type: integer
          description: Cgroups the guest itself had already frozen before the sweep ran (docker pause writes cgroup.freeze). Not written to and deliberately left frozen by the resume thaw, so the guest's own suspension survives the snapshot
        requested:
          type: integer
          description: Cgroups this call wrote cgroup.freeze to
        frozen:
          type: integer
          description: Cgroups that read back "frozen 1" from cgroup.events within the budget; their tasks have stopped
        notFrozen:
          type: integer
          description: Cgroups still reading "frozen 0" when the budget expired; their tasks may still be running, so a snapshot taken now can capture a live workload
        failed:
          type: integer
          description: Cgroups that errored for a reason that is not simply being gone - the write was refused, or the state could not be read. A cgroup the hierarchy walk discovered that merely went away is counted vanished instead; one of envd's own static cgroups that goes away is counted here, by design
        vanished:
          type: integer
          description: Cgroups the hierarchy walk enumerated that the guest then removed before the sweep finished with them - envd's own static cgroups are excluded and report failed instead. A race rather than a failure, and a claim about the cgroup only - tasks migrated out of it before its removal can still be running. Like failed it spans both phases, so it does not reconcile against requested on its own - one removed during the settle poll was counted in requested, one removed before its write never was
        unobservable:
          type: integer
          description: Cgroups whose freeze state cannot be read because this guest has no cgroup manager; the write was accepted but nothing can be read back, so these are neither frozen nor notFrozen
        sweepMs:
          type: integer
          format: int64
          description: Time spent issuing the freeze writes, in milliseconds (scales with cgroup count)
        waitMs:
          type: integer
          format: int64
          description: Time spent polling cgroup.events, in milliseconds (scales with how deep in I/O the guest tasks were). Outcome neutral - the wait ends either because everything stopped or because the budget ran out
    CollapseResult:
      type: object
      description: Per-call statistics from a heap collapse
      properties:
        regions:
          type: integer
          description: Anonymous read-write regions scanned
        chunks:
          type: integer
          description: 2 MiB chunks attempted
        collapsed:
          type: integer
          description: Chunks whose base pages were actually migrated into a new hugepage (real work)
        alreadyHuge:
          type: integer
          description: Chunks MADV_COLLAPSE accepted but were already hugepages (no work)
        skipped:
          type: integer
          description: Chunks that could not be collapsed (empty or ineligible)
        elapsedMs:
          type: integer
          format: int64
          description: Wall-clock time spent collapsing, in milliseconds
    ComposeRequest:
      type: object
      required:
        - source_paths
        - destination
      properties:
        source_paths:
          type: array
          items:
            type: string
          description: Ordered list of source file paths to concatenate
        destination:
          type: string
          description: Destination file path for the composed file
        username:
          type: string
          description: User for setting ownership and resolving relative paths
    VolumeMount:
      type: object
      description: Volume mount configuration
      additionalProperties: false
      properties:
        nfs_target:
          type: string
          description: Server target address
        path:
          type: string
          description: Mount path inside the sandbox
      required:
        - nfs_target
        - path