package platform import ( "context" "encoding/json" "io" "net/http" "net/http/httptest" "strings" "testing" ) type seen struct { method, path, auth, message string body map[string]any } func server(t *testing.T, status int, body string) (*httptest.Server, *seen) { t.Helper() s := &seen{} ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.method, s.path = r.Method, r.URL.Path s.auth, s.message = r.Header.Get("Authorization"), r.Header.Get("X-Carlos-Message") if b, _ := io.ReadAll(r.Body); len(b) > 0 { if err := json.Unmarshal(b, &s.body); err != nil { t.Errorf("body not JSON: %v", err) } } w.WriteHeader(status) io.WriteString(w, body) })) t.Cleanup(ts.Close) return ts, s } func TestSetEnvShape(t *testing.T) { ts, s := server(t, 200, `{}`) c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) if err := c.SetEnv(context.Background(), "scratchpad", "base-scratchpad", map[string]string{"K": "V"}); err != nil { t.Fatal(err) } if s.method != "PUT" || s.path != "/api/cli/apps/acct1/scratchpad/config" { t.Fatalf("got %s %s", s.method, s.path) } if s.auth != "Bearer op-tok" { t.Fatalf("auth %q", s.auth) } got, _ := json.Marshal(s.body) want := `{"environment":"base-scratchpad","message":"Base: install","set":{"K":{"kind":"env","value":"V"}}}` if string(got) != want { t.Fatalf("body %s", got) } } func TestCreateInstanceShape(t *testing.T) { for _, status := range []int{200, 201} { ts, s := server(t, status, `{}`) c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) if err := c.CreateInstance(context.Background(), "scratchpad", "b-scratchpad.example.com", "b-scratchpad"); err != nil { t.Fatalf("status %d: %v", status, err) } if s.method != "POST" || s.path != "/api/cli/apps/acct1/scratchpad/instances" { t.Fatalf("got %s %s", s.method, s.path) } if s.auth != "Bearer inst-tok" { t.Fatalf("auth %q", s.auth) } got, _ := json.Marshal(s.body) want := `{"channel":"edge","environment":"b-scratchpad","host":"b-scratchpad.example.com","message":"Base: install"}` if string(got) != want { t.Fatalf("body %s", got) } } } func TestDeleteInstanceShape(t *testing.T) { ts, s := server(t, 200, `{"result":"deleted"}`) c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) if err := c.DeleteInstance(context.Background(), "scratchpad", "b-scratchpad.example.com"); err != nil { t.Fatal(err) } if s.method != "DELETE" || s.path != "/api/cli/apps/acct1/scratchpad/instances/b-scratchpad.example.com" { t.Fatalf("got %s %s", s.method, s.path) } if s.auth != "Bearer inst-tok" || s.message != "Base: uninstall" { t.Fatalf("auth %q message %q", s.auth, s.message) } } func TestErrorsCarryStatusNotBody(t *testing.T) { ts, _ := server(t, 403, "SECRET-BODY") c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) ctx := context.Background() errs := map[string]error{ "CreateInstance": c.CreateInstance(ctx, "a", "h", "e"), "DeleteInstance": c.DeleteInstance(ctx, "a", "h"), "SetEnv": c.SetEnv(ctx, "a", "e", map[string]string{"K": "V"}), } for name, err := range errs { if err == nil { t.Fatalf("%s: want error", name) } msg := err.Error() if !strings.Contains(msg, name) || !strings.Contains(msg, "403") || strings.Contains(msg, "SECRET") { t.Errorf("%s: error %q", name, msg) } } } func TestFakeRecordsAndFails(t *testing.T) { f := NewFake() ctx := context.Background() f.CreateInstance(ctx, "a", "h", "e") f.Fail("DeleteInstance", io.ErrUnexpectedEOF) if err := f.DeleteInstance(ctx, "a", "h"); err != io.ErrUnexpectedEOF { t.Fatalf("got %v", err) } f.SetEnv(ctx, "a", "e", map[string]string{"K": "V"}) calls := f.Calls() if len(calls) != 3 || calls[0].Method != "CreateInstance" || calls[1].Method != "DeleteInstance" || calls[2].Method != "SetEnv" { t.Fatalf("calls %+v", calls) } if calls[2].Vars["K"] != "V" || calls[0].Host != "h" || calls[0].Environment != "e" { t.Fatalf("args %+v", calls) } } // conflictServer answers the create with 409 and the record read with // status and body, and remembers the read's path and credential. func conflictServer(t *testing.T, status int, body string) (*httptest.Server, *seen) { t.Helper() read := &seen{} ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost { w.WriteHeader(http.StatusConflict) io.WriteString(w, `{"error":"instance already exists"}`) return } read.method, read.path, read.auth = r.Method, r.URL.Path, r.Header.Get("Authorization") w.WriteHeader(status) io.WriteString(w, body) })) t.Cleanup(ts.Close) return ts, read } // Finding 3 (R27): a 409 is success only when the existing record is this // app's instance at this host, bound to this environment. func TestCreateInstanceConflictMatchingRecord(t *testing.T) { ts, read := conflictServer(t, 200, `{"schema":1,"host":"b-scratchpad.example.com","app":"scratchpad","account":"acct1","environment":"b-scratchpad","gated":false}`) c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) if err := c.CreateInstance(context.Background(), "scratchpad", "b-scratchpad.example.com", "b-scratchpad"); err != nil { t.Fatal(err) } if read.method != "GET" || read.path != "/api/cli/apps/acct1/scratchpad/instances/b-scratchpad.example.com" || read.auth != "Bearer inst-tok" { t.Fatalf("record read %+v", read) } } func TestCreateInstanceConflictOtherRecord(t *testing.T) { for name, tc := range map[string]struct { status int body string }{ "no record for this app": {404, `404 page not found`}, "another app's record": {200, `{"host":"b-scratchpad.example.com","app":"welcome","environment":"b-scratchpad"}`}, "another environment": {200, `{"host":"b-scratchpad.example.com","app":"scratchpad","environment":"other"}`}, "no environment": {200, `{"host":"b-scratchpad.example.com","app":"scratchpad"}`}, "another host": {200, `{"host":"x.example.com","app":"scratchpad","environment":"b-scratchpad"}`}, "unreadable record": {200, `not json`}, "record read fails": {502, `{"error":"SECRET"}`}, } { t.Run(name, func(t *testing.T) { ts, _ := conflictServer(t, tc.status, tc.body) c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) err := c.CreateInstance(context.Background(), "scratchpad", "b-scratchpad.example.com", "b-scratchpad") if err == nil { t.Fatal("a conflict with another record counted as success") } if !strings.Contains(err.Error(), "CreateInstance") || strings.Contains(err.Error(), "SECRET") { t.Errorf("error %q", err) } }) } }