Skip to content

An open-source, faster Devin alternative

TypeScript

Security hardening: egress allowlist enforcement, mTLS for gRPC, encryption key rotation

Brian Reardonce0f8a9db5e7
diff --git a/cmd/server/main.go b/cmd/server/main.go
index b5d44afc..b275ff61 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -60,14 +60,19 @@ func main() {
}
log.Println("opensandbox: database migrations complete")
- // Configure encryption for project secrets if key is provided
+ // Configure encryption for project secrets.
+ // Supports key rotation: OPENSANDBOX_SECRET_ENCRYPTION_KEY is the primary key,
+ // OPENSANDBOX_SECRET_ENCRYPTION_KEY_V1..V9 are previous keys for decrypting
+ // legacy secrets during rotation.
if cfg.SecretEncryptionKey != "" {
- enc, err := crypto.NewEncryptor(cfg.SecretEncryptionKey)
+ ring, err := crypto.NewKeyRingFromEnv()
if err != nil {
- log.Fatalf("invalid OPENSANDBOX_SECRET_ENCRYPTION_KEY: %v", err)
+ log.Fatalf("invalid encryption key config: %v", err)
+ }
+ if ring != nil {
+ store.SetEncryptor(ring.AsEncryptor())
+ log.Printf("opensandbox: project secret encryption configured (key version %d)", ring.PrimaryVersion())
}
- store.SetEncryptor(enc)
- log.Println("opensandbox: project secret encryption configured")
}
opts.Store = store
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index aff06d83..2ba4fd66 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -11,9 +11,10 @@ import (
"github.com/redis/go-redis/v9"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
- "google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
+ "github.com/opensandbox/opensandbox/internal/grpctls"
+
pb "github.com/opensandbox/opensandbox/proto/worker"
)
@@ -241,8 +242,13 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {
// dialWorkerLocked dials a gRPC connection to a worker. Must be called with r.mu held.
func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {
+ creds, err := grpctls.ClientCredentials()
+ if err != nil {
+ log.Printf("redis_registry: failed to load TLS credentials for worker %s: %v", workerID, err)
+ return
+ }
conn, err := grpc.NewClient(grpcAddr,
- grpc.WithTransportCredentials(insecure.NewCredentials()),
+ grpc.WithTransportCredentials(creds),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: 30 * time.Second,
Timeout: 10 * time.Second,
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index f3048712..ac3aa986 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -10,10 +10,10 @@ import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"google.golang.org/grpc"
- "google.golang.org/grpc/credentials/insecure"
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/grpctls"
pb "github.com/opensandbox/opensandbox/proto/worker"
)
@@ -122,6 +122,7 @@ func (s *Server) createSandbox(c echo.Context) error {
// Resolve project: inherit config defaults + decrypt and merge secrets
var projectID *string
+ var egressAllowlist []string
if req.Project != "" {
project, err := s.store.GetProjectByName(c.Request().Context(), orgID, req.Project)
if err != nil {
@@ -144,6 +145,9 @@ func (s *Server) createSandbox(c echo.Context) error {
req.Timeout = project.TimeoutSec
}
+ // Inherit egress allowlist from project
+ egressAllowlist = project.EgressAllowlist
+
// 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 {
@@ -183,7 +187,11 @@ func (s *Server) createSandbox(c echo.Context) error {
ctx, cancel := context.WithTimeout(c.Request().Context(), 60*time.Second)
defer cancel()
- conn, err := grpc.NewClient(worker.GRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ creds, err := grpctls.ClientCredentials()
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to load TLS credentials"})
+ }
+ conn, err := grpc.NewClient(worker.GRPCAddr, grpc.WithTransportCredentials(creds))
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to connect to worker"})
}
@@ -191,12 +199,13 @@ func (s *Server) createSandbox(c echo.Context) error {
client := pb.NewSandboxWorkerClient(conn)
grpcResp, err := client.CreateSandbox(ctx, &pb.CreateSandboxRequest{
- Template: req.TemplateID,
- Timeout: int32(req.Timeout),
- Envs: req.Envs,
- MemoryMb: int32(req.MemoryMB),
- CpuCount: int32(req.CpuCount),
- NetworkEnabled: req.NetworkEnabled,
+ Template: req.TemplateID,
+ Timeout: int32(req.Timeout),
+ Envs: req.Envs,
+ MemoryMb: int32(req.MemoryMB),
+ CpuCount: int32(req.CpuCount),
+ NetworkEnabled: req.NetworkEnabled,
+ EgressAllowlist: egressAllowlist,
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "worker create failed: " + err.Error()})
@@ -285,7 +294,11 @@ func (s *Server) destroySandbox(c echo.Context) error {
ctx, cancel := context.WithTimeout(c.Request().Context(), 10*time.Second)
defer cancel()
- conn, err := grpc.NewClient(worker.GRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ creds2, err := grpctls.ClientCredentials()
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to load TLS credentials"})
+ }
+ conn, err := grpc.NewClient(worker.GRPCAddr, grpc.WithTransportCredentials(creds2))
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to connect to worker"})
}
diff --git a/internal/crypto/encrypt.go b/internal/crypto/encrypt.go
index b225b990..cb87d38b 100644
--- a/internal/crypto/encrypt.go
+++ b/internal/crypto/encrypt.go
@@ -11,8 +11,10 @@ import (
)
// Encryptor provides AES-256-GCM encryption/decryption using a 32-byte key.
+// If keyRing is set, Encrypt/Decrypt delegate to it for versioned key support.
type Encryptor struct {
- gcm cipher.AEAD
+ gcm cipher.AEAD
+ keyRing *KeyRing // non-nil when created via KeyRing.AsEncryptor()
}
// NewEncryptor creates an Encryptor from a hex-encoded 32-byte key.
@@ -39,7 +41,11 @@ func NewEncryptor(hexKey string) (*Encryptor, error) {
}
// Encrypt returns nonce || ciphertext (suitable for storing as BYTEA).
+// If a KeyRing is attached, delegates to it for versioned encryption.
func (e *Encryptor) Encrypt(plaintext []byte) ([]byte, error) {
+ if e.keyRing != nil {
+ return e.keyRing.Encrypt(plaintext)
+ }
nonce := make([]byte, e.gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("generate nonce: %w", err)
@@ -48,7 +54,11 @@ func (e *Encryptor) Encrypt(plaintext []byte) ([]byte, error) {
}
// Decrypt expects nonce || ciphertext as produced by Encrypt.
+// If a KeyRing is attached, delegates to it for versioned decryption.
func (e *Encryptor) Decrypt(data []byte) ([]byte, error) {
+ if e.keyRing != nil {
+ return e.keyRing.Decrypt(data)
+ }
nonceSize := e.gcm.NonceSize()
if len(data) < nonceSize {
return nil, fmt.Errorf("ciphertext too short")
diff --git a/internal/crypto/keyring.go b/internal/crypto/keyring.go
new file mode 100644
index 00000000..180e010a
--- /dev/null
+++ b/internal/crypto/keyring.go
@@ -0,0 +1,91 @@
+package crypto
+
+import (
+ "encoding/binary"
+ "fmt"
+)
+
+// KeyRing holds multiple versioned encryption keys. New data is always encrypted
+// with the primary (highest-version) key; decryption tries the key matching the
+// version stored in the ciphertext header.
+//
+// Ciphertext format: [2-byte big-endian version] [nonce] [AES-256-GCM ciphertext]
+//
+// Configuration:
+//
+// OPENSANDBOX_SECRET_ENCRYPTION_KEY — primary key (hex, required)
+// OPENSANDBOX_SECRET_ENCRYPTION_KEY_V1 — previous key for rotation (hex, optional)
+// OPENSANDBOX_SECRET_ENCRYPTION_KEY_V2 — etc.
+type KeyRing struct {
+ primary *Encryptor
+ primaryVersion uint16
+ keys map[uint16]*Encryptor
+}
+
+// NewKeyRing creates a KeyRing from versioned keys. The map must contain at least
+// one key. The highest version is used for encryption.
+func NewKeyRing(keys map[uint16]string) (*KeyRing, error) {
+ if len(keys) == 0 {
+ return nil, fmt.Errorf("keyring: at least one key is required")
+ }
+
+ ring := &KeyRing{keys: make(map[uint16]*Encryptor, len(keys))}
+ for ver, hexKey := range keys {
+ enc, err := NewEncryptor(hexKey)
+ if err != nil {
+ return nil, fmt.Errorf("keyring: key v%d: %w", ver, err)
+ }
+ ring.keys[ver] = enc
+ if ring.primary == nil || ver > ring.primaryVersion {
+ ring.primary = enc
+ ring.primaryVersion = ver
+ }
+ }
+ return ring, nil
+}
+
+// Encrypt encrypts data with the primary key, prepending the version header.
+func (r *KeyRing) Encrypt(plaintext []byte) ([]byte, error) {
+ inner, err := r.primary.Encrypt(plaintext)
+ if err != nil {
+ return nil, err
+ }
+ out := make([]byte, 2+len(inner))
+ binary.BigEndian.PutUint16(out[:2], r.primaryVersion)
+ copy(out[2:], inner)
+ return out, nil
+}
+
+// Decrypt reads the version header and decrypts with the matching key.
+// Falls back to the primary key for legacy data without a version header
+// (ciphertext shorter than expected or version 0 with no v0 key registered).
+func (r *KeyRing) Decrypt(data []byte) ([]byte, error) {
+ // Legacy unversioned data: try primary key directly
+ if len(data) < 2 {
+ return r.primary.Decrypt(data)
+ }
+
+ ver := binary.BigEndian.Uint16(data[:2])
+ if enc, ok := r.keys[ver]; ok {
+ result, err := enc.Decrypt(data[2:])
+ if err == nil {
+ return result, nil
+ }
+ // If versioned decrypt fails, fall through to legacy
+ }
+
+ // Legacy fallback: data may not have a version header (pre-rotation secrets).
+ // Try primary key on the full blob.
+ return r.primary.Decrypt(data)
+}
+
+// PrimaryVersion returns the version number of the active encryption key.
+func (r *KeyRing) PrimaryVersion() uint16 {
+ return r.primaryVersion
+}
+
+// AsEncryptor returns an Encryptor-compatible wrapper so the KeyRing can be
+// used anywhere an Encryptor is expected without changing call sites.
+func (r *KeyRing) AsEncryptor() *Encryptor {
+ return &Encryptor{gcm: r.primary.gcm, keyRing: r}
+}
diff --git a/internal/crypto/keyring_env.go b/internal/crypto/keyring_env.go
new file mode 100644
index 00000000..c1d90903
--- /dev/null
+++ b/internal/crypto/keyring_env.go
@@ -0,0 +1,45 @@
+package crypto
+
+import (
+ "fmt"
+ "os"
+)
+
+// NewKeyRingFromEnv builds a KeyRing from environment variables:
+//
+// OPENSANDBOX_SECRET_ENCRYPTION_KEY — primary key (version 0 if no _V* keys exist)
+// OPENSANDBOX_SECRET_ENCRYPTION_KEY_V1 — version 1
+// OPENSANDBOX_SECRET_ENCRYPTION_KEY_V2 — version 2 (highest = primary)
+// ...up to V9
+//
+// Returns nil if no key is configured.
+func NewKeyRingFromEnv() (*KeyRing, error) {
+ baseKey := os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY")
+ if baseKey == "" {
+ return nil, nil
+ }
+
+ keys := make(map[uint16]string)
+
+ // Check for versioned keys V1..V9
+ hasVersioned := false
+ for v := uint16(1); v <= 9; v++ {
+ envKey := fmt.Sprintf("OPENSANDBOX_SECRET_ENCRYPTION_KEY_V%d", v)
+ if hexKey := os.Getenv(envKey); hexKey != "" {
+ keys[v] = hexKey
+ hasVersioned = true
+ }
+ }
+
+ if hasVersioned {
+ // If versioned keys exist, the base key is used as the fallback for
+ // legacy (unversioned) data. Assign it as version 0 so KeyRing.Decrypt
+ // can find it for legacy blobs, but the highest V* key becomes primary.
+ keys[0] = baseKey
+ } else {
+ // No versioned keys — single-key mode. Version 1.
+ keys[1] = baseKey
+ }
+
+ return NewKeyRing(keys)
+}
diff --git a/internal/crypto/keyring_test.go b/internal/crypto/keyring_test.go
new file mode 100644
index 00000000..7be42a0d
--- /dev/null
+++ b/internal/crypto/keyring_test.go
@@ -0,0 +1,110 @@
+package crypto
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "testing"
+)
+
+func randomHexKey() string {
+ key := make([]byte, 32)
+ rand.Read(key)
+ return hex.EncodeToString(key)
+}
+
+func TestKeyRingEncryptDecrypt(t *testing.T) {
+ ring, err := NewKeyRing(map[uint16]string{
+ 1: randomHexKey(),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ plaintext := []byte("super-secret-api-key")
+ ct, err := ring.Encrypt(plaintext)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ got, err := ring.Decrypt(ct)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(got) != string(plaintext) {
+ t.Errorf("got %q, want %q", got, plaintext)
+ }
+}
+
+func TestKeyRingRotation(t *testing.T) {
+ oldKey := randomHexKey()
+ newKey := randomHexKey()
+
+ // Encrypt with old key (v1)
+ oldRing, _ := NewKeyRing(map[uint16]string{1: oldKey})
+ ct, _ := oldRing.Encrypt([]byte("old-secret"))
+
+ // Create new ring with both keys (v2 is primary)
+ newRing, _ := NewKeyRing(map[uint16]string{
+ 1: oldKey,
+ 2: newKey,
+ })
+
+ // Should decrypt old data
+ got, err := newRing.Decrypt(ct)
+ if err != nil {
+ t.Fatalf("decrypt old ciphertext with rotated keyring: %v", err)
+ }
+ if string(got) != "old-secret" {
+ t.Errorf("got %q, want %q", got, "old-secret")
+ }
+
+ // New encryption uses v2
+ ct2, _ := newRing.Encrypt([]byte("new-secret"))
+ got2, _ := newRing.Decrypt(ct2)
+ if string(got2) != "new-secret" {
+ t.Errorf("got %q, want %q", got2, "new-secret")
+ }
+
+ // Verify primary version is 2
+ if newRing.PrimaryVersion() != 2 {
+ t.Errorf("primary version = %d, want 2", newRing.PrimaryVersion())
+ }
+}
+
+func TestKeyRingLegacyFallback(t *testing.T) {
+ key := randomHexKey()
+
+ // Encrypt without keyring (legacy format: no version header)
+ enc, _ := NewEncryptor(key)
+ ct, _ := enc.Encrypt([]byte("legacy-data"))
+
+ // KeyRing should still decrypt legacy data via fallback
+ ring, _ := NewKeyRing(map[uint16]string{1: key})
+ got, err := ring.Decrypt(ct)
+ if err != nil {
+ t.Fatalf("decrypt legacy ciphertext: %v", err)
+ }
+ if string(got) != "legacy-data" {
+ t.Errorf("got %q, want %q", got, "legacy-data")
+ }
+}
+
+func TestKeyRingAsEncryptor(t *testing.T) {
+ key := randomHexKey()
+ ring, _ := NewKeyRing(map[uint16]string{1: key})
+
+ // AsEncryptor returns an Encryptor that delegates to the KeyRing
+ enc := ring.AsEncryptor()
+ ct, err := enc.Encrypt([]byte("via-encryptor"))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ got, err := enc.Decrypt(ct)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(got) != "via-encryptor" {
+ t.Errorf("got %q, want %q", got, "via-encryptor")
+ }
+}
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 282d8e2a..aeb73814 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -435,7 +435,7 @@ func (m *Manager) createWithID(ctx context.Context, id string, cfg types.Sandbox
// 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)
+ sealedEnvs := m.secretsProxy.CreateSealedEnvs(id, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, nil)
if sealedEnvs != nil {
envsToInject = sealedEnvs
// Redirect VM HTTPS traffic through the proxy
diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.go
index 15bfd612..c9e5adb6 100644
--- a/internal/firecracker/snapshot.go
+++ b/internal/firecracker/snapshot.go
@@ -1877,7 +1877,7 @@ func (m *Manager) warmForkFromCheckpoint(ctx context.Context, checkpointID strin
// 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)
+ sealedEnvs := m.secretsProxy.CreateSealedEnvs(newID, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, nil)
if sealedEnvs != nil {
envsToInject = sealedEnvs
if err := AddProxyRedirect(netCfg); err != nil {
@@ -2357,7 +2357,7 @@ func (m *Manager) createFromGoldenSnapshot(ctx context.Context, id string, cfg t
// 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)
+ sealedEnvs := m.secretsProxy.CreateSealedEnvs(id, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, nil)
if sealedEnvs != nil {
envsToInject = sealedEnvs
if err := AddProxyRedirect(netCfg); err != nil {
diff --git a/internal/grpctls/grpctls.go b/internal/grpctls/grpctls.go
new file mode 100644
index 00000000..94cee7ff
--- /dev/null
+++ b/internal/grpctls/grpctls.go
@@ -0,0 +1,101 @@
+// Package grpctls provides mTLS configuration for gRPC connections between
+// the control plane and workers. Both sides authenticate using certificates
+// signed by a shared CA.
+//
+// Configuration via environment variables:
+//
+// OPENSANDBOX_GRPC_TLS_CA — path to CA certificate (PEM)
+// OPENSANDBOX_GRPC_TLS_CERT — path to own certificate (PEM)
+// OPENSANDBOX_GRPC_TLS_KEY — path to own private key (PEM)
+//
+// If any of these are unset, TLS is disabled and insecure credentials are used.
+package grpctls
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "fmt"
+ "os"
+
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/credentials/insecure"
+)
+
+// ServerCredentials returns gRPC server transport credentials.
+// If TLS is not configured, returns insecure credentials.
+func ServerCredentials() (credentials.TransportCredentials, error) {
+ caPath, certPath, keyPath := paths()
+ if caPath == "" || certPath == "" || keyPath == "" {
+ return insecure.NewCredentials(), nil
+ }
+
+ cert, err := tls.LoadX509KeyPair(certPath, keyPath)
+ if err != nil {
+ return nil, fmt.Errorf("grpctls: load server cert: %w", err)
+ }
+
+ caPool, err := loadCAPool(caPath)
+ if err != nil {
+ return nil, err
+ }
+
+ cfg := &tls.Config{
+ Certificates: []tls.Certificate{cert},
+ ClientCAs: caPool,
+ ClientAuth: tls.RequireAndVerifyClientCert,
+ MinVersion: tls.VersionTLS13,
+ }
+
+ return credentials.NewTLS(cfg), nil
+}
+
+// ClientCredentials returns gRPC client transport credentials.
+// If TLS is not configured, returns insecure credentials.
+func ClientCredentials() (credentials.TransportCredentials, error) {
+ caPath, certPath, keyPath := paths()
+ if caPath == "" || certPath == "" || keyPath == "" {
+ return insecure.NewCredentials(), nil
+ }
+
+ cert, err := tls.LoadX509KeyPair(certPath, keyPath)
+ if err != nil {
+ return nil, fmt.Errorf("grpctls: load client cert: %w", err)
+ }
+
+ caPool, err := loadCAPool(caPath)
+ if err != nil {
+ return nil, err
+ }
+
+ cfg := &tls.Config{
+ Certificates: []tls.Certificate{cert},
+ RootCAs: caPool,
+ MinVersion: tls.VersionTLS13,
+ }
+
+ return credentials.NewTLS(cfg), nil
+}
+
+// Enabled returns true if all three TLS env vars are set.
+func Enabled() bool {
+ ca, cert, key := paths()
+ return ca != "" && cert != "" && key != ""
+}
+
+func paths() (ca, cert, key string) {
+ return os.Getenv("OPENSANDBOX_GRPC_TLS_CA"),
+ os.Getenv("OPENSANDBOX_GRPC_TLS_CERT"),
+ os.Getenv("OPENSANDBOX_GRPC_TLS_KEY")
+}
+
+func loadCAPool(caPath string) (*x509.CertPool, error) {
+ caPEM, err := os.ReadFile(caPath)
+ if err != nil {
+ return nil, fmt.Errorf("grpctls: read CA cert: %w", err)
+ }
+ pool := x509.NewCertPool()
+ if !pool.AppendCertsFromPEM(caPEM) {
+ return nil, fmt.Errorf("grpctls: CA cert %s contains no valid certificates", caPath)
+ }
+ return pool, nil
+}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 442c424a..7a957dee 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -16,6 +16,7 @@ import (
"google.golang.org/grpc/keepalive"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/grpctls"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/sparse"
"github.com/opensandbox/opensandbox/internal/storage"
@@ -39,7 +40,29 @@ type GRPCServer struct {
}
// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.
+// If OPENSANDBOX_GRPC_TLS_* env vars are set, the server uses mTLS.
func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder, store *db.Store) *GRPCServer {
+ serverOpts := []grpc.ServerOption{
+ grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
+ MinTime: 5 * time.Second,
+ PermitWithoutStream: true,
+ }),
+ grpc.KeepaliveParams(keepalive.ServerParameters{
+ Time: 30 * time.Second,
+ Timeout: 10 * time.Second,
+ }),
+ }
+
+ // Enable mTLS if configured
+ if grpctls.Enabled() {
+ creds, err := grpctls.ServerCredentials()
+ if err != nil {
+ log.Fatalf("grpc: failed to load TLS credentials: %v", err)
+ }
+ serverOpts = append(serverOpts, grpc.Creds(creds))
+ log.Println("grpc: mTLS enabled for worker gRPC server")
+ }
+
s := &GRPCServer{
manager: mgr,
router: router,
@@ -49,16 +72,7 @@ func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *san
checkpointStore: checkpointStore,
builder: builder,
store: store,
- server: grpc.NewServer(
- grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
- MinTime: 5 * time.Second,
- PermitWithoutStream: true,
- }),
- grpc.KeepaliveParams(keepalive.ServerParameters{
- Time: 30 * time.Second,
- Timeout: 10 * time.Second,
- }),
- ),
+ server: grpc.NewServer(serverOpts...),
}
pb.RegisterSandboxWorkerServer(s.server, s)
return s
@@ -80,15 +94,16 @@ func (s *GRPCServer) Stop() {
func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxRequest) (*pb.CreateSandboxResponse, error) {
cfg := types.SandboxConfig{
- Template: req.Template,
- Timeout: int(req.Timeout),
- Envs: req.Envs,
- MemoryMB: int(req.MemoryMb),
- CpuCount: int(req.CpuCount),
- NetworkEnabled: req.NetworkEnabled,
- ImageRef: req.ImageRef,
- Port: int(req.Port),
- SandboxID: req.SandboxId, // use server-assigned ID if provided
+ Template: req.Template,
+ Timeout: int(req.Timeout),
+ Envs: req.Envs,
+ MemoryMB: int(req.MemoryMb),
+ CpuCount: int(req.CpuCount),
+ NetworkEnabled: req.NetworkEnabled,
+ ImageRef: req.ImageRef,
+ Port: int(req.Port),
+ SandboxID: req.SandboxId, // use server-assigned ID if provided
+ EgressAllowlist: req.EgressAllowlist,
}
// Warm fork: if checkpoint_id is set, try snapshot-based fork first.
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index 8019395d..5d92b055 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -48,6 +48,10 @@ type SandboxConfig struct {
TemplateWorkspaceKey string `json:"templateWorkspaceKey,omitempty"`
// Project name — resolves config defaults + secrets from the project.
Project string `json:"project,omitempty"`
+ // EgressAllowlist restricts outbound HTTPS from the sandbox to these hosts.
+ // Supports exact matches ("api.anthropic.com") and wildcards ("*.openai.com").
+ // Empty = all hosts allowed (no restriction).
+ EgressAllowlist []string `json:"egressAllowlist,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/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 4e096f66..a98108ed 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
-// protoc v7.34.0
+// protoc v6.33.4
// source: proto/worker/worker.proto
package worker
@@ -83,9 +83,13 @@ type CreateSandboxRequest struct {
// If set, attempt warm fork from local checkpoint snapshot (LoadSnapshot instead of cold boot).
CheckpointId string `protobuf:"bytes,11,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"`
// Server-assigned sandbox ID. If non-empty, worker uses this instead of generating one.
- SandboxId string `protobuf:"bytes,12,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ SandboxId string `protobuf:"bytes,12,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ // Egress allowlist: restrict outbound HTTPS to these hosts.
+ // Supports exact ("api.anthropic.com") and wildcard ("*.openai.com") patterns.
+ // Empty = all hosts allowed.
+ EgressAllowlist []string `protobuf:"bytes,13,rep,name=egress_allowlist,json=egressAllowlist,proto3" json:"egress_allowlist,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *CreateSandboxRequest) Reset() {
@@ -202,6 +206,13 @@ func (x *CreateSandboxRequest) GetSandboxId() string {
return ""
}
+func (x *CreateSandboxRequest) GetEgressAllowlist() []string {
+ if x != nil {
+ return x.EgressAllowlist
+ }
+ return nil
+}
+
type CreateSandboxResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -2576,7 +2587,7 @@ var File_proto_worker_worker_proto protoreflect.FileDescriptor
const file_proto_worker_worker_proto_rawDesc = "" +
"\n" +
- "\x19proto/worker/worker.proto\x12\x06worker\"\xff\x03\n" +
+ "\x19proto/worker/worker.proto\x12\x06worker\"\xaa\x04\n" +
"\x14CreateSandboxRequest\x12\x1a\n" +
"\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +
"\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +
@@ -2591,7 +2602,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
" \x01(\tR\x14templateWorkspaceKey\x12#\n" +
"\rcheckpoint_id\x18\v \x01(\tR\fcheckpointId\x12\x1d\n" +
"\n" +
- "sandbox_id\x18\f \x01(\tR\tsandboxId\x1a7\n" +
+ "sandbox_id\x18\f \x01(\tR\tsandboxId\x12)\n" +
+ "\x10egress_allowlist\x18\r \x03(\tR\x0fegressAllowlist\x1a7\n" +
"\tEnvsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"N\n" +
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 91acad5f..32a075bb 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -53,6 +53,10 @@ message CreateSandboxRequest {
string checkpoint_id = 11;
// Server-assigned sandbox ID. If non-empty, worker uses this instead of generating one.
string sandbox_id = 12;
+ // Egress allowlist: restrict outbound HTTPS to these hosts.
+ // Supports exact ("api.anthropic.com") and wildcard ("*.openai.com") patterns.
+ // Empty = all hosts allowed.
+ repeated string egress_allowlist = 13;
}
message CreateSandboxResponse {
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
index 9696af6d..99375341 100644
--- a/proto/worker/worker_grpc.pb.go
+++ b/proto/worker/worker_grpc.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
-// - protoc v7.34.0
+// - protoc v6.33.4
// source: proto/worker/worker.proto
package worker