carlos / platform Public

Require owner expectations for every devbox socket request

Refuse unknown devbox sockets while preserving ordinary edge behavior.
Strip visitor trailers, bound identity lookups, and verify real Unix
upgrades. Document the config contracts and connection-reuse constraint.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d07e7ad41a684640ae1979a026d9ebb94f296c66 parent 1a04d83
3 files changed, +257 −20
  • internal/edge/devbox.go +13 −3
  • internal/edge/devboxfront.go +31 −2
  • internal/edge/devboxfront_test.go +213 −15

CI failed — run details

diff --git a/internal/edge/devbox.go b/internal/edge/devbox.go
index d2a45846a..6987d871f 100644
--- a/internal/edge/devbox.go
+++ b/internal/edge/devbox.go
@@ -36,9 +36,19 @@ import (
// wildcard parent and the DNS provider come from the environment Run already
// reads (CARLOS_WILDCARD_DOMAINS, CARLOS_DNS_PROVIDER and its credential).
type DevboxConfig struct {
- Identity VisitorIdentity
- SharedNodes []string
- AllowFor func(host string) []string
+ // Identity resolves visitors; nil, errors and timeouts mean anonymous.
+ // Who must honor its context, which has a maximum two-second deadline.
+ Identity VisitorIdentity
+ // SharedNodes names devices whose visitors are anonymous, matched
+ // case-insensitively. The ListenAddr IP is always anonymous too.
+ SharedNodes []string
+ // AllowFor reads the current login list for the unmodified request Host.
+ // A nil callback or empty list allows anonymous visitors.
+ AllowFor func(host string) []string
+ // SocketOwnerFor returns the expected socket path and listener UID for
+ // the unmodified request Host. Nil or ok=false refuses socket routes.
+ // Each socket request uses a fresh connection and peer-UID check: pooling
+ // would let an earlier connection bypass a changed owner expectation.
SocketOwnerFor func(host string) (path string, uid uint32, ok bool)
Registry *registry.Registry
ListenAddr string // host:port; host must be a specific IP
diff --git a/internal/edge/devboxfront.go b/internal/edge/devboxfront.go
index 986a86578..db3345e5b 100644
--- a/internal/edge/devboxfront.go
+++ b/internal/edge/devboxfront.go
@@ -5,17 +5,21 @@ import (
"errors"
"fmt"
"html"
+ "io"
"net"
"net/http"
"net/http/httputil"
"net/netip"
"strings"
+ "time"
)
// These are http.StatusText(http.StatusForbidden) until DBX-C107/C108 are approved.
const devboxPrivateTitle = "Forbidden"
const devboxPrivateSentence = "Forbidden"
+const devboxIdentityTimeout = 2 * time.Second
+
type devboxFrontKey struct{}
type devboxSocketOwner struct {
@@ -31,14 +35,20 @@ type devboxFrontRequest struct {
func devboxFront(next http.Handler, cfg DevboxConfig, selfIP netip.Addr) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
stripVisitorHeaders(r.Header)
+ stripVisitorHeaders(r.Trailer)
+ if r.Body != nil && r.Body != http.NoBody {
+ r.Body = &devboxTrailerBody{ReadCloser: r.Body, request: r}
+ }
var visitor Visitor
var known bool
remote, err := netip.ParseAddrPort(r.RemoteAddr)
if err == nil {
remote = netip.AddrPortFrom(remote.Addr().Unmap(), remote.Port())
if cfg.Identity != nil {
- visitor, known, err = cfg.Identity.Who(r.Context(), remote)
- known = known && err == nil
+ lookupCtx, cancel := context.WithTimeout(r.Context(), devboxIdentityTimeout)
+ visitor, known, err = cfg.Identity.Who(lookupCtx, remote)
+ known = known && err == nil && lookupCtx.Err() == nil
+ cancel()
}
if anonymousSource(remote.Addr(), selfIP, visitor, cfg.SharedNodes) {
known = false
@@ -77,6 +87,21 @@ func devboxFront(next http.Handler, cfg DevboxConfig, selfIP netip.Addr) http.Ha
})
}
+// HTTP request trailers are populated at EOF. Strip again before a handler
+// can read them; stripping only the initial declarations leaves late values.
+type devboxTrailerBody struct {
+ io.ReadCloser
+ request *http.Request
+}
+
+func (b *devboxTrailerBody) Read(p []byte) (int, error) {
+ n, err := b.ReadCloser.Read(p)
+ if err == io.EOF {
+ stripVisitorHeaders(b.request.Trailer)
+ }
+ return n, err
+}
+
func stripVisitorHeaders(h http.Header) {
for key := range h {
if strings.EqualFold(key, "Carlos-Visitor-Login") || strings.EqualFold(key, "Carlos-Visitor-Name") || strings.EqualFold(key, "Carlos-Visitor-Node") {
@@ -117,6 +142,7 @@ func configureDevboxProxy(p *httputil.ReverseProxy, socketPath string) {
rewrite := p.Rewrite
p.Rewrite = func(pr *httputil.ProxyRequest) {
rewrite(pr)
+ stripVisitorHeaders(pr.Out.Trailer)
if front, ok := pr.In.Context().Value(devboxFrontKey{}).(devboxFrontRequest); ok {
stripVisitorHeaders(pr.Out.Header)
if front.visitor != nil {
@@ -138,6 +164,9 @@ func (t devboxProxyTransport) RoundTrip(r *http.Request) (*http.Response, error)
front, _ := r.Context().Value(devboxFrontKey{}).(devboxFrontRequest)
expected := front.socketOwner
if expected == nil {
+ if t.socketPath != "" {
+ return nil, errDevboxSocketOwner
+ }
return t.base.RoundTrip(r)
}
if t.socketPath == "" || t.socketPath != expected.path {
diff --git a/internal/edge/devboxfront_test.go b/internal/edge/devboxfront_test.go
index b5ad5e0e2..4ee7bd882 100644
--- a/internal/edge/devboxfront_test.go
+++ b/internal/edge/devboxfront_test.go
@@ -1,8 +1,11 @@
package edge
import (
+ "bufio"
"context"
"errors"
+ "fmt"
+ "io"
"net"
"net/http"
"net/http/httptest"
@@ -13,6 +16,8 @@ import (
"strings"
"sync/atomic"
"testing"
+ "testing/synctest"
+ "time"
"github.com/carlosframework/platform/internal/registry"
)
@@ -296,7 +301,6 @@ func TestDevboxFrontUnixUpstreamIdentityAndOwner(t *testing.T) {
{"uid mismatch after success", path, uint32(os.Getuid()) + 1, http.StatusBadGateway},
{"path mismatch", path + ".other", uint32(os.Getuid()), http.StatusBadGateway},
{"match again", path, uint32(os.Getuid()), http.StatusNoContent},
- {"upgrade", path, uint32(os.Getuid()), http.StatusNoContent},
} {
t.Run(step.name, func(t *testing.T) {
wantPath, wantUID = step.path, step.uid
@@ -305,13 +309,7 @@ func TestDevboxFrontUnixUpstreamIdentityAndOwner(t *testing.T) {
r.Header.Set("Carlos-Visitor-Login", "mallory@github")
r.Header["cArLoS-vIsItOr-LoGiN"] = []string{"forged"}
r.Header.Set("Connection", "Carlos-Visitor-Login, Carlos-Visitor-Name, Carlos-Visitor-Node")
- if step.name == "upgrade" {
- if err := e.Reload(); err != nil {
- t.Fatal(err)
- }
- r.Header.Add("Connection", "Upgrade")
- r.Header.Set("Upgrade", "websocket")
- }
+
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != step.code {
@@ -319,8 +317,8 @@ func TestDevboxFrontUnixUpstreamIdentityAndOwner(t *testing.T) {
}
})
}
- if calls.Load() != 3 {
- t.Fatalf("upstream calls=%d, want 3", calls.Load())
+ if calls.Load() != 2 {
+ t.Fatalf("upstream calls=%d, want 2", calls.Load())
}
}
@@ -397,20 +395,47 @@ func TestFrontSelfStillLooksUpIdentity(t *testing.T) {
}
func TestDevboxSocketExpectationAbsent(t *testing.T) {
- path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }))
+ var calls atomic.Int32
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ w.WriteHeader(http.StatusNoContent)
+ }))
reg := openReg(t)
if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil {
t.Fatal(err)
}
- cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), SocketOwnerFor: func(string) (string, uint32, bool) { return "ignored", ^uint32(0), false }}
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir()}
e, err := newDevboxEdge(cfg)
if err != nil {
t.Fatal(err)
}
+ for _, mode := range []string{"nil callback", "unknown host", "no front door"} {
+ t.Run(mode, func(t *testing.T) {
+ if mode == "unknown host" {
+ cfg.SocketOwnerFor = func(string) (string, uint32, bool) { return "ignored", ^uint32(0), false }
+ }
+ var h http.Handler = devboxFront(e, cfg, frontSelf)
+ if mode == "no front door" {
+ h = e
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, frontRequest())
+ if w.Code != http.StatusBadGateway {
+ t.Errorf("code=%d want=502", w.Code)
+ }
+ })
+ }
+ if got := calls.Load(); got != 0 {
+ t.Errorf("unchecked upstream calls=%d want=0", got)
+ }
+ ordinary, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
w := httptest.NewRecorder()
- devboxFront(e, cfg, frontSelf).ServeHTTP(w, frontRequest())
- if w.Code != http.StatusNoContent {
- t.Fatalf("code=%d want=204", w.Code)
+ ordinary.ServeHTTP(w, frontRequest())
+ if w.Code != http.StatusNoContent || calls.Load() != 1 {
+ t.Errorf("ordinary edge code=%d calls=%d want=204,1", w.Code, calls.Load())
}
}
@@ -446,3 +471,176 @@ func TestFrontPrintableASCIIBoundaries(t *testing.T) {
}
}), DevboxConfig{Identity: frontIdentity(v)}, frontSelf).ServeHTTP(httptest.NewRecorder(), frontRequest())
}
+
+func frontTrailerRequest(t *testing.T) *http.Request {
+ t.Helper()
+ raw := "POST / HTTP/1.1\r\nHost: shop.example.com\r\nTransfer-Encoding: chunked\r\nTrailer: Carlos-Visitor-Login, Carlos-Visitor-Name, Carlos-Visitor-Node, X-Other\r\n\r\n" +
+ "4\r\nbody\r\n0\r\ncArLoS-vIsItOr-LoGiN: mallory@github\r\ncarlos-visitor-name: Mallory\r\nCARLOS-VISITOR-NODE: forged\r\nX-Other: preserved\r\n\r\n"
+ r, err := http.ReadRequest(bufio.NewReader(strings.NewReader(raw)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.RemoteAddr = "100.64.0.2:12345"
+ t.Cleanup(func() { r.Body.Close() })
+ return r
+}
+
+func TestFrontStripsVisitorTrailers(t *testing.T) {
+ r := frontTrailerRequest(t)
+ r.Trailer["cArLoS-vIsItOr-LoGiN"] = []string{"already populated"}
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ assertNoVisitorHeaders(t, r.Trailer)
+ return frontVisitor, true, nil
+ })}
+ devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ assertNoVisitorHeaders(t, r.Trailer)
+ body, err := io.ReadAll(r.Body)
+ if err != nil || string(body) != "body" {
+ t.Errorf("body=%q err=%v", body, err)
+ }
+ assertNoVisitorHeaders(t, r.Trailer)
+ if got := r.Trailer.Get("X-Other"); got != "preserved" {
+ t.Errorf("unrelated trailer=%q", got)
+ }
+ }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), r)
+}
+
+func TestDevboxFrontUnixStripsVisitorTrailers(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("socket identities require Linux")
+ }
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ assertNoVisitorHeaders(t, r.Trailer)
+ if _, err := io.Copy(io.Discard, r.Body); err != nil {
+ t.Error(err)
+ }
+ assertNoVisitorHeaders(t, r.Trailer)
+ if got := r.Header.Get("Carlos-Visitor-Login"); got != frontVisitor.Login {
+ t.Errorf("login=%q", got)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), Identity: frontIdentity(frontVisitor), SocketOwnerFor: func(string) (string, uint32, bool) { return path, uint32(os.Getuid()), true }}
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := frontTrailerRequest(t)
+ w := httptest.NewRecorder()
+ devboxFront(e, cfg, frontSelf).ServeHTTP(w, r)
+ if w.Code != http.StatusNoContent {
+ t.Errorf("code=%d want=204", w.Code)
+ }
+}
+
+func TestFrontIdentityDeadline(t *testing.T) {
+ for _, private := range []bool{false, true} {
+ t.Run(fmt.Sprintf("private=%v", private), func(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ started := time.Now()
+ cfg := DevboxConfig{Identity: visitorIdentityFunc(func(ctx context.Context, _ netip.AddrPort) (Visitor, bool, error) {
+ deadline, ok := ctx.Deadline()
+ if !ok {
+ t.Error("lookup has no deadline")
+ return Visitor{}, false, errors.New("no deadline")
+ }
+ if got := deadline.Sub(started); got != 2*time.Second {
+ t.Errorf("lookup budget=%s want=2s", got)
+ }
+ <-ctx.Done()
+ return Visitor{}, false, ctx.Err()
+ })}
+ if private {
+ cfg.AllowFor = func(string) []string { return []string{frontVisitor.Login} }
+ }
+ calls := 0
+ h := devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ assertNoVisitorHeaders(t, r.Header)
+ if err := r.Context().Err(); err != nil {
+ t.Errorf("lookup canceled request context: %v", err)
+ }
+ }), cfg, frontSelf)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, frontRequest())
+ wantCode, wantCalls := http.StatusOK, 1
+ if private {
+ wantCode, wantCalls = http.StatusForbidden, 0
+ }
+ if w.Code != wantCode || calls != wantCalls {
+ t.Errorf("code=%d calls=%d want=%d,%d", w.Code, calls, wantCode, wantCalls)
+ }
+ if elapsed := time.Since(started); elapsed != 2*time.Second {
+ t.Errorf("elapsed=%s want=2s", elapsed)
+ }
+ })
+ })
+ }
+}
+
+func TestDevboxFrontUnixUpgrade101(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("socket identities require Linux")
+ }
+ done := make(chan struct{})
+ echo := upgradeEchoHandler("socket")
+ path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer close(done)
+ for k, want := range map[string]string{"Carlos-Visitor-Login": frontVisitor.Login, "Carlos-Visitor-Name": frontVisitor.Name, "Carlos-Visitor-Node": frontVisitor.Node} {
+ if got := r.Header.Get(k); got != want {
+ t.Errorf("upstream %s=%q want=%q", k, got, want)
+ }
+ }
+ echo.ServeHTTP(w, r)
+ }))
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), Identity: frontIdentity(frontVisitor), SocketOwnerFor: func(string) (string, uint32, bool) { return path, uint32(os.Getuid()), true }}
+ e, err := newDevboxEdge(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(devboxFront(e, cfg, frontSelf))
+ defer srv.Close()
+ conn, err := net.Dial("tcp", srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ _, err = fmt.Fprint(conn, "GET /ws HTTP/1.1\r\nHost: shop.example.com\r\nConnection: Upgrade, Carlos-Visitor-Login, Carlos-Visitor-Name, Carlos-Visitor-Node\r\nUpgrade: websocket\r\ncArLoS-vIsItOr-LoGiN: mallory@github\r\nCarlos-Visitor-Name: Forged\r\nCarlos-Visitor-Node: Forged\r\n\r\n")
+ if err != nil {
+ t.Fatal(err)
+ }
+ reader := bufio.NewReader(conn)
+ resp, err := http.ReadResponse(reader, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("status=%d want=101", resp.StatusCode)
+ }
+ if _, err := fmt.Fprint(conn, "hello\n"); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := reader.ReadString('\n'); err != nil || got != "socket:hello\n" {
+ t.Fatalf("echo=%q err=%v", got, err)
+ }
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("upgraded upstream did not finish")
+ }
+}