An open-source, faster Devin alternative
TypeScript
rollout safety, tests, preserve subnet, anycast proxy
Brian Reardon9ceabb00bf6a
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 72de4f1b..b66866b6 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -126,6 +126,15 @@ func main() {if err != nil {log.Printf("opensandbox-worker: secrets proxy listen failed: %v", err)} else {+ // Make 169.254.169.253:3128 reachable from every TAP via lo. The+ // proxy already binds 0.0.0.0:3128 so this is just the host-side+ // address the kernel should answer. Without this, VMs created+ // with the new HTTPS_PROXY env (anycast) can't reach the proxy.+ if anyErr := secretsproxy.EnsureAnycastInterface(); anyErr != nil {+ log.Printf("opensandbox-worker: WARNING: failed to set up secrets-proxy anycast address (%v) — VMs with anycast HTTPS_PROXY env will lose outbound until this is fixed", anyErr)+ } else {+ log.Printf("opensandbox-worker: secrets-proxy anycast address %s assigned to lo", secretsproxy.AnycastIP)+ }secretsProxy.Start()defer secretsProxy.Stop()log.Println("opensandbox-worker: secrets proxy started on :3128")diff --git a/internal/api/projects.go b/internal/api/projects.goindex 55cc725d..791c216b 100644--- a/internal/api/projects.go+++ b/internal/api/projects.go@@ -11,6 +11,8 @@ import ("github.com/google/uuid""github.com/labstack/echo/v4"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/status""github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/db"@@ -326,6 +328,16 @@ func (s *Server) fanoutSecretRefresh(parentCtx context.Context, storeID uuid.UUIValue: newValue,})if err != nil {+ // Rollout safety: a worker that hasn't picked up the new binary yet+ // returns Unimplemented for this RPC. Treat as a soft skip — the+ // sandbox keeps its old value until its next handoff (wake/fork/+ // migrate) re-resolves from the store. This lets the server be+ // deployed before the worker fleet has fully rolled over without+ // every PUT /secrets call surfacing failures during the dance.+ if status.Code(err) == codes.Unimplemented {+ log.Printf("secret-refresh: worker %s on old binary (Unimplemented); skipping sandbox=%s, will refresh on next handoff", workerID, sandboxID)+ return result{sandboxID: sandboxID, ok: false}+ }return result{sandboxID: sandboxID, err: fmt.Errorf("worker %s rpc: %w", workerID, err)}}return result{sandboxID: sandboxID, ok: resp.Updated}diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 8f075634..121e08a9 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -371,10 +371,31 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn nil, fmt.Errorf("workspace not found at %s", workspacePath)}- // Step 3: Set up network- netCfg, err := m.subnets.Allocate()- if err != nil {- return nil, fmt.Errorf("allocate subnet: %w", err)+ // Step 3: Set up network. Prefer the original TAP/subnet so the gateway+ // IP remains stable across hibernate→wake cycles. The VM's HTTPS_PROXY+ // env var was baked at create time pointing at the original gateway IP+ // (e.g. 172.16.0.1). If wake reallocates a fresh subnet, the env still+ // points at the stale gateway and every outbound HTTPS through the+ // secrets proxy times out — silent breakage of the entire proxy path+ // for any sandbox with a secret store.+ //+ // Fall back to a fresh allocation if the original block was claimed by a+ // different sandbox while this one was hibernated. The fallback path+ // will leave HTTPS_PROXY stale, so log a clear warning — operators who+ // see this in journal know why post-wake outbound HTTPS is broken.+ var netCfg *NetworkConfig+ if meta.Network != nil && meta.Network.TAPName != "" {+ netCfg, err = m.subnets.AllocateSpecific(meta.Network.TAPName)+ if err != nil {+ log.Printf("qemu: wake %s: original TAP %q unavailable (%v) — falling back to fresh subnet; HTTPS_PROXY env will be stale, outbound HTTPS through proxy will fail until sandbox is recreated",+ sandboxID, meta.Network.TAPName, err)+ }+ }+ if netCfg == nil {+ netCfg, err = m.subnets.Allocate()+ if err != nil {+ return nil, fmt.Errorf("allocate subnet: %w", err)+ }}if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)diff --git a/internal/secretsproxy/proxy.go b/internal/secretsproxy/proxy.goindex 555cd0aa..df8a390d 100644--- a/internal/secretsproxy/proxy.go+++ b/internal/secretsproxy/proxy.go@@ -11,11 +11,52 @@ import ("log""net""net/http"+ "os/exec""strings""sync""time")+// AnycastAddr is the link-local IP every VM uses to reach the secrets proxy.+// One byte off the metadata server (169.254.169.254) so the two services have+// adjacent, easy-to-remember addresses.+//+// Why link-local instead of the per-VM TAP gateway: HTTPS_PROXY is baked into+// the VM env at create time. If we used the gateway IP, that env became stale+// the moment the VM moved to a different /30 subnet (wake → reallocated+// block, migrate → different worker's allocator). Customers saw "every+// outbound HTTPS times out post-handoff" because the env pointed at an+// unreachable address. Link-local is host-scoped, so each worker answers the+// same address locally — the env is correct on whichever host the VM lives on.+const (+ AnycastIP = "169.254.169.253"+ AnycastPort = 3128+)++// AnycastEndpoint returns the proxy URL VMs should use as HTTPS_PROXY.+func AnycastEndpoint() string {+ return fmt.Sprintf("http://%s:%d", AnycastIP, AnycastPort)+}++// EnsureAnycastInterface assigns AnycastIP to the loopback interface so the+// kernel answers it locally. Idempotent — succeeds even if already assigned+// (the underlying `ip addr add` returns "File exists" which we treat as ok).+//+// Worker startup must call this before sandboxes are created or the proxy+// won't be reachable at the stable address.+func EnsureAnycastInterface() error {+ cmd := exec.Command("ip", "addr", "add", AnycastIP+"/32", "dev", "lo")+ out, err := cmd.CombinedOutput()+ if err != nil {+ // "RTNETLINK answers: File exists" → already configured, fine.+ if strings.Contains(string(out), "File exists") {+ return nil+ }+ return fmt.Errorf("ip addr add %s/32 dev lo: %w (%s)", AnycastIP, err, strings.TrimSpace(string(out)))+ }+ return nil+}+// privateIPNets contains the CIDR ranges considered private/internal.// Connections to these ranges are blocked to prevent SSRF attacks.var privateIPNets []*net.IPNet@@ -307,7 +348,16 @@ func (p *SecretsProxy) CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, pl}// Merge into the env map for the VM. plaintextEnvs win on collision.- proxyURL := fmt.Sprintf("http://%s:3128", gatewayIP)+ //+ // Use the anycast link-local address (169.254.169.253:3128) instead of the+ // per-VM gateway IP. The env value is baked into the VM at create time and+ // must keep working through hibernate/wake (subnet may be reallocated) and+ // live migration (target worker has its own subnet allocator). Each worker+ // answers the anycast IP locally on lo (see EnsureAnycastInterface) so the+ // VM reaches the right proxy regardless of which host it's currently on.+ // gatewayIP is still a parameter for backwards compat / non-anycast paths.+ _ = gatewayIP+ proxyURL := AnycastEndpoint()caCertPath := "/usr/local/share/ca-certificates/opensandbox-proxy.crt"noProxy := "localhost,127.0.0.1,::1"diff --git a/internal/secretsproxy/proxy_test.go b/internal/secretsproxy/proxy_test.goindex d15e1cb9..624cfd28 100644--- a/internal/secretsproxy/proxy_test.go+++ b/internal/secretsproxy/proxy_test.go@@ -106,3 +106,148 @@ func TestCreateSealedEnvs_SecretsOnlyStillRegisters(t *testing.T) {t.Errorf("expected empty allowlist; got %v", sess.Allowlist)}}++// TestCreateSealedEnvs_NamesIndexBuilt asserts the env-var-name → sealed-token+// index is populated whenever a session is registered. UpdateSecretValue uses+// this index; if it isn't built, refresh-by-name silently misses every time.+func TestCreateSealedEnvs_NamesIndexBuilt(t *testing.T) {+ cases := []struct {+ name string+ secretEnvs map[string]string+ allowlist []string+ wantNames []string // env var names expected in session.Names+ guestIP string+ }{+ {+ name: "secrets only",+ secretEnvs: map[string]string{"API_KEY": "v1", "DB_URL": "v2"},+ allowlist: nil,+ wantNames: []string{"API_KEY", "DB_URL"},+ guestIP: "10.0.0.10",+ },+ {+ name: "secrets + allowlist",+ secretEnvs: map[string]string{"TOKEN": "v"},+ allowlist: []string{"api.example.com"},+ wantNames: []string{"TOKEN"},+ guestIP: "10.0.0.11",+ },+ {+ name: "allowlist only",+ secretEnvs: nil,+ allowlist: []string{"api.example.com"},+ wantNames: []string{}, // no secrets, no name entries — but session still exists+ guestIP: "10.0.0.12",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ p := newProxyForTest(t)+ p.CreateSealedEnvs("sb-"+tc.name, tc.guestIP, "10.0.0.1",+ nil, tc.secretEnvs, tc.allowlist, nil)+ sess := p.sessions[tc.guestIP]+ if sess == nil {+ t.Fatal("expected session to be registered")+ }+ if len(sess.Names) != len(tc.wantNames) {+ t.Errorf("session.Names len = %d, want %d (names=%v)", len(sess.Names), len(tc.wantNames), sess.Names)+ }+ for _, n := range tc.wantNames {+ token, ok := sess.Names[n]+ if !ok {+ t.Errorf("expected Names[%q] to be set", n)+ continue+ }+ // And the token must point back to a real entry in Secrets.+ if _, ok := sess.Secrets[token]; !ok {+ t.Errorf("Names[%q] = %q but Secrets has no such token (index out of sync)", n, token)+ }+ }+ })+ }+}++// TestUpdateSecretValue_HappyPath replaces the value the sealed token resolves+// to without changing the token id. Sandbox env vars stay the same; the next+// outbound HTTPS substitution uses the new value.+func TestUpdateSecretValue_HappyPath(t *testing.T) {+ p := newProxyForTest(t)+ p.CreateSealedEnvs("sb-update", "10.0.0.20", "10.0.0.1",+ nil,+ map[string]string{"API_KEY": "old-value"},+ nil, nil,+ )+ sess := p.sessions["10.0.0.20"]+ if sess == nil {+ t.Fatal("expected session")+ }+ originalToken, ok := sess.Names["API_KEY"]+ if !ok {+ t.Fatal("expected API_KEY in Names index")+ }++ if !p.UpdateSecretValue("sb-update", "API_KEY", "new-value") {+ t.Fatal("UpdateSecretValue returned false on a known sandbox+name")+ }++ // Sealed token id must NOT change — VM env vars hold this string.+ tokenAfter, ok := sess.Names["API_KEY"]+ if !ok || tokenAfter != originalToken {+ t.Errorf("sealed token id changed: before=%q after=%q (must be stable so guest env vars stay valid)", originalToken, tokenAfter)+ }+ if got := sess.Secrets[originalToken]; got != "new-value" {+ t.Errorf("Secrets[token] = %q, want %q", got, "new-value")+ }+}++// TestUpdateSecretValue_NameMiss covers a refresh for a name the session+// doesn't know about — possible mid-migration or if the customer added a new+// secret to the store after the sandbox was created (env vars are baked at+// create-time, so a brand new name has no sealed token in the session).+// Returns false; caller logs but doesn't treat as fatal.+func TestUpdateSecretValue_NameMiss(t *testing.T) {+ p := newProxyForTest(t)+ p.CreateSealedEnvs("sb-miss", "10.0.0.21", "10.0.0.1",+ nil,+ map[string]string{"API_KEY": "v"},+ nil, nil,+ )+ if p.UpdateSecretValue("sb-miss", "UNKNOWN_NAME", "x") {+ t.Error("UpdateSecretValue returned true for an unknown name; expected false")+ }+ // Existing secret untouched.+ sess := p.sessions["10.0.0.21"]+ tok := sess.Names["API_KEY"]+ if sess.Secrets[tok] != "v" {+ t.Errorf("existing secret value clobbered by miss; got %q", sess.Secrets[tok])+ }+}++// TestUpdateSecretValue_NoSession covers fanout to a worker that has no+// session for the sandbox — happens during the brief window where the source+// has unregistered post-migration but the destination hasn't re-registered+// yet, or when the worker simply isn't hosting the sandbox. Must not panic+// and must return false.+func TestUpdateSecretValue_NoSession(t *testing.T) {+ p := newProxyForTest(t)+ if p.UpdateSecretValue("sb-nope", "API_KEY", "x") {+ t.Error("UpdateSecretValue returned true with no registered session; expected false")+ }+}++// TestUpdateSecretValue_NamesNilNoPanic guards the "session exists but Names+// is nil" case — possible for sessions registered before the SealedNames+// index existed (e.g. a sandbox hibernated on an old binary, woken on a new+// one with no SealedNames in snapshot-meta.json). Must return false, not+// crash.+func TestUpdateSecretValue_NamesNilNoPanic(t *testing.T) {+ p := newProxyForTest(t)+ p.RegisterSession("10.0.0.22", &Session{+ SandboxID: "sb-legacy",+ Secrets: map[string]string{"osb_sealed_xxx": "value"},+ // Names intentionally nil — pre-fix session shape.+ })+ if p.UpdateSecretValue("sb-legacy", "API_KEY", "x") {+ t.Error("UpdateSecretValue returned true on a session with nil Names; expected false")+ }+}