oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package egress
2
3import (
4 "bufio"
5 "context"
6 "crypto/sha256"
7 "crypto/tls"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "io"
12 "net"
13 "net/http"
14 "net/http/httptest"
15 "net/netip"
16 "net/url"
17 "os"
18 "path/filepath"
19 "strings"
20 "sync/atomic"
21 "testing"
22 "time"
23
24 "amadan.net/oficina/equipo/internal/runner/provider"
25 "amadan.net/oficina/equipo/internal/wire"
26)
27
28func scratch(t *testing.T) string {
29 t.Helper()
30 dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e3-")
31 if err != nil {
32 t.Fatal(err)
33 }
34 t.Cleanup(func() { os.RemoveAll(dir) })
35 return dir
36}
37func fixtureProxy(t *testing.T, addresses []netip.Addr, dial func(context.Context, string, string) (net.Conn, error)) *Proxy {
38 t.Helper()
39 d := defaults()
40 d.lookup = func(context.Context, string) ([]netip.Addr, error) { return addresses, nil }
41 d.dial = dial
42 p, err := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
43 if err != nil {
44 t.Fatal(err)
45 }
46 t.Cleanup(func() { p.Close() })
47 return p
48}
49func connect(t *testing.T, p *Proxy, request string) (net.Conn, *bufio.Reader, string) {
50 t.Helper()
51 c, err := net.Dial("unix", p.SocketPath())
52 if err != nil {
53 t.Fatal(err)
54 }
55 t.Cleanup(func() { c.Close() })
56 c.SetDeadline(time.Now().Add(3 * time.Second))
57 if _, err = io.WriteString(c, request); err != nil {
58 t.Fatal(err)
59 }
60 r := bufio.NewReader(c)
61 line, _ := r.ReadString('\n')
62 return c, r, line
63}
64func request(host string) string {
65 return "CONNECT " + host + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n"
66}
67
68func TestEgressRejectsHostServices(t *testing.T) {
69 var calls atomic.Int32
70 dial := func(context.Context, string, string) (net.Conn, error) {
71 calls.Add(1)
72 return nil, errors.New("unexpected dial")
73 }
74 p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, dial)
75 for _, host := range []string{"localhost:443", "127.0.0.1:443", "[::1]:443", "100.64.0.1:443", "192.168.1.1:443", "169.254.169.254:443", "metadata.google.internal:443", "fixture.example:80", "other.example:443", "sub.fixture.example:443", "fixture.example.evil:443", "fixture.example.:443", "FIXTURE.EXAMPLE:443", "fixture.example:0443", "fixture.example:443@other.example:443"} {
76 t.Run(host, func(t *testing.T) {
77 _, _, line := connect(t, p, request(host))
78 if strings.Contains(line, "200") {
79 t.Fatal("forbidden authority accepted")
80 }
81 })
82 }
83 if calls.Load() != 0 {
84 t.Fatal("denied request reached dialer")
85 }
86 for _, ip := range []string{"127.0.0.1", "10.0.0.1", "172.16.0.1", "192.168.0.1", "100.64.0.1", "100.127.255.254", "169.254.169.254", "0.0.0.0", "224.0.0.1", "240.0.0.1", "192.0.0.8", "198.18.0.1", "192.0.2.1", "198.51.100.1", "203.0.113.1", "::1", "::", "fc00::1", "fe80::1", "ff02::1", "::ffff:127.0.0.1", "64:ff9b::7f00:1", "2002:7f00:1::", "2001:db8::1"} {
87 t.Run(ip, func(t *testing.T) {
88 before := calls.Load()
89 q := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr(ip)}, dial)
90 _, _, line := connect(t, q, request("fixture.example:443"))
91 if strings.Contains(line, "200") || calls.Load() != before {
92 t.Fatal("nonpublic DNS answer reached dialer")
93 }
94 })
95 }
96 t.Run("resolver_error", func(t *testing.T) {
97 d := defaults()
98 d.lookup = func(context.Context, string) ([]netip.Addr, error) {
99 return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, errors.New("dns unavailable")
100 }
101 d.dial = dial
102 q, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
103 if e != nil {
104 t.Fatal(e)
105 }
106 defer q.Close()
107 before := calls.Load()
108 connect(t, q, request("fixture.example:443"))
109 if calls.Load() != before {
110 t.Fatal("DNS error dialled")
111 }
112 })
113}
114
115func TestEgressAllowsOnlyProviderTLS(t *testing.T) {
116 server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "fixture TLS") }))
117 defer server.Close()
118 var lookups, dials atomic.Int32
119 d := defaults()
120 d.lookup = func(_ context.Context, host string) ([]netip.Addr, error) {
121 if host != "fixture.example" {
122 t.Errorf("unexpected lookup: %s", host)
123 }
124 if lookups.Add(1) > 1 {
125 return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
126 }
127 return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
128 }
129 d.dial = func(ctx context.Context, network, address string) (net.Conn, error) {
130 dials.Add(1)
131 if network != "tcp" || address != "8.8.8.8:443" {
132 t.Errorf("unvalidated dial: %s %s", network, address)
133 }
134 return (&net.Dialer{}).DialContext(ctx, "tcp", server.Listener.Addr().String())
135 }
136 p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
137 if e != nil {
138 t.Fatal(e)
139 }
140 defer p.Close()
141 c, r, line := connect(t, p, request("fixture.example:443"))
142 if !strings.Contains(line, "200") {
143 t.Fatalf("CONNECT: %q", line)
144 }
145 if line, e = r.ReadString('\n'); e != nil || line != "\r\n" {
146 t.Fatalf("response headers: %q %v", line, e)
147 }
148 tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
149 tlsConfig.ServerName = "127.0.0.1"
150 tlsConn := tls.Client(c, tlsConfig)
151 if e = tlsConn.Handshake(); e != nil {
152 t.Fatal(e)
153 }
154 io.WriteString(tlsConn, "GET / HTTP/1.1\r\nHost: fixture.example\r\nConnection: close\r\n\r\n")
155 b, e := io.ReadAll(tlsConn)
156 if e != nil || !strings.Contains(string(b), "fixture TLS") {
157 t.Fatalf("TLS tunnel: %q %v", b, e)
158 }
159 connect(t, p, request("fixture.example:443"))
160 if lookups.Load() != 2 || dials.Load() != 1 {
161 t.Fatalf("rebinding guard: lookups=%d dials=%d", lookups.Load(), dials.Load())
162 }
163}
164
165func TestEgressRejectsSmuggling(t *testing.T) {
166 var calls atomic.Int32
167 p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, func(context.Context, string, string) (net.Conn, error) { calls.Add(1); return nil, errors.New("dial") })
168 for _, raw := range []string{
169 "GET https://fixture.example/ HTTP/1.1\r\n\r\n",
170 "POST fixture.example:443 HTTP/1.1\r\n\r\n",
171 "CONNECT fixture.example:443 HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
172 "CONNECT fixture.example:443 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n",
173 "CONNECT fixture.example:443 HTTP/1.1\r\nHost: other.example:443\r\n\r\n",
174 "CONNECT fixture.example:443 HTTP/1.1\r\nHost: fixture.example:443\r\nHost: fixture.example:443\r\n\r\n",
175 "CONNECT fixture.example:443 HTTP/1.1\r\nUser-Agent: a\r\nUser-Agent: b\r\n\r\n",
176 "CONNECT fixture.example:443 HTTP/1.1\r\n Host: fixture.example:443\r\n\r\n",
177 "CONNECT fixture.example:443 HTTP/1.1\r\nX: a\x00b\r\n\r\n",
178 "CONNECT fixture.example:443 HTTP/1.1\n\n",
179 "CONNECT fixture.example:443 HTTP/2.0\r\n\r\n",
180 request("fixture.example:443") + "GET / HTTP/1.1\r\n\r\n",
181 } {
182 t.Run(fmt.Sprintf("case%d", calls.Load())+fmt.Sprint(len(raw)), func(t *testing.T) {
183 before := calls.Load()
184 _, _, line := connect(t, p, raw)
185 if strings.Contains(line, "200") || calls.Load() != before {
186 t.Fatalf("smuggling reached dial: %q", raw)
187 }
188 })
189 }
190}
191
192func closePromptly(t *testing.T, p *Proxy, connections ...net.Conn) {
193 t.Helper()
194 done := make(chan struct{})
195 go func() { p.Close(); close(done) }()
196 select {
197 case <-done:
198 case <-time.After(time.Second):
199 for _, c := range connections {
200 c.Close()
201 }
202 <-done
203 t.Fatal("proxy close did not interrupt sockets")
204 }
205}
206
207func TestEgressDiesWithAttempt(t *testing.T) {
208 ctx, cancel := context.WithCancel(context.Background())
209 defer cancel()
210 p, e := Open(ctx, scratch(t), Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}})
211 if e != nil {
212 t.Fatal(e)
213 }
214 defer p.Close()
215 c, e := net.Dial("unix", p.SocketPath())
216 if e != nil {
217 t.Fatal(e)
218 }
219 defer c.Close()
220 cancel()
221 select {
222 case <-p.Done():
223 case <-time.After(time.Second):
224 t.Fatal("proxy outlived context")
225 }
226 closePromptly(t, p, c)
227 c.SetReadDeadline(time.Now().Add(time.Second))
228 b := make([]byte, 1)
229 if _, e = c.Read(b); e == nil {
230 t.Fatal("connection survived close")
231 }
232 if _, e = os.Stat(p.SocketPath()); !os.IsNotExist(e) {
233 t.Fatalf("socket survived: %v", e)
234 }
235 if c, e = net.Dial("unix", p.SocketPath()); e == nil {
236 c.Close()
237 t.Fatal("listener survived")
238 }
239}
240
241func TestEgressLimits(t *testing.T) {
242 if MaxHeaders != 8*1024 || MaxTunnels != 16 || ConnectTimeout != 15*time.Second || IdleTimeout != 60*time.Second {
243 t.Fatal("limits differ from brief")
244 }
245 t.Run("headers", func(t *testing.T) {
246 var called atomic.Bool
247 p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, func(context.Context, string, string) (net.Conn, error) {
248 called.Store(true)
249 return nil, errors.New("dial")
250 })
251 _, _, line := connect(t, p, "CONNECT fixture.example:443 HTTP/1.1\r\nUser-Agent: "+strings.Repeat("x", MaxHeaders)+"\r\n\r\n")
252 if strings.Contains(line, "200") || called.Load() {
253 t.Fatal("oversized headers dialled")
254 }
255 })
256 t.Run("concurrent", func(t *testing.T) {
257 p := fixtureProxy(t, nil, nil)
258 var cs []net.Conn
259 defer func() {
260 for _, c := range cs {
261 c.Close()
262 }
263 }()
264 for i := 0; i < MaxTunnels; i++ {
265 c, e := net.Dial("unix", p.SocketPath())
266 if e != nil {
267 t.Fatal(e)
268 }
269 cs = append(cs, c)
270 }
271 deadline := time.Now().Add(time.Second)
272 for p.active() != MaxTunnels && time.Now().Before(deadline) {
273 time.Sleep(time.Millisecond)
274 }
275 if p.active() != MaxTunnels {
276 t.Fatal("slots not occupied")
277 }
278 c, e := net.Dial("unix", p.SocketPath())
279 if e != nil {
280 t.Fatal(e)
281 }
282 defer c.Close()
283 c.SetReadDeadline(time.Now().Add(time.Second))
284 _, e = c.Read(make([]byte, 1))
285 if e == nil {
286 t.Fatal("extra connection survived")
287 }
288 if ne, ok := e.(net.Error); ok && ne.Timeout() {
289 t.Fatal("extra socket remained open")
290 }
291 })
292 t.Run("idle", func(t *testing.T) {
293 d := defaults()
294 d.idle = 80 * time.Millisecond
295 d.lookup = func(context.Context, string) ([]netip.Addr, error) {
296 return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
297 }
298 d.dial = func(context.Context, string, string) (net.Conn, error) {
299 a, b := net.Pipe()
300 t.Cleanup(func() { b.Close() })
301 return a, nil
302 }
303 p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
304 if e != nil {
305 t.Fatal(e)
306 }
307 defer p.Close()
308 c, r, line := connect(t, p, request("fixture.example:443"))
309 if !strings.Contains(line, "200") {
310 t.Fatal(line)
311 }
312 r.ReadString('\n')
313 c.SetReadDeadline(time.Now().Add(time.Second))
314 _, e = r.ReadByte()
315 if e == nil {
316 t.Fatal("idle tunnel survived")
317 }
318 if ne, ok := e.(net.Error); ok && ne.Timeout() {
319 t.Fatal("idle tunnel not closed")
320 }
321 })
322 t.Run("connect", func(t *testing.T) {
323 d := defaults()
324 d.connect = 80 * time.Millisecond
325 d.lookup = func(context.Context, string) ([]netip.Addr, error) {
326 return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
327 }
328 d.dial = func(ctx context.Context, _, _ string) (net.Conn, error) { <-ctx.Done(); return nil, ctx.Err() }
329 p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
330 if e != nil {
331 t.Fatal(e)
332 }
333 defer p.Close()
334 start := time.Now()
335 connect(t, p, request("fixture.example:443"))
336 if time.Since(start) > time.Second {
337 t.Fatal("connect timeout missing")
338 }
339 })
340}
341
342func TestEgressPolicy(t *testing.T) {
343 for _, name := range []string{"claude", "codex"} {
344 want := "api.anthropic.com"
345 if name == "codex" {
346 want = "chatgpt.com"
347 }
348 p, e := ProviderPolicy(provider.NetworkContract{Provider: name}, false)
349 if e != nil || len(p.Hosts) != 1 || p.Hosts[0] != want {
350 t.Fatalf("default: %+v %v", p, e)
351 }
352 p, e = ProviderPolicy(provider.NetworkContract{Provider: name, AuthHost: "refresh.example"}, false)
353 if e == nil {
354 t.Fatal("shared home got refresh")
355 }
356 p, e = ProviderPolicy(provider.NetworkContract{Provider: name, AuthHost: "refresh.example"}, true)
357 if e == nil {
358 t.Fatal("dedicated refresh admitted")
359 }
360 }
361 for _, p := range []Policy{{Provider: "other", Hosts: []string{"fixture.example"}}, {Provider: "claude"}, {Provider: "claude", Hosts: []string{"*.example"}}, {Provider: "claude", Hosts: []string{"127.0.0.1"}}, {Provider: "claude", Hosts: []string{"localhost"}}, {Provider: "claude", Hosts: []string{"fixture.example", "fixture.example"}}} {
362 if _, e := p.Hash(); e == nil {
363 t.Fatalf("invalid policy accepted: %+v", p)
364 }
365 }
366 a, _ := (Policy{Provider: "claude", Hosts: []string{"a.example", "b.example"}}).Hash()
367 b, _ := (Policy{Provider: "claude", Hosts: []string{"b.example", "a.example"}}).Hash()
368 c, _ := (Policy{Provider: "claude", Hosts: []string{"a.example"}}).Hash()
369 d, _ := (Policy{Provider: "codex", Hosts: []string{"a.example", "b.example"}}).Hash()
370 if len(a) != 64 || a != b || a == c || a == d {
371 t.Fatal("policy hash does not bind exact host set and provider")
372 }
373}
374
375func TestEgressPrivateSocket(t *testing.T) {
376 dir := scratch(t)
377 p, e := Open(context.Background(), dir, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}})
378 if e != nil {
379 t.Fatal(e)
380 }
381 defer p.Close()
382 info, e := os.Stat(p.SocketPath())
383 if e != nil || info.Mode().Perm() != 0600 {
384 t.Fatalf("socket mode: %v %v", info, e)
385 }
386 if _, e = Open(context.Background(), dir, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil {
387 t.Fatal("existing socket replaced")
388 }
389 bad := scratch(t)
390 os.Chmod(bad, 0755)
391 if q, e := Open(context.Background(), bad, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil {
392 q.Close()
393 t.Fatal("nonprivate directory accepted")
394 }
395 link := filepath.Join(scratch(t), "link")
396 os.Symlink(scratch(t), link)
397 if q, e := Open(context.Background(), link, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil {
398 q.Close()
399 t.Fatal("symlink directory accepted")
400 }
401}
402
403func TestEgressSocketDirectoryPinned(t *testing.T) {
404 root := scratch(t)
405 dir := filepath.Join(root, "private")
406 if e := os.Mkdir(dir, 0700); e != nil {
407 t.Fatal(e)
408 }
409 p, e := Open(context.Background(), dir, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}})
410 if e != nil {
411 t.Fatal(e)
412 }
413 defer p.Close()
414 moved := filepath.Join(root, "moved")
415 if e = os.Rename(dir, moved); e != nil {
416 t.Fatal(e)
417 }
418 if e = os.Mkdir(dir, 0700); e != nil {
419 t.Fatal(e)
420 }
421 decoy := filepath.Join(dir, "proxy.sock")
422 if e = os.WriteFile(decoy, []byte("replacement"), 0600); e != nil {
423 t.Fatal(e)
424 }
425 if e = p.Close(); e != nil {
426 t.Fatal(e)
427 }
428 if _, e = os.Stat(filepath.Join(moved, "proxy.sock")); !os.IsNotExist(e) {
429 t.Errorf("socket survived close in verified directory: %v", e)
430 }
431 if b, e := os.ReadFile(decoy); e != nil || string(b) != "replacement" {
432 t.Fatalf("close touched replacement directory: %q %v", b, e)
433 }
434}
435
436func TestEgressActiveTunnelClose(t *testing.T) {
437 for _, mode := range []string{"close", "cancel", "listener_failure"} {
438 t.Run(mode, func(t *testing.T) {
439 ctx, cancel := context.WithCancel(context.Background())
440 defer cancel()
441 a, b := net.Pipe()
442 defer b.Close()
443 d := defaults()
444 d.lookup = func(context.Context, string) ([]netip.Addr, error) {
445 return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
446 }
447 d.dial = func(context.Context, string, string) (net.Conn, error) { return a, nil }
448 p, e := open(ctx, scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
449 if e != nil {
450 t.Fatal(e)
451 }
452 defer p.Close()
453 c, r, line := connect(t, p, request("fixture.example:443"))
454 if !strings.Contains(line, "200") {
455 t.Fatal(line)
456 }
457 r.ReadString('\n')
458 switch mode {
459 case "close":
460 closePromptly(t, p, c, b)
461 case "cancel":
462 cancel()
463 case "listener_failure":
464 p.listener.Close()
465 }
466 select {
467 case <-p.Done():
468 case <-time.After(time.Second):
469 t.Fatal("proxy failure not reported")
470 }
471 closePromptly(t, p, c, b)
472 for _, conn := range []net.Conn{c, b} {
473 conn.SetReadDeadline(time.Now().Add(time.Second))
474 _, e := conn.Read(make([]byte, 1))
475 if e == nil {
476 t.Fatal("socket survived shutdown")
477 }
478 if ne, ok := e.(net.Error); ok && ne.Timeout() {
479 t.Fatal("socket not closed")
480 }
481 }
482 })
483 }
484}
485
486func TestEgressPolicyFrozen(t *testing.T) {
487 hosts := []string{"fixture.example"}
488 var called atomic.Bool
489 d := defaults()
490 d.lookup = func(context.Context, string) ([]netip.Addr, error) { called.Store(true); return nil, errors.New("dns") }
491 p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: hosts}, d)
492 if e != nil {
493 t.Fatal(e)
494 }
495 defer p.Close()
496 hosts[0] = "other.example"
497 connect(t, p, request("other.example:443"))
498 if called.Load() {
499 t.Fatal("policy changed after open")
500 }
501 for _, ip := range []string{"8.8.8.8", "2606:4700:4700::1111", "::ffff:8.8.8.8"} {
502 if !publicAddress(netip.MustParseAddr(ip)) {
503 t.Fatalf("public address rejected: %s", ip)
504 }
505 }
506}
507
508func TestEgressHeaderTimeout(t *testing.T) {
509 d := defaults()
510 d.connect = 80 * time.Millisecond
511 p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
512 if e != nil {
513 t.Fatal(e)
514 }
515 defer p.Close()
516 c, e := net.Dial("unix", p.SocketPath())
517 if e != nil {
518 t.Fatal(e)
519 }
520 defer c.Close()
521 c.SetReadDeadline(time.Now().Add(time.Second))
522 _, e = io.ReadAll(c)
523 if ne, ok := e.(net.Error); ok && ne.Timeout() {
524 t.Fatal("incomplete header kept socket open")
525 }
526}
527
528// TestEgressTableKeyedByHarnessAndProvider: the egress table (connectors
529// spec §2.2) gives a metered connection exactly its provider's host, and
530// nothing for a harness and provider that are not a row; the Claude and
531// Codex policies hash as they always did; and each API-key provider's
532// row is its upstream's host.
533func TestEgressTableKeyedByHarnessAndProvider(t *testing.T) {
534 p, e := ProviderPolicy(provider.NetworkContract{Provider: "tensorx", Harness: "pi"}, true)
535 if e != nil || p.Provider != "tensorx" || p.Harness != "pi" || len(p.Hosts) != 1 || p.Hosts[0] != "api.tensorx.ai" {
536 t.Fatalf("tensorx through pi: %+v %v", p, e)
537 }
538 if _, e := p.Hash(); e != nil {
539 t.Fatal(e)
540 }
541 // OpenCode Go through OpenCode reaches opencode.ai only (slice S5);
542 // the OpenCode to TensorX fallback row is not in the table.
543 if p, e := ProviderPolicy(provider.NetworkContract{Provider: "opencode-go", Harness: "opencode"}, true); e != nil || len(p.Hosts) != 1 || p.Hosts[0] != "opencode.ai" || p.Harness != "opencode" {
544 t.Fatalf("opencode-go through opencode: %+v %v", p, e)
545 }
546 for _, c := range []provider.NetworkContract{{Provider: "opencode-go"}, {Provider: "opencode-go", Harness: "pi"}, {Provider: "tensorx", Harness: "opencode"}, {Provider: "claude", Harness: "opencode"}} {
547 if p, e := ProviderPolicy(c, true); e == nil {
548 t.Fatalf("%+v admitted: %+v", c, p)
549 }
550 }
551 for _, c := range []provider.NetworkContract{{Provider: "tensorx"}, {Provider: "tensorx", Harness: "claude"}, {Provider: "claude", Harness: "pi"}, {Provider: "codex", Harness: "pi"}, {Provider: "tensorx", Harness: "codex"}, {Provider: "tensorx", Harness: "pi", AuthHost: "auth.tensorx.ai"}} {
552 if p, e := ProviderPolicy(c, true); e == nil {
553 t.Fatalf("%+v admitted: %+v", c, p)
554 }
555 }
556 for _, bad := range []Policy{{Provider: "tensorx", Hosts: []string{"api.tensorx.ai"}}, {Provider: "claude", Harness: "pi", Hosts: []string{"api.anthropic.com"}}, {Provider: "claude", Harness: "claude", Hosts: []string{"api.anthropic.com"}}} {
557 if _, e := bad.Hash(); e == nil {
558 t.Fatalf("hash of %+v", bad)
559 }
560 }
561 // The Claude and Codex policies' hashes are those of the policy before
562 // the table: the manifests that pin them stay valid.
563 for name, host := range map[string]string{"claude": "api.anthropic.com", "codex": "chatgpt.com"} {
564 p, _ := ProviderPolicy(provider.NetworkContract{Provider: name}, true)
565 got, _ := p.Hash()
566 sum := sha256.Sum256([]byte(`{"Provider":"` + name + `","Hosts":["` + host + `"]}`))
567 if got != hex.EncodeToString(sum[:]) || p.Harness != "" {
568 t.Fatalf("%s policy hash changed: %s", name, got)
569 }
570 }
571 a, _ := (Policy{Provider: "tensorx", Harness: "pi", Hosts: []string{"api.tensorx.ai"}}).Hash()
572 b, _ := (Policy{Provider: "tensorx", Harness: "pi", Hosts: []string{"api.tensorx.ai", "other.example"}}).Hash()
573 if a == "" || a == b {
574 t.Fatal("hash does not bind the host set")
575 }
576 for name, kp := range wire.APIKeyProviders {
577 u, err := url.Parse(kp.Upstream)
578 if err != nil {
579 t.Fatal(err)
580 }
581 hosts := Routes()[Route{Harness: kp.Harness, Provider: name}]
582 if len(hosts) != 1 || hosts[0] != u.Hostname() || u.Scheme != "https" || kp.Endpoint != "https://"+u.Hostname()+":443" {
583 t.Fatalf("%s: table %v, upstream %s, endpoint %s", name, hosts, kp.Upstream, kp.Endpoint)
584 }
585 }
586}
587
588// Node's fetch (undici, which Pi uses) names the host without its port
589// when it is 443, as RFC 9110 allows for the default port: that is the
590// same authority and is carried. Another host, or another port, is not.
591func TestEgressAcceptsNodeConnect(t *testing.T) {
592 var calls atomic.Int32
593 p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, func(context.Context, string, string) (net.Conn, error) {
594 calls.Add(1)
595 a, b := net.Pipe()
596 go func() { io.Copy(io.Discard, b) }()
597 return a, nil
598 })
599 node := "CONNECT fixture.example:443 HTTP/1.1\r\nhost: fixture.example\r\nconnection: close\r\nproxy-connection: keep-alive\r\n\r\n"
600 if _, _, line := connect(t, p, node); !strings.Contains(line, "200") || calls.Load() != 1 {
601 t.Fatalf("Node's CONNECT refused: %q", line)
602 }
603 for _, raw := range []string{
604 "CONNECT fixture.example:443 HTTP/1.1\r\nhost: other.example\r\n\r\n",
605 "CONNECT fixture.example:443 HTTP/1.1\r\nhost: fixture.example:8443\r\n\r\n",
606 "CONNECT fixture.example:443 HTTP/1.1\r\nhost: fixture.example:\r\n\r\n",
607 "CONNECT fixture.example:443 HTTP/1.1\r\nhost: FIXTURE.EXAMPLE\r\n\r\n",
608 } {
609 before := calls.Load()
610 if _, _, line := connect(t, p, raw); strings.Contains(line, "200") || calls.Load() != before {
611 t.Fatalf("carried %q", raw)
612 }
613 }
614}
615