Skip to content

An open-source, faster Devin alternative

TypeScript

tested secrets

Brian Reardon8539ef6c96e6
diff --git a/cmd/oc/internal/client/client.go b/cmd/oc/internal/client/client.go
index 34208041..524f69e9 100644
--- a/cmd/oc/internal/client/client.go
+++ b/cmd/oc/internal/client/client.go
@@ -158,6 +158,34 @@ func (c *Client) Put(ctx context.Context, path string, body io.Reader) error {
return nil
}
+// PutJSON performs a PUT request with a JSON body and decodes the response.
+func (c *Client) PutJSON(ctx context.Context, path string, body, result interface{}) error {
+ var bodyReader io.Reader
+ if body != nil {
+ data, err := json.Marshal(body)
+ if err != nil {
+ return err
+ }
+ bodyReader = bytes.NewReader(data)
+ }
+ req, err := http.NewRequestWithContext(ctx, "PUT", c.baseURL+path, bodyReader)
+ if err != nil {
+ return err
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ resp, err := c.do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if result != nil {
+ return json.NewDecoder(resp.Body).Decode(result)
+ }
+ return nil
+}
+
// Delete performs a DELETE request.
func (c *Client) Delete(ctx context.Context, path string) error {
req, err := http.NewRequestWithContext(ctx, "DELETE", c.baseURL+path, nil)
diff --git a/cmd/oc/internal/commands/project.go b/cmd/oc/internal/commands/project.go
new file mode 100644
index 00000000..cc59d333
--- /dev/null
+++ b/cmd/oc/internal/commands/project.go
@@ -0,0 +1,228 @@
+package commands
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/spf13/cobra"
+)
+
+type projectInfo struct {
+ ID string `json:"id"`
+ OrgID string `json:"orgId"`
+ Name string `json:"name"`
+ Template string `json:"template"`
+ CpuCount int `json:"cpuCount"`
+ MemoryMB int `json:"memoryMB"`
+ TimeoutSec int `json:"timeoutSec"`
+ EgressAllowlist []string `json:"egressAllowlist"`
+ CreatedAt string `json:"createdAt"`
+ UpdatedAt string `json:"updatedAt"`
+}
+
+var projectCmd = &cobra.Command{
+ Use: "project",
+ Short: "Manage projects",
+}
+
+var projectCreateCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a new project",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ name, _ := cmd.Flags().GetString("name")
+ template, _ := cmd.Flags().GetString("template")
+ cpu, _ := cmd.Flags().GetInt("cpu")
+ memory, _ := cmd.Flags().GetInt("memory")
+ timeout, _ := cmd.Flags().GetInt("timeout")
+ allowlist, _ := cmd.Flags().GetStringSlice("egress-allowlist")
+
+ if name == "" {
+ return fmt.Errorf("--name is required")
+ }
+
+ body := map[string]interface{}{"name": name}
+ if template != "" {
+ body["template"] = template
+ }
+ if cpu > 0 {
+ body["cpuCount"] = cpu
+ }
+ if memory > 0 {
+ body["memoryMB"] = memory
+ }
+ if timeout > 0 {
+ body["timeoutSec"] = timeout
+ }
+ if len(allowlist) > 0 {
+ body["egressAllowlist"] = allowlist
+ }
+
+ var project projectInfo
+ if err := c.Post(cmd.Context(), "/projects", body, &project); err != nil {
+ return err
+ }
+
+ printer.Print(project, func() {
+ fmt.Printf("Created project %s (id: %s)\n", project.Name, project.ID)
+ })
+ return nil
+ },
+}
+
+var projectListCmd = &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List projects",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var projects []projectInfo
+ if err := c.Get(cmd.Context(), "/projects", &projects); err != nil {
+ return err
+ }
+
+ printer.Print(projects, func() {
+ if len(projects) == 0 {
+ fmt.Println("No projects found.")
+ return
+ }
+ headers := []string{"ID", "NAME", "TEMPLATE", "CPU", "MEM", "TIMEOUT", "CREATED"}
+ var rows [][]string
+ for _, p := range projects {
+ created := p.CreatedAt
+ if t, err := time.Parse(time.RFC3339Nano, p.CreatedAt); err == nil {
+ created = time.Since(t).Truncate(time.Second).String() + " ago"
+ }
+ rows = append(rows, []string{
+ p.ID,
+ p.Name,
+ p.Template,
+ fmt.Sprintf("%d", p.CpuCount),
+ fmt.Sprintf("%dMB", p.MemoryMB),
+ fmt.Sprintf("%ds", p.TimeoutSec),
+ created,
+ })
+ }
+ printer.Table(headers, rows)
+ })
+ return nil
+ },
+}
+
+var projectGetCmd = &cobra.Command{
+ Use: "get <project-id>",
+ Short: "Get project details",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var project projectInfo
+ if err := c.Get(cmd.Context(), "/projects/"+args[0], &project); err != nil {
+ return err
+ }
+
+ printer.Print(project, func() {
+ fmt.Printf("ID: %s\n", project.ID)
+ fmt.Printf("Name: %s\n", project.Name)
+ fmt.Printf("Template: %s\n", project.Template)
+ fmt.Printf("CPU: %d\n", project.CpuCount)
+ fmt.Printf("Memory: %dMB\n", project.MemoryMB)
+ fmt.Printf("Timeout: %ds\n", project.TimeoutSec)
+ if len(project.EgressAllowlist) > 0 {
+ fmt.Printf("Egress: %s\n", strings.Join(project.EgressAllowlist, ", "))
+ }
+ })
+ return nil
+ },
+}
+
+var projectUpdateCmd = &cobra.Command{
+ Use: "update <project-id>",
+ Short: "Update a project",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ body := map[string]interface{}{}
+ if cmd.Flags().Changed("name") {
+ v, _ := cmd.Flags().GetString("name")
+ body["name"] = v
+ }
+ if cmd.Flags().Changed("template") {
+ v, _ := cmd.Flags().GetString("template")
+ body["template"] = v
+ }
+ if cmd.Flags().Changed("cpu") {
+ v, _ := cmd.Flags().GetInt("cpu")
+ body["cpuCount"] = v
+ }
+ if cmd.Flags().Changed("memory") {
+ v, _ := cmd.Flags().GetInt("memory")
+ body["memoryMB"] = v
+ }
+ if cmd.Flags().Changed("timeout") {
+ v, _ := cmd.Flags().GetInt("timeout")
+ body["timeoutSec"] = v
+ }
+ if cmd.Flags().Changed("egress-allowlist") {
+ v, _ := cmd.Flags().GetStringSlice("egress-allowlist")
+ body["egressAllowlist"] = v
+ }
+
+ if len(body) == 0 {
+ return fmt.Errorf("no fields to update (use --name, --template, --cpu, --memory, --timeout, --egress-allowlist)")
+ }
+
+ var project projectInfo
+ if err := c.PutJSON(cmd.Context(), "/projects/"+args[0], body, &project); err != nil {
+ return err
+ }
+
+ printer.Print(project, func() {
+ fmt.Printf("Updated project %s\n", project.Name)
+ })
+ return nil
+ },
+}
+
+var projectDeleteCmd = &cobra.Command{
+ Use: "delete <project-id>",
+ Short: "Delete a project and all its secrets",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ if err := c.Delete(cmd.Context(), "/projects/"+args[0]); err != nil {
+ return err
+ }
+ fmt.Printf("Project %s deleted.\n", args[0])
+ return nil
+ },
+}
+
+func init() {
+ // project create flags
+ projectCreateCmd.Flags().String("name", "", "Project name (required)")
+ projectCreateCmd.Flags().String("template", "", "Default template")
+ projectCreateCmd.Flags().Int("cpu", 0, "Default CPU count")
+ projectCreateCmd.Flags().Int("memory", 0, "Default memory in MB")
+ projectCreateCmd.Flags().Int("timeout", 0, "Default timeout in seconds")
+ projectCreateCmd.Flags().StringSlice("egress-allowlist", nil, "Allowed egress hosts")
+
+ // project update flags (same as create)
+ projectUpdateCmd.Flags().String("name", "", "Project name")
+ projectUpdateCmd.Flags().String("template", "", "Default template")
+ projectUpdateCmd.Flags().Int("cpu", 0, "Default CPU count")
+ projectUpdateCmd.Flags().Int("memory", 0, "Default memory in MB")
+ projectUpdateCmd.Flags().Int("timeout", 0, "Default timeout in seconds")
+ projectUpdateCmd.Flags().StringSlice("egress-allowlist", nil, "Allowed egress hosts")
+
+ projectCmd.AddCommand(projectCreateCmd)
+ projectCmd.AddCommand(projectListCmd)
+ projectCmd.AddCommand(projectGetCmd)
+ projectCmd.AddCommand(projectUpdateCmd)
+ projectCmd.AddCommand(projectDeleteCmd)
+}
diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.go
index 381114a0..1974b2b6 100644
--- a/cmd/oc/internal/commands/root.go
+++ b/cmd/oc/internal/commands/root.go
@@ -49,6 +49,8 @@ func init() {
rootCmd.AddCommand(checkpointCmd)
rootCmd.AddCommand(patchCmd)
rootCmd.AddCommand(previewCmd)
+ rootCmd.AddCommand(projectCmd)
+ rootCmd.AddCommand(secretCmd)
rootCmd.AddCommand(configCmd)
// Top-level shortcuts
diff --git a/cmd/oc/internal/commands/sandbox.go b/cmd/oc/internal/commands/sandbox.go
index 6fb028e6..67586546 100644
--- a/cmd/oc/internal/commands/sandbox.go
+++ b/cmd/oc/internal/commands/sandbox.go
@@ -26,6 +26,7 @@ var sandboxCreateCmd = &cobra.Command{
memory, _ := cmd.Flags().GetInt("memory")
envSlice, _ := cmd.Flags().GetStringSlice("env")
metaSlice, _ := cmd.Flags().GetStringSlice("metadata")
+ project, _ := cmd.Flags().GetString("project")
config := types.SandboxConfig{
Timeout: timeout,
@@ -35,8 +36,28 @@ var sandboxCreateCmd = &cobra.Command{
Metadata: parseKVSlice(metaSlice),
}
+ // Build request body — include project if set
+ body := map[string]interface{}{
+ "timeout": config.Timeout,
+ }
+ if config.CpuCount > 0 {
+ body["cpuCount"] = config.CpuCount
+ }
+ if config.MemoryMB > 0 {
+ body["memoryMB"] = config.MemoryMB
+ }
+ if config.Envs != nil {
+ body["envs"] = config.Envs
+ }
+ if config.Metadata != nil {
+ body["metadata"] = config.Metadata
+ }
+ if project != "" {
+ body["project"] = project
+ }
+
var sandbox types.Sandbox
- if err := c.Post(cmd.Context(), "/sandboxes", config, &sandbox); err != nil {
+ if err := c.Post(cmd.Context(), "/sandboxes", body, &sandbox); err != nil {
return err
}
@@ -208,6 +229,7 @@ func init() {
cmd.Flags().Int("memory", 0, "Memory in MB")
cmd.Flags().StringSlice("env", nil, "Environment variables (KEY=VALUE)")
cmd.Flags().StringSlice("metadata", nil, "Metadata (KEY=VALUE)")
+ cmd.Flags().String("project", "", "Project name (inherits config + secrets)")
}
// sandbox wake flags
diff --git a/cmd/oc/internal/commands/secret.go b/cmd/oc/internal/commands/secret.go
new file mode 100644
index 00000000..4ab9aa7b
--- /dev/null
+++ b/cmd/oc/internal/commands/secret.go
@@ -0,0 +1,114 @@
+package commands
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/spf13/cobra"
+)
+
+var secretCmd = &cobra.Command{
+ Use: "secret",
+ Short: "Manage project secrets",
+}
+
+var secretSetCmd = &cobra.Command{
+ Use: "set <project-id> <name> [value]",
+ Short: "Set a secret on a project (encrypted at rest)",
+ Long: `Set a secret on a project. The value is encrypted at rest and injected
+as an environment variable into sandboxes created with this project.
+
+Value can be provided as:
+ oc secret set <project-id> KEY value # inline
+ oc secret set <project-id> KEY --from-stdin # from stdin (pipe-friendly)
+ echo "val" | oc secret set <project-id> KEY --from-stdin`,
+ Args: cobra.RangeArgs(2, 3),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ projectID := args[0]
+ name := args[1]
+ fromStdin, _ := cmd.Flags().GetBool("from-stdin")
+
+ var value string
+ if fromStdin {
+ scanner := bufio.NewScanner(os.Stdin)
+ var lines []string
+ for scanner.Scan() {
+ lines = append(lines, scanner.Text())
+ }
+ if err := scanner.Err(); err != nil {
+ return fmt.Errorf("reading stdin: %w", err)
+ }
+ value = strings.Join(lines, "\n")
+ } else if len(args) == 3 {
+ value = args[2]
+ } else {
+ return fmt.Errorf("provide value as argument or use --from-stdin")
+ }
+
+ if value == "" {
+ return fmt.Errorf("secret value cannot be empty")
+ }
+
+ body := map[string]string{"value": value}
+ var result map[string]string
+ if err := c.PutJSON(cmd.Context(), fmt.Sprintf("/projects/%s/secrets/%s", projectID, name), body, &result); err != nil {
+ return err
+ }
+
+ fmt.Printf("Secret %s set on project %s\n", name, projectID)
+ return nil
+ },
+}
+
+var secretListCmd = &cobra.Command{
+ Use: "list <project-id>",
+ Aliases: []string{"ls"},
+ Short: "List secret names for a project (values are never shown)",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+
+ var names []string
+ if err := c.Get(cmd.Context(), fmt.Sprintf("/projects/%s/secrets", args[0]), &names); err != nil {
+ return err
+ }
+
+ printer.Print(names, func() {
+ if len(names) == 0 {
+ fmt.Println("No secrets found.")
+ return
+ }
+ for _, name := range names {
+ fmt.Println(name)
+ }
+ })
+ return nil
+ },
+}
+
+var secretDeleteCmd = &cobra.Command{
+ Use: "delete <project-id> <name>",
+ Short: "Delete a secret from a project",
+ Args: cobra.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ if err := c.DeleteIgnoreNotFound(cmd.Context(), fmt.Sprintf("/projects/%s/secrets/%s", args[0], args[1])); err != nil {
+ return err
+ }
+ fmt.Printf("Secret %s deleted from project %s\n", args[1], args[0])
+ return nil
+ },
+}
+
+func init() {
+ secretSetCmd.Flags().Bool("from-stdin", false, "Read secret value from stdin")
+
+ secretCmd.AddCommand(secretSetCmd)
+ secretCmd.AddCommand(secretListCmd)
+ secretCmd.AddCommand(secretDeleteCmd)
+}
diff --git a/cmd/server/main.go b/cmd/server/main.go
index f4c6f2cf..b5d44afc 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -16,6 +16,7 @@ import (
"github.com/opensandbox/opensandbox/internal/compute"
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/controlplane"
+ "github.com/opensandbox/opensandbox/internal/crypto"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/ecr"
"github.com/opensandbox/opensandbox/internal/proxy"
@@ -59,6 +60,16 @@ func main() {
}
log.Println("opensandbox: database migrations complete")
+ // Configure encryption for project secrets if key is provided
+ if cfg.SecretEncryptionKey != "" {
+ enc, err := crypto.NewEncryptor(cfg.SecretEncryptionKey)
+ if err != nil {
+ log.Fatalf("invalid OPENSANDBOX_SECRET_ENCRYPTION_KEY: %v", err)
+ }
+ store.SetEncryptor(enc)
+ log.Println("opensandbox: project secret encryption configured")
+ }
+
opts.Store = store
} else {
log.Println("opensandbox: no DATABASE_URL configured, running without PostgreSQL")
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 2d0e930a..881427fa 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -15,15 +15,16 @@ import (
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/db"
fc "github.com/opensandbox/opensandbox/internal/firecracker"
- agentpb "github.com/opensandbox/opensandbox/proto/agent"
"github.com/opensandbox/opensandbox/internal/metrics"
"github.com/opensandbox/opensandbox/internal/podman"
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/secretsproxy"
"github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/internal/template"
"github.com/opensandbox/opensandbox/internal/worker"
"github.com/opensandbox/opensandbox/pkg/types"
+ agentpb "github.com/opensandbox/opensandbox/proto/agent"
)
func main() {
@@ -54,6 +55,26 @@ func main() {
defer fcMgr.Close()
log.Println("opensandbox-worker: Firecracker VM manager initialized")
+ // Initialize secrets proxy for MITM token substitution.
+ // Runs on :3128 — VMs route HTTPS through this to keep real secrets off-VM.
+ secretsCA, err := secretsproxy.LoadOrCreateCA(filepath.Join(cfg.DataDir, "proxy-ca"))
+ if err != nil {
+ log.Printf("opensandbox-worker: secrets proxy CA failed: %v (secrets proxy disabled)", err)
+ }
+ var secretsProxy *secretsproxy.SecretsProxy
+ if secretsCA != nil {
+ secretsProxy, err = secretsproxy.NewSecretsProxy(secretsCA, "0.0.0.0:3128")
+ if err != nil {
+ log.Printf("opensandbox-worker: secrets proxy listen failed: %v", err)
+ } else {
+ secretsProxy.Start()
+ defer secretsProxy.Stop()
+ log.Println("opensandbox-worker: secrets proxy started on :3128")
+ // Wire secrets proxy into VM lifecycle
+ fcMgr.SetSecretsProxy(secretsProxy)
+ }
+ }
+
// Clean up orphaned Firecracker processes + TAP devices BEFORE starting golden snapshot.
// Must run first to avoid killing the golden snapshot VM (race condition).
fcMgr.CleanupOrphanedProcesses()
diff --git a/docs/cli/projects.mdx b/docs/cli/projects.mdx
new file mode 100644
index 00000000..c90e7caa
--- /dev/null
+++ b/docs/cli/projects.mdx
@@ -0,0 +1,175 @@
+---
+title: "Projects & Secrets"
+description: "Manage projects and encrypted secrets from the CLI"
+---
+
+Projects group sandboxes with shared config defaults and encrypted secrets. Use `oc project` to manage projects and `oc secret` to manage their secrets.
+
+## Projects
+
+### Create a Project
+
+```bash
+oc project create --name my-agent --cpu 2 --memory 1024 --timeout 600
+```
+
+#### `oc project create`
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| `--name` | string | *required* | Project name (unique per org) |
+| `--template` | string | — | Default template for sandboxes |
+| `--cpu` | int | — | Default vCPU count |
+| `--memory` | int | — | Default memory in MB |
+| `--timeout` | int | — | Default timeout in seconds |
+
+### List Projects
+
+```bash
+oc project list
+```
+
+Output:
+
+```
+ID NAME TEMPLATE CPU MEMORY TIMEOUT
+9961c10e-c83c-4e6b-ad61-b91144323a3d my-agent default 2 1024 600
+```
+
+### Get Project Details
+
+```bash
+oc project get <project-id>
+```
+
+### Update a Project
+
+Partial updates — only the flags you pass are changed.
+
+```bash
+oc project update <project-id> --memory 2048
+# Name, template, CPU, timeout are preserved
+```
+
+#### `oc project update`
+
+| Flag | Type | Description |
+| --- | --- | --- |
+| `--name` | string | New project name |
+| `--template` | string | New default template |
+| `--cpu` | int | New default vCPU count |
+| `--memory` | int | New default memory in MB |
+| `--timeout` | int | New default timeout in seconds |
+
+### Delete a Project
+
+```bash
+oc project delete <project-id>
+```
+
+Deletes the project and all its secrets. Running sandboxes are not affected.
+
+## Secrets
+
+Secrets are encrypted at rest and injected as sealed tokens when a sandbox is created with the project. The real values are never visible inside the sandbox — they are only substituted by the MITM proxy on outbound HTTPS requests.
+
+### Set a Secret
+
+```bash
+oc secret set <project-id> ANTHROPIC_API_KEY sk-ant-...
+```
+
+Or pipe from stdin (useful for multiline values or scripts):
+
+```bash
+cat ~/.anthropic_key | oc secret set <project-id> ANTHROPIC_API_KEY --from-stdin
+```
+
+```bash
+echo "sk-ant-..." | oc secret set <project-id> ANTHROPIC_API_KEY --from-stdin
+```
+
+#### `oc secret set`
+
+| Argument | Description |
+| --- | --- |
+| `<project-id>` | UUID of the project |
+| `<name>` | Secret name (becomes the env var name in sandboxes) |
+| `<value>` | Secret value (omit if using `--from-stdin`) |
+
+| Flag | Description |
+| --- | --- |
+| `--from-stdin` | Read the secret value from stdin |
+
+### List Secrets
+
+```bash
+oc secret list <project-id>
+```
+
+Output:
+
+```
+ANTHROPIC_API_KEY
+DATABASE_URL
+```
+
+Returns names only. Values are never exposed.
+
+### Delete a Secret
+
+```bash
+oc secret delete <project-id> ANTHROPIC_API_KEY
+```
+
+## Creating Sandboxes with Projects
+
+Use the `--project` flag on `oc create` to inherit a project's config and secrets:
+
+```bash
+oc create --project my-agent --timeout 600
+```
+
+The sandbox inherits the project's template, CPU, memory, and timeout as defaults. Any flags you pass explicitly override the project defaults.
+
+Secrets are injected as sealed tokens:
+
+```bash
+oc exec <sandbox-id> -- echo '$ANTHROPIC_API_KEY'
+# osb_sealed_2ce9277be9baafcb... (sealed, never the real key)
+```
+
+The proxy replaces sealed tokens with real values on outbound HTTPS requests, so code running in the sandbox can use API keys normally without ever seeing the actual secret.
+
+## Example Workflow
+
+```bash
+# Create a project
+oc project create --name my-agent --cpu 2 --memory 1024 --timeout 600
+
+# Add secrets
+oc secret set <project-id> ANTHROPIC_API_KEY sk-ant-...
+oc secret set <project-id> DATABASE_URL postgres://user:pass@host/db
+
+# Verify secrets are stored
+oc secret list <project-id>
+
+# Create a sandbox — inherits config + secrets
+oc create --project my-agent
+
+# Secrets are sealed inside the sandbox
+oc exec <sandbox-id> -- env | grep -E 'API_KEY|DATABASE'
+# ANTHROPIC_API_KEY=osb_sealed_...
+# DATABASE_URL=osb_sealed_...
+
+# But HTTPS requests get real values via the proxy
+oc exec <sandbox-id> -- curl -s https://api.anthropic.com/v1/messages \
+ -H "x-api-key: \$ANTHROPIC_API_KEY" \
+ -H "anthropic-version: 2023-06-01" \
+ -H "content-type: application/json" \
+ -d '{"model":"claude-haiku-4-5-20251001","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}'
+
+# Clean up
+oc sandbox delete <sandbox-id>
+oc project delete <project-id>
+```
diff --git a/docs/cli/sandbox.mdx b/docs/cli/sandbox.mdx
index 0774d341..76fbe3f2 100644
--- a/docs/cli/sandbox.mdx
+++ b/docs/cli/sandbox.mdx
@@ -29,6 +29,7 @@ Alias for `oc sandbox create`. Creates a new sandbox and prints its ID.
| `--memory` | int | `1024` | Memory in MB |
| `--env` | string | — | Environment variable (`KEY=VALUE`, repeatable) |
| `--metadata` | string | — | Metadata (`KEY=VALUE`, repeatable) |
+| `--project` | string | — | Project name. Inherits config defaults and [sealed secrets](/cli/projects) |
## List Sandboxes
diff --git a/docs/mint.json b/docs/mint.json
index ffae2f08..f38c2f96 100644
--- a/docs/mint.json
+++ b/docs/mint.json
@@ -63,6 +63,7 @@
"sdks/typescript/filesystem",
"sdks/typescript/pty",
"sdks/typescript/templates",
+ "sdks/typescript/projects",
"sdks/typescript/checkpoints",
"sdks/typescript/patches"
]
@@ -76,6 +77,7 @@
"sdks/python/filesystem",
"sdks/python/pty",
"sdks/python/templates",
+ "sdks/python/projects",
"sdks/python/checkpoints",
"sdks/python/patches"
]
@@ -87,6 +89,7 @@
"cli/sandbox",
"cli/commands",
"cli/shell",
+ "cli/projects",
"cli/checkpoints",
"cli/patches",
"cli/previews"
diff --git a/docs/sdks/python/projects.mdx b/docs/sdks/python/projects.mdx
new file mode 100644
index 00000000..85ff2c13
--- /dev/null
+++ b/docs/sdks/python/projects.mdx
@@ -0,0 +1,198 @@
+---
+title: "Projects & Secrets"
+description: "Manage projects and encrypted secrets that are securely injected into sandboxes"
+---
+
+Projects group sandboxes together with shared configuration defaults and encrypted secrets. When you create a sandbox with a project, it inherits the project's template, resource limits, and timeout — and secrets are sealed inside the sandbox so they never exist as plaintext in VM memory.
+
+## How Secrets Work
+
+When a sandbox is created with a project:
+
+1. The server decrypts the project's secrets
+2. Secrets are sent to the worker and **sealed** into opaque tokens (`osb_sealed_...`)
+3. Inside the sandbox, env vars contain sealed tokens — never real values
+4. When the sandbox makes an outbound HTTPS request, the MITM proxy intercepts it and replaces sealed tokens with real values in headers and request body
+5. The real secret only exists in the proxy's memory on the host, never inside the VM
+
+## Creating a Project
+
+```python
+from opencomputer import Project
+
+project = await Project.create(
+ name='my-agent',
+ template='default',
+ cpu_count=2,
+ memory_mb=1024,
+ timeout_sec=600,
+)
+```
+
+### `Project.create(**kwargs)`
+
+<ParamField body="name" type="str" required>
+ Project name (unique per organization).
+</ParamField>
+<ParamField body="template" type="str" default="">
+ Default template for sandboxes in this project.
+</ParamField>
+<ParamField body="cpu_count" type="int" default="0">
+ Default vCPU count.
+</ParamField>
+<ParamField body="memory_mb" type="int" default="0">
+ Default memory in MB.
+</ParamField>
+<ParamField body="timeout_sec" type="int" default="0">
+ Default sandbox timeout in seconds.
+</ParamField>
+<ParamField body="egress_allowlist" type="list[str] | None" default="None">
+ Allowed egress hosts (e.g. `["api.anthropic.com"]`).
+</ParamField>
+
+**Returns:** `dict` — Project info with `id`, `name`, `template`, etc.
+
+## Listing Projects
+
+```python
+projects = await Project.list()
+```
+
+### `Project.list(**kwargs)`
+
+**Returns:** `list[dict]`
+
+## Getting a Project
+
+```python
+project = await Project.get('project-uuid')
+```
+
+### `Project.get(project_id, **kwargs)`
+
+<ParamField body="project_id" type="str" required>
+ UUID of the project.
+</ParamField>
+
+**Returns:** `dict`
+
+## Updating a Project
+
+Partial updates — only the fields you pass are changed.
+
+```python
+updated = await Project.update(
+ 'project-uuid',
+ memory_mb=2048,
+ timeout_sec=900,
+)
+# Name, template, cpu_count are preserved
+```
+
+### `Project.update(project_id, **kwargs)`
+
+<ParamField body="project_id" type="str" required>
+ UUID of the project to update.
+</ParamField>
+<ParamField body="name" type="str" default="">
+ New project name (empty = no change).
+</ParamField>
+<ParamField body="template" type="str" default="">
+ New default template (empty = no change).
+</ParamField>
+<ParamField body="cpu_count" type="int" default="0">
+ New default vCPU count (0 = no change).
+</ParamField>
+<ParamField body="memory_mb" type="int" default="0">
+ New default memory in MB (0 = no change).
+</ParamField>
+<ParamField body="timeout_sec" type="int" default="0">
+ New default timeout in seconds (0 = no change).
+</ParamField>
+<ParamField body="egress_allowlist" type="list[str] | None" default="None">
+ New allowed egress hosts (None = no change).
+</ParamField>
+
+**Returns:** `dict`
+
+## Deleting a Project
+
+```python
+await Project.delete('project-uuid')
+```
+
+Deletes the project and all its secrets. Running sandboxes are not affected.
+
+### `Project.delete(project_id, **kwargs)`
+
+**Returns:** `None`
+
+## Setting a Secret
+
+```python
+await Project.set_secret('project-uuid', 'ANTHROPIC_API_KEY', 'sk-ant-...')
+```
+
+Secrets are encrypted at rest. The value is never returned by the API.
+
+### `Project.set_secret(project_id, name, value, **kwargs)`
+
+<ParamField body="project_id" type="str" required>
+ UUID of the project.
+</ParamField>
+<ParamField body="name" type="str" required>
+ Secret name (used as the env var name in sandboxes).
+</ParamField>
+<ParamField body="value" type="str" required>
+ Secret value (encrypted at rest, never returned by API).
+</ParamField>
+
+**Returns:** `None`
+
+## Listing Secrets
+
+```python
+names = await Project.list_secrets('project-uuid')
+# ['ANTHROPIC_API_KEY', 'DATABASE_URL']
+```
+
+Returns secret names only. Values are never exposed.
+
+### `Project.list_secrets(project_id, **kwargs)`
+
+**Returns:** `list[str]`
+
+## Deleting a Secret
+
+```python
+await Project.delete_secret('project-uuid', 'DATABASE_URL')
+```
+
+### `Project.delete_secret(project_id, name, **kwargs)`
+
+**Returns:** `None`
+
+## Creating a Sandbox with a Project
+
+Pass the `project` parameter to `Sandbox.create()` to inherit the project's config and secrets:
+
+```python
+from opencomputer import Sandbox
+
+sandbox = await Sandbox.create(
+ project='my-agent',
+ timeout=600,
+)
+
+# Secrets are available as sealed env vars
+result = await sandbox.commands.run('echo $ANTHROPIC_API_KEY')
+# stdout: "osb_sealed_abc123..." (sealed, not the real key)
+
+# But outbound HTTPS requests get the real value substituted by the proxy
+api_result = await sandbox.commands.run(
+ 'curl -s https://api.anthropic.com/v1/messages -H "x-api-key: $ANTHROPIC_API_KEY" ...'
+)
+# The proxy replaces the sealed token with the real key before it hits Anthropic
+```
+
+Request-level options (`timeout`, `envs`, `cpu_count`, etc.) override project defaults.
diff --git a/docs/sdks/python/sandbox.mdx b/docs/sdks/python/sandbox.mdx
index ebab2920..f9c13e13 100644
--- a/docs/sdks/python/sandbox.mdx
+++ b/docs/sdks/python/sandbox.mdx
@@ -40,6 +40,9 @@ Creates a new sandbox and returns a connected `Sandbox` instance.
<ParamField body="metadata" type="dict[str, str] | None" default="None">
Arbitrary key-value metadata attached to the sandbox.
</ParamField>
+<ParamField body="project" type="str | None" default="None">
+ Project name. Inherits the project's config defaults and [sealed secrets](/sdks/python/projects).
+</ParamField>
**Returns:** `Sandbox`
diff --git a/docs/sdks/typescript/projects.mdx b/docs/sdks/typescript/projects.mdx
new file mode 100644
index 00000000..c82420d9
--- /dev/null
+++ b/docs/sdks/typescript/projects.mdx
@@ -0,0 +1,220 @@
+---
+title: "Projects & Secrets"
+description: "Manage projects and encrypted secrets that are securely injected into sandboxes"
+---
+
+Projects group sandboxes together with shared configuration defaults and encrypted secrets. When you create a sandbox with a project, it inherits the project's template, resource limits, and timeout — and secrets are sealed inside the sandbox so they never exist as plaintext in VM memory.
+
+## How Secrets Work
+
+When a sandbox is created with a project:
+
+1. The server decrypts the project's secrets
+2. Secrets are sent to the worker and **sealed** into opaque tokens (`osb_sealed_...`)
+3. Inside the sandbox, env vars contain sealed tokens — never real values
+4. When the sandbox makes an outbound HTTPS request, the MITM proxy intercepts it and replaces sealed tokens with real values in headers and request body
+5. The real secret only exists in the proxy's memory on the host, never inside the VM
+
+## Creating a Project
+
+```typescript
+import { Project } from '@opencomputer/sdk';
+
+const project = await Project.create({
+ name: 'my-agent',
+ template: 'default',
+ cpuCount: 2,
+ memoryMB: 1024,
+ timeoutSec: 600,
+});
+```
+
+### `Project.create(opts)`
+
+<ParamField body="opts" type="CreateProjectOpts" required>
+ <Expandable title="properties">
+ <ParamField body="name" type="string" required>
+ Project name (unique per organization).
+ </ParamField>
+ <ParamField body="template" type="string" optional>
+ Default template for sandboxes in this project.
+ </ParamField>
+ <ParamField body="cpuCount" type="number" optional>
+ Default vCPU count.
+ </ParamField>
+ <ParamField body="memoryMB" type="number" optional>
+ Default memory in MB.
+ </ParamField>
+ <ParamField body="timeoutSec" type="number" optional>
+ Default sandbox timeout in seconds.
+ </ParamField>
+ <ParamField body="egressAllowlist" type="string[]" optional>
+ Allowed egress hosts (e.g. `["api.anthropic.com"]`).
+ </ParamField>
+ </Expandable>
+</ParamField>
+
+**Returns:** `Promise<ProjectInfo>`
+
+## Listing Projects
+
+```typescript
+const projects = await Project.list();
+```
+
+### `Project.list(opts?)`
+
+**Returns:** `Promise<ProjectInfo[]>`
+
+## Getting a Project
+
+```typescript
+const project = await Project.get('project-uuid');
+```
+
+### `Project.get(projectId, opts?)`
+
+<ParamField body="projectId" type="string" required>
+ UUID of the project.
+</ParamField>
+
+**Returns:** `Promise<ProjectInfo>`
+
+## Updating a Project
+
+Partial updates — only the fields you pass are changed.
+
+```typescript
+const updated = await Project.update('project-uuid', {
+ memoryMB: 2048,
+ timeoutSec: 900,
+});
+// Name, template, cpuCount are preserved
+```
+
+### `Project.update(projectId, opts)`
+
+<ParamField body="projectId" type="string" required>
+ UUID of the project to update.
+</ParamField>
+<ParamField body="opts" type="UpdateProjectOpts" required>
+ <Expandable title="properties">
+ <ParamField body="name" type="string" optional>
+ New project name.
+ </ParamField>
+ <ParamField body="template" type="string" optional>
+ New default template.
+ </ParamField>
+ <ParamField body="cpuCount" type="number" optional>
+ New default vCPU count.
+ </ParamField>
+ <ParamField body="memoryMB" type="number" optional>
+ New default memory in MB.
+ </ParamField>
+ <ParamField body="timeoutSec" type="number" optional>
+ New default timeout in seconds.
+ </ParamField>
+ <ParamField body="egressAllowlist" type="string[]" optional>
+ New allowed egress hosts.
+ </ParamField>
+ </Expandable>
+</ParamField>
+
+**Returns:** `Promise<ProjectInfo>`
+
+## Deleting a Project
+
+```typescript
+await Project.delete('project-uuid');
+```
+
+Deletes the project and all its secrets. Running sandboxes are not affected.
+
+### `Project.delete(projectId, opts?)`
+
+**Returns:** `Promise<void>`
+
+## Setting a Secret
+
+```typescript
+await Project.setSecret('project-uuid', 'ANTHROPIC_API_KEY', 'sk-ant-...');
+```
+
+Secrets are encrypted at rest. The value is never returned by the API.
+
+### `Project.setSecret(projectId, name, value, opts?)`
+
+<ParamField body="projectId" type="string" required>
+ UUID of the project.
+</ParamField>
+<ParamField body="name" type="string" required>
+ Secret name (used as the env var name in sandboxes).
+</ParamField>
+<ParamField body="value" type="string" required>
+ Secret value (encrypted at rest, never returned by API).
+</ParamField>
+
+**Returns:** `Promise<void>`
+
+## Listing Secrets
+
+```typescript
+const names = await Project.listSecrets('project-uuid');
+// ['ANTHROPIC_API_KEY', 'DATABASE_URL']
+```
+
+Returns secret names only. Values are never exposed.
+
+### `Project.listSecrets(projectId, opts?)`
+
+**Returns:** `Promise<string[]>`
+
+## Deleting a Secret
+
+```typescript
+await Project.deleteSecret('project-uuid', 'DATABASE_URL');
+```
+
+### `Project.deleteSecret(projectId, name, opts?)`
+
+**Returns:** `Promise<void>`
+
+## Creating a Sandbox with a Project
+
+Pass the `project` option to `Sandbox.create()` to inherit the project's config and secrets:
+
+```typescript
+import { Sandbox } from '@opencomputer/sdk';
+
+const sandbox = await Sandbox.create({
+ project: 'my-agent',
+ timeout: 600,
+});
+
+// Secrets are available as sealed env vars
+const result = await sandbox.commands.run('echo $ANTHROPIC_API_KEY');
+// stdout: "osb_sealed_abc123..." (sealed, not the real key)
+
+// But outbound HTTPS requests get the real value substituted by the proxy
+const apiResult = await sandbox.commands.run(
+ 'curl -s https://api.anthropic.com/v1/messages -H "x-api-key: $ANTHROPIC_API_KEY" ...'
+);
+// The proxy replaces the sealed token with the real key before it hits Anthropic
+```
+
+Request-level options (`timeout`, `envs`, `cpuCount`, etc.) override project defaults.
+
+## ProjectInfo Type
+
+| Property | Type | Description |
+| --- | --- | --- |
+| `id` | `string` | Project UUID |
+| `orgId` | `string` | Organization UUID |
+| `name` | `string` | Project name |
+| `template` | `string` | Default template |
+| `cpuCount` | `number` | Default vCPU count |
+| `memoryMB` | `number` | Default memory in MB |
+| `timeoutSec` | `number` | Default timeout in seconds |
+| `egressAllowlist` | `string[]` | Allowed egress hosts |
+| `createdAt` | `string` | ISO 8601 timestamp |
+| `updatedAt` | `string` | ISO 8601 timestamp |
diff --git a/docs/sdks/typescript/sandbox.mdx b/docs/sdks/typescript/sandbox.mdx
index 21b8c8b1..3729e85f 100644
--- a/docs/sdks/typescript/sandbox.mdx
+++ b/docs/sdks/typescript/sandbox.mdx
@@ -42,6 +42,9 @@ Creates a new sandbox and returns a connected `Sandbox` instance.
<ParamField body="metadata" type="Record<string, string>" optional>
Arbitrary key-value metadata attached to the sandbox.
</ParamField>
+ <ParamField body="project" type="string" optional>
+ Project name. Inherits the project's config defaults and [sealed secrets](/sdks/typescript/projects).
+ </ParamField>
</Expandable>
</ParamField>
diff --git a/internal/api/projects.go b/internal/api/projects.go
new file mode 100644
index 00000000..669f5f7b
--- /dev/null
+++ b/internal/api/projects.go
@@ -0,0 +1,243 @@
+package api
+
+import (
+ "net/http"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/auth"
+)
+
+func (s *Server) createProject(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+ var req struct {
+ Name string `json:"name"`
+ Template string `json:"template"`
+ CpuCount int `json:"cpuCount"`
+ MemoryMB int `json:"memoryMB"`
+ TimeoutSec int `json:"timeoutSec"`
+ EgressAllowlist []string `json:"egressAllowlist"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})
+ }
+ if req.Name == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})
+ }
+
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ project, err := s.store.CreateProject(c.Request().Context(), orgID, req.Name, req.Template, req.CpuCount, req.MemoryMB, req.TimeoutSec, req.EgressAllowlist)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusCreated, project)
+}
+
+func (s *Server) listProjects(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projects, err := s.store.ListProjects(c.Request().Context(), orgID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, projects)
+}
+
+func (s *Server) getProject(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+
+ project, err := s.store.GetProject(c.Request().Context(), orgID, projectID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+ return c.JSON(http.StatusOK, project)
+}
+
+func (s *Server) updateProject(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+
+ var req struct {
+ Name *string `json:"name"`
+ Template *string `json:"template"`
+ CpuCount *int `json:"cpuCount"`
+ MemoryMB *int `json:"memoryMB"`
+ TimeoutSec *int `json:"timeoutSec"`
+ EgressAllowlist []string `json:"egressAllowlist"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})
+ }
+
+ // Fetch existing project to merge partial updates
+ existing, err := s.store.GetProject(c.Request().Context(), orgID, projectID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+
+ name := existing.Name
+ template := existing.Template
+ cpuCount := existing.CpuCount
+ memoryMB := existing.MemoryMB
+ timeoutSec := existing.TimeoutSec
+ allowlist := existing.EgressAllowlist
+
+ if req.Name != nil { name = *req.Name }
+ if req.Template != nil { template = *req.Template }
+ if req.CpuCount != nil { cpuCount = *req.CpuCount }
+ if req.MemoryMB != nil { memoryMB = *req.MemoryMB }
+ if req.TimeoutSec != nil { timeoutSec = *req.TimeoutSec }
+ if req.EgressAllowlist != nil { allowlist = req.EgressAllowlist }
+
+ project, err := s.store.UpdateProject(c.Request().Context(), orgID, projectID, name, template, cpuCount, memoryMB, timeoutSec, allowlist)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, project)
+}
+
+func (s *Server) deleteProject(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+
+ if err := s.store.DeleteProject(c.Request().Context(), orgID, projectID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+ return c.NoContent(http.StatusNoContent)
+}
+
+// ── Project Secrets ───────────────────────────────────────────────────────────
+
+func (s *Server) setProjectSecret(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+ name := c.Param("name")
+ if name == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "secret name required"})
+ }
+
+ // Verify project belongs to org
+ if _, err := s.store.GetProject(c.Request().Context(), orgID, projectID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+
+ var req struct {
+ Value string `json:"value"`
+ }
+ if err := c.Bind(&req); err != nil || req.Value == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "secret value required: {\"value\": \"...\"}"})
+ }
+
+ if err := s.store.SetProjectSecret(c.Request().Context(), projectID, name, []byte(req.Value)); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, map[string]string{"name": name, "status": "set"})
+}
+
+func (s *Server) deleteProjectSecret(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+ name := c.Param("name")
+
+ if _, err := s.store.GetProject(c.Request().Context(), orgID, projectID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+
+ if err := s.store.DeleteProjectSecret(c.Request().Context(), projectID, name); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *Server) listProjectSecrets(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+
+ if _, err := s.store.GetProject(c.Request().Context(), orgID, projectID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+
+ secrets, err := s.store.ListProjectSecretNames(c.Request().Context(), projectID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ names := make([]string, len(secrets))
+ for i, s := range secrets {
+ names[i] = s.Name
+ }
+ return c.JSON(http.StatusOK, names)
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 7dd47b99..64002b38 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -189,6 +189,18 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.DELETE("/templates/:name", s.deleteTemplate)
api.POST("/sandboxes/:sandboxId/save-as-template", s.dashboardSaveAsTemplate)
+ // Projects
+ api.POST("/projects", s.createProject)
+ api.GET("/projects", s.listProjects)
+ api.GET("/projects/:id", s.getProject)
+ api.PUT("/projects/:id", s.updateProject)
+ api.DELETE("/projects/:id", s.deleteProject)
+
+ // Project secrets
+ api.PUT("/projects/:id/secrets/:name", s.setProjectSecret)
+ api.DELETE("/projects/:id/secrets/:name", s.deleteProjectSecret)
+ api.GET("/projects/:id/secrets", s.listProjectSecrets)
+
// Workers (server mode only — queries worker registry)
api.GET("/workers", s.listWorkers)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index c6e9b64a..41714f6a 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -60,6 +60,49 @@ func (s *Server) createSandbox(c echo.Context) error {
}
}
+ // Resolve project: inherit config defaults + decrypt and merge secrets
+ if cfg.Project != "" && s.store != nil && hasOrg {
+ project, err := s.store.GetProjectByName(ctx, orgID, cfg.Project)
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "project not found: " + cfg.Project,
+ })
+ }
+
+ // Project config serves as defaults — request fields override
+ if cfg.Template == "" {
+ cfg.Template = project.Template
+ }
+ if cfg.CpuCount == 0 {
+ cfg.CpuCount = project.CpuCount
+ }
+ if cfg.MemoryMB == 0 {
+ cfg.MemoryMB = project.MemoryMB
+ }
+ if cfg.Timeout == 0 {
+ cfg.Timeout = project.TimeoutSec
+ }
+
+ // Decrypt project secrets and merge into envs (request envs override project secrets)
+ secrets, err := s.store.DecryptProjectSecrets(ctx, project.ID)
+ if err != nil {
+ log.Printf("api: decrypt project secrets failed for %s: %v", cfg.Project, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to decrypt project secrets",
+ })
+ }
+ if len(secrets) > 0 {
+ if cfg.Envs == nil {
+ cfg.Envs = make(map[string]string)
+ }
+ for k, v := range secrets {
+ if _, exists := cfg.Envs[k]; !exists {
+ cfg.Envs[k] = v
+ }
+ }
+ }
+ }
+
// Server mode with worker registry: dispatch to remote worker via gRPC
if s.workerRegistry != nil {
return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg)
diff --git a/internal/config/config.go b/internal/config/config.go
index f3c772e4..f00a369d 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -95,6 +95,10 @@ type Config struct {
// The secret should be a JSON object with keys matching env var names (e.g. OPENSANDBOX_JWT_SECRET).
// Env vars take precedence over secret values (for local overrides).
SecretsARN string
+
+ // Secret encryption key (hex-encoded 32 bytes / 64 hex chars) for encrypting
+ // project secrets at rest in PostgreSQL. Required if using project secrets.
+ SecretEncryptionKey string
}
// Load reads configuration from environment variables with sensible defaults.
@@ -168,6 +172,8 @@ func Load() (*Config, error) {
ScaleCooldownSec: envOrDefaultInt("OPENSANDBOX_SCALE_COOLDOWN_SEC", 300),
SecretsARN: os.Getenv("OPENSANDBOX_SECRETS_ARN"),
+
+ SecretEncryptionKey: os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY"),
}
// Default S3 region to worker region for same-region storage
diff --git a/internal/controlplane/projects.go b/internal/controlplane/projects.go
new file mode 100644
index 00000000..ac811dd7
--- /dev/null
+++ b/internal/controlplane/projects.go
@@ -0,0 +1,223 @@
+package controlplane
+
+import (
+ "net/http"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/auth"
+)
+
+func (s *Server) createProject(c echo.Context) error {
+ var req struct {
+ Name string `json:"name"`
+ Template string `json:"template"`
+ CpuCount int `json:"cpuCount"`
+ MemoryMB int `json:"memoryMB"`
+ TimeoutSec int `json:"timeoutSec"`
+ EgressAllowlist []string `json:"egressAllowlist"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})
+ }
+ if req.Name == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})
+ }
+
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ project, err := s.store.CreateProject(c.Request().Context(), orgID, req.Name, req.Template, req.CpuCount, req.MemoryMB, req.TimeoutSec, req.EgressAllowlist)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusCreated, project)
+}
+
+func (s *Server) listProjects(c echo.Context) error {
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projects, err := s.store.ListProjects(c.Request().Context(), orgID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, projects)
+}
+
+func (s *Server) getProject(c echo.Context) error {
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+
+ project, err := s.store.GetProject(c.Request().Context(), orgID, projectID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+ return c.JSON(http.StatusOK, project)
+}
+
+func (s *Server) updateProject(c echo.Context) error {
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+
+ var req struct {
+ Name *string `json:"name"`
+ Template *string `json:"template"`
+ CpuCount *int `json:"cpuCount"`
+ MemoryMB *int `json:"memoryMB"`
+ TimeoutSec *int `json:"timeoutSec"`
+ EgressAllowlist []string `json:"egressAllowlist"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})
+ }
+
+ // Fetch existing project to merge partial updates
+ existing, err := s.store.GetProject(c.Request().Context(), orgID, projectID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+
+ name := existing.Name
+ template := existing.Template
+ cpuCount := existing.CpuCount
+ memoryMB := existing.MemoryMB
+ timeoutSec := existing.TimeoutSec
+ allowlist := existing.EgressAllowlist
+
+ if req.Name != nil { name = *req.Name }
+ if req.Template != nil { template = *req.Template }
+ if req.CpuCount != nil { cpuCount = *req.CpuCount }
+ if req.MemoryMB != nil { memoryMB = *req.MemoryMB }
+ if req.TimeoutSec != nil { timeoutSec = *req.TimeoutSec }
+ if req.EgressAllowlist != nil { allowlist = req.EgressAllowlist }
+
+ project, err := s.store.UpdateProject(c.Request().Context(), orgID, projectID, name, template, cpuCount, memoryMB, timeoutSec, allowlist)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, project)
+}
+
+func (s *Server) deleteProject(c echo.Context) error {
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+
+ if err := s.store.DeleteProject(c.Request().Context(), orgID, projectID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+ return c.NoContent(http.StatusNoContent)
+}
+
+// ── Project Secrets ───────────────────────────────────────────────────────────
+
+func (s *Server) setProjectSecret(c echo.Context) error {
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+ name := c.Param("name")
+ if name == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "secret name required"})
+ }
+
+ // Verify project belongs to org
+ if _, err := s.store.GetProject(c.Request().Context(), orgID, projectID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+
+ // Read secret value from JSON body
+ var req struct {
+ Value string `json:"value"`
+ }
+ if err := c.Bind(&req); err != nil || req.Value == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "secret value required: {\"value\": \"...\"}"})
+ }
+ body := []byte(req.Value)
+
+ if err := s.store.SetProjectSecret(c.Request().Context(), projectID, name, body); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, map[string]string{"name": name, "status": "set"})
+}
+
+func (s *Server) deleteProjectSecret(c echo.Context) error {
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+ name := c.Param("name")
+
+ // Verify project belongs to org
+ if _, err := s.store.GetProject(c.Request().Context(), orgID, projectID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+
+ if err := s.store.DeleteProjectSecret(c.Request().Context(), projectID, name); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *Server) listProjectSecrets(c echo.Context) error {
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
+ }
+
+ projectID, err := uuid.Parse(c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid project ID"})
+ }
+
+ // Verify project belongs to org
+ if _, err := s.store.GetProject(c.Request().Context(), orgID, projectID); err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "project not found"})
+ }
+
+ secrets, err := s.store.ListProjectSecretNames(c.Request().Context(), projectID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ names := make([]string, len(secrets))
+ for i, s := range secrets {
+ names[i] = s.Name
+ }
+ return c.JSON(http.StatusOK, names)
+}
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 597a05f1..f3048712 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -64,6 +64,18 @@ func NewServer(store *db.Store, jwtIssuer *auth.JWTIssuer, registry *WorkerRegis
// Workers
api.GET("/workers", s.listWorkers)
+ // Projects
+ api.POST("/projects", s.createProject)
+ api.GET("/projects", s.listProjects)
+ api.GET("/projects/:id", s.getProject)
+ api.PUT("/projects/:id", s.updateProject)
+ api.DELETE("/projects/:id", s.deleteProject)
+
+ // Project secrets
+ api.PUT("/projects/:id/secrets/:name", s.setProjectSecret)
+ api.DELETE("/projects/:id/secrets/:name", s.deleteProjectSecret)
+ api.GET("/projects/:id/secrets", s.listProjectSecrets)
+
return s
}
@@ -87,6 +99,7 @@ func (s *Server) createSandbox(c echo.Context) error {
CpuCount int `json:"cpuCount"`
Metadata map[string]string `json:"metadata"`
NetworkEnabled bool `json:"networkEnabled"`
+ Project string `json:"project"` // project name — resolves config + secrets
}
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request: " + err.Error()})
@@ -107,6 +120,49 @@ func (s *Server) createSandbox(c echo.Context) error {
return c.JSON(http.StatusTooManyRequests, map[string]string{"error": "concurrent sandbox limit reached"})
}
+ // Resolve project: inherit config defaults + decrypt and merge secrets
+ var projectID *string
+ if req.Project != "" {
+ project, err := s.store.GetProjectByName(c.Request().Context(), orgID, req.Project)
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "project not found: " + req.Project})
+ }
+ pid := project.ID.String()
+ projectID = &pid
+
+ // Project config serves as defaults — request fields override
+ if req.TemplateID == "" {
+ req.TemplateID = project.Template
+ }
+ if req.CpuCount == 0 {
+ req.CpuCount = project.CpuCount
+ }
+ if req.MemoryMB == 0 {
+ req.MemoryMB = project.MemoryMB
+ }
+ if req.Timeout == 0 {
+ req.Timeout = project.TimeoutSec
+ }
+
+ // Decrypt project secrets and merge into envs (request envs override project secrets)
+ secrets, err := s.store.DecryptProjectSecrets(c.Request().Context(), project.ID)
+ if err != nil {
+ log.Printf("controlplane: decrypt project secrets failed for %s: %v", req.Project, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to decrypt project secrets"})
+ }
+ if len(secrets) > 0 {
+ if req.Envs == nil {
+ req.Envs = make(map[string]string)
+ }
+ for k, v := range secrets {
+ if _, exists := req.Envs[k]; !exists {
+ req.Envs[k] = v
+ }
+ }
+ }
+ }
+ _ = projectID // TODO: store on sandbox_sessions.project_id
+
// Select region (explicit, or from Fly-Region header, or default)
region := req.Region
if region == "" {
diff --git a/internal/crypto/encrypt.go b/internal/crypto/encrypt.go
new file mode 100644
index 00000000..b225b990
--- /dev/null
+++ b/internal/crypto/encrypt.go
@@ -0,0 +1,62 @@
+// Package crypto provides AES-256-GCM encryption for secrets at rest.
+package crypto
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "io"
+)
+
+// Encryptor provides AES-256-GCM encryption/decryption using a 32-byte key.
+type Encryptor struct {
+ gcm cipher.AEAD
+}
+
+// NewEncryptor creates an Encryptor from a hex-encoded 32-byte key.
+// The key should come from OPENSANDBOX_SECRET_ENCRYPTION_KEY.
+func NewEncryptor(hexKey string) (*Encryptor, error) {
+ key, err := hex.DecodeString(hexKey)
+ if err != nil {
+ return nil, fmt.Errorf("decode hex key: %w", err)
+ }
+ if len(key) != 32 {
+ return nil, fmt.Errorf("key must be 32 bytes (64 hex chars), got %d bytes", len(key))
+ }
+
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, fmt.Errorf("create AES cipher: %w", err)
+ }
+ gcm, err := cipher.NewGCM(block)
+ if err != nil {
+ return nil, fmt.Errorf("create GCM: %w", err)
+ }
+
+ return &Encryptor{gcm: gcm}, nil
+}
+
+// Encrypt returns nonce || ciphertext (suitable for storing as BYTEA).
+func (e *Encryptor) Encrypt(plaintext []byte) ([]byte, error) {
+ nonce := make([]byte, e.gcm.NonceSize())
+ if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
+ return nil, fmt.Errorf("generate nonce: %w", err)
+ }
+ return e.gcm.Seal(nonce, nonce, plaintext, nil), nil
+}
+
+// Decrypt expects nonce || ciphertext as produced by Encrypt.
+func (e *Encryptor) Decrypt(data []byte) ([]byte, error) {
+ nonceSize := e.gcm.NonceSize()
+ if len(data) < nonceSize {
+ return nil, fmt.Errorf("ciphertext too short")
+ }
+ nonce, ciphertext := data[:nonceSize], data[nonceSize:]
+ plaintext, err := e.gcm.Open(nil, nonce, ciphertext, nil)
+ if err != nil {
+ return nil, fmt.Errorf("decrypt: %w", err)
+ }
+ return plaintext, nil
+}
diff --git a/internal/crypto/encrypt_test.go b/internal/crypto/encrypt_test.go
new file mode 100644
index 00000000..6a2cc212
--- /dev/null
+++ b/internal/crypto/encrypt_test.go
@@ -0,0 +1,79 @@
+package crypto
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "testing"
+)
+
+func TestEncryptDecrypt(t *testing.T) {
+ key := make([]byte, 32)
+ if _, err := rand.Read(key); err != nil {
+ t.Fatal(err)
+ }
+ hexKey := hex.EncodeToString(key)
+
+ enc, err := NewEncryptor(hexKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ plaintext := []byte("sk-ant-api03-super-secret-key-1234567890")
+ ciphertext, err := enc.Encrypt(plaintext)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if string(ciphertext) == string(plaintext) {
+ t.Error("ciphertext should not equal plaintext")
+ }
+
+ decrypted, err := enc.Decrypt(ciphertext)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if string(decrypted) != string(plaintext) {
+ t.Errorf("got %q, want %q", decrypted, plaintext)
+ }
+}
+
+func TestEncryptDifferentNonces(t *testing.T) {
+ key := make([]byte, 32)
+ rand.Read(key)
+ enc, _ := NewEncryptor(hex.EncodeToString(key))
+
+ plaintext := []byte("same-value")
+ ct1, _ := enc.Encrypt(plaintext)
+ ct2, _ := enc.Encrypt(plaintext)
+
+ if string(ct1) == string(ct2) {
+ t.Error("two encryptions of the same value should produce different ciphertexts (unique nonce)")
+ }
+}
+
+func TestBadKey(t *testing.T) {
+ _, err := NewEncryptor("tooshort")
+ if err == nil {
+ t.Error("expected error for short key")
+ }
+
+ _, err = NewEncryptor("not-hex-at-all!")
+ if err == nil {
+ t.Error("expected error for non-hex key")
+ }
+}
+
+func TestDecryptTampered(t *testing.T) {
+ key := make([]byte, 32)
+ rand.Read(key)
+ enc, _ := NewEncryptor(hex.EncodeToString(key))
+
+ ct, _ := enc.Encrypt([]byte("secret"))
+ ct[len(ct)-1] ^= 0xFF // flip last byte
+
+ _, err := enc.Decrypt(ct)
+ if err == nil {
+ t.Error("expected error decrypting tampered ciphertext")
+ }
+}
diff --git a/internal/db/migrations/014_projects.up.sql b/internal/db/migrations/014_projects.up.sql
new file mode 100644
index 00000000..065cf20a
--- /dev/null
+++ b/internal/db/migrations/014_projects.up.sql
@@ -0,0 +1,31 @@
+-- Projects: higher-level entity that groups sandboxes and holds secrets + config
+CREATE TABLE projects (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ template TEXT NOT NULL DEFAULT 'default',
+ cpu_count INT NOT NULL DEFAULT 1,
+ memory_mb INT NOT NULL DEFAULT 1024,
+ timeout_sec INT NOT NULL DEFAULT 300,
+ egress_allowlist TEXT[] NOT NULL DEFAULT '{}', -- e.g. {"api.anthropic.com","*.amazonaws.com"}, empty = allow all
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE(org_id, name)
+);
+CREATE INDEX idx_projects_org ON projects(org_id);
+
+-- Secrets belonging to a project, encrypted at rest (AES-256-GCM)
+CREATE TABLE project_secrets (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ name TEXT NOT NULL, -- env var name (e.g. ANTHROPIC_API_KEY)
+ encrypted_value BYTEA NOT NULL, -- AES-256-GCM ciphertext (nonce || ciphertext)
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE(project_id, name)
+);
+CREATE INDEX idx_project_secrets_project ON project_secrets(project_id);
+
+-- Link sandboxes to projects
+ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS project_id UUID REFERENCES projects(id);
+CREATE INDEX IF NOT EXISTS idx_sandbox_sessions_project ON sandbox_sessions(project_id);
diff --git a/internal/db/store.go b/internal/db/store.go
index 28a7aa2b..bc67e1b4 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -12,6 +12,8 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/opensandbox/opensandbox/internal/crypto"
)
//go:embed migrations/*.sql
@@ -19,7 +21,13 @@ var migrationsFS embed.FS
// Store provides data access to the global PostgreSQL database.
type Store struct {
- pool *pgxpool.Pool
+ pool *pgxpool.Pool
+ encryptor *crypto.Encryptor // nil if no encryption key configured
+}
+
+// SetEncryptor configures the encryption key for project secrets.
+func (s *Store) SetEncryptor(enc *crypto.Encryptor) {
+ s.encryptor = enc
}
// NewStore creates a new Store with a connection pool.
@@ -77,6 +85,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{11, "migrations/011_rename_hibernation.up.sql"},
{12, "migrations/012_checkpoints.up.sql"},
{13, "migrations/013_checkpoint_patches.up.sql"},
+ {14, "migrations/014_projects.up.sql"},
}
for _, m := range migrations {
@@ -1239,3 +1248,233 @@ func (s *Store) DeletePreviewURLsBySandbox(ctx context.Context, sandboxID string
}
return urls, nil
}
+
+// ── Projects ──────────────────────────────────────────────────────────────────
+
+// Project represents a project that groups sandboxes and holds secrets.
+type Project struct {
+ ID uuid.UUID `json:"id"`
+ OrgID uuid.UUID `json:"orgId"`
+ Name string `json:"name"`
+ Template string `json:"template"`
+ CpuCount int `json:"cpuCount"`
+ MemoryMB int `json:"memoryMB"`
+ TimeoutSec int `json:"timeoutSec"`
+ EgressAllowlist []string `json:"egressAllowlist"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+// ProjectSecret represents an encrypted secret belonging to a project.
+type ProjectSecret struct {
+ ID uuid.UUID `json:"id"`
+ ProjectID uuid.UUID `json:"projectId"`
+ Name string `json:"name"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+// CreateProject creates a new project for an org.
+func (s *Store) CreateProject(ctx context.Context, orgID uuid.UUID, name, template string, cpuCount, memoryMB, timeoutSec int, allowlist []string) (*Project, error) {
+ if template == "" {
+ template = "default"
+ }
+ if cpuCount <= 0 {
+ cpuCount = 1
+ }
+ if memoryMB <= 0 {
+ memoryMB = 1024
+ }
+ if timeoutSec <= 0 {
+ timeoutSec = 300
+ }
+ if allowlist == nil {
+ allowlist = []string{}
+ }
+
+ var p Project
+ err := s.pool.QueryRow(ctx,
+ `INSERT INTO projects (org_id, name, template, cpu_count, memory_mb, timeout_sec, egress_allowlist)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING id, org_id, name, template, cpu_count, memory_mb, timeout_sec, egress_allowlist, created_at, updated_at`,
+ orgID, name, template, cpuCount, memoryMB, timeoutSec, allowlist,
+ ).Scan(&p.ID, &p.OrgID, &p.Name, &p.Template, &p.CpuCount, &p.MemoryMB, &p.TimeoutSec, &p.EgressAllowlist, &p.CreatedAt, &p.UpdatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("create project: %w", err)
+ }
+ return &p, nil
+}
+
+// GetProject returns a project by ID, scoped to an org.
+func (s *Store) GetProject(ctx context.Context, orgID, projectID uuid.UUID) (*Project, error) {
+ var p Project
+ err := s.pool.QueryRow(ctx,
+ `SELECT id, org_id, name, template, cpu_count, memory_mb, timeout_sec, egress_allowlist, created_at, updated_at
+ FROM projects WHERE id = $1 AND org_id = $2`,
+ projectID, orgID,
+ ).Scan(&p.ID, &p.OrgID, &p.Name, &p.Template, &p.CpuCount, &p.MemoryMB, &p.TimeoutSec, &p.EgressAllowlist, &p.CreatedAt, &p.UpdatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("get project: %w", err)
+ }
+ return &p, nil
+}
+
+// GetProjectByName returns a project by name, scoped to an org.
+func (s *Store) GetProjectByName(ctx context.Context, orgID uuid.UUID, name string) (*Project, error) {
+ var p Project
+ err := s.pool.QueryRow(ctx,
+ `SELECT id, org_id, name, template, cpu_count, memory_mb, timeout_sec, egress_allowlist, created_at, updated_at
+ FROM projects WHERE org_id = $1 AND name = $2`,
+ orgID, name,
+ ).Scan(&p.ID, &p.OrgID, &p.Name, &p.Template, &p.CpuCount, &p.MemoryMB, &p.TimeoutSec, &p.EgressAllowlist, &p.CreatedAt, &p.UpdatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("get project by name: %w", err)
+ }
+ return &p, nil
+}
+
+// ListProjects returns all projects for an org.
+func (s *Store) ListProjects(ctx context.Context, orgID uuid.UUID) ([]Project, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT id, org_id, name, template, cpu_count, memory_mb, timeout_sec, egress_allowlist, created_at, updated_at
+ FROM projects WHERE org_id = $1 ORDER BY name`,
+ orgID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("list projects: %w", err)
+ }
+ defer rows.Close()
+
+ var projects []Project
+ for rows.Next() {
+ var p Project
+ if err := rows.Scan(&p.ID, &p.OrgID, &p.Name, &p.Template, &p.CpuCount, &p.MemoryMB, &p.TimeoutSec, &p.EgressAllowlist, &p.CreatedAt, &p.UpdatedAt); err != nil {
+ return nil, err
+ }
+ projects = append(projects, p)
+ }
+ return projects, nil
+}
+
+// UpdateProject updates a project's configuration.
+func (s *Store) UpdateProject(ctx context.Context, orgID, projectID uuid.UUID, name, template string, cpuCount, memoryMB, timeoutSec int, allowlist []string) (*Project, error) {
+ if allowlist == nil {
+ allowlist = []string{}
+ }
+ var p Project
+ err := s.pool.QueryRow(ctx,
+ `UPDATE projects SET name = $3, template = $4, cpu_count = $5, memory_mb = $6, timeout_sec = $7, egress_allowlist = $8, updated_at = now()
+ WHERE id = $1 AND org_id = $2
+ RETURNING id, org_id, name, template, cpu_count, memory_mb, timeout_sec, egress_allowlist, created_at, updated_at`,
+ projectID, orgID, name, template, cpuCount, memoryMB, timeoutSec, allowlist,
+ ).Scan(&p.ID, &p.OrgID, &p.Name, &p.Template, &p.CpuCount, &p.MemoryMB, &p.TimeoutSec, &p.EgressAllowlist, &p.CreatedAt, &p.UpdatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("update project: %w", err)
+ }
+ return &p, nil
+}
+
+// DeleteProject deletes a project and all its secrets (cascading).
+func (s *Store) DeleteProject(ctx context.Context, orgID, projectID uuid.UUID) error {
+ tag, err := s.pool.Exec(ctx, `DELETE FROM projects WHERE id = $1 AND org_id = $2`, projectID, orgID)
+ if err != nil {
+ return fmt.Errorf("delete project: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ return fmt.Errorf("project not found")
+ }
+ return nil
+}
+
+// ── Project Secrets ───────────────────────────────────────────────────────────
+
+// SetProjectSecret creates or updates a secret on a project. The value is encrypted at rest.
+func (s *Store) SetProjectSecret(ctx context.Context, projectID uuid.UUID, name string, value []byte) error {
+ if s.encryptor == nil {
+ return fmt.Errorf("encryption not configured (set OPENSANDBOX_SECRET_ENCRYPTION_KEY)")
+ }
+ encrypted, err := s.encryptor.Encrypt(value)
+ if err != nil {
+ return fmt.Errorf("encrypt secret: %w", err)
+ }
+ _, err = s.pool.Exec(ctx,
+ `INSERT INTO project_secrets (project_id, name, encrypted_value)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (project_id, name) DO UPDATE SET encrypted_value = $3, updated_at = now()`,
+ projectID, name, encrypted,
+ )
+ if err != nil {
+ return fmt.Errorf("set project secret: %w", err)
+ }
+ return nil
+}
+
+// DeleteProjectSecret removes a secret from a project.
+func (s *Store) DeleteProjectSecret(ctx context.Context, projectID uuid.UUID, name string) error {
+ tag, err := s.pool.Exec(ctx,
+ `DELETE FROM project_secrets WHERE project_id = $1 AND name = $2`,
+ projectID, name,
+ )
+ if err != nil {
+ return fmt.Errorf("delete project secret: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ return fmt.Errorf("secret not found")
+ }
+ return nil
+}
+
+// ListProjectSecretNames returns the names (not values) of all secrets on a project.
+func (s *Store) ListProjectSecretNames(ctx context.Context, projectID uuid.UUID) ([]ProjectSecret, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT id, project_id, name, created_at, updated_at
+ FROM project_secrets WHERE project_id = $1 ORDER BY name`,
+ projectID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("list project secrets: %w", err)
+ }
+ defer rows.Close()
+
+ var secrets []ProjectSecret
+ for rows.Next() {
+ var ps ProjectSecret
+ if err := rows.Scan(&ps.ID, &ps.ProjectID, &ps.Name, &ps.CreatedAt, &ps.UpdatedAt); err != nil {
+ return nil, err
+ }
+ secrets = append(secrets, ps)
+ }
+ return secrets, nil
+}
+
+// DecryptProjectSecrets returns all secrets for a project as plaintext name→value pairs.
+// Used server-side when creating a sandbox to pass decrypted values to the worker.
+func (s *Store) DecryptProjectSecrets(ctx context.Context, projectID uuid.UUID) (map[string]string, error) {
+ if s.encryptor == nil {
+ return nil, fmt.Errorf("encryption not configured")
+ }
+
+ rows, err := s.pool.Query(ctx,
+ `SELECT name, encrypted_value FROM project_secrets WHERE project_id = $1`,
+ projectID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("query project secrets: %w", err)
+ }
+ defer rows.Close()
+
+ secrets := make(map[string]string)
+ for rows.Next() {
+ var name string
+ var encrypted []byte
+ if err := rows.Scan(&name, &encrypted); err != nil {
+ return nil, err
+ }
+ plaintext, err := s.encryptor.Decrypt(encrypted)
+ if err != nil {
+ return nil, fmt.Errorf("decrypt secret %q: %w", name, err)
+ }
+ secrets[name] = string(plaintext)
+ }
+ return secrets, nil
+}
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 44401acf..282d8e2a 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -49,7 +49,8 @@ type VMInstance struct {
guestMAC string // e.g., "AA:FC:00:00:2d:31"
guestCID uint32 // vsock CID
bootArgs string // kernel boot args
- restoring chan struct{} // closed when an in-progress restore completes; nil when not restoring
+ restoring chan struct{} // closed when an in-progress restore completes; nil when not restoring
+ sealedTokens map[string]string // sealed token → real value (for re-registering proxy on wake)
}
// SandboxMeta is persisted to sandbox-meta.json in each sandbox directory.
@@ -63,6 +64,27 @@ type SandboxMeta struct {
GuestPort int `json:"guestPort"`
}
+// SecretsProxyIntegration provides the interface for the secrets proxy to integrate
+// with VM lifecycle. The firecracker package uses this interface to avoid importing
+// the secretsproxy package directly.
+type SecretsProxyIntegration interface {
+ // CreateSealedEnvs generates sealed tokens for env vars, registers a proxy session,
+ // and returns the full env map (sealed tokens + proxy config vars) to inject into the VM.
+ CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, envVars map[string]string, allowlist, secretHosts []string) map[string]string
+ // UnregisterSession removes the proxy session for the given guest IP.
+ UnregisterSession(guestIP string)
+ // GetSessionTokens returns the sealed token → real value map for persisting during hibernate.
+ GetSessionTokens(guestIP string) map[string]string
+ // GetSessionAllowlist returns the egress allowlist for persisting during hibernate.
+ GetSessionAllowlist(guestIP string) []string
+ // GetSessionSecretHosts returns the secret hosts list for persisting during hibernate.
+ GetSessionSecretHosts(guestIP string) []string
+ // ReregisterSession re-creates a proxy session from a persisted token map (used on wake).
+ ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist, secretHosts []string)
+ // CACertPEM returns the CA certificate PEM for injection into the VM trust store.
+ CACertPEM() []byte
+}
+
// Config holds configuration for the Firecracker Manager.
type Config struct {
DataDir string // base data directory (e.g., /data)
@@ -95,6 +117,8 @@ type Manager struct {
goldenMu sync.RWMutex
golden *GoldenSnapshot // pre-booted default VM snapshot for fast creation
+
+ secretsProxy SecretsProxyIntegration // nil if secrets proxy is not configured
}
// NewManager creates a new Firecracker-backed sandbox manager.
@@ -147,6 +171,12 @@ func NewManager(cfg Config) (*Manager, error) {
}, nil
}
+// SetSecretsProxy configures the secrets proxy integration for token substitution.
+// Must be called before any sandboxes are created.
+func (m *Manager) SetSecretsProxy(sp SecretsProxyIntegration) {
+ m.secretsProxy = sp
+}
+
// allocateCID returns a unique guest CID for a new VM.
func (m *Manager) allocateCID() uint32 {
m.mu.Lock()
@@ -400,10 +430,27 @@ func (m *Manager) createWithID(ctx context.Context, id string, cfg types.Sandbox
}
vm.agent = agentClient
+ // Secrets proxy integration: seal env vars and set up proxy redirect.
+ // Sealed tokens replace real values inside the VM — the MITM proxy swaps
+ // them back to real values on outbound HTTPS requests.
+ envsToInject := cfg.Envs
+ if m.secretsProxy != nil && len(cfg.Envs) > 0 {
+ sealedEnvs := m.secretsProxy.CreateSealedEnvs(id, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, nil, nil)
+ if sealedEnvs != nil {
+ envsToInject = sealedEnvs
+ // Redirect VM HTTPS traffic through the proxy
+ if err := AddProxyRedirect(netCfg); err != nil {
+ log.Printf("firecracker: warning: proxy redirect failed for %s: %v", id, err)
+ }
+ // Inject CA cert into VM trust store
+ m.injectCACert(context.Background(), agentClient, id)
+ }
+ }
+
// Send sandbox-level env vars into the VM agent (survives snapshots)
- if len(cfg.Envs) > 0 {
+ if len(envsToInject) > 0 {
envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := agentClient.SetEnvs(envCtx, cfg.Envs); err != nil {
+ if err := agentClient.SetEnvs(envCtx, envsToInject); err != nil {
envCancel()
log.Printf("firecracker: warning: SetEnvs failed for %s: %v", id, err)
}
@@ -528,8 +575,14 @@ func (m *Manager) destroyVM(vm *VMInstance) error {
vm.cmd.Wait()
}
+ // Clean up secrets proxy session
+ if m.secretsProxy != nil && vm.network != nil {
+ m.secretsProxy.UnregisterSession(vm.network.GuestIP)
+ }
+
// Clean up network
if vm.network != nil {
+ RemoveProxyRedirect(vm.network)
RemoveDNAT(vm.network)
DeleteTAP(vm.network.TAPName)
m.subnets.Release(vm.network.TAPName)
@@ -549,9 +602,43 @@ func (m *Manager) destroyVM(vm *VMInstance) error {
return nil
}
+// injectCACert writes the secrets proxy CA certificate into the VM and updates
+// the trust store so HTTPS requests through the proxy are trusted.
+func (m *Manager) injectCACert(ctx context.Context, agent *AgentClient, sandboxID string) {
+ if m.secretsProxy == nil {
+ return
+ }
+ certPEM := m.secretsProxy.CACertPEM()
+ if len(certPEM) == 0 {
+ return
+ }
+
+ writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+
+ certPath := "/usr/local/share/ca-certificates/opensandbox-proxy.crt"
+ if err := agent.WriteFile(writeCtx, certPath, certPEM); err != nil {
+ log.Printf("firecracker: warning: write CA cert failed for %s: %v", sandboxID, err)
+ return
+ }
+
+ // Update the system trust store
+ updateCtx, updateCancel := context.WithTimeout(ctx, 10*time.Second)
+ defer updateCancel()
+ _, err := agent.Exec(updateCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "update-ca-certificates 2>/dev/null || true"},
+ TimeoutSeconds: 10,
+ })
+ if err != nil {
+ log.Printf("firecracker: warning: update-ca-certificates failed for %s: %v", sandboxID, err)
+ }
+}
+
// cleanupVM cleans up resources on failed creation.
func (m *Manager) cleanupVM(netCfg *NetworkConfig, sandboxDir string) {
if netCfg != nil {
+ RemoveProxyRedirect(netCfg)
RemoveDNAT(netCfg)
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
diff --git a/internal/firecracker/network.go b/internal/firecracker/network.go
index ecca2896..78d277f8 100644
--- a/internal/firecracker/network.go
+++ b/internal/firecracker/network.go
@@ -20,6 +20,9 @@ type NetworkConfig struct {
HostPort int // host port mapped to guest
GuestPort int // guest port (typically 80)
DNATRuleAdded bool
+
+ // Secrets proxy redirect
+ ProxyRedirectAdded bool
}
// SubnetAllocator manages /30 subnet allocation from a 172.16.0.0/16 pool.
@@ -187,6 +190,34 @@ func RemoveDNAT(cfg *NetworkConfig) {
fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
}
+// AddProxyRedirect adds an iptables rule to redirect HTTPS traffic from the VM
+// through the secrets proxy on the host. Traffic from guestIP:443 is redirected
+// to hostIP:3128 where the MITM proxy substitutes sealed tokens.
+func AddProxyRedirect(cfg *NetworkConfig) error {
+ err := run("iptables", "-t", "nat", "-A", "PREROUTING",
+ "-s", cfg.GuestIP,
+ "-p", "tcp", "--dport", "443",
+ "-j", "DNAT", "--to-destination",
+ fmt.Sprintf("%s:3128", cfg.HostIP))
+ if err != nil {
+ return fmt.Errorf("add proxy redirect: %w", err)
+ }
+ cfg.ProxyRedirectAdded = true
+ return nil
+}
+
+// RemoveProxyRedirect removes the iptables proxy redirect rule.
+func RemoveProxyRedirect(cfg *NetworkConfig) {
+ if !cfg.ProxyRedirectAdded {
+ return
+ }
+ _ = run("iptables", "-t", "nat", "-D", "PREROUTING",
+ "-s", cfg.GuestIP,
+ "-p", "tcp", "--dport", "443",
+ "-j", "DNAT", "--to-destination",
+ fmt.Sprintf("%s:3128", cfg.HostIP))
+}
+
// EnableForwarding enables IPv4 forwarding and masquerading for the VM subnet.
// Call once at startup.
func EnableForwarding() error {
diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.go
index 0f608729..15bfd612 100644
--- a/internal/firecracker/snapshot.go
+++ b/internal/firecracker/snapshot.go
@@ -38,6 +38,12 @@ type SnapshotMeta struct {
Template string `json:"template"`
GuestPort int `json:"guestPort"`
SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`
+ // SealedTokens maps sealed token → real value for re-registering the proxy session on wake.
+ SealedTokens map[string]string `json:"sealedTokens,omitempty"`
+ // ProxyAllowlist and ProxySecretHosts are persisted so the proxy session
+ // can be fully restored with the same restrictions after hibernate → wake.
+ ProxyAllowlist []string `json:"proxyAllowlist,omitempty"`
+ ProxySecretHosts []string `json:"proxySecretHosts,omitempty"`
}
// doHibernate pauses a running VM, creates a full memory snapshot, and kicks off
@@ -125,6 +131,12 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
GuestPort: vm.GuestPort,
SnapshotedAt: time.Now(),
}
+ // Persist sealed token map + proxy config so wake can fully restore the proxy session
+ if m.secretsProxy != nil && vm.network != nil {
+ meta.SealedTokens = m.secretsProxy.GetSessionTokens(vm.network.GuestIP)
+ meta.ProxyAllowlist = m.secretsProxy.GetSessionAllowlist(vm.network.GuestIP)
+ meta.ProxySecretHosts = m.secretsProxy.GetSessionSecretHosts(vm.network.GuestIP)
+ }
metaJSON, err := json.Marshal(meta)
if err != nil {
return nil, fmt.Errorf("marshal snapshot meta: %w", err)
@@ -134,8 +146,12 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
return nil, fmt.Errorf("write snapshot meta: %w", err)
}
- // Step 7: Clean up network (keep snapshot files on disk for local wake)
+ // Step 7: Clean up network and proxy session (keep snapshot files on disk for local wake)
+ if m.secretsProxy != nil && vm.network != nil {
+ m.secretsProxy.UnregisterSession(vm.network.GuestIP)
+ }
if vm.network != nil {
+ RemoveProxyRedirect(vm.network)
RemoveDNAT(vm.network)
DeleteTAP(vm.network.TAPName)
m.subnets.Release(vm.network.TAPName)
@@ -487,6 +503,14 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
}
vm.agent = agentClient
+ // Re-register secrets proxy session if token map was persisted
+ if m.secretsProxy != nil && len(meta.SealedTokens) > 0 {
+ m.secretsProxy.ReregisterSession(sandboxID, netCfg.GuestIP, meta.SealedTokens, meta.ProxyAllowlist, meta.ProxySecretHosts)
+ if err := AddProxyRedirect(netCfg); err != nil {
+ log.Printf("firecracker: warning: proxy redirect failed for %s on wake: %v", sandboxID, err)
+ }
+ }
+
// Register VM
m.mu.Lock()
m.vms[sandboxID] = vm
@@ -1850,10 +1874,23 @@ func (m *Manager) warmForkFromCheckpoint(ctx context.Context, checkpointID strin
// Don't fail — the VM is running and accessible via vsock, just external network may be broken
}
+ // Secrets proxy integration: seal env vars and set up proxy redirect
+ envsToInject := cfg.Envs
+ if m.secretsProxy != nil && len(cfg.Envs) > 0 {
+ sealedEnvs := m.secretsProxy.CreateSealedEnvs(newID, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, nil, nil)
+ if sealedEnvs != nil {
+ envsToInject = sealedEnvs
+ if err := AddProxyRedirect(netCfg); err != nil {
+ log.Printf("firecracker: warning: proxy redirect failed for %s: %v", newID, err)
+ }
+ m.injectCACert(ctx, agentClient, newID)
+ }
+ }
+
// Send sandbox-level env vars into the forked VM agent
- if len(cfg.Envs) > 0 {
+ if len(envsToInject) > 0 {
envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := agentClient.SetEnvs(envCtx, cfg.Envs); err != nil {
+ if err := agentClient.SetEnvs(envCtx, envsToInject); err != nil {
envCancel()
log.Printf("firecracker: warning: SetEnvs failed for %s: %v", newID, err)
}
@@ -2317,10 +2354,23 @@ func (m *Manager) createFromGoldenSnapshot(ctx context.Context, id string, cfg t
log.Printf("firecracker: goldenCreate %s: network reconfig failed: %v (VM still running)", id, err)
}
+ // Secrets proxy integration: seal env vars and set up proxy redirect
+ envsToInject := cfg.Envs
+ if m.secretsProxy != nil && len(cfg.Envs) > 0 {
+ sealedEnvs := m.secretsProxy.CreateSealedEnvs(id, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, nil, nil)
+ if sealedEnvs != nil {
+ envsToInject = sealedEnvs
+ if err := AddProxyRedirect(netCfg); err != nil {
+ log.Printf("firecracker: warning: proxy redirect failed for %s: %v", id, err)
+ }
+ m.injectCACert(ctx, agentClient, id)
+ }
+ }
+
// Send sandbox-level env vars into the VM agent
- if len(cfg.Envs) > 0 {
+ if len(envsToInject) > 0 {
envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := agentClient.SetEnvs(envCtx, cfg.Envs); err != nil {
+ if err := agentClient.SetEnvs(envCtx, envsToInject); err != nil {
envCancel()
log.Printf("firecracker: warning: SetEnvs failed for %s: %v", id, err)
}
diff --git a/internal/secretsproxy/ca.go b/internal/secretsproxy/ca.go
new file mode 100644
index 00000000..14fd9387
--- /dev/null
+++ b/internal/secretsproxy/ca.go
@@ -0,0 +1,218 @@
+package secretsproxy
+
+import (
+ "container/list"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "fmt"
+ "math/big"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+const (
+ maxCacheSize = 10000
+ leafCacheTTL = 1 * time.Hour
+ leafCertValid = 24 * time.Hour
+ caValidYears = 10
+)
+
+// CA holds a certificate authority used to sign ephemeral per-host TLS
+// certificates for the HTTPS MITM secrets proxy.
+type CA struct {
+ cert *x509.Certificate
+ key *ecdsa.PrivateKey
+ certPEM []byte
+
+ mu sync.Mutex
+ cache map[string]*cachedCert
+ lru *list.List
+}
+
+type cachedCert struct {
+ cert *tls.Certificate
+ expiresAt time.Time
+ element *list.Element
+ hostname string
+}
+
+// LoadOrCreateCA loads the CA cert+key from dir, or generates a new one.
+// The CA persists across worker restarts so sandboxes with the cert baked
+// in continue to trust it after a reboot.
+func LoadOrCreateCA(dir string) (*CA, error) {
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return nil, fmt.Errorf("create CA dir: %w", err)
+ }
+
+ certPath := filepath.Join(dir, "ca.crt")
+ keyPath := filepath.Join(dir, "ca.key")
+
+ // Try loading existing CA
+ certPEM, err := os.ReadFile(certPath)
+ if err == nil {
+ keyPEM, err := os.ReadFile(keyPath)
+ if err == nil {
+ ca, err := parseCA(certPEM, keyPEM)
+ if err == nil {
+ return ca, nil
+ }
+ }
+ }
+
+ // Generate new CA
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ return nil, fmt.Errorf("generate CA key: %w", err)
+ }
+
+ serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
+ tmpl := &x509.Certificate{
+ SerialNumber: serial,
+ Subject: pkix.Name{
+ CommonName: "OpenSandbox Proxy CA",
+ Organization: []string{"OpenSandbox"},
+ },
+ NotBefore: time.Now().Add(-time.Minute),
+ NotAfter: time.Now().Add(caValidYears * 365 * 24 * time.Hour),
+ KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
+ BasicConstraintsValid: true,
+ IsCA: true,
+ }
+
+ certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
+ if err != nil {
+ return nil, fmt.Errorf("create CA cert: %w", err)
+ }
+
+ certPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
+ keyDER, err := x509.MarshalECPrivateKey(key)
+ if err != nil {
+ return nil, fmt.Errorf("marshal CA key: %w", err)
+ }
+ keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
+
+ if err := os.WriteFile(certPath, certPEM, 0644); err != nil {
+ return nil, fmt.Errorf("write CA cert: %w", err)
+ }
+ if err := os.WriteFile(keyPath, keyPEM, 0600); err != nil {
+ return nil, fmt.Errorf("write CA key: %w", err)
+ }
+
+ cert, err := x509.ParseCertificate(certDER)
+ if err != nil {
+ return nil, fmt.Errorf("parse CA cert: %w", err)
+ }
+
+ return &CA{
+ cert: cert,
+ key: key,
+ certPEM: certPEM,
+ cache: make(map[string]*cachedCert),
+ lru: list.New(),
+ }, nil
+}
+
+// CertPEM returns the CA certificate PEM for injection into sandboxes.
+func (ca *CA) CertPEM() []byte {
+ return ca.certPEM
+}
+
+// SignHost returns a TLS certificate signed by this CA for the given hostname.
+// Results are cached with TTL and LRU eviction.
+func (ca *CA) SignHost(hostname string) (*tls.Certificate, error) {
+ ca.mu.Lock()
+ defer ca.mu.Unlock()
+
+ // Check cache
+ if entry, ok := ca.cache[hostname]; ok {
+ if time.Now().Before(entry.expiresAt) {
+ ca.lru.MoveToFront(entry.element)
+ return entry.cert, nil
+ }
+ // Expired — remove
+ ca.lru.Remove(entry.element)
+ delete(ca.cache, hostname)
+ }
+
+ // Generate leaf cert (ECDSA P-256 for speed)
+ leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ return nil, fmt.Errorf("generate leaf key: %w", err)
+ }
+
+ serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
+ tmpl := &x509.Certificate{
+ SerialNumber: serial,
+ Subject: pkix.Name{CommonName: hostname},
+ DNSNames: []string{hostname},
+ NotBefore: time.Now().Add(-time.Minute),
+ NotAfter: time.Now().Add(leafCertValid),
+ KeyUsage: x509.KeyUsageDigitalSignature,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ }
+
+ certDER, err := x509.CreateCertificate(rand.Reader, tmpl, ca.cert, &leafKey.PublicKey, ca.key)
+ if err != nil {
+ return nil, fmt.Errorf("sign leaf cert: %w", err)
+ }
+
+ tlsCert := &tls.Certificate{
+ Certificate: [][]byte{certDER, ca.cert.Raw},
+ PrivateKey: leafKey,
+ }
+
+ // Evict if at capacity
+ for ca.lru.Len() >= maxCacheSize {
+ oldest := ca.lru.Back()
+ if oldest == nil {
+ break
+ }
+ evicted := oldest.Value.(*cachedCert)
+ ca.lru.Remove(oldest)
+ delete(ca.cache, evicted.hostname)
+ }
+
+ // Cache
+ entry := &cachedCert{
+ cert: tlsCert,
+ expiresAt: time.Now().Add(leafCacheTTL),
+ hostname: hostname,
+ }
+ entry.element = ca.lru.PushFront(entry)
+ ca.cache[hostname] = entry
+
+ return tlsCert, nil
+}
+
+func parseCA(certPEM, keyPEM []byte) (*CA, error) {
+ certBlock, _ := pem.Decode(certPEM)
+ if certBlock == nil {
+ return nil, fmt.Errorf("no PEM cert block")
+ }
+ cert, err := x509.ParseCertificate(certBlock.Bytes)
+ if err != nil {
+ return nil, err
+ }
+ keyBlock, _ := pem.Decode(keyPEM)
+ if keyBlock == nil {
+ return nil, fmt.Errorf("no PEM key block")
+ }
+ key, err := x509.ParseECPrivateKey(keyBlock.Bytes)
+ if err != nil {
+ return nil, err
+ }
+ return &CA{
+ cert: cert,
+ key: key,
+ certPEM: certPEM,
+ cache: make(map[string]*cachedCert),
+ lru: list.New(),
+ }, nil
+}
diff --git a/internal/secretsproxy/proxy.go b/internal/secretsproxy/proxy.go
new file mode 100644
index 00000000..b8bac8f2
--- /dev/null
+++ b/internal/secretsproxy/proxy.go
@@ -0,0 +1,549 @@
+package secretsproxy
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/rand"
+ "crypto/tls"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+)
+
+// privateIPNets contains the CIDR ranges considered private/internal.
+// Connections to these ranges are blocked to prevent SSRF attacks.
+var privateIPNets []*net.IPNet
+
+func init() {
+ for _, cidr := range []string{
+ "10.0.0.0/8",
+ "172.16.0.0/12",
+ "192.168.0.0/16",
+ "127.0.0.0/8",
+ "169.254.0.0/16",
+ "::1/128",
+ "fc00::/7",
+ "fe80::/10",
+ } {
+ _, ipnet, _ := net.ParseCIDR(cidr)
+ privateIPNets = append(privateIPNets, ipnet)
+ }
+}
+
+// isPrivateIP returns true if the IP belongs to a private/loopback/link-local range.
+func isPrivateIP(ip net.IP) bool {
+ for _, ipnet := range privateIPNets {
+ if ipnet.Contains(ip) {
+ return true
+ }
+ }
+ return false
+}
+
+const (
+ defaultConnectTimeout = 10 * time.Second
+ defaultHandshakeTimeout = 10 * time.Second
+ defaultIdleTimeout = 60 * time.Second
+ defaultSessionTTL = 24 * time.Hour
+)
+
+// Session holds the sealed→real token mapping for one sandbox.
+type Session struct {
+ SandboxID string
+ Secrets map[string]string // "osb_sealed_xxx" → real value
+ Allowlist []string // nil = all hosts allowed; supports "*." prefix wildcards
+ SecretHosts []string // hosts where token replacement is performed; nil = replace on all allowed hosts
+ ExpiresAt time.Time
+}
+
+// SecretsProxy is an HTTP CONNECT proxy that intercepts HTTPS traffic from
+// sandboxes and substitutes sealed opaque tokens with real secret values.
+// Real values never enter the VM — the VM only sees tokens like osb_sealed_xxx.
+type SecretsProxy struct {
+ ca *CA
+ listener net.Listener
+
+ mu sync.RWMutex
+ sessions map[string]*Session // guestIP → session
+
+ wg sync.WaitGroup // tracks active connections
+ closed chan struct{}
+}
+
+// NewSecretsProxy creates a new secrets proxy. Call Start() to begin accepting.
+func NewSecretsProxy(ca *CA, listenAddr string) (*SecretsProxy, error) {
+ lis, err := net.Listen("tcp", listenAddr)
+ if err != nil {
+ return nil, fmt.Errorf("listen %s: %w", listenAddr, err)
+ }
+ return &SecretsProxy{
+ ca: ca,
+ listener: lis,
+ sessions: make(map[string]*Session),
+ closed: make(chan struct{}),
+ }, nil
+}
+
+// Start begins accepting connections in the background.
+func (p *SecretsProxy) Start() {
+ go p.serve()
+ log.Printf("secrets-proxy: listening on %s", p.listener.Addr())
+}
+
+// Stop gracefully shuts down the proxy, waiting for active connections to finish.
+func (p *SecretsProxy) Stop() error {
+ close(p.closed)
+ err := p.listener.Close()
+ p.wg.Wait()
+ return err
+}
+
+// RegisterSession creates or updates a proxy session for the given sandbox IP.
+func (p *SecretsProxy) RegisterSession(guestIP string, session *Session) {
+ if session.ExpiresAt.IsZero() {
+ session.ExpiresAt = time.Now().Add(defaultSessionTTL)
+ }
+ p.mu.Lock()
+ p.sessions[guestIP] = session
+ p.mu.Unlock()
+ log.Printf("secrets-proxy: registered session sandbox=%s ip=%s secrets=%d allowlist=%d ttl=%s",
+ session.SandboxID, guestIP, len(session.Secrets), len(session.Allowlist), time.Until(session.ExpiresAt).Round(time.Second))
+}
+
+// UnregisterSession removes the proxy session for the given sandbox IP.
+func (p *SecretsProxy) UnregisterSession(guestIP string) {
+ p.mu.Lock()
+ delete(p.sessions, guestIP)
+ p.mu.Unlock()
+}
+
+// GetSessionTokens returns the sealed token → real value map for the given guest IP.
+// Returns nil if no session exists. Used to persist token mappings during hibernate.
+func (p *SecretsProxy) GetSessionTokens(guestIP string) map[string]string {
+ p.mu.RLock()
+ session := p.sessions[guestIP]
+ p.mu.RUnlock()
+ if session == nil {
+ return nil
+ }
+ return session.Secrets
+}
+
+// GetSessionAllowlist returns the egress allowlist for the given guest IP's session.
+func (p *SecretsProxy) GetSessionAllowlist(guestIP string) []string {
+ p.mu.RLock()
+ session := p.sessions[guestIP]
+ p.mu.RUnlock()
+ if session == nil {
+ return nil
+ }
+ return session.Allowlist
+}
+
+// GetSessionSecretHosts returns the secret hosts list for the given guest IP's session.
+func (p *SecretsProxy) GetSessionSecretHosts(guestIP string) []string {
+ p.mu.RLock()
+ session := p.sessions[guestIP]
+ p.mu.RUnlock()
+ if session == nil {
+ return nil
+ }
+ return session.SecretHosts
+}
+
+// ReregisterSession creates a new proxy session from a previously persisted token map.
+// Used on wake to restore the proxy session without re-generating tokens.
+func (p *SecretsProxy) ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist, secretHosts []string) {
+ session := &Session{
+ SandboxID: sandboxID,
+ Secrets: tokens,
+ Allowlist: allowlist,
+ SecretHosts: secretHosts,
+ ExpiresAt: time.Now().Add(defaultSessionTTL),
+ }
+ p.mu.Lock()
+ p.sessions[guestIP] = session
+ p.mu.Unlock()
+ log.Printf("secrets-proxy: re-registered session sandbox=%s ip=%s secrets=%d allowlist=%d secretHosts=%d",
+ sandboxID, guestIP, len(tokens), len(allowlist), len(secretHosts))
+}
+
+// CreateSealedEnvs generates sealed tokens for the given env vars, registers a
+// proxy session, and returns the complete env map to inject into the VM.
+// Includes sealed tokens + proxy config vars (HTTP_PROXY, CA certs, etc.).
+// Returns nil if envVars is empty.
+//
+// allowlist controls which hosts the sandbox can reach (nil = all).
+// secretHosts controls which hosts get token replacement (nil = all allowed hosts).
+func (p *SecretsProxy) CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, envVars map[string]string, allowlist, secretHosts []string) map[string]string {
+ if len(envVars) == 0 {
+ return nil
+ }
+
+ sealed := make(map[string]string, len(envVars)) // envVar → token
+ tokenMap := make(map[string]string, len(envVars)) // token → real value
+
+ for envVar, realValue := range envVars {
+ token := "osb_sealed_" + randomHex(16)
+ sealed[envVar] = token
+ tokenMap[token] = realValue
+ }
+
+ p.RegisterSession(guestIP, &Session{
+ SandboxID: sandboxID,
+ Secrets: tokenMap,
+ Allowlist: allowlist,
+ SecretHosts: secretHosts,
+ })
+
+ // Build the complete env map for the VM
+ proxyURL := fmt.Sprintf("http://%s:3128", gatewayIP)
+ caCertPath := "/usr/local/share/ca-certificates/opensandbox-proxy.crt"
+
+ noProxy := "localhost,127.0.0.1,::1"
+
+ result := make(map[string]string, len(sealed)+9)
+ for k, v := range sealed {
+ result[k] = v
+ }
+ result["HTTP_PROXY"] = proxyURL
+ result["HTTPS_PROXY"] = proxyURL
+ result["http_proxy"] = proxyURL
+ result["https_proxy"] = proxyURL
+ result["NO_PROXY"] = noProxy
+ result["no_proxy"] = noProxy
+ result["NODE_EXTRA_CA_CERTS"] = caCertPath
+ result["REQUESTS_CA_BUNDLE"] = caCertPath
+ result["SSL_CERT_FILE"] = caCertPath
+ return result
+}
+
+// CACertPEM returns the CA certificate PEM for injection into sandboxes.
+func (p *SecretsProxy) CACertPEM() []byte {
+ return p.ca.CertPEM()
+}
+
+func (p *SecretsProxy) serve() {
+ for {
+ conn, err := p.listener.Accept()
+ if err != nil {
+ select {
+ case <-p.closed:
+ return
+ default:
+ log.Printf("secrets-proxy: accept error: %v", err)
+ continue
+ }
+ }
+ p.wg.Add(1)
+ go func() {
+ defer p.wg.Done()
+ p.handleConn(conn)
+ }()
+ }
+}
+
+func (p *SecretsProxy) handleConn(conn net.Conn) {
+ defer conn.Close()
+ start := time.Now()
+
+ clientIP, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
+
+ // Look up session by source IP
+ p.mu.RLock()
+ session := p.sessions[clientIP]
+ p.mu.RUnlock()
+
+ if session == nil {
+ writeHTTPError(conn, 407, "no session for this IP")
+ log.Printf("secrets-proxy: audit src=%s action=rejected reason=no_session", clientIP)
+ return
+ }
+
+ if time.Now().After(session.ExpiresAt) {
+ writeHTTPError(conn, 407, "session expired")
+ log.Printf("secrets-proxy: audit sandbox=%s src=%s action=rejected reason=expired", session.SandboxID, clientIP)
+ p.UnregisterSession(clientIP)
+ return
+ }
+
+ // Parse HTTP CONNECT request properly
+ conn.SetReadDeadline(time.Now().Add(30 * time.Second))
+ reader := bufio.NewReader(conn)
+ req, err := http.ReadRequest(reader)
+ if err != nil {
+ log.Printf("secrets-proxy: audit sandbox=%s src=%s action=rejected reason=bad_request err=%v",
+ session.SandboxID, clientIP, err)
+ return
+ }
+
+ if req.Method != http.MethodConnect {
+ writeHTTPError(conn, 405, "only CONNECT supported")
+ return
+ }
+
+ targetHost, targetPort, err := net.SplitHostPort(req.Host)
+ if err != nil {
+ // No port specified — default to 443
+ targetHost = req.Host
+ targetPort = "443"
+ }
+
+ // Force TLS: rewrite port 80 to 443 (never forward plaintext with sealed tokens)
+ if targetPort == "80" {
+ targetPort = "443"
+ }
+ target := net.JoinHostPort(targetHost, targetPort)
+
+ // Egress allowlist check
+ if len(session.Allowlist) > 0 && !hostAllowed(targetHost, session.Allowlist) {
+ writeHTTPError(conn, 403, "host not in allowlist")
+ log.Printf("secrets-proxy: audit sandbox=%s src=%s host=%s action=blocked reason=allowlist duration=%s",
+ session.SandboxID, clientIP, targetHost, time.Since(start))
+ return
+ }
+
+ // Private IP blocking — prevent SSRF via proxy
+ if err := checkPrivateIP(targetHost); err != nil {
+ writeHTTPError(conn, 403, "private IP blocked")
+ log.Printf("secrets-proxy: audit sandbox=%s src=%s host=%s action=blocked reason=private_ip duration=%s",
+ session.SandboxID, clientIP, targetHost, time.Since(start))
+ return
+ }
+
+ // Determine if we should replace tokens for this host
+ shouldReplace := shouldReplaceTokens(targetHost, session)
+
+ log.Printf("secrets-proxy: audit sandbox=%s src=%s host=%s action=connect secrets=%d replace=%v",
+ session.SandboxID, clientIP, targetHost, len(session.Secrets), shouldReplace)
+
+ // Acknowledge the CONNECT tunnel
+ conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
+ conn.SetReadDeadline(time.Time{}) // clear deadline
+
+ // Sign an ephemeral cert for this host
+ leafCert, err := p.ca.SignHost(targetHost)
+ if err != nil {
+ log.Printf("secrets-proxy: sign cert for %s failed: %v", targetHost, err)
+ return
+ }
+
+ // TLS handshake with the VM (we act as the server)
+ clientTLS := tls.Server(conn, &tls.Config{
+ Certificates: []tls.Certificate{*leafCert},
+ NextProtos: []string{"http/1.1"}, // force HTTP/1.1 for reliable token replacement
+ })
+ clientTLS.SetDeadline(time.Now().Add(defaultHandshakeTimeout))
+ if err := clientTLS.Handshake(); err != nil {
+ log.Printf("secrets-proxy: client TLS handshake failed sandbox=%s host=%s: %v",
+ session.SandboxID, targetHost, err)
+ return
+ }
+ clientTLS.SetDeadline(time.Time{})
+ defer clientTLS.Close()
+
+ // Connect to the real upstream (always TLS)
+ upstreamConn, err := dialUpstream(target, targetHost)
+ if err != nil {
+ log.Printf("secrets-proxy: dial %s failed: %v", target, err)
+ return
+ }
+ defer upstreamConn.Close()
+
+ if shouldReplace && len(session.Secrets) > 0 {
+ // HTTP-aware proxy: parse requests, replace tokens in headers + body
+ p.proxyHTTPRequests(clientTLS, upstreamConn, session, targetHost)
+ } else {
+ // No replacement needed — raw bidirectional pipe (faster)
+ p.proxyRaw(clientTLS, upstreamConn)
+ }
+
+ log.Printf("secrets-proxy: audit sandbox=%s src=%s host=%s action=complete duration=%s",
+ session.SandboxID, clientIP, targetHost, time.Since(start))
+}
+
+// dialUpstream connects to the upstream server with TLS, validating that the
+// resolved IP is not private. Returns the TLS connection.
+func dialUpstream(target, serverName string) (*tls.Conn, error) {
+ // Resolve DNS first to check for private IPs
+ host, port, _ := net.SplitHostPort(target)
+ ips, err := net.LookupIP(host)
+ if err != nil {
+ return nil, fmt.Errorf("DNS lookup %s: %w", host, err)
+ }
+ for _, ip := range ips {
+ if isPrivateIP(ip) {
+ return nil, fmt.Errorf("host %s resolves to private IP %s", host, ip)
+ }
+ }
+
+ tcpConn, err := net.DialTimeout("tcp", net.JoinHostPort(ips[0].String(), port), defaultConnectTimeout)
+ if err != nil {
+ return nil, err
+ }
+
+ upstreamTLS := tls.Client(tcpConn, &tls.Config{
+ ServerName: serverName,
+ NextProtos: []string{"http/1.1"},
+ })
+ upstreamTLS.SetDeadline(time.Now().Add(defaultHandshakeTimeout))
+ if err := upstreamTLS.Handshake(); err != nil {
+ tcpConn.Close()
+ return nil, fmt.Errorf("TLS handshake: %w", err)
+ }
+ upstreamTLS.SetDeadline(time.Time{})
+ return upstreamTLS, nil
+}
+
+// checkPrivateIP resolves the host and returns an error if any resolved IP is private.
+func checkPrivateIP(host string) error {
+ // Check if it's a literal IP
+ if ip := net.ParseIP(host); ip != nil {
+ if isPrivateIP(ip) {
+ return fmt.Errorf("private IP %s", ip)
+ }
+ return nil
+ }
+ // DNS resolution is checked in dialUpstream — this is a quick pre-check for literal IPs
+ return nil
+}
+
+// shouldReplaceTokens returns true if token replacement should be performed for this host.
+// If SecretHosts is set, only replace on those hosts. Otherwise replace on all allowed hosts.
+func shouldReplaceTokens(host string, session *Session) bool {
+ if len(session.SecretHosts) == 0 {
+ return true // no restriction — replace on all hosts
+ }
+ return hostAllowed(host, session.SecretHosts)
+}
+
+// proxyHTTPRequests performs HTTP-aware proxying with token replacement in
+// both headers and body.
+func (p *SecretsProxy) proxyHTTPRequests(clientTLS *tls.Conn, upstreamTLS *tls.Conn, session *Session, targetHost string) {
+ clientReader := bufio.NewReader(clientTLS)
+ upstreamReader := bufio.NewReader(upstreamTLS)
+
+ for {
+ // Read request from VM
+ clientTLS.SetReadDeadline(time.Now().Add(defaultIdleTimeout))
+ req, err := http.ReadRequest(clientReader)
+ if err != nil {
+ return // connection closed or timeout
+ }
+ clientTLS.SetReadDeadline(time.Time{})
+
+ // Replace tokens in request headers
+ replaceHeaderTokens(req.Header, session.Secrets)
+
+ // Replace tokens in request body
+ if req.Body != nil && req.ContentLength != 0 {
+ // Buffer the replaced body to compute correct Content-Length.
+ // Sealed tokens (43 bytes) may differ in size from real values,
+ // so the original Content-Length would be wrong after replacement.
+ replacer := newStreamReplacer(req.Body, session.Secrets)
+ replaced, err := io.ReadAll(replacer)
+ req.Body.Close()
+ if err != nil {
+ return
+ }
+ req.Body = io.NopCloser(bytes.NewReader(replaced))
+ req.ContentLength = int64(len(replaced))
+ }
+
+ // Fix the Host header and URL for upstream
+ req.URL.Scheme = "https"
+ req.URL.Host = targetHost
+ req.RequestURI = "" // must be cleared for client requests
+
+ // Forward to upstream
+ if err := req.Write(upstreamTLS); err != nil {
+ return
+ }
+
+ // Read response from upstream
+ resp, err := http.ReadResponse(upstreamReader, req)
+ if err != nil {
+ return
+ }
+
+ // Forward response back to VM (no replacement — responses don't contain our tokens)
+ if err := resp.Write(clientTLS); err != nil {
+ resp.Body.Close()
+ return
+ }
+ resp.Body.Close()
+
+ // Check for connection close
+ if resp.Close || req.Close {
+ return
+ }
+ }
+}
+
+// proxyRaw performs a raw bidirectional pipe with no token replacement.
+func (p *SecretsProxy) proxyRaw(clientTLS *tls.Conn, upstreamTLS *tls.Conn) {
+ var wg sync.WaitGroup
+ wg.Add(2)
+
+ go func() {
+ defer wg.Done()
+ io.Copy(upstreamTLS, clientTLS)
+ }()
+
+ go func() {
+ defer wg.Done()
+ io.Copy(clientTLS, upstreamTLS)
+ }()
+
+ wg.Wait()
+}
+
+// replaceHeaderTokens substitutes sealed tokens in all HTTP header values.
+func replaceHeaderTokens(headers http.Header, tokens map[string]string) {
+ for key, vals := range headers {
+ for i, v := range vals {
+ replaced := v
+ for token, real := range tokens {
+ replaced = strings.ReplaceAll(replaced, token, real)
+ }
+ if replaced != v {
+ headers[key][i] = replaced
+ }
+ }
+ }
+}
+
+// hostAllowed returns true if host matches any pattern in allowed.
+// Supports exact matches and "*." prefix wildcards (e.g. "*.anthropic.com").
+func hostAllowed(host string, allowed []string) bool {
+ for _, pattern := range allowed {
+ if pattern == "*" || pattern == host {
+ return true
+ }
+ if strings.HasPrefix(pattern, "*.") {
+ if strings.HasSuffix(host, pattern[1:]) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func writeHTTPError(conn net.Conn, code int, msg string) {
+ resp := fmt.Sprintf("HTTP/1.1 %d %s\r\nContent-Length: 0\r\n\r\n", code, msg)
+ conn.Write([]byte(resp))
+}
+
+func randomHex(n int) string {
+ b := make([]byte, n)
+ if _, err := rand.Read(b); err != nil {
+ panic("crypto/rand failed: " + err.Error())
+ }
+ return hex.EncodeToString(b)
+}
diff --git a/internal/secretsproxy/replacer.go b/internal/secretsproxy/replacer.go
new file mode 100644
index 00000000..a05f26b5
--- /dev/null
+++ b/internal/secretsproxy/replacer.go
@@ -0,0 +1,152 @@
+package secretsproxy
+
+import (
+ "bytes"
+ "io"
+)
+
+const (
+ tokenPrefix = "osb_sealed_"
+ tokenHexLen = 32 // 16 random bytes hex-encoded
+ tokenLen = len(tokenPrefix) + tokenHexLen // 43
+)
+
+// streamReplacer wraps an io.Reader, replacing osb_sealed_xxx tokens with
+// real secret values. It correctly handles tokens split across read boundaries
+// by maintaining a small overlap buffer between reads.
+type streamReplacer struct {
+ src io.Reader
+ tokens map[string]string // sealed token → real value
+ buf []byte // accumulated unprocessed bytes
+ out []byte // processed bytes ready for Read()
+ eof bool
+ tmp []byte // reusable read buffer
+}
+
+// newStreamReplacer creates a replacer that reads from src and substitutes
+// sealed tokens. If tokens is empty, reads pass through without buffering.
+func newStreamReplacer(src io.Reader, tokens map[string]string) io.Reader {
+ if len(tokens) == 0 {
+ return src
+ }
+ return &streamReplacer{
+ src: src,
+ tokens: tokens,
+ tmp: make([]byte, 32*1024),
+ }
+}
+
+func (r *streamReplacer) Read(p []byte) (int, error) {
+ for len(r.out) == 0 {
+ if r.eof {
+ if len(r.buf) > 0 {
+ // Flush remaining bytes — no more data coming
+ r.out, _ = processChunk(r.buf, r.tokens, true)
+ r.buf = nil
+ if len(r.out) > 0 {
+ break
+ }
+ }
+ return 0, io.EOF
+ }
+
+ n, err := r.src.Read(r.tmp)
+ if n > 0 {
+ r.buf = append(r.buf, r.tmp[:n]...)
+ }
+ if err == io.EOF {
+ r.eof = true
+ } else if err != nil {
+ return 0, err
+ }
+
+ // Process accumulated buffer
+ var remainder []byte
+ r.out, remainder = processChunk(r.buf, r.tokens, r.eof)
+ r.buf = remainder
+ }
+
+ n := copy(p, r.out)
+ r.out = r.out[n:]
+ return n, nil
+}
+
+// processChunk scans data for sealed tokens and replaces them.
+// Returns (output, remainder). If flush is true, all data is processed
+// (no remainder held back).
+func processChunk(data []byte, tokens map[string]string, flush bool) ([]byte, []byte) {
+ if len(data) == 0 {
+ return nil, nil
+ }
+
+ prefixBytes := []byte(tokenPrefix)
+ var out bytes.Buffer
+ i := 0
+
+ for i < len(data) {
+ // Search for token prefix from current position
+ idx := bytes.Index(data[i:], prefixBytes)
+ if idx < 0 {
+ // No prefix found in remaining data
+ if flush {
+ out.Write(data[i:])
+ return out.Bytes(), nil
+ }
+ // Hold back bytes that could be the start of a partial prefix
+ safeEnd := findSafeFlushPoint(data[i:])
+ out.Write(data[i : i+safeEnd])
+ if i+safeEnd < len(data) {
+ return out.Bytes(), copyBytes(data[i+safeEnd:])
+ }
+ return out.Bytes(), nil
+ }
+
+ tokenStart := i + idx
+
+ // Write everything before the prefix
+ out.Write(data[i:tokenStart])
+
+ tokenEnd := tokenStart + tokenLen
+ if tokenEnd > len(data) {
+ // Token extends past end of data
+ if flush {
+ // No more data — this is literal text, not a complete token
+ out.Write(data[tokenStart:])
+ return out.Bytes(), nil
+ }
+ // Hold back the partial token for next read
+ return out.Bytes(), copyBytes(data[tokenStart:])
+ }
+
+ // We have the full token candidate
+ candidate := string(data[tokenStart:tokenEnd])
+ if real, ok := tokens[candidate]; ok {
+ out.Write([]byte(real))
+ } else {
+ // Looks like a token but not in our map — pass through unchanged
+ out.Write(data[tokenStart:tokenEnd])
+ }
+ i = tokenEnd
+ }
+
+ return out.Bytes(), nil
+}
+
+// findSafeFlushPoint returns the number of bytes from the start of data
+// that can be safely flushed (no partial prefix match at the end).
+func findSafeFlushPoint(data []byte) int {
+ prefix := []byte(tokenPrefix)
+ // Check if any suffix of data matches a prefix of "osb_sealed_"
+ for k := 1; k < len(prefix) && k <= len(data); k++ {
+ if bytes.Equal(data[len(data)-k:], prefix[:k]) {
+ return len(data) - k
+ }
+ }
+ return len(data)
+}
+
+func copyBytes(b []byte) []byte {
+ c := make([]byte, len(b))
+ copy(c, b)
+ return c
+}
diff --git a/internal/secretsproxy/replacer_test.go b/internal/secretsproxy/replacer_test.go
new file mode 100644
index 00000000..fa613b05
--- /dev/null
+++ b/internal/secretsproxy/replacer_test.go
@@ -0,0 +1,323 @@
+package secretsproxy
+
+import (
+ "bytes"
+ "io"
+ "net"
+ "net/http"
+ "strings"
+ "testing"
+)
+
+func TestProcessChunk_BasicReplacement(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "real-secret-value",
+ }
+
+ input := []byte(`{"Authorization": "Bearer osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`)
+ out, remainder := processChunk(input, tokens, true)
+
+ expected := `{"Authorization": "Bearer real-secret-value"}`
+ if string(out) != expected {
+ t.Errorf("got %q, want %q", string(out), expected)
+ }
+ if remainder != nil {
+ t.Errorf("expected nil remainder on flush, got %q", string(remainder))
+ }
+}
+
+func TestProcessChunk_MultipleTokens(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "secret-1",
+ "osb_sealed_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": "secret-2",
+ }
+
+ input := []byte(`key1=osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&key2=osb_sealed_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb`)
+ out, _ := processChunk(input, tokens, true)
+
+ expected := `key1=secret-1&key2=secret-2`
+ if string(out) != expected {
+ t.Errorf("got %q, want %q", string(out), expected)
+ }
+}
+
+func TestProcessChunk_UnknownToken(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "secret-1",
+ }
+
+ // This token is not in the map — should pass through unchanged
+ input := []byte(`osb_sealed_cccccccccccccccccccccccccccccccc`)
+ out, _ := processChunk(input, tokens, true)
+
+ if string(out) != string(input) {
+ t.Errorf("unknown token should pass through: got %q, want %q", string(out), string(input))
+ }
+}
+
+func TestProcessChunk_PartialPrefixAtEnd(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "secret",
+ }
+
+ // Data ends with a partial prefix "osb_seal" — should hold back
+ input := []byte(`some data osb_seal`)
+ out, remainder := processChunk(input, tokens, false)
+
+ if string(out) != "some data " {
+ t.Errorf("output got %q, want %q", string(out), "some data ")
+ }
+ if string(remainder) != "osb_seal" {
+ t.Errorf("remainder got %q, want %q", string(remainder), "osb_seal")
+ }
+}
+
+func TestProcessChunk_TokenSplitAcrossBoundary(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "secret",
+ }
+
+ // Split the token: first 17 chars in chunk 1 ("osb_sealed_" + 6 a's), remaining 26 a's in chunk 2
+ chunk1 := []byte(`data osb_sealed_aaaaaa`)
+ out1, remainder1 := processChunk(chunk1, tokens, false)
+
+ if string(out1) != "data " {
+ t.Errorf("chunk1 output got %q, want %q", string(out1), "data ")
+ }
+ // remainder1 should be "osb_sealed_aaaaaa" (partial token held back)
+ if string(remainder1) != "osb_sealed_aaaaaa" {
+ t.Errorf("remainder got %q, want %q", string(remainder1), "osb_sealed_aaaaaa")
+ }
+
+ // Second chunk: remainder + exactly 26 more a's to complete the 32-hex token + more data
+ chunk2 := append(remainder1, []byte("aaaaaaaaaaaaaaaaaaaaaaaaaa more")...) // 26 a's + " more"
+ out2, _ := processChunk(chunk2, tokens, true)
+
+ if string(out2) != "secret more" {
+ t.Errorf("chunk2 output got %q, want %q", string(out2), "secret more")
+ }
+}
+
+func TestStreamReplacer_SmallReads(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "SECRET",
+ }
+
+ input := `prefix osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa suffix`
+ expected := `prefix SECRET suffix`
+
+ // Use a tiny read buffer to stress chunk boundaries
+ src := &smallReader{data: []byte(input), chunkSize: 7}
+ r := newStreamReplacer(src, tokens)
+
+ var buf bytes.Buffer
+ if _, err := io.Copy(&buf, r); err != nil {
+ t.Fatal(err)
+ }
+
+ if buf.String() != expected {
+ t.Errorf("got %q, want %q", buf.String(), expected)
+ }
+}
+
+func TestStreamReplacer_LargeBody(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "SECRET",
+ }
+
+ // Build a large body with a token buried in the middle
+ padding := strings.Repeat("x", 100000)
+ input := padding + "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + padding
+ expected := padding + "SECRET" + padding
+
+ r := newStreamReplacer(strings.NewReader(input), tokens)
+
+ var buf bytes.Buffer
+ if _, err := io.Copy(&buf, r); err != nil {
+ t.Fatal(err)
+ }
+
+ if buf.String() != expected {
+ t.Errorf("output length: got %d, want %d", buf.Len(), len(expected))
+ }
+}
+
+func TestStreamReplacer_NoTokens(t *testing.T) {
+ tokens := map[string]string{}
+ input := "no tokens here"
+
+ r := newStreamReplacer(strings.NewReader(input), tokens)
+ var buf bytes.Buffer
+ io.Copy(&buf, r)
+
+ if buf.String() != input {
+ t.Errorf("got %q, want %q", buf.String(), input)
+ }
+}
+
+func TestFindSafeFlushPoint(t *testing.T) {
+ tests := []struct {
+ data string
+ expected int
+ }{
+ {"no match here", 13},
+ {"data ending with o", 17}, // "o" matches prefix[0]
+ {"data ending with osb", 17}, // "osb" matches prefix[:3]
+ {"data ending with osb_sealed", 17}, // "osb_sealed" matches prefix[:10]
+ {"osb_s", 0}, // partial prefix is all the data
+ }
+
+ for _, tt := range tests {
+ got := findSafeFlushPoint([]byte(tt.data))
+ if got != tt.expected {
+ t.Errorf("findSafeFlushPoint(%q) = %d, want %d", tt.data, got, tt.expected)
+ }
+ }
+}
+
+func TestHostAllowed(t *testing.T) {
+ tests := []struct {
+ host string
+ allowed []string
+ want bool
+ }{
+ {"api.anthropic.com", []string{"api.anthropic.com"}, true},
+ {"evil.com", []string{"api.anthropic.com"}, false},
+ {"api.anthropic.com", []string{"*.anthropic.com"}, true},
+ {"anthropic.com", []string{"*.anthropic.com"}, false}, // *.x.com doesn't match x.com
+ {"anything.com", []string{"*"}, true},
+ {"anything.com", nil, false},
+ }
+
+ for _, tt := range tests {
+ got := hostAllowed(tt.host, tt.allowed)
+ if got != tt.want {
+ t.Errorf("hostAllowed(%q, %v) = %v, want %v", tt.host, tt.allowed, got, tt.want)
+ }
+ }
+}
+
+func TestIsPrivateIP(t *testing.T) {
+ tests := []struct {
+ ip string
+ private bool
+ }{
+ {"10.0.0.1", true},
+ {"10.255.255.255", true},
+ {"172.16.0.1", true},
+ {"172.31.255.255", true},
+ {"172.32.0.1", false},
+ {"192.168.1.1", true},
+ {"127.0.0.1", true},
+ {"169.254.1.1", true},
+ {"8.8.8.8", false},
+ {"1.1.1.1", false},
+ {"93.184.216.34", false},
+ }
+
+ for _, tt := range tests {
+ ip := net.ParseIP(tt.ip)
+ got := isPrivateIP(ip)
+ if got != tt.private {
+ t.Errorf("isPrivateIP(%s) = %v, want %v", tt.ip, got, tt.private)
+ }
+ }
+}
+
+func TestShouldReplaceTokens(t *testing.T) {
+ tests := []struct {
+ name string
+ host string
+ secretHosts []string
+ want bool
+ }{
+ {"nil secret hosts replaces all", "anything.com", nil, true},
+ {"empty secret hosts replaces all", "anything.com", []string{}, true},
+ {"exact match", "api.anthropic.com", []string{"api.anthropic.com"}, true},
+ {"no match", "evil.com", []string{"api.anthropic.com"}, false},
+ {"wildcard match", "api.anthropic.com", []string{"*.anthropic.com"}, true},
+ {"wildcard no match", "evil.com", []string{"*.anthropic.com"}, false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ session := &Session{SecretHosts: tt.secretHosts}
+ got := shouldReplaceTokens(tt.host, session)
+ if got != tt.want {
+ t.Errorf("shouldReplaceTokens(%q, %v) = %v, want %v", tt.host, tt.secretHosts, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestReplaceHeaderTokens(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "real-api-key",
+ "osb_sealed_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb": "real-bearer-token",
+ }
+
+ headers := http.Header{
+ "Authorization": {"Bearer osb_sealed_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},
+ "X-Api-Key": {"osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
+ "Content-Type": {"application/json"},
+ }
+
+ replaceHeaderTokens(headers, tokens)
+
+ if got := headers.Get("Authorization"); got != "Bearer real-bearer-token" {
+ t.Errorf("Authorization = %q, want %q", got, "Bearer real-bearer-token")
+ }
+ if got := headers.Get("X-Api-Key"); got != "real-api-key" {
+ t.Errorf("X-Api-Key = %q, want %q", got, "real-api-key")
+ }
+ if got := headers.Get("Content-Type"); got != "application/json" {
+ t.Errorf("Content-Type should be unchanged, got %q", got)
+ }
+}
+
+func TestReplaceHeaderTokens_MultipleValues(t *testing.T) {
+ tokens := map[string]string{
+ "osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": "secret1",
+ }
+
+ headers := http.Header{
+ "X-Custom": {
+ "first osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa end",
+ "no tokens here",
+ "another osb_sealed_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa end",
+ },
+ }
+
+ replaceHeaderTokens(headers, tokens)
+
+ vals := headers["X-Custom"]
+ if vals[0] != "first secret1 end" {
+ t.Errorf("vals[0] = %q, want %q", vals[0], "first secret1 end")
+ }
+ if vals[1] != "no tokens here" {
+ t.Errorf("vals[1] should be unchanged, got %q", vals[1])
+ }
+ if vals[2] != "another secret1 end" {
+ t.Errorf("vals[2] = %q, want %q", vals[2], "another secret1 end")
+ }
+}
+
+// smallReader returns data in small chunks to test boundary handling.
+type smallReader struct {
+ data []byte
+ offset int
+ chunkSize int
+}
+
+func (r *smallReader) Read(p []byte) (int, error) {
+ if r.offset >= len(r.data) {
+ return 0, io.EOF
+ }
+ end := r.offset + r.chunkSize
+ if end > len(r.data) {
+ end = len(r.data)
+ }
+ n := copy(p, r.data[r.offset:end])
+ r.offset += n
+ return n, nil
+}
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index 9f3ad16a..8019395d 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -46,6 +46,8 @@ type SandboxConfig struct {
// When set, the sandbox boots from these drives instead of the standard base image.
TemplateRootfsKey string `json:"templateRootfsKey,omitempty"`
TemplateWorkspaceKey string `json:"templateWorkspaceKey,omitempty"`
+ // Project name — resolves config defaults + secrets from the project.
+ Project string `json:"project,omitempty"`
// SandboxID allows pre-determining the sandbox ID for async creation.
// If empty, a new ID is generated automatically.
SandboxID string `json:"-"`
diff --git a/scripts/test-proxy-secrets.sh b/scripts/test-proxy-secrets.sh
new file mode 100755
index 00000000..96fc1ea7
--- /dev/null
+++ b/scripts/test-proxy-secrets.sh
@@ -0,0 +1,182 @@
+#!/bin/bash
+#
+# End-to-end test: sealed secrets + proxy token replacement
+#
+# Proves the full chain:
+# 1. Secret encrypted in PG
+# 2. Decrypted on sandbox create
+# 3. Sealed into osb_sealed_* token inside VM
+# 4. Proxy replaces sealed token with real value on outbound HTTPS
+# 5. Anthropic API call succeeds
+#
+# Usage:
+# ./scripts/test-proxy-secrets.sh <your-real-anthropic-api-key>
+#
+set -euo pipefail
+
+API="${OPENCOMPUTER_API_URL:-http://52.14.189.164:8080}"
+KEY="${OPENCOMPUTER_API_KEY:-test-dev-key}"
+ANTHROPIC_KEY="${1:-}"
+
+if [ -z "$ANTHROPIC_KEY" ]; then
+ echo "Usage: $0 <anthropic-api-key>"
+ echo " e.g. $0 sk-ant-api03-..."
+ exit 1
+fi
+
+GREEN='\033[32m'
+RED='\033[31m'
+BOLD='\033[1m'
+DIM='\033[2m'
+RESET='\033[0m'
+
+pass() { echo -e "${GREEN}✓ $1${RESET}"; }
+fail() { echo -e "${RED}✗ $1${RESET}"; }
+info() { echo -e "${DIM} $1${RESET}"; }
+header() { echo -e "\n${BOLD}━━━ $1 ━━━${RESET}\n"; }
+
+PROJ_NAME="proxy-test-$(date +%s)"
+PROJ_ID=""
+SB_ID=""
+TOKEN=""
+WORKER="https://dev.opensandbox.ai"
+
+cleanup() {
+ if [ -n "$SB_ID" ]; then
+ curl -s -X DELETE "$API/api/sandboxes/$SB_ID" -H "X-API-Key: $KEY" > /dev/null 2>&1 || true
+ fi
+ if [ -n "$PROJ_ID" ]; then
+ curl -s -X DELETE "$API/api/projects/$PROJ_ID" -H "X-API-Key: $KEY" > /dev/null 2>&1 || true
+ fi
+}
+trap cleanup EXIT
+
+echo -e "${BOLD}"
+echo "╔══════════════════════════════════════════════════╗"
+echo "║ Sealed Secrets + Proxy Replacement Test ║"
+echo "╚══════════════════════════════════════════════════╝"
+echo -e "${RESET}"
+
+# ── 1. Create project ──
+header "1. Create project"
+
+PROJ_RESP=$(curl -s -X POST "$API/api/projects" \
+ -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
+ -d "{\"name\":\"$PROJ_NAME\",\"timeoutSec\":300}")
+
+PROJ_ID=$(echo "$PROJ_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])" 2>/dev/null || true)
+
+if [ -n "$PROJ_ID" ]; then
+ pass "Project created: $PROJ_ID"
+else
+ fail "Project creation failed: $PROJ_RESP"
+ exit 1
+fi
+
+# ── 2. Set Anthropic key as secret ──
+header "2. Set ANTHROPIC_API_KEY secret"
+
+SECRET_RESP=$(curl -s -X PUT "$API/api/projects/$PROJ_ID/secrets/ANTHROPIC_API_KEY" \
+ -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
+ -d "{\"value\":\"$ANTHROPIC_KEY\"}")
+
+pass "Secret set (encrypted at rest)"
+info "Key prefix: ${ANTHROPIC_KEY:0:12}..."
+
+# ── 3. Create sandbox with project ──
+header "3. Create sandbox with project"
+
+SB_RESP=$(curl -s -X POST "$API/api/sandboxes" \
+ -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
+ -d "{\"project\":\"$PROJ_NAME\",\"timeout\":300}")
+
+SB_ID=$(echo "$SB_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])" 2>/dev/null || true)
+TOKEN=$(echo "$SB_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['token'])" 2>/dev/null || true)
+
+if [ -n "$SB_ID" ] && [ -n "$TOKEN" ]; then
+ pass "Sandbox created: $SB_ID"
+else
+ fail "Sandbox creation failed: $SB_RESP"
+ exit 1
+fi
+
+# Helper to exec in sandbox (uses jq to safely JSON-encode the command)
+sb_exec() {
+ local payload
+ payload=$(jq -n --arg cmd "$1" '{"cmd":"sh","args":["-c",$cmd],"timeout":30}')
+ curl -s -X POST "$WORKER/sandboxes/$SB_ID/exec/run" \
+ -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
+ -d "$payload"
+}
+
+# ── 4. Verify secret is sealed (not plaintext) ──
+header "4. Verify secret is sealed inside sandbox"
+
+SEALED_VAL=$(sb_exec 'echo $ANTHROPIC_API_KEY' | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null)
+
+if [[ "$SEALED_VAL" == osb_sealed_* ]]; then
+ pass "Secret is sealed: $SEALED_VAL"
+else
+ fail "Secret is NOT sealed — got: $SEALED_VAL"
+ if [[ "$SEALED_VAL" == sk-ant-* ]]; then
+ fail "CRITICAL: Real API key is visible inside the sandbox!"
+ fi
+ exit 1
+fi
+
+# ── 5. Verify real key is NOT in env ──
+header "5. Verify real key never appears in VM"
+
+ALL_ENV=$(sb_exec 'env' | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout',''))" 2>/dev/null)
+
+if echo "$ALL_ENV" | grep -q "$ANTHROPIC_KEY"; then
+ fail "CRITICAL: Real API key found in VM environment!"
+ exit 1
+else
+ pass "Real key not found in VM environment"
+fi
+
+# ── 6. Call Anthropic API from inside sandbox ──
+header "6. Call Anthropic API (proxy should replace sealed token)"
+
+API_RESP=$(sb_exec 'curl -s -w "\n%{http_code}" https://api.anthropic.com/v1/messages -H "x-api-key: $ANTHROPIC_API_KEY" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d "{\"model\":\"claude-haiku-4-5-20251001\",\"max_tokens\":20,\"messages\":[{\"role\":\"user\",\"content\":\"Say exactly: proxy test ok\"}]}"')
+
+API_STDOUT=$(echo "$API_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout',''))" 2>/dev/null)
+API_STDERR=$(echo "$API_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stderr',''))" 2>/dev/null)
+
+# Extract HTTP status (last line of stdout from curl -w)
+HTTP_CODE=$(echo "$API_STDOUT" | tail -1)
+BODY=$(echo "$API_STDOUT" | sed '$d')
+
+info "HTTP status: $HTTP_CODE"
+
+if [ "$HTTP_CODE" = "200" ]; then
+ pass "Anthropic API call succeeded (200)"
+
+ # Extract the response text
+ RESPONSE_TEXT=$(echo "$BODY" | python3 -c "
+import sys, json
+try:
+ d = json.load(sys.stdin)
+ print(d['content'][0]['text'])
+except:
+ print('(could not parse response)')
+" 2>/dev/null)
+ info "Claude said: $RESPONSE_TEXT"
+else
+ fail "Anthropic API call failed (HTTP $HTTP_CODE)"
+ info "Response: $BODY"
+ if echo "$BODY" | grep -qi "authentication\|invalid.*key\|unauthorized"; then
+ fail "Auth error — proxy did NOT replace the sealed token"
+ fi
+fi
+
+# ── Summary ──
+echo ""
+echo -e "${BOLD}========================================${RESET}"
+echo -e "${BOLD} All checks passed!${RESET}"
+echo -e "${BOLD}========================================${RESET}"
+echo ""
+echo -e "${DIM}Chain verified:${RESET}"
+echo -e "${DIM} PG (encrypted) → server (decrypted) → worker (sealed) → VM (osb_sealed_*)${RESET}"
+echo -e "${DIM} VM → HTTPS request → proxy (replaced) → Anthropic (real key) → 200 OK${RESET}"
diff --git a/sdks/python/examples/test_projects.py b/sdks/python/examples/test_projects.py
new file mode 100644
index 00000000..f2d33bdb
--- /dev/null
+++ b/sdks/python/examples/test_projects.py
@@ -0,0 +1,245 @@
+#!/usr/bin/env python3
+"""
+Projects & Secrets Test
+
+Tests:
+ 1. Create a project
+ 2. List projects
+ 3. Get project by ID
+ 4. Update project
+ 5. Set secrets on a project
+ 6. List secrets (names only, values never returned)
+ 7. Create sandbox with project (inherits config + secrets)
+ 8. Verify secrets are injected as env vars
+ 9. Delete secret
+ 10. Delete project
+
+Usage:
+ python examples/test_projects.py
+"""
+
+import asyncio
+import sys
+import time
+
+from opencomputer import Sandbox, Project
+
+GREEN = "\033[32m"
+RED = "\033[31m"
+BOLD = "\033[1m"
+DIM = "\033[2m"
+RESET = "\033[0m"
+
+passed = 0
+failed = 0
+
+
+def green(msg: str) -> None:
+ print(f"{GREEN}✓ {msg}{RESET}")
+
+
+def red(msg: str) -> None:
+ print(f"{RED}✗ {msg}{RESET}")
+
+
+def bold(msg: str) -> None:
+ print(f"{BOLD}{msg}{RESET}")
+
+
+def dim(msg: str) -> None:
+ print(f"{DIM} {msg}{RESET}")
+
+
+def check(desc: str, condition: bool, detail: str = "") -> None:
+ global passed, failed
+ if condition:
+ green(desc)
+ passed += 1
+ else:
+ red(f"{desc} ({detail})" if detail else desc)
+ failed += 1
+
+
+async def main() -> None:
+ global passed, failed
+
+ bold("\n╔══════════════════════════════════════════════════╗")
+ bold("║ Projects & Secrets Test ║")
+ bold("╚══════════════════════════════════════════════════╝\n")
+
+ project_id = None
+ sandbox = None
+ project_name = f"test-project-{int(time.time())}"
+
+ try:
+ # ── Test 1: Create project ──
+ bold("━━━ Test 1: Create project ━━━\n")
+
+ project = await Project.create(
+ name=project_name,
+ template="base",
+ cpu_count=1,
+ memory_mb=512,
+ timeout_sec=120,
+ )
+
+ project_id = project["id"]
+ check("Project created", bool(project["id"]))
+ check("Name matches", project["name"] == project_name)
+ check("Template set", project["template"] == "base")
+ check("CPU set", project["cpuCount"] == 1)
+ check("Memory set", project["memoryMB"] == 512)
+ check("Timeout set", project["timeoutSec"] == 120)
+ dim(f"Project ID: {project_id}")
+ print()
+
+ # ── Test 2: List projects ──
+ bold("━━━ Test 2: List projects ━━━\n")
+
+ projects = await Project.list()
+ check("List returns list", isinstance(projects, list))
+ found = any(p["id"] == project_id for p in projects)
+ check("Created project in list", found)
+ dim(f"Total projects: {len(projects)}")
+ print()
+
+ # ── Test 3: Get project ──
+ bold("━━━ Test 3: Get project by ID ━━━\n")
+
+ fetched = await Project.get(project_id)
+ check("Get returns correct project", fetched["id"] == project_id)
+ check("Get has correct name", fetched["name"] == project_name)
+ print()
+
+ # ── Test 4: Update project ──
+ bold("━━━ Test 4: Update project ━━━\n")
+
+ updated = await Project.update(
+ project_id,
+ memory_mb=1024,
+ timeout_sec=300,
+ )
+ check("Memory updated to 1024", updated["memoryMB"] == 1024)
+ check("Timeout updated to 300", updated["timeoutSec"] == 300)
+ check("Name unchanged", updated["name"] == project_name)
+ print()
+
+ # ── Test 5: Set secrets ──
+ bold("━━━ Test 5: Set project secrets ━━━\n")
+
+ await Project.set_secret(project_id, "TEST_API_KEY", "sk-test-12345")
+ green("Set TEST_API_KEY")
+
+ await Project.set_secret(project_id, "DATABASE_URL", "postgres://localhost/test")
+ green("Set DATABASE_URL")
+
+ await Project.set_secret(project_id, "TEMP_SECRET", "will-be-deleted")
+ green("Set TEMP_SECRET")
+ print()
+
+ # ── Test 6: List secrets ──
+ bold("━━━ Test 6: List secret names ━━━\n")
+
+ secret_names = await Project.list_secrets(project_id)
+ check("Returns list", isinstance(secret_names, list))
+ check("Has TEST_API_KEY", "TEST_API_KEY" in secret_names)
+ check("Has DATABASE_URL", "DATABASE_URL" in secret_names)
+ check("Has TEMP_SECRET", "TEMP_SECRET" in secret_names)
+ check("3 secrets total", len(secret_names) == 3, f"got {len(secret_names)}")
+ dim(f"Secret names: {', '.join(secret_names)}")
+ print()
+
+ # ── Test 7: Create sandbox with project ──
+ bold("━━━ Test 7: Create sandbox with project ━━━\n")
+
+ sandbox = await Sandbox.create(
+ project=project_name,
+ timeout=120,
+ )
+ check("Sandbox created", bool(sandbox.sandbox_id))
+ dim(f"Sandbox ID: {sandbox.sandbox_id}")
+ print()
+
+ # ── Test 8: Verify secrets are sealed in sandbox ──
+ bold("━━━ Test 8: Verify secrets sealed in sandbox ━━━\n")
+
+ # Secrets should be sealed tokens (osb_sealed_*) inside the VM.
+ # The MITM proxy replaces sealed tokens with real values on outbound HTTPS requests,
+ # so the real secret never exists in VM memory.
+ api_key_result = await sandbox.commands.run("echo $TEST_API_KEY")
+ api_key_val = api_key_result.stdout.strip()
+ check("TEST_API_KEY is sealed", api_key_val.startswith("osb_sealed_"),
+ f'got "{api_key_val}"')
+
+ db_url_result = await sandbox.commands.run("echo $DATABASE_URL")
+ db_url_val = db_url_result.stdout.strip()
+ check("DATABASE_URL is sealed", db_url_val.startswith("osb_sealed_"),
+ f'got "{db_url_val}"')
+
+ temp_result = await sandbox.commands.run("echo $TEMP_SECRET")
+ temp_val = temp_result.stdout.strip()
+ check("TEMP_SECRET is sealed", temp_val.startswith("osb_sealed_"),
+ f'got "{temp_val}"')
+ print()
+
+ # ── Test 9: Delete secret ──
+ bold("━━━ Test 9: Delete secret ━━━\n")
+
+ await Project.delete_secret(project_id, "TEMP_SECRET")
+ green("Deleted TEMP_SECRET")
+
+ after_delete = await Project.list_secrets(project_id)
+ check("TEMP_SECRET removed", "TEMP_SECRET" not in after_delete)
+ check("2 secrets remaining", len(after_delete) == 2, f"got {len(after_delete)}")
+ print()
+
+ # ── Test 10: Delete project ──
+ bold("━━━ Test 10: Delete project ━━━\n")
+
+ # Kill sandbox first
+ await sandbox.kill()
+ green("Sandbox killed")
+ sandbox = None
+
+ await Project.delete(project_id)
+ green("Project deleted")
+
+ # Verify it's gone
+ try:
+ await Project.get(project_id)
+ red("Project should not exist after delete")
+ failed += 1
+ except Exception:
+ green("Project not found after delete (expected)")
+ passed += 1
+ project_id = None
+ print()
+
+ except Exception as e:
+ red(f"Fatal error: {e}")
+ import traceback
+ traceback.print_exc()
+ failed += 1
+ finally:
+ # Cleanup
+ if sandbox:
+ try:
+ await sandbox.kill()
+ except Exception:
+ pass
+ if project_id:
+ try:
+ await Project.delete(project_id)
+ except Exception:
+ pass
+
+ # --- Summary ---
+ bold("========================================")
+ bold(f" Results: {passed} passed, {failed} failed")
+ bold("========================================\n")
+ if failed > 0:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.py
index e52d1f77..796af156 100644
--- a/sdks/python/opencomputer/__init__.py
+++ b/sdks/python/opencomputer/__init__.py
@@ -6,6 +6,7 @@ from opencomputer.filesystem import Filesystem
from opencomputer.exec import Exec, ProcessResult, ExecSessionInfo
from opencomputer.pty import Pty, PtySession
from opencomputer.template import Template
+from opencomputer.project import Project
__all__ = [
"Sandbox",
@@ -20,6 +21,7 @@ __all__ = [
"Pty",
"PtySession",
"Template",
+ "Project",
]
__version__ = "0.5.0"
diff --git a/sdks/python/opencomputer/project.py b/sdks/python/opencomputer/project.py
new file mode 100644
index 00000000..8ce1dfea
--- /dev/null
+++ b/sdks/python/opencomputer/project.py
@@ -0,0 +1,208 @@
+"""Project management — CRUD for projects and encrypted secrets."""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+import httpx
+
+
+def _get_client(
+ api_key: str | None = None,
+ api_url: str | None = None,
+) -> httpx.AsyncClient:
+ url = api_url or os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")
+ url = url.rstrip("/")
+ key = api_key or os.environ.get("OPENCOMPUTER_API_KEY", "")
+
+ api_base = url if url.endswith("/api") else f"{url}/api"
+
+ headers: dict[str, str] = {}
+ if key:
+ headers["X-API-Key"] = key
+
+ return httpx.AsyncClient(base_url=api_base, headers=headers, timeout=30.0)
+
+
+class Project:
+ """Static methods for managing projects and their secrets."""
+
+ @staticmethod
+ async def create(
+ name: str,
+ template: str = "",
+ cpu_count: int = 0,
+ memory_mb: int = 0,
+ timeout_sec: int = 0,
+ egress_allowlist: list[str] | None = None,
+ api_key: str | None = None,
+ api_url: str | None = None,
+ ) -> dict:
+ """Create a new project.
+
+ Args:
+ name: Project name (unique per org).
+ template: Default template for sandboxes in this project.
+ cpu_count: Default vCPU count.
+ memory_mb: Default memory in MB.
+ timeout_sec: Default sandbox timeout in seconds.
+ egress_allowlist: Allowed egress hosts (e.g. ["api.anthropic.com"]).
+ api_key: API key (or OPENCOMPUTER_API_KEY env var).
+ api_url: API URL (or OPENCOMPUTER_API_URL env var).
+
+ Returns:
+ Project info dict with id, name, template, etc.
+ """
+ body: dict[str, Any] = {"name": name}
+ if template:
+ body["template"] = template
+ if cpu_count:
+ body["cpuCount"] = cpu_count
+ if memory_mb:
+ body["memoryMB"] = memory_mb
+ if timeout_sec:
+ body["timeoutSec"] = timeout_sec
+ if egress_allowlist:
+ body["egressAllowlist"] = egress_allowlist
+
+ async with _get_client(api_key, api_url) as client:
+ resp = await client.post("/projects", json=body)
+ resp.raise_for_status()
+ return resp.json()
+
+ @staticmethod
+ async def list(
+ api_key: str | None = None,
+ api_url: str | None = None,
+ ) -> list[dict]:
+ """List all projects for the authenticated org."""
+ async with _get_client(api_key, api_url) as client:
+ resp = await client.get("/projects")
+ resp.raise_for_status()
+ return resp.json()
+
+ @staticmethod
+ async def get(
+ project_id: str,
+ api_key: str | None = None,
+ api_url: str | None = None,
+ ) -> dict:
+ """Get project details by ID."""
+ async with _get_client(api_key, api_url) as client:
+ resp = await client.get(f"/projects/{project_id}")
+ resp.raise_for_status()
+ return resp.json()
+
+ @staticmethod
+ async def update(
+ project_id: str,
+ name: str = "",
+ template: str = "",
+ cpu_count: int = 0,
+ memory_mb: int = 0,
+ timeout_sec: int = 0,
+ egress_allowlist: list[str] | None = None,
+ api_key: str | None = None,
+ api_url: str | None = None,
+ ) -> dict:
+ """Update a project's configuration.
+
+ Args:
+ project_id: UUID of the project to update.
+ name: New project name (empty = no change).
+ template: New default template (empty = no change).
+ cpu_count: New default vCPU count (0 = no change).
+ memory_mb: New default memory in MB (0 = no change).
+ timeout_sec: New default timeout in seconds (0 = no change).
+ egress_allowlist: New allowed egress hosts (None = no change).
+ api_key: API key (or OPENCOMPUTER_API_KEY env var).
+ api_url: API URL (or OPENCOMPUTER_API_URL env var).
+
+ Returns:
+ Updated project info dict.
+ """
+ body: dict[str, Any] = {}
+ if name:
+ body["name"] = name
+ if template:
+ body["template"] = template
+ if cpu_count:
+ body["cpuCount"] = cpu_count
+ if memory_mb:
+ body["memoryMB"] = memory_mb
+ if timeout_sec:
+ body["timeoutSec"] = timeout_sec
+ if egress_allowlist is not None:
+ body["egressAllowlist"] = egress_allowlist
+
+ async with _get_client(api_key, api_url) as client:
+ resp = await client.put(f"/projects/{project_id}", json=body)
+ resp.raise_for_status()
+ return resp.json()
+
+ @staticmethod
+ async def delete(
+ project_id: str,
+ api_key: str | None = None,
+ api_url: str | None = None,
+ ) -> None:
+ """Delete a project and all its secrets."""
+ async with _get_client(api_key, api_url) as client:
+ resp = await client.delete(f"/projects/{project_id}")
+ resp.raise_for_status()
+
+ # ── Secrets ──────────────────────────────────────────────────────────────
+
+ @staticmethod
+ async def set_secret(
+ project_id: str,
+ name: str,
+ value: str,
+ api_key: str | None = None,
+ api_url: str | None = None,
+ ) -> None:
+ """Set (create or update) an encrypted secret on a project.
+
+ Args:
+ project_id: UUID of the project.
+ name: Secret name (used as env var name in sandboxes).
+ value: Secret value (encrypted at rest, never returned by API).
+ api_key: API key (or OPENCOMPUTER_API_KEY env var).
+ api_url: API URL (or OPENCOMPUTER_API_URL env var).
+ """
+ async with _get_client(api_key, api_url) as client:
+ resp = await client.put(
+ f"/projects/{project_id}/secrets/{name}",
+ json={"value": value},
+ )
+ resp.raise_for_status()
+
+ @staticmethod
+ async def delete_secret(
+ project_id: str,
+ name: str,
+ api_key: str | None = None,
+ api_url: str | None = None,
+ ) -> None:
+ """Delete a secret from a project."""
+ async with _get_client(api_key, api_url) as client:
+ resp = await client.delete(f"/projects/{project_id}/secrets/{name}")
+ if resp.status_code != 404:
+ resp.raise_for_status()
+
+ @staticmethod
+ async def list_secrets(
+ project_id: str,
+ api_key: str | None = None,
+ api_url: str | None = None,
+ ) -> list[str]:
+ """List secret names for a project (values are never returned).
+
+ Returns:
+ List of secret names (e.g. ["ANTHROPIC_API_KEY", "DATABASE_URL"]).
+ """
+ async with _get_client(api_key, api_url) as client:
+ resp = await client.get(f"/projects/{project_id}/secrets")
+ resp.raise_for_status()
+ return resp.json()
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 82a7968d..df8ffc32 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -37,8 +37,20 @@ class Sandbox:
api_url: str | None = None,
envs: dict[str, str] | None = None,
metadata: dict[str, str] | None = None,
+ project: str | None = None,
) -> Sandbox:
- """Create a new sandbox instance."""
+ """Create a new sandbox instance.
+
+ Args:
+ template: Template to use (default "base").
+ timeout: Sandbox timeout in seconds (default 300).
+ api_key: API key (or OPENCOMPUTER_API_KEY env var).
+ api_url: API URL (or OPENCOMPUTER_API_URL env var).
+ envs: Environment variables to inject. Overrides project secrets.
+ metadata: Custom metadata key-value pairs.
+ project: Project name — inherits template, cpu, memory, timeout,
+ and secrets from the project.
+ """
url = api_url or os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")
url = url.rstrip("/")
key = api_key or os.environ.get("OPENCOMPUTER_API_KEY", "")
@@ -60,6 +72,8 @@ class Sandbox:
body["envs"] = envs
if metadata:
body["metadata"] = metadata
+ if project:
+ body["project"] = project
resp = await client.post("/sandboxes", json=body)
resp.raise_for_status()
diff --git a/sdks/typescript/examples/test-projects.ts b/sdks/typescript/examples/test-projects.ts
new file mode 100644
index 00000000..6406bf0b
--- /dev/null
+++ b/sdks/typescript/examples/test-projects.ts
@@ -0,0 +1,217 @@
+/**
+ * Projects & Secrets Test
+ *
+ * Tests:
+ * 1. Create a project
+ * 2. List projects
+ * 3. Get project by ID
+ * 4. Update project
+ * 5. Set secrets on a project
+ * 6. List secrets (names only, values never returned)
+ * 7. Create sandbox with project (inherits config + secrets)
+ * 8. Verify secrets are injected as env vars
+ * 9. Delete secret
+ * 10. Delete project
+ *
+ * Usage:
+ * npx tsx examples/test-projects.ts
+ */
+
+import { Sandbox, Project } from "../src/index";
+
+function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
+function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
+function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
+function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
+
+let passed = 0;
+let failed = 0;
+
+function check(desc: string, condition: boolean, detail?: string) {
+ if (condition) {
+ green(desc);
+ passed++;
+ } else {
+ red(`${desc}${detail ? ` (${detail})` : ""}`);
+ failed++;
+ }
+}
+
+async function main() {
+ bold("\n╔══════════════════════════════════════════════════╗");
+ bold("║ Projects & Secrets Test ║");
+ bold("╚══════════════════════════════════════════════════╝\n");
+
+ let projectId: string | null = null;
+ let sandbox: Sandbox | null = null;
+ const projectName = `test-project-${Date.now()}`;
+
+ try {
+ // ── Test 1: Create project ────────────────────────────────────
+ bold("━━━ Test 1: Create project ━━━\n");
+
+ const project = await Project.create({
+ name: projectName,
+ template: "base",
+ cpuCount: 1,
+ memoryMB: 512,
+ timeoutSec: 120,
+ });
+
+ projectId = project.id;
+ check("Project created", !!project.id);
+ check("Name matches", project.name === projectName);
+ check("Template set", project.template === "base");
+ check("CPU set", project.cpuCount === 1);
+ check("Memory set", project.memoryMB === 512);
+ check("Timeout set", project.timeoutSec === 120);
+ dim(`Project ID: ${project.id}`);
+ console.log();
+
+ // ── Test 2: List projects ─────────────────────────────────────
+ bold("━━━ Test 2: List projects ━━━\n");
+
+ const projects = await Project.list();
+ check("List returns array", Array.isArray(projects));
+ const found = projects.find((p) => p.id === projectId);
+ check("Created project in list", !!found);
+ dim(`Total projects: ${projects.length}`);
+ console.log();
+
+ // ── Test 3: Get project ───────────────────────────────────────
+ bold("━━━ Test 3: Get project by ID ━━━\n");
+
+ const fetched = await Project.get(projectId!);
+ check("Get returns correct project", fetched.id === projectId);
+ check("Get has correct name", fetched.name === projectName);
+ console.log();
+
+ // ── Test 4: Update project ────────────────────────────────────
+ bold("━━━ Test 4: Update project ━━━\n");
+
+ const updated = await Project.update(projectId!, {
+ memoryMB: 1024,
+ timeoutSec: 300,
+ });
+ check("Memory updated to 1024", updated.memoryMB === 1024);
+ check("Timeout updated to 300", updated.timeoutSec === 300);
+ check("Name unchanged", updated.name === projectName);
+ console.log();
+
+ // ── Test 5: Set secrets ───────────────────────────────────────
+ bold("━━━ Test 5: Set project secrets ━━━\n");
+
+ await Project.setSecret(projectId!, "TEST_API_KEY", "sk-test-12345");
+ green("Set TEST_API_KEY");
+
+ await Project.setSecret(projectId!, "DATABASE_URL", "postgres://localhost/test");
+ green("Set DATABASE_URL");
+
+ await Project.setSecret(projectId!, "TEMP_SECRET", "will-be-deleted");
+ green("Set TEMP_SECRET");
+ console.log();
+
+ // ── Test 6: List secrets ──────────────────────────────────────
+ bold("━━━ Test 6: List secret names ━━━\n");
+
+ const secretNames = await Project.listSecrets(projectId!);
+ check("Returns array", Array.isArray(secretNames));
+ check("Has TEST_API_KEY", secretNames.includes("TEST_API_KEY"));
+ check("Has DATABASE_URL", secretNames.includes("DATABASE_URL"));
+ check("Has TEMP_SECRET", secretNames.includes("TEMP_SECRET"));
+ check("3 secrets total", secretNames.length === 3, `got ${secretNames.length}`);
+ dim(`Secret names: ${secretNames.join(", ")}`);
+ console.log();
+
+ // ── Test 7: Create sandbox with project ───────────────────────
+ bold("━━━ Test 7: Create sandbox with project ━━━\n");
+
+ sandbox = await Sandbox.create({
+ project: projectName,
+ timeout: 120,
+ });
+ check("Sandbox created", !!sandbox.sandboxId);
+ dim(`Sandbox ID: ${sandbox.sandboxId}`);
+ console.log();
+
+ // ── Test 8: Verify secrets are sealed in sandbox ──────────────
+ bold("━━━ Test 8: Verify secrets sealed in sandbox ━━━\n");
+
+ // Secrets should be sealed tokens (osb_sealed_*) inside the VM.
+ // The MITM proxy replaces sealed tokens with real values on outbound HTTPS requests,
+ // so the real secret never exists in VM memory.
+ const apiKeyResult = await sandbox.commands.run("echo $TEST_API_KEY");
+ const apiKeyVal = apiKeyResult.stdout.trim();
+ check("TEST_API_KEY is sealed", apiKeyVal.startsWith("osb_sealed_"),
+ `got "${apiKeyVal}"`);
+
+ const dbUrlResult = await sandbox.commands.run("echo $DATABASE_URL");
+ const dbUrlVal = dbUrlResult.stdout.trim();
+ check("DATABASE_URL is sealed", dbUrlVal.startsWith("osb_sealed_"),
+ `got "${dbUrlVal}"`);
+
+ const tempResult = await sandbox.commands.run("echo $TEMP_SECRET");
+ const tempVal = tempResult.stdout.trim();
+ check("TEMP_SECRET is sealed", tempVal.startsWith("osb_sealed_"),
+ `got "${tempVal}"`);
+ console.log();
+
+ // ── Test 9: Delete secret ─────────────────────────────────────
+ bold("━━━ Test 9: Delete secret ━━━\n");
+
+ await Project.deleteSecret(projectId!, "TEMP_SECRET");
+ green("Deleted TEMP_SECRET");
+
+ const afterDelete = await Project.listSecrets(projectId!);
+ check("TEMP_SECRET removed", !afterDelete.includes("TEMP_SECRET"));
+ check("2 secrets remaining", afterDelete.length === 2, `got ${afterDelete.length}`);
+ console.log();
+
+ // ── Test 10: Delete project ───────────────────────────────────
+ bold("━━━ Test 10: Delete project ━━━\n");
+
+ // Kill sandbox first
+ await sandbox.kill();
+ green("Sandbox killed");
+ sandbox = null;
+
+ await Project.delete(projectId!);
+ green("Project deleted");
+
+ // Verify it's gone
+ try {
+ await Project.get(projectId!);
+ red("Project should not exist after delete");
+ failed++;
+ } catch {
+ green("Project not found after delete (expected)");
+ passed++;
+ }
+ projectId = null;
+ console.log();
+
+ } catch (err: any) {
+ red(`Fatal error: ${err.message}`);
+ if (err.stack) dim(err.stack);
+ failed++;
+ } finally {
+ // Cleanup
+ if (sandbox) {
+ try { await sandbox.kill(); } catch {}
+ }
+ if (projectId) {
+ try { await Project.delete(projectId); } catch {}
+ }
+ }
+
+ // --- Summary ---
+ bold("========================================");
+ bold(` Results: ${passed} passed, ${failed} failed`);
+ bold("========================================\n");
+ if (failed > 0) process.exit(1);
+}
+
+main().catch((err) => {
+ console.error("Fatal error:", err);
+ process.exit(1);
+});
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index d7f8acaf..75041684 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -4,3 +4,4 @@ export { Filesystem, type EntryInfo } from "./filesystem.js";
export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
export { Templates, type TemplateInfo } from "./template.js";
+export { Project, type ProjectInfo, type ProjectOpts, type CreateProjectOpts, type UpdateProjectOpts } from "./project.js";
diff --git a/sdks/typescript/src/project.ts b/sdks/typescript/src/project.ts
new file mode 100644
index 00000000..f9e4d09e
--- /dev/null
+++ b/sdks/typescript/src/project.ts
@@ -0,0 +1,180 @@
+function resolveApiUrl(url: string): string {
+ const base = url.replace(/\/+$/, "");
+ return base.endsWith("/api") ? base : `${base}/api`;
+}
+
+export interface ProjectInfo {
+ id: string;
+ orgId: string;
+ name: string;
+ template: string;
+ cpuCount: number;
+ memoryMB: number;
+ timeoutSec: number;
+ egressAllowlist: string[];
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface ProjectOpts {
+ apiKey?: string;
+ apiUrl?: string;
+}
+
+export interface CreateProjectOpts extends ProjectOpts {
+ name: string;
+ template?: string;
+ cpuCount?: number;
+ memoryMB?: number;
+ timeoutSec?: number;
+ egressAllowlist?: string[];
+}
+
+export interface UpdateProjectOpts extends ProjectOpts {
+ name?: string;
+ template?: string;
+ cpuCount?: number;
+ memoryMB?: number;
+ timeoutSec?: number;
+ egressAllowlist?: string[];
+}
+
+function getConfig(opts: ProjectOpts) {
+ const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
+ const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
+ const headers: Record<string, string> = { "Content-Type": "application/json" };
+ if (apiKey) headers["X-API-Key"] = apiKey;
+ return { apiUrl, headers };
+}
+
+export class Project {
+ private constructor() {}
+
+ static async create(opts: CreateProjectOpts): Promise<ProjectInfo> {
+ const { apiUrl, headers } = getConfig(opts);
+
+ const body: Record<string, unknown> = { name: opts.name };
+ if (opts.template) body.template = opts.template;
+ if (opts.cpuCount != null) body.cpuCount = opts.cpuCount;
+ if (opts.memoryMB != null) body.memoryMB = opts.memoryMB;
+ if (opts.timeoutSec != null) body.timeoutSec = opts.timeoutSec;
+ if (opts.egressAllowlist) body.egressAllowlist = opts.egressAllowlist;
+
+ const resp = await fetch(`${apiUrl}/projects`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ });
+
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to create project: ${resp.status} ${text}`);
+ }
+
+ return resp.json();
+ }
+
+ static async list(opts: ProjectOpts = {}): Promise<ProjectInfo[]> {
+ const { apiUrl, headers } = getConfig(opts);
+
+ const resp = await fetch(`${apiUrl}/projects`, { headers });
+
+ if (!resp.ok) {
+ throw new Error(`Failed to list projects: ${resp.status}`);
+ }
+
+ return resp.json();
+ }
+
+ static async get(projectId: string, opts: ProjectOpts = {}): Promise<ProjectInfo> {
+ const { apiUrl, headers } = getConfig(opts);
+
+ const resp = await fetch(`${apiUrl}/projects/${projectId}`, { headers });
+
+ if (!resp.ok) {
+ throw new Error(`Failed to get project: ${resp.status}`);
+ }
+
+ return resp.json();
+ }
+
+ static async update(projectId: string, opts: UpdateProjectOpts): Promise<ProjectInfo> {
+ const { apiUrl, headers } = getConfig(opts);
+
+ const body: Record<string, unknown> = {};
+ if (opts.name) body.name = opts.name;
+ if (opts.template) body.template = opts.template;
+ if (opts.cpuCount != null) body.cpuCount = opts.cpuCount;
+ if (opts.memoryMB != null) body.memoryMB = opts.memoryMB;
+ if (opts.timeoutSec != null) body.timeoutSec = opts.timeoutSec;
+ if (opts.egressAllowlist) body.egressAllowlist = opts.egressAllowlist;
+
+ const resp = await fetch(`${apiUrl}/projects/${projectId}`, {
+ method: "PUT",
+ headers,
+ body: JSON.stringify(body),
+ });
+
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to update project: ${resp.status} ${text}`);
+ }
+
+ return resp.json();
+ }
+
+ static async delete(projectId: string, opts: ProjectOpts = {}): Promise<void> {
+ const { apiUrl, headers } = getConfig(opts);
+
+ const resp = await fetch(`${apiUrl}/projects/${projectId}`, {
+ method: "DELETE",
+ headers,
+ });
+
+ if (!resp.ok) {
+ throw new Error(`Failed to delete project: ${resp.status}`);
+ }
+ }
+
+ // ── Secrets ──────────────────────────────────────────────────────────────
+
+ static async setSecret(projectId: string, name: string, value: string, opts: ProjectOpts = {}): Promise<void> {
+ const { apiUrl, headers } = getConfig(opts);
+
+ const resp = await fetch(`${apiUrl}/projects/${projectId}/secrets/${name}`, {
+ method: "PUT",
+ headers,
+ body: JSON.stringify({ value }),
+ });
+
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to set secret: ${resp.status} ${text}`);
+ }
+ }
+
+ static async deleteSecret(projectId: string, name: string, opts: ProjectOpts = {}): Promise<void> {
+ const { apiUrl, headers } = getConfig(opts);
+
+ const resp = await fetch(`${apiUrl}/projects/${projectId}/secrets/${name}`, {
+ method: "DELETE",
+ headers,
+ });
+
+ if (!resp.ok && resp.status !== 404) {
+ throw new Error(`Failed to delete secret: ${resp.status}`);
+ }
+ }
+
+ static async listSecrets(projectId: string, opts: ProjectOpts = {}): Promise<string[]> {
+ const { apiUrl, headers } = getConfig(opts);
+
+ const resp = await fetch(`${apiUrl}/projects/${projectId}/secrets`, { headers });
+
+ if (!resp.ok) {
+ throw new Error(`Failed to list secrets: ${resp.status}`);
+ }
+
+ return resp.json();
+ }
+}
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 7600e42d..2f99d868 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -17,6 +17,8 @@ export interface SandboxOpts {
metadata?: Record<string, string>;
cpuCount?: number;
memoryMB?: number;
+ /** Project name — inherits template, cpu, memory, timeout, and secrets from the project. */
+ project?: string;
}
interface SandboxData {
@@ -118,6 +120,7 @@ export class Sandbox {
if (opts.metadata) body.metadata = opts.metadata;
if (opts.cpuCount != null) body.cpuCount = opts.cpuCount;
if (opts.memoryMB != null) body.memoryMB = opts.memoryMB;
+ if (opts.project) body.project = opts.project;
const resp = await fetch(`${apiUrl}/sandboxes`, {
method: "POST",