An open-source, faster Devin alternative
TypeScript
allow list api per sandbox (#236)
Brian Reardon4dce3a3526da
diff --git a/cmd/oc/internal/commands/allowed_hosts.go b/cmd/oc/internal/commands/allowed_hosts.gonew file mode 100644index 00000000..3a9d3266--- /dev/null+++ b/cmd/oc/internal/commands/allowed_hosts.go@@ -0,0 +1,75 @@+package commands++import (+ "fmt"+ "sort"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/spf13/cobra"+)++var sandboxAllowedHostsCmd = &cobra.Command{+ Use: "allowed-hosts <sandbox-id>",+ Short: "Show the egress allowlist + per-secret allowed hosts for a sandbox",+ Long: `Show the egress allowlist (and any per-secret host restrictions) the+sandbox's secrets proxy enforces. Useful for debugging "why is my+outbound HTTP call being blocked" without having to cross-reference the+secret store config separately.++Sandboxes created without --secret-store have no per-store egress+restriction; this command reports an empty list for those.`,+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())+ var resp struct {+ SandboxID string `json:"sandboxID"`+ SecretStore string `json:"secretStore"`+ EgressAllowlist []string `json:"egressAllowlist"`+ PerSecretAllowedHosts map[string][]string `json:"perSecretAllowedHosts"`+ }+ if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/allowed-hosts", &resp); err != nil {+ return err+ }++ printer.Print(resp, func() {+ if resp.SecretStore == "" {+ fmt.Printf("Sandbox %s has no secret store attached — no per-store egress restriction.\n", resp.SandboxID)+ return+ }+ fmt.Printf("Sandbox %s (secret store: %s)\n", resp.SandboxID, resp.SecretStore)++ fmt.Println()+ fmt.Println("Egress allowlist:")+ if len(resp.EgressAllowlist) == 0 {+ fmt.Println(" (empty — store has no allowlist; egress is governed by platform-level policy)")+ } else {+ for _, h := range resp.EgressAllowlist {+ fmt.Printf(" • %s\n", h)+ }+ }++ if len(resp.PerSecretAllowedHosts) > 0 {+ fmt.Println()+ fmt.Println("Per-secret allowed hosts:")+ // Sort keys for deterministic output+ names := make([]string, 0, len(resp.PerSecretAllowedHosts))+ for k := range resp.PerSecretAllowedHosts {+ names = append(names, k)+ }+ sort.Strings(names)+ for _, name := range names {+ hosts := resp.PerSecretAllowedHosts[name]+ fmt.Printf(" %s:\n", name)+ for _, h := range hosts {+ fmt.Printf(" • %s\n", h)+ }+ }+ }+ })+ return nil+ },+}++func init() {+ sandboxCmd.AddCommand(sandboxAllowedHostsCmd)+}diff --git a/docs/reference/cli/sandbox.mdx b/docs/reference/cli/sandbox.mdxindex c413f4af..76bcb029 100644--- a/docs/reference/cli/sandbox.mdx+++ b/docs/reference/cli/sandbox.mdx@@ -91,3 +91,59 @@ oc sandbox set-timeout sb-abc123 600---For commands that resize a sandbox or freeze its size — `scale`, `autoscale`, `lock`, `unlock`, `lock-status` — see [Scaling](/reference/cli/scaling).++---++## `oc sandbox allowed-hosts <id>`++Show the egress allowlist + per-secret allowed hosts the sandbox's secrets proxy enforces. Useful for debugging "why is my outbound HTTP call being blocked" without having to cross-reference the [secret store](/sandboxes/secrets) config separately.++Sandboxes created without `--secret-store` return an empty allowlist — the sandbox has no per-store egress restriction.++```bash+oc sandbox allowed-hosts sb-abc123+# Sandbox sb-abc123 (secret store: my-store)+#+# Egress allowlist:+# • api.openai.com+# • api.anthropic.com+#+# Per-secret allowed hosts:+# OPENAI_API_KEY:+# • api.openai.com+```++Use `--json` for the structured form:++```bash+oc sandbox allowed-hosts sb-abc123 --json+```++```json+{+ "sandboxID": "sb-abc123",+ "secretStore": "my-store",+ "egressAllowlist": ["api.openai.com", "api.anthropic.com"],+ "perSecretAllowedHosts": {+ "OPENAI_API_KEY": ["api.openai.com"]+ }+}+```++### Layered forks++When a fork layers an additional `--secret-store` on top of an inherited one, `egressAllowlist` is the **union** of both stores' allowlists (matches what the runtime proxy enforces). The response includes both store names — `secretStore` is the primary (whose secrets shadow the base on env-name collisions), `baseSecretStore` is the inherited parent:++```json+{+ "sandboxID": "sb-fork456",+ "secretStore": "fork-override",+ "baseSecretStore": "fork-parent",+ "egressAllowlist": ["api.openai.com", "api.anthropic.com", "api.example.com"],+ "perSecretAllowedHosts": {+ "OPENAI_API_KEY": ["api.openai.com"]+ }+}+```++`baseSecretStore` is omitted in the single-store case (no layering).diff --git a/docs/reference/python-sdk/sandbox.mdx b/docs/reference/python-sdk/sandbox.mdxindex d844b2bd..04c1cced 100644--- a/docs/reference/python-sdk/sandbox.mdx+++ b/docs/reference/python-sdk/sandbox.mdx@@ -234,6 +234,34 @@ Generate a signed upload URL. [HTTP API →](/api-reference/files/generate-uploa[HTTP API →](/api-reference/preview/delete) — **Returns:** `None`+### `await sandbox.get_allowed_hosts()`++Return the egress allowlist + per-secret allowed hosts the sandbox's secrets proxy enforces. Useful for debugging "why is my outbound HTTP call being blocked" without having to cross-reference the [secret store](/sandboxes/secrets) config separately.++Sandboxes created without a `secret_store` option return an empty allowlist with `secretStore` omitted — the sandbox has no per-store egress restriction.++**Returns:** `dict` with the shape:++```python+{+ "sandboxID": "sb-...",+ "secretStore": "my-store", # omitted if no store+ "baseSecretStore": "parent-store", # omitted unless this is a layered fork+ "egressAllowlist": ["api.openai.com", ...],+ "perSecretAllowedHosts": {+ "OPENAI_API_KEY": ["api.openai.com"],+ },+}+```++For forks that layered an additional ``secret_store`` on top of an inherited one, ``egressAllowlist`` is the **union** of both stores' allowlists (matches what the runtime proxy enforces) and ``baseSecretStore`` is populated with the inherited parent's name. For sandboxes with a single store (or none), ``baseSecretStore`` is omitted.++```python+info = await sandbox.get_allowed_hosts()+print(info["egressAllowlist"]) # ['api.openai.com', 'api.anthropic.com']+print(info["perSecretAllowedHosts"]) # {'OPENAI_API_KEY': ['api.openai.com']}+```+### `await sandbox.close()`Close HTTP clients. Called automatically by the context manager.diff --git a/docs/reference/typescript-sdk/sandbox.mdx b/docs/reference/typescript-sdk/sandbox.mdxindex 8db74229..45525539 100644--- a/docs/reference/typescript-sdk/sandbox.mdx+++ b/docs/reference/typescript-sdk/sandbox.mdx@@ -286,6 +286,44 @@ Generate a signed upload URL. [HTTP API →](/api-reference/files/generate-uploa---+### `sandbox.getAllowedHosts()`++Return the egress allowlist + per-secret allowed hosts the sandbox's secrets proxy enforces. Useful for debugging "why is my outbound HTTP call being blocked" without having to cross-reference the [secret store](/sandboxes/secrets) config separately.++Sandboxes created without a `secretStore` option return an empty allowlist with `secretStore` undefined — the sandbox has no per-store egress restriction.++**Returns:** `Promise<AllowedHostsInfo>`++```typescript+const info = await sandbox.getAllowedHosts();+console.log(info.egressAllowlist); // ['api.openai.com', 'api.anthropic.com']+console.log(info.perSecretAllowedHosts); // { 'OPENAI_API_KEY': ['api.openai.com'] }+```++The returned `AllowedHostsInfo`:++<ParamField body="sandboxID" type="string">+ Sandbox ID+</ParamField>++<ParamField body="secretStore" type="string">+ Name of the primary secret store the sandbox is bound to (the "winning" store on the row, whose secrets shadow the base store on env-name collisions). Empty when the sandbox was created without a `secretStore` option.+</ParamField>++<ParamField body="baseSecretStore" type="string">+ Name of the inherited parent store, present only when a fork layered an additional `secretStore` on top of an inherited one. Empty for sandboxes created from scratch and for forks without an override.+</ParamField>++<ParamField body="egressAllowlist" type="string[]">+ Hosts the sandbox can reach via the secrets proxy. For layered forks this is the **union** of every layered store's allowlist (base first, primary's additions appended, deduped) — matches what the runtime proxy actually enforces.+</ParamField>++<ParamField body="perSecretAllowedHosts" type="Record<string, string[]>">+ Optional per-secret restrictions. When the sandbox uses a listed secret in a request, only the listed hosts are reachable for that request. For layered forks, the primary store's secrets shadow the base on name collisions (matches runtime env-collision behavior).+</ParamField>++---+## Properties<ParamField body="sandboxId" type="string">diff --git a/internal/api/router.go b/internal/api/router.goindex e8edd3ac..78fb59bd 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -259,6 +259,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.GET("/sandboxes/:id/autoscale", s.getAutoscale)api.PUT("/sandboxes/:id/scaling-lock", s.setScalingLock)api.GET("/sandboxes/:id/scaling-lock", s.getScalingLock)+ api.GET("/sandboxes/:id/allowed-hosts", s.getSandboxAllowedHosts)// Checkpointsapi.POST("/sandboxes/:id/checkpoints", s.createCheckpoint)diff --git a/internal/api/sandbox_allowed_hosts.go b/internal/api/sandbox_allowed_hosts.gonew file mode 100644index 00000000..529286b8--- /dev/null+++ b/internal/api/sandbox_allowed_hosts.go@@ -0,0 +1,135 @@+package api++import (+ "context"+ "net/http"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db"+)++// AllowedHostsResponse is the shape returned by GET /api/sandboxes/:id/allowed-hosts.+//+// EgressAllowlist + PerSecretAllowedHosts represent the runtime view — the+// union of every layered store's allowlist, exactly as the secrets proxy+// enforces it. Most sandboxes have a single store and the union is trivially+// that one store's allowlist; forks that layer an additional store on top of+// an inherited one have BOTH stores' allowlists merged here.+//+// SecretStoreName is the "primary" (last/winning) store on the sandbox row —+// the one whose secrets shadow the base store on env-name collisions.+// BaseSecretStoreName is the inherited parent store from the fork chain;+// populated only when there's actual layering. Both empty = sandbox created+// without a secretStore (no per-store egress restriction enforced).+type AllowedHostsResponse struct {+ SandboxID string `json:"sandboxID"`+ SecretStoreName string `json:"secretStore,omitempty"`+ BaseSecretStoreName string `json:"baseSecretStore,omitempty"`+ EgressAllowlist []string `json:"egressAllowlist"`+ PerSecretAllowedHosts map[string][]string `json:"perSecretAllowedHosts"`+}++// getSandboxAllowedHosts handles GET /api/sandboxes/:id/allowed-hosts.+//+// Returns the egress allowlist + per-secret allowed hosts the sandbox's+// secrets proxy enforces. Useful for debugging "why is my outbound HTTP call+// being blocked" without having to cross-reference store config separately.+//+// For forks that layered a new secretStore on top of an inherited one, the+// response merges both stores' allowlists — the runtime proxy enforces the+// union, so this matches actual behavior. The primary store's secrets shadow+// the base store on env-name collisions.+//+// Auth: same as other /api/sandboxes/:id routes — PGAPIKeyMiddleware sets+// orgID on the context. Sandbox lookup is org-scoped to prevent cross-tenant+// reads via guessed sandbox IDs.+func (s *Server) getSandboxAllowedHosts(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ orgID, hasOrg := auth.GetOrgID(c)+ if !hasOrg {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }++ sandboxID := c.Param("id")+ ctx := c.Request().Context()++ primaryID, baseStoreName, err := s.store.GetSandboxStoreRefs(ctx, orgID, sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }++ // Sandbox has neither a primary store nor an inherited base. Return an+ // empty (well-formed) response so callers always see the same shape.+ if primaryID == nil && baseStoreName == "" {+ return c.JSON(http.StatusOK, AllowedHostsResponse{+ SandboxID: sandboxID,+ EgressAllowlist: []string{},+ PerSecretAllowedHosts: map[string][]string{},+ })+ }++ resp := AllowedHostsResponse{+ SandboxID: sandboxID,+ EgressAllowlist: []string{},+ PerSecretAllowedHosts: map[string][]string{},+ }++ // Fetch base store first so primary's per-secret entries can shadow on+ // name collision (matches the runtime proxy: later layer wins for envs).+ if baseStoreName != "" {+ base, err := s.store.GetSecretStoreByName(ctx, orgID, baseStoreName)+ if err == nil {+ resp.BaseSecretStoreName = base.Name+ mergeStoreInto(ctx, s.store, base, &resp)+ }+ // Base store missing (deleted under us) is treated as a soft no-op+ // rather than 500 — proxy already snapshotted whatever it needs.+ }++ if primaryID != nil {+ primary, err := s.store.GetSecretStore(ctx, orgID, *primaryID)+ if err == nil {+ resp.SecretStoreName = primary.Name+ mergeStoreInto(ctx, s.store, primary, &resp)+ }+ }++ return c.JSON(http.StatusOK, resp)+}++// mergeStoreInto folds one store's allowlist + per-secret restrictions into+// the running response. Egress hosts dedupe (preserving insertion order so+// base-store hosts appear before primary's additions). Per-secret entries+// with empty AllowedHosts are skipped — empty means "inherits store+// allowlist," and surfacing them as [] would falsely imply "no hosts allowed+// for this secret." Per-secret name collisions are last-write-wins, so the+// primary store (called second) shadows the base.+func mergeStoreInto(ctx context.Context, store *db.Store, ss *db.SecretStore, resp *AllowedHostsResponse) {+ // Build a set view of existing egress hosts so we can dedupe in O(1).+ existing := make(map[string]bool, len(resp.EgressAllowlist))+ for _, h := range resp.EgressAllowlist {+ existing[h] = true+ }+ for _, h := range ss.EgressAllowlist {+ if !existing[h] {+ existing[h] = true+ resp.EgressAllowlist = append(resp.EgressAllowlist, h)+ }+ }++ entries, err := store.ListSecretEntries(ctx, ss.ID)+ if err != nil {+ return+ }+ for _, e := range entries {+ if len(e.AllowedHosts) == 0 {+ continue+ }+ resp.PerSecretAllowedHosts[e.Name] = e.AllowedHosts+ }+}+diff --git a/internal/db/store.go b/internal/db/store.goindex aa6b1968..69e5218e 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -2034,6 +2034,35 @@ func (s *Store) GetSecretStoreByName(ctx context.Context, orgID uuid.UUID, namereturn &ss, nil}+// GetSandboxStoreRefs returns the secret stores attached to a sandbox:+//+// - primaryID is sandbox_sessions.secret_store_id, the "winning" store on+// the row (last layer for env-collision resolution; nil if no store).+// - baseStoreName is config->>'baseSecretStore' (parent store from the+// fork chain), populated when a fork layered an additional store on top+// of an inherited one. Empty string when there's no parent.+//+// Both are needed to reconstruct the runtime egress allowlist accurately:+// the secrets proxy enforces the union of egress hosts from EVERY layered+// store, while sandbox_sessions.secret_store_id only records the last one.+// Without including the base store, an /allowed-hosts response on a layered+// fork would underrepresent what the proxy actually allows.+//+// Org-scoped: sandbox IDs aren't globally unique, so a leaked ID from+// another org won't return that org's data.+func (s *Store) GetSandboxStoreRefs(ctx context.Context, orgID uuid.UUID, sandboxID string) (primaryID *uuid.UUID, baseStoreName string, err error) {+ err = s.pool.QueryRow(ctx,+ `SELECT secret_store_id, COALESCE(config->>'baseSecretStore', '')+ FROM sandbox_sessions+ WHERE org_id = $1 AND sandbox_id = $2 ORDER BY started_at DESC LIMIT 1`,+ orgID, sandboxID,+ ).Scan(&primaryID, &baseStoreName)+ if err != nil {+ return nil, "", fmt.Errorf("get sandbox store refs: %w", err)+ }+ return primaryID, baseStoreName, nil+}+// ListSecretStores returns all secret stores for an org.func (s *Store) ListSecretStores(ctx context.Context, orgID uuid.UUID) ([]SecretStore, error) {rows, err := s.pool.Query(ctx,diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.pyindex 4fe77367..84a15153 100644--- a/sdks/python/opencomputer/sandbox.py+++ b/sdks/python/opencomputer/sandbox.py@@ -402,6 +402,34 @@ class Sandbox:resp.raise_for_status()return resp.json()+ async def get_allowed_hosts(self) -> dict:+ """Return the egress allowlist + per-secret allowed hosts the+ sandbox's secrets proxy enforces.++ Useful for debugging "why is my outbound HTTP call being blocked"+ without having to cross-reference the secret store config separately.++ Sandboxes created without a ``secret_store`` option return an empty+ allowlist and ``secretStore`` is omitted — the sandbox has no+ per-store egress restriction.++ Returns:+ Dict with::++ {+ "sandboxID": "sb-...",+ "secretStore": "<store-name>", # omitted if no store+ "egressAllowlist": ["api.openai.com", ...],+ "perSecretAllowedHosts": {+ "OPENAI_API_KEY": ["api.openai.com"],+ ...+ },+ }+ """+ resp = await self._client.get(f"/sandboxes/{self.sandbox_id}/allowed-hosts")+ resp.raise_for_status()+ return resp.json()+async def set_timeout(self, timeout: int) -> None:"""Update the sandbox timeout in seconds."""# Route to worker directly (like commands/files/pty) — the control planediff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.tsindex 2b8a96b4..1632fd68 100644--- a/sdks/typescript/src/index.ts+++ b/sdks/typescript/src/index.ts@@ -10,6 +10,7 @@ export {type AutoscaleConfig,type AutoscaleStatus,type ScalingLockStatus,+ type AllowedHostsInfo,} from "./sandbox.js";export { Agent, type AgentEvent, type AgentConfig, type AgentStartOpts, type AgentSession, type McpServerConfig } from "./agent.js";export { Filesystem, type EntryInfo } from "./filesystem.js";diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex a56894ed..b1f9cb1a 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -165,6 +165,26 @@ export interface ScalingLockStatus {locked: boolean;}+/**+ * Result of `sandbox.getAllowedHosts()`. Describes the egress-allowlist that+ * a sandbox's secrets proxy enforces.+ *+ * - `egressAllowlist` is the cluster-wide list of hosts the sandbox can+ * reach via the secrets proxy. Comes from the secret store the sandbox+ * was created with.+ * - `perSecretAllowedHosts` is an optional finer restriction per individual+ * secret. When the sandbox uses one of these secrets in a request, only+ * the listed hosts are reachable for that request.+ * - `secretStore` is the name of the store the sandbox is bound to. Empty+ * when the sandbox was created without a `secretStore` option.+ */+export interface AllowedHostsInfo {+ sandboxID: string;+ secretStore?: string;+ egressAllowlist: string[];+ perSecretAllowedHosts: Record<string, string[]>;+}+export class Sandbox {readonly sandboxId: string;readonly agent: Agent;@@ -521,6 +541,27 @@ export class Sandbox {return resp.json();}+ /**+ * Get the egress-allowlist + per-secret allowed hosts the sandbox's+ * secrets proxy enforces. Useful for debugging "why is my outbound HTTP+ * call being blocked" without having to cross-reference the secret store+ * config separately.+ *+ * Sandboxes created without a `secretStore` option return an empty+ * allowlist and `secretStore` is undefined — the sandbox has no+ * per-store egress restriction.+ */+ async getAllowedHosts(): Promise<AllowedHostsInfo> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/allowed-hosts`, {+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ });+ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to get allowed hosts: ${resp.status} ${text}`);+ }+ return resp.json();+ }+async setTimeout(timeout: number): Promise<void> {const headers: Record<string, string> = { "Content-Type": "application/json" };if (this.apiKey) {