| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/http/httptest" |
| 6 | "runtime" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | ) |
| 10 | |
| 11 | func TestFetchManifestUsesUpdaterClientAndRejectsChallenges(t *testing.T) { |
| 12 | for _, test := range []struct { |
| 13 | name, body, mitigation string |
| 14 | status int |
| 15 | wantError string |
| 16 | }{ |
| 17 | {name: "public manifest", body: `{"version":"v1.38.11"}`, status: http.StatusOK}, |
| 18 | {name: "challenge", body: "<html>challenge</html>", status: http.StatusForbidden, mitigation: "challenge", wantError: "HTTP 403"}, |
| 19 | {name: "malformed JSON", body: "<html>challenge</html>", status: http.StatusOK, wantError: "not JSON"}, |
| 20 | {name: "invalid version", body: `{"version":"preview"}`, status: http.StatusOK, wantError: "valid Stable version"}, |
| 21 | } { |
| 22 | t.Run(test.name, func(t *testing.T) { |
| 23 | server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { |
| 24 | wantAgent := "Reasonix-Updater/v1.38.12 (" + runtime.GOOS + "/" + runtime.GOARCH + "; build=stable; update=stable)" |
| 25 | if got := request.Header.Get("User-Agent"); got != wantAgent { |
| 26 | t.Errorf("User-Agent = %q, want %q", got, wantAgent) |
| 27 | } |
| 28 | writer.Header().Set("cf-mitigated", test.mitigation) |
| 29 | writer.WriteHeader(test.status) |
| 30 | _, _ = writer.Write([]byte(test.body)) |
| 31 | })) |
| 32 | defer server.Close() |
| 33 | body, err := fetchManifest(server.Client(), server.URL, "1.38.12") |
| 34 | if test.wantError != "" { |
| 35 | if err == nil || !strings.Contains(err.Error(), test.wantError) { |
| 36 | t.Fatalf("error = %v, want %q", err, test.wantError) |
| 37 | } |
| 38 | if len(body) != 0 { |
| 39 | t.Fatalf("failed response returned %d bytes", len(body)) |
| 40 | } |
| 41 | return |
| 42 | } |
| 43 | if err != nil || string(body) != test.body { |
| 44 | t.Fatalf("body = %q, error = %v", body, err) |
| 45 | } |
| 46 | }) |
| 47 | } |
| 48 | } |
| 49 |