| 1 | package connect |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/wire" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/netip" |
| 12 | "strings" |
| 13 | "sync/atomic" |
| 14 | "testing" |
| 15 | ) |
| 16 | |
| 17 | // fakeProvider is an OpenAI-compatible provider on 127.0.0.1: it lists |
| 18 | // models and answers a one-token completion for one key. |
| 19 | func fakeProvider(t *testing.T, key string) *httptest.Server { |
| 20 | s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 21 | if r.Header.Get("Authorization") != "Bearer "+key { |
| 22 | w.WriteHeader(http.StatusUnauthorized) |
| 23 | return |
| 24 | } |
| 25 | switch r.Method + " " + r.URL.Path { |
| 26 | case "GET /v1/models", "GET /inference/go/v1/models": |
| 27 | w.Write([]byte(`{"object":"list","data":[{"id":"z-ai/glm-5.3"},{"id":"vendor/other"},{"id":"z-ai/glm-5.3"}]}`)) |
| 28 | case "POST /v1/chat/completions", "POST /inference/go/openai/v1/chat/completions": |
| 29 | var in struct { |
| 30 | Model string `json:"model"` |
| 31 | MaxTokens int `json:"max_tokens"` |
| 32 | } |
| 33 | if json.NewDecoder(r.Body).Decode(&in) != nil || in.MaxTokens != 1 { |
| 34 | w.WriteHeader(http.StatusBadRequest) |
| 35 | return |
| 36 | } |
| 37 | model := in.Model |
| 38 | if model == "z-ai/glm-5.3-swap" { |
| 39 | model = "vendor/other" |
| 40 | } |
| 41 | switch model { |
| 42 | case "vendor/gone": |
| 43 | w.WriteHeader(http.StatusNotFound) |
| 44 | w.Write([]byte(`{"error":{"code":"model_not_found"}}`)) |
| 45 | return |
| 46 | case "vendor/gone-400": |
| 47 | w.WriteHeader(http.StatusBadRequest) |
| 48 | w.Write([]byte(`{"error":{"code":"model_not_found","message":"no such model"}}`)) |
| 49 | return |
| 50 | case "vendor/broken": |
| 51 | w.WriteHeader(http.StatusBadGateway) |
| 52 | return |
| 53 | } |
| 54 | w.Write([]byte(`{"model":"` + model + `","choices":[{"message":{"content":"ok"}}],"usage":{"prompt_tokens":12,"completion_tokens":1,"prompt_tokens_details":{"cached_tokens":2}}}`)) |
| 55 | default: |
| 56 | w.WriteHeader(http.StatusNotFound) |
| 57 | } |
| 58 | })) |
| 59 | t.Cleanup(s.Close) |
| 60 | if !strings.HasPrefix(s.URL, "http://127.0.0.1:") { |
| 61 | t.Fatalf("fake provider not on loopback: %s", s.URL) |
| 62 | } |
| 63 | return s |
| 64 | } |
| 65 | |
| 66 | func TestAPIClientModelsAndProbe(t *testing.T) { |
| 67 | s := fakeProvider(t, "tx-key-1") |
| 68 | // The production transport, with the fake's loopback address allowed. |
| 69 | c := APIClient{HTTP: SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), Origin: s.URL, Path: "/v1"} |
| 70 | models, err := c.Models(context.Background(), []byte("tx-key-1")) |
| 71 | if err != nil || strings.Join(models, ",") != "vendor/other,z-ai/glm-5.3" { |
| 72 | t.Fatalf("models %v %v", models, err) |
| 73 | } |
| 74 | u, err := c.Probe(context.Background(), []byte("tx-key-1"), "z-ai/glm-5.3") |
| 75 | if err != nil || !u.Reported || u.Input != 10 || u.Cached != 2 || u.Output != 1 || u.Model != "z-ai/glm-5.3" { |
| 76 | t.Fatalf("probe %+v %v", u, err) |
| 77 | } |
| 78 | // Security round finding 6: another model answering is no proof of |
| 79 | // the selected one, and its row is that model's, priced as it. |
| 80 | swap, err := c.Probe(context.Background(), []byte("tx-key-1"), "z-ai/glm-5.3-swap") |
| 81 | if !errors.Is(err, ErrModelMismatch) || swap.Model != "vendor/other" || swap.Row("tensorx", "tensorx-1", "z-ai/glm-5.3-swap", 1, false).Model != "vendor/other" { |
| 82 | t.Fatalf("another model answered: %+v %v", swap, err) |
| 83 | } |
| 84 | row := u.Row("tensorx", "tensorx-1", "z-ai/glm-5.3", 1, true) |
| 85 | if !row.Complete || *row.InputTokens != 10 || *row.CachedInputTokens != 2 || *row.OutputTokens != 1 || row.Outcome != "replied" { |
| 86 | t.Fatalf("row %+v", row) |
| 87 | } |
| 88 | _, err = c.Models(context.Background(), []byte("wrong")) |
| 89 | if !errors.Is(err, ErrKeyRefused) || strings.Contains(err.Error(), "wrong") { |
| 90 | t.Fatalf("refused: %v", err) |
| 91 | } |
| 92 | if _, err = c.Probe(context.Background(), []byte("wrong"), "z-ai/glm-5.3"); !errors.Is(err, ErrKeyRefused) { |
| 93 | t.Fatalf("probe refused: %v", err) |
| 94 | } |
| 95 | if row := (ProbeUsage{}).Row("tensorx", "tensorx-1", "z-ai/glm-5.3", 1, true); row.Complete || row.InputTokens != nil { |
| 96 | t.Fatalf("no usage reported: %+v", row) |
| 97 | } |
| 98 | // §16.4: a model the provider does not have is that model's fault, not |
| 99 | // the key's; a provider failure is neither. |
| 100 | for _, m := range []string{"vendor/gone", "vendor/gone-400"} { |
| 101 | if _, err := c.Probe(context.Background(), []byte("tx-key-1"), m); !errors.Is(err, ErrModelNotFound) { |
| 102 | t.Fatalf("%s: %v", m, err) |
| 103 | } |
| 104 | } |
| 105 | if _, err := c.Probe(context.Background(), []byte("tx-key-1"), "vendor/broken"); errors.Is(err, ErrModelNotFound) || errors.Is(err, ErrKeyRefused) || err == nil { |
| 106 | t.Fatalf("a 502: %v", err) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | // OpenCode Go's model list and chat completions are under different |
| 111 | // paths (wire.APIKeyProvider.ModelsPath): the client reads each where the |
| 112 | // provider table says, and nowhere else. |
| 113 | func TestAPIClientModelsPath(t *testing.T) { |
| 114 | s := fakeProvider(t, "go-key-1") |
| 115 | kp := wire.APIKeyProviders[wire.ProviderOpenCodeGo] |
| 116 | c := APIClient{HTTP: SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), Origin: s.URL, Path: kp.APIPath, ModelsPath: kp.ModelsPath} |
| 117 | models, err := c.Models(context.Background(), []byte("go-key-1")) |
| 118 | if err != nil || len(models) != 2 { |
| 119 | t.Fatalf("models %v %v", models, err) |
| 120 | } |
| 121 | if u, err := c.Probe(context.Background(), []byte("go-key-1"), "z-ai/glm-5.3"); err != nil || !u.Reported { |
| 122 | t.Fatalf("probe %+v %v", u, err) |
| 123 | } |
| 124 | // Without the models path the list is looked for under the API path, |
| 125 | // where Go has none. |
| 126 | c.ModelsPath = "" |
| 127 | if _, err := c.Models(context.Background(), []byte("go-key-1")); err == nil { |
| 128 | t.Fatal("the models were read under the completions path") |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // Security round finding 5: the probe's client reaches public addresses |
| 133 | // only, pinned to what it resolved, through no ambient proxy, follows no |
| 134 | // redirect and reads no answer over its cap. |
| 135 | func TestAPIClientTransport(t *testing.T) { |
| 136 | ctx := context.Background() |
| 137 | for name, answer := range map[string][]netip.Addr{ |
| 138 | "loopback": {netip.MustParseAddr("127.0.0.1")}, |
| 139 | "private": {netip.MustParseAddr("10.0.0.7")}, |
| 140 | "link-local": {netip.MustParseAddr("169.254.169.254")}, |
| 141 | "public and local": {netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("192.168.1.2")}, |
| 142 | "none": {}, |
| 143 | } { |
| 144 | dialed := false |
| 145 | c := APIClient{HTTP: SafeClient(func(context.Context, string) ([]netip.Addr, error) { return answer, nil }, nil, func(context.Context, string, string) (net.Conn, error) { |
| 146 | dialed = true |
| 147 | return nil, errors.New("dialed") |
| 148 | }), Origin: "https://api.provider.example", Path: "/v1"} |
| 149 | if _, err := c.Models(ctx, []byte("k")); err == nil || dialed { |
| 150 | t.Fatalf("%s: dialed %v, %v", name, dialed, err) |
| 151 | } |
| 152 | } |
| 153 | // A public answer is dialed at the address resolved, not resolved |
| 154 | // again; the TLS name stays the provider's host. |
| 155 | var dialedTo string |
| 156 | c := APIClient{HTTP: SafeClient(func(context.Context, string) ([]netip.Addr, error) { |
| 157 | return []netip.Addr{netip.MustParseAddr("8.8.4.4")}, nil |
| 158 | }, nil, func(_ context.Context, _, addr string) (net.Conn, error) { |
| 159 | dialedTo = addr |
| 160 | return nil, errors.New("stop") |
| 161 | }), Origin: "https://api.provider.example", Path: "/v1"} |
| 162 | c.Models(ctx, []byte("k")) |
| 163 | if dialedTo != "8.8.4.4:443" { |
| 164 | t.Fatalf("dialed %q", dialedTo) |
| 165 | } |
| 166 | tr := c.HTTP.Transport.(*http.Transport) |
| 167 | if tr.Proxy != nil || tr.TLSClientConfig == nil || tr.TLSClientConfig.InsecureSkipVerify { |
| 168 | t.Fatal("the transport takes an ambient proxy or skips TLS verification") |
| 169 | } |
| 170 | // Redirects are refused (the target is never asked); an answer over |
| 171 | // the cap is not read. |
| 172 | var reached atomic.Bool |
| 173 | target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached.Store(true) })) |
| 174 | t.Cleanup(target.Close) |
| 175 | src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 176 | switch r.URL.Path { |
| 177 | case "/v1/models": |
| 178 | http.Redirect(w, r, target.URL+"/v1/models", http.StatusFound) |
| 179 | default: |
| 180 | w.Write([]byte(`{"usage":{"prompt_tokens":1,"completion_tokens":1},"pad":"` + strings.Repeat("x", 2<<20) + `"}`)) |
| 181 | } |
| 182 | })) |
| 183 | t.Cleanup(src.Close) |
| 184 | loopback := APIClient{HTTP: SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), Origin: src.URL, Path: "/v1"} |
| 185 | if _, err := loopback.Models(ctx, []byte("k")); err == nil || reached.Load() { |
| 186 | t.Fatalf("a redirect was followed: %v", err) |
| 187 | } |
| 188 | if _, err := loopback.Probe(ctx, []byte("k"), "m"); !errors.Is(err, ErrProviderAnswer) { |
| 189 | t.Fatalf("an oversized answer: %v", err) |
| 190 | } |
| 191 | if (APIClient{}).client().Transport == nil { |
| 192 | t.Fatal("the default client uses the default transport") |
| 193 | } |
| 194 | } |
| 195 | |