carlos / platform Public

Add devbox visitor identity adapter and bounded cache

Resolve personal-device identity through the Tailscale Unix LocalAPI.
Cache answers by unmapped IP with 60-second hits and 5-second misses,
including failures, and provide the shared-node anonymity helper.

Cover response refusals, request deadlines, concurrency and cache bounds.
Focused tests and race tests pass; Darwin builds pass. Darwin edge vet
is blocked by the existing Linux-only readerConn test helper.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 6d59ecc7357120a6a8fd0e7a1dff5c104260bf3b parent af57ab9
4 files changed, +502 −0
  • internal/edge/visitor.go +105 −0
  • internal/edge/visitor_test.go +170 −0
  • internal/tsidentity/whois.go +85 −0
  • internal/tsidentity/whois_test.go +142 −0

CI failed — run details

diff --git a/internal/edge/visitor.go b/internal/edge/visitor.go
new file mode 100644
index 000000000..78f9c3467
--- /dev/null
+++ b/internal/edge/visitor.go
@@ -0,0 +1,105 @@
+package edge
+
+import (
+ "context"
+ "net/netip"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Visitor identifies the owner of a personal device. Values are supplied by
+// the identity provider; the front door sanitizes them before setting headers.
+type Visitor struct{ Login, Name, Node string }
+
+type VisitorIdentity interface {
+ // Who returns the visitor at remote, or ok=false if unknown.
+ Who(ctx context.Context, remote netip.AddrPort) (Visitor, bool, error)
+}
+
+const visitorCacheLimit = 4096
+
+type visitorCacheEntry struct {
+ visitor Visitor
+ ok bool
+ expires time.Time
+ ready chan struct{}
+}
+
+type cachedIdentity struct {
+ inner VisitorIdentity
+ now func() time.Time
+ mu sync.Mutex
+ entries map[netip.Addr]*visitorCacheEntry
+}
+
+// NewCachedIdentity caches identities by unmapped IP for 60 seconds, and
+// misses or errors for 5 seconds. Cached errors return an anonymous miss with
+// nil error. At 4096 entries, a new IP resets the cache to bound memory.
+func NewCachedIdentity(inner VisitorIdentity, now func() time.Time) VisitorIdentity {
+ return &cachedIdentity{inner: inner, now: now, entries: make(map[netip.Addr]*visitorCacheEntry)}
+}
+
+func (c *cachedIdentity) Who(ctx context.Context, remote netip.AddrPort) (Visitor, bool, error) {
+ key := remote.Addr().Unmap()
+ for {
+ if err := ctx.Err(); err != nil {
+ return Visitor{}, false, err
+ }
+ c.mu.Lock()
+ if entry := c.entries[key]; entry != nil {
+ if entry.ready != nil {
+ ready := entry.ready
+ c.mu.Unlock()
+ select {
+ case <-ctx.Done():
+ return Visitor{}, false, ctx.Err()
+ case <-ready:
+ continue
+ }
+ }
+ if c.now().Before(entry.expires) {
+ visitor, ok := entry.visitor, entry.ok
+ c.mu.Unlock()
+ return visitor, ok, nil
+ }
+ delete(c.entries, key)
+ }
+ if len(c.entries) >= visitorCacheLimit {
+ clear(c.entries)
+ }
+ entry := &visitorCacheEntry{ready: make(chan struct{})}
+ c.entries[key] = entry
+ c.mu.Unlock()
+
+ // Keep the port for the provider. Requests for this IP wait above without
+ // holding the mutex, and can leave when their own context is canceled.
+ visitor, ok, err := c.inner.Who(ctx, remote)
+ ttl := 60 * time.Second
+ if !ok || err != nil {
+ visitor, ok = Visitor{}, false
+ ttl = 5 * time.Second
+ }
+ c.mu.Lock()
+ entry.visitor, entry.ok, entry.expires = visitor, ok, c.now().Add(ttl)
+ close(entry.ready)
+ entry.ready = nil
+ c.mu.Unlock()
+ return visitor, ok, err
+ }
+}
+
+// anonymousSource is the front door's shared-machine rule: the devbox's own
+// IP (unmapped on both sides), or an exact, case-insensitive shared node name.
+// Match Node, not Login: a shared machine identifies its owner, not its user.
+func anonymousSource(remote netip.Addr, self netip.Addr, v Visitor, sharedNodes []string) bool {
+ if remote.Unmap() == self.Unmap() {
+ return true
+ }
+ for _, node := range sharedNodes {
+ if strings.EqualFold(v.Node, node) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/edge/visitor_test.go b/internal/edge/visitor_test.go
new file mode 100644
index 000000000..fea768d81
--- /dev/null
+++ b/internal/edge/visitor_test.go
@@ -0,0 +1,170 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "net/netip"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type visitorIdentityFunc func(context.Context, netip.AddrPort) (Visitor, bool, error)
+
+func (f visitorIdentityFunc) Who(ctx context.Context, remote netip.AddrPort) (Visitor, bool, error) {
+ return f(ctx, remote)
+}
+
+func TestCachedIdentityTTLs(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ ok bool
+ err error
+ ttl time.Duration
+ }{
+ {"hit", true, nil, 60 * time.Second},
+ {"miss", false, nil, 5 * time.Second},
+ {"error", true, errors.New("lookup failed"), 5 * time.Second},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ now := time.Unix(1000, 0)
+ calls := 0
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ visitor := Visitor{"alice@github", "Alice", "laptop"}
+ identity := NewCachedIdentity(visitorIdentityFunc(func(ctx context.Context, got netip.AddrPort) (Visitor, bool, error) {
+ calls++
+ if got != remote {
+ t.Errorf("remote = %v, want %v", got, remote)
+ }
+ return visitor, tc.ok, tc.err
+ }), func() time.Time { return now })
+ got, ok, err := identity.Who(context.Background(), remote)
+ wantOK := tc.ok && tc.err == nil
+ if ok != wantOK || !errors.Is(err, tc.err) {
+ t.Fatalf("first lookup = %v, %v", ok, err)
+ }
+ if wantOK && got != visitor {
+ t.Fatalf("visitor = %+v", got)
+ }
+ if !wantOK && got != (Visitor{}) {
+ t.Fatalf("anonymous lookup leaked %+v", got)
+ }
+ now = now.Add(tc.ttl - time.Nanosecond)
+ got, ok, err = identity.Who(context.Background(), remote)
+ if ok != wantOK || err != nil || calls != 1 {
+ t.Fatalf("cached lookup = %v, %v; calls %d", ok, err, calls)
+ }
+ if !wantOK && got != (Visitor{}) {
+ t.Fatalf("cached miss leaked %+v", got)
+ }
+ now = now.Add(time.Nanosecond)
+ _, _, _ = identity.Who(context.Background(), remote)
+ if calls != 2 {
+ t.Fatalf("at expiry: calls %d, want 2", calls)
+ }
+ })
+ }
+}
+
+func TestCachedIdentityKeysByUnmappedIP(t *testing.T) {
+ calls := 0
+ first := netip.MustParseAddrPort("[::ffff:100.64.0.1]:1234")
+ identity := NewCachedIdentity(visitorIdentityFunc(func(_ context.Context, remote netip.AddrPort) (Visitor, bool, error) {
+ calls++
+ if calls == 1 && remote != first {
+ t.Errorf("inner remote = %v, want full %v", remote, first)
+ }
+ return Visitor{Login: remote.Addr().Unmap().String()}, true, nil
+ }), time.Now)
+ a, _, _ := identity.Who(context.Background(), first)
+ b, _, _ := identity.Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:5678"))
+ c, _, _ := identity.Who(context.Background(), netip.MustParseAddrPort("100.64.0.2:5678"))
+ if calls != 2 || a != b || a == c {
+ t.Fatalf("calls %d; visitors %+v, %+v, %+v", calls, a, b, c)
+ }
+}
+
+func TestCachedIdentityBound(t *testing.T) {
+ calls := 0
+ identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ calls++
+ return Visitor{}, false, nil
+ }), time.Now)
+ for i := 0; i < 4097; i++ {
+ remote := netip.AddrPortFrom(netip.AddrFrom4([4]byte{100, 64, byte(i >> 8), byte(i)}), 1234)
+ _, _, _ = identity.Who(context.Background(), remote)
+ }
+ _, _, _ = identity.Who(context.Background(), netip.MustParseAddrPort("100.64.0.0:4321"))
+ if calls != 4098 {
+ t.Fatalf("oldest entry retained beyond cap: calls %d", calls)
+ }
+}
+
+func TestCachedIdentityConcurrent(t *testing.T) {
+ var calls atomic.Int32
+ started, release := make(chan struct{}), make(chan struct{})
+ identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ if calls.Add(1) == 1 {
+ close(started)
+ }
+ <-release
+ return Visitor{Login: "alice@github"}, true, nil
+ }), time.Now)
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ var wg sync.WaitGroup
+ for i := 0; i < 32; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ v, ok, err := identity.Who(context.Background(), remote)
+ if !ok || err != nil || v.Login != "alice@github" {
+ t.Errorf("lookup = %+v, %v, %v", v, ok, err)
+ }
+ }()
+ }
+ <-started
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ done := make(chan error, 1)
+ go func() { _, _, err := identity.Who(ctx, remote); done <- err }()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Errorf("canceled waiter: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Error("canceled waiter blocked behind lookup")
+ }
+ close(release)
+ wg.Wait()
+ if calls.Load() != 1 {
+ t.Fatalf("concurrent lookups: %d, want 1", calls.Load())
+ }
+}
+
+func TestAnonymousSource(t *testing.T) {
+ self := netip.MustParseAddr("100.64.0.1")
+ for _, tc := range []struct {
+ name, remote, node string
+ shared []string
+ want bool
+ }{
+ {"self", "100.64.0.1", "laptop", nil, true},
+ {"mapped self", "::ffff:100.64.0.1", "laptop", nil, true},
+ {"shared mixed case", "100.64.0.2", "SHOP-DEV", []string{"other", "shop-dev"}, true},
+ {"personal", "100.64.0.2", "laptop", []string{"shop-dev"}, false},
+ {"not prefix", "100.64.0.2", "shop-dev-extra", []string{"shop-dev"}, false},
+ {"not suffix", "100.64.0.2", "my-shop-dev", []string{"shop-dev"}, false},
+ {"not login", "100.64.0.2", "laptop", []string{"alice@github"}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ v := Visitor{Login: "alice@github", Node: tc.node}
+ for _, local := range []netip.Addr{self, netip.MustParseAddr("::ffff:100.64.0.1")} {
+ if got := anonymousSource(netip.MustParseAddr(tc.remote), local, v, tc.shared); got != tc.want {
+ t.Fatalf("anonymousSource = %v, want %v", got, tc.want)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/tsidentity/whois.go b/internal/tsidentity/whois.go
new file mode 100644
index 000000000..a0bd8eade
--- /dev/null
+++ b/internal/tsidentity/whois.go
@@ -0,0 +1,85 @@
+// Package tsidentity resolves visitor identities through tailscaled's LocalAPI.
+package tsidentity
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+const maxWhoisBody = 1 << 20
+
+type identity struct {
+ client *http.Client
+}
+
+// New uses HTTP over socketPath with the caller's context and a request
+// timeout. A nonpositive timeout uses the devbox default of two seconds.
+func New(socketPath string, timeout time.Duration) edge.VisitorIdentity {
+ if timeout <= 0 {
+ timeout = 2 * time.Second
+ }
+ dialer := &net.Dialer{}
+ return &identity{client: &http.Client{
+ Timeout: timeout,
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return dialer.DialContext(ctx, "unix", socketPath)
+ },
+ // Calls are cached by the edge; no idle socket needs to outlive a lookup.
+ DisableKeepAlives: true,
+ },
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ }}
+}
+
+func (i *identity) Who(ctx context.Context, remote netip.AddrPort) (edge.Visitor, bool, error) {
+ endpoint := "http://local-tailscaled.sock/localapi/v0/whois?" + url.Values{"addr": {remote.String()}}.Encode()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ if err != nil {
+ return edge.Visitor{}, false, err
+ }
+ resp, err := i.client.Do(req)
+ if err != nil {
+ return edge.Visitor{}, false, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode == http.StatusNotFound {
+ return edge.Visitor{}, false, nil
+ }
+ if resp.StatusCode != http.StatusOK {
+ return edge.Visitor{}, false, fmt.Errorf("tailscale whois: HTTP %d", resp.StatusCode)
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxWhoisBody+1))
+ if err != nil {
+ return edge.Visitor{}, false, fmt.Errorf("tailscale whois: read response: %w", err)
+ }
+ if len(body) > maxWhoisBody {
+ return edge.Visitor{}, false, fmt.Errorf("tailscale whois: response exceeds %d bytes", maxWhoisBody)
+ }
+ var result struct {
+ Node struct {
+ ComputedName string
+ Tags []string
+ }
+ UserProfile struct {
+ LoginName string
+ DisplayName string
+ }
+ }
+ if err := json.Unmarshal(body, &result); err != nil {
+ return edge.Visitor{}, false, fmt.Errorf("tailscale whois: decode response: %w", err)
+ }
+ if len(result.Node.Tags) > 0 || result.UserProfile.LoginName == "" {
+ return edge.Visitor{}, false, nil
+ }
+ return edge.Visitor{Login: result.UserProfile.LoginName, Name: result.UserProfile.DisplayName, Node: result.Node.ComputedName}, true, nil
+}
diff --git a/internal/tsidentity/whois_test.go b/internal/tsidentity/whois_test.go
new file mode 100644
index 000000000..58d5f6724
--- /dev/null
+++ b/internal/tsidentity/whois_test.go
@@ -0,0 +1,142 @@
+package tsidentity
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+func fakeWhois(t *testing.T, handler http.HandlerFunc) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "whois.sock")
+ listener, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewUnstartedServer(handler)
+ if err := server.Listener.Close(); err != nil {
+ t.Fatal(err)
+ }
+ server.Listener = listener
+ server.Start()
+ t.Cleanup(server.Close)
+ return path
+}
+
+func TestWhoisParsesLoginNameNode(t *testing.T) {
+ for _, addr := range []string{"100.64.0.1:4321", "[fd7a:115c:a1e0::1]:4321"} {
+ t.Run(addr, func(t *testing.T) {
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "GET" || r.Host != "local-tailscaled.sock" || r.URL.Path != "/localapi/v0/whois" || r.URL.Query().Get("addr") != addr {
+ t.Errorf("request: %s %s host=%q", r.Method, r.URL, r.Host)
+ }
+ fmt.Fprint(w, `{"Node":{"ComputedName":"Laptop","Tags":null},"UserProfile":{"LoginName":"Alice@github","DisplayName":"Alïce\r\n"}}`)
+ })
+ got, ok, err := New(path, 2*time.Second).Who(context.Background(), netip.MustParseAddrPort(addr))
+ want := edge.Visitor{Login: "Alice@github", Name: "Alïce\r\n", Node: "Laptop"}
+ if err != nil || !ok || got != want {
+ t.Fatalf("Who = %+v, %v, %v; want %+v", got, ok, err, want)
+ }
+ })
+ }
+}
+
+func TestWhoisTaggedNodeIsAnonymous(t *testing.T) {
+ for _, body := range []string{
+ `{"Node":{"ComputedName":"shop-dev","Tags":["tag:server"]},"UserProfile":{"LoginName":"alice@github"}}`,
+ `{"Node":{"ComputedName":"laptop"},"UserProfile":{"LoginName":"","DisplayName":"Alice"}}`,
+ `{}`, `null`,
+ } {
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, body) })
+ v, ok, err := New(path, 2*time.Second).Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:4321"))
+ if err != nil || ok || v != (edge.Visitor{}) {
+ t.Fatalf("body %s: %+v, %v, %v", body, v, ok, err)
+ }
+ }
+}
+
+func TestWhoisResponses(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status int
+ body string
+ wantErr bool
+ }{
+ {"not found", 404, "not found", false},
+ {"forbidden", 403, "forbidden", true},
+ {"unavailable", 503, "unavailable", true},
+ {"redirect", 302, "", true},
+ {"other success", 204, "", true},
+ {"invalid JSON", 200, "{", true},
+ {"trailing JSON", 200, `{"UserProfile":{"LoginName":"alice@github"}}{}`, true},
+ {"oversized", 200, `{"UserProfile":{"LoginName":"alice@github"},"padding":"` + strings.Repeat("x", 1<<20) + `"}`, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var requests atomic.Int32
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ if tc.status == 302 {
+ w.Header().Set("Location", "/redirected")
+ }
+ w.WriteHeader(tc.status)
+ fmt.Fprint(w, tc.body)
+ })
+ v, ok, err := New(path, 2*time.Second).Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:4321"))
+ if (err != nil) != tc.wantErr || ok || v != (edge.Visitor{}) {
+ t.Fatalf("Who = %+v, %v, %v", v, ok, err)
+ }
+ if requests.Load() != 1 {
+ t.Fatalf("requests = %d, want 1", requests.Load())
+ }
+ })
+ }
+}
+
+func TestWhoisTimeout(t *testing.T) {
+ for _, bodyStarted := range []bool{false, true} {
+ t.Run(fmt.Sprintf("body=%v", bodyStarted), func(t *testing.T) {
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) {
+ if bodyStarted {
+ w.WriteHeader(200)
+ w.(http.Flusher).Flush()
+ }
+ <-r.Context().Done()
+ })
+ start := time.Now()
+ _, ok, err := New(path, 2*time.Second).Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:4321"))
+ elapsed := time.Since(start)
+ if ok || !errors.Is(err, context.DeadlineExceeded) || elapsed < 1500*time.Millisecond || elapsed > 4*time.Second {
+ t.Fatalf("Who = %v, %v after %v", ok, err, elapsed)
+ }
+ })
+ }
+}
+
+func TestWhoisCallerContext(t *testing.T) {
+ path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ _, ok, err := New(path, 2*time.Second).Who(ctx, netip.MustParseAddrPort("100.64.0.1:4321"))
+ if ok || !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > time.Second {
+ t.Fatalf("Who = %v, %v after %v", ok, err, time.Since(start))
+ }
+}
+
+func TestWhoisMissingSocket(t *testing.T) {
+ _, ok, err := New(filepath.Join(t.TempDir(), "absent.sock"), 2*time.Second).Who(context.Background(), netip.MustParseAddrPort("100.64.0.1:4321"))
+ if ok || err == nil {
+ t.Fatalf("Who = %v, %v", ok, err)
+ }
+}