| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | ) |
| 10 | |
| 11 | func TestBrowserCopyContextUsesAuthenticatedGuestRoute(t *testing.T) { |
| 12 | s := testServer(t) |
| 13 | s.ready, s.credentials.Token = true, "private-test-token" |
| 14 | calls := 0 |
| 15 | s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { |
| 16 | calls++ |
| 17 | if r.Method != http.MethodPost || r.URL.Path != "/copy-context" || r.Header.Get("Authorization") != "Bearer private-test-token" { |
| 18 | t.Fatalf("unexpected copy route: %s %s", r.Method, r.URL.Path) |
| 19 | } |
| 20 | var input browserInput |
| 21 | if err := json.NewDecoder(r.Body).Decode(&input); err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | if input.ID != "tab" || input.Context != strings.Repeat("a", 32) { |
| 25 | t.Fatal("copy context or tab was lost") |
| 26 | } |
| 27 | return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"ok":true}`))}, nil |
| 28 | })) |
| 29 | body := `{"id":"tab","context":"` + strings.Repeat("a", 32) + `"}` |
| 30 | if response := request(s, "POST", "/api/browser/copy-context", s.origin, body, true); response.Code != http.StatusOK { |
| 31 | t.Fatalf("copy context: %d %s", response.Code, response.Body.String()) |
| 32 | } |
| 33 | for _, body := range []string{`{"id":"tab"}`, `{"context":"invalid"}`} { |
| 34 | if response := request(s, "POST", "/api/browser/copy-context", s.origin, body, true); response.Code != http.StatusBadRequest { |
| 35 | t.Fatalf("invalid copy context accepted: %d", response.Code) |
| 36 | } |
| 37 | } |
| 38 | if response := request(s, "POST", "/api/browser/copy-context", s.origin, body, false); response.Code != http.StatusUnauthorized { |
| 39 | t.Fatalf("unauthenticated copy context accepted: %d", response.Code) |
| 40 | } |
| 41 | if calls != 1 { |
| 42 | t.Fatalf("rejected request reached guest: %d calls", calls) |
| 43 | } |
| 44 | } |