| 1 | package serve |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/http/httptest" |
| 6 | "strings" |
| 7 | "sync" |
| 8 | "testing" |
| 9 | |
| 10 | "reasonix/internal/config" |
| 11 | "reasonix/internal/control" |
| 12 | "reasonix/internal/provider" |
| 13 | ) |
| 14 | |
| 15 | // TestControllerAccessorIsRaceSafe guards the switchModel concurrency contract: |
| 16 | // handlers read the controller through ctl() while a swap runs under the write |
| 17 | // lock. With the lock removed this fails under `go test -race` (the CI race job). |
| 18 | func TestControllerAccessorIsRaceSafe(t *testing.T) { |
| 19 | a, b := &control.Controller{}, &control.Controller{} |
| 20 | s := &Server{ctrl: a} |
| 21 | |
| 22 | var wg sync.WaitGroup |
| 23 | for range 64 { |
| 24 | wg.Go(func() { |
| 25 | if got := s.ctl(); got != a && got != b { |
| 26 | t.Errorf("ctl() returned a pointer that was never set") |
| 27 | } |
| 28 | }) |
| 29 | } |
| 30 | for range 16 { |
| 31 | wg.Go(func() { |
| 32 | s.mu.Lock() |
| 33 | if s.ctrl == a { |
| 34 | s.ctrl = b |
| 35 | } else { |
| 36 | s.ctrl = a |
| 37 | } |
| 38 | s.mu.Unlock() |
| 39 | }) |
| 40 | } |
| 41 | wg.Wait() |
| 42 | } |
| 43 | |
| 44 | func TestCanonicalRuntimeModelRefUsesCatalogOwnedValue(t *testing.T) { |
| 45 | ctrl := control.New(control.Options{ProviderResolver: &provider.StaticResolver{ |
| 46 | Descriptors: []provider.Descriptor{{Ref: "safe/model"}}, |
| 47 | }}) |
| 48 | defer ctrl.Close() |
| 49 | s := &Server{ctrl: ctrl} |
| 50 | |
| 51 | ref, err := s.canonicalRuntimeModelRef(" safe/model ") |
| 52 | if err != nil || ref != "safe/model" { |
| 53 | t.Fatalf("canonical ref = %q, %v", ref, err) |
| 54 | } |
| 55 | if _, err := s.canonicalRuntimeModelRef("attacker/model"); err == nil { |
| 56 | t.Fatal("unknown request model was not rejected") |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // TestModelAndEffortRoutesValidateInput pins the HTTP routes for model and |
| 61 | // effort switching: registered (not 404) and rejecting invalid bodies |
| 62 | // before any controller work. Switch semantics are covered by the |
| 63 | // switchModel / switch_recovery tests. |
| 64 | func TestModelAndEffortRoutesValidateInput(t *testing.T) { |
| 65 | s := &Server{ctrl: &control.Controller{}, auth: newAuthGate(config.ServeConfig{AuthMode: "none"})} |
| 66 | srv := httptest.NewServer(s.handler()) |
| 67 | defer srv.Close() |
| 68 | |
| 69 | for _, tc := range []struct{ path, body string }{ |
| 70 | {"/model", `{"ref":""}`}, |
| 71 | {"/model", `not-json`}, |
| 72 | {"/effort", `{"level":""}`}, |
| 73 | {"/effort", `not-json`}, |
| 74 | } { |
| 75 | resp, err := http.Post(srv.URL+tc.path, "application/json", strings.NewReader(tc.body)) |
| 76 | if err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | resp.Body.Close() |
| 80 | if resp.StatusCode != http.StatusBadRequest { |
| 81 | t.Fatalf("POST %s %s = %d, want 400", tc.path, tc.body, resp.StatusCode) |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 |