package transport import ( "context" "errors" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "sync" "sync/atomic" "testing" "time" "yetano.dev/yetano/yetano-clients/atlassian" ) func quietLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } // testClient starts h and returns a client against it that records // (instead of doing) every wait. func testClient(t *testing.T, h http.HandlerFunc, mod func(*atlassian.Options)) (*Client, *[]time.Duration) { t.Helper() srv := httptest.NewServer(h) t.Cleanup(srv.Close) o := atlassian.Options{BaseURL: srv.URL + "/", MaxRetries: 3, Logger: quietLogger(), Auth: atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@example.com", Password: "secret-token"}} if mod != nil { mod(&o) } c, err := New(o) if err != nil { t.Fatal(err) } var mu sync.Mutex var slept []time.Duration c.SetSleep(func(ctx context.Context, d time.Duration) error { if d > 0 { mu.Lock() slept = append(slept, d) mu.Unlock() } return ctx.Err() }) return c, &slept } func get(c *Client, path string) error { _, err := c.Do(context.Background(), http.MethodGet, path, nil, nil) return err } func TestRetryOn5xxThenSuccess(t *testing.T) { var calls atomic.Int32 c, slept := testClient(t, func(w http.ResponseWriter, r *http.Request) { if calls.Add(1) < 3 { w.WriteHeader(http.StatusBadGateway) return } fmt.Fprint(w, `{"displayName":"Ada"}`) }, nil) raw, err := c.Do(context.Background(), http.MethodGet, "/rest/api/3/myself", nil, nil) if err != nil || !strings.Contains(string(raw), "Ada") || calls.Load() != 3 { t.Fatalf("got %s, %v after %d calls", raw, err, calls.Load()) } if len(*slept) != 2 || (*slept)[0] != 2*time.Second || (*slept)[1] != 4*time.Second { t.Errorf("backoff = %v, want [2s 4s]", *slept) } } func TestRetryExhaustedReturnsAPIError(t *testing.T) { c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusServiceUnavailable) fmt.Fprint(w, "down") }, nil) err := get(c, "/x") if atlassian.StatusOf(err) != http.StatusServiceUnavailable { t.Fatalf("err = %v, want APIError 503", err) } } func TestStatusHandling(t *testing.T) { cases := []struct { status int body string wantErr bool want string }{ {200, `{"a":1}`, false, `{"a":1}`}, {201, `{"id":"1"}`, false, `{"id":"1"}`}, {204, ``, false, `{}`}, {200, ``, false, `{}`}, {200, `login`, true, ""}, {400, `{"errorMessages":["bad jql"]}`, true, ""}, {404, ``, true, ""}, } for _, tc := range cases { var calls atomic.Int32 c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) w.WriteHeader(tc.status) fmt.Fprint(w, tc.body) }, nil) raw, err := c.Do(context.Background(), http.MethodGet, "/x", nil, nil) if (err != nil) != tc.wantErr || (!tc.wantErr && string(raw) != tc.want) { t.Errorf("HTTP %d %q: got %s, %v", tc.status, tc.body, raw, err) } if tc.status >= 400 && calls.Load() != 1 { t.Errorf("HTTP %d retried %d times", tc.status, calls.Load()) } } } func TestNonJSONSuccessIsAnError(t *testing.T) { c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") fmt.Fprint(w, "SSO") }, nil) if err := get(c, "/x"); !errors.Is(err, atlassian.ErrNotJSON) { t.Fatalf("err = %v, want ErrNotJSON", err) } } func TestAPIErrorMessage(t *testing.T) { cases := map[string]string{ `{"errorMessages":["Issue does not exist"]}`: "Issue does not exist", `{"message":"No space"}`: "No space", `{"errors":{"summary":"required"}}`: "summary: required", ``: "no additional detail from upstream", `plain text`: "plain text", } for body, want := range cases { if got := (&atlassian.APIError{StatusCode: 400, Body: body}).Message(); got != want { t.Errorf("Message(%q) = %q, want %q", body, got, want) } } } func TestRateLimitDoesNotUseRetriesAndHonoursRetryAfter(t *testing.T) { var calls atomic.Int32 c, slept := testClient(t, func(w http.ResponseWriter, r *http.Request) { // four 429s in a row -- more than MaxRetries (3) if calls.Add(1) <= 4 { w.Header().Set("Retry-After", "7") w.WriteHeader(http.StatusTooManyRequests) return } fmt.Fprint(w, `{}`) }, nil) if err := get(c, "/x"); err != nil { t.Fatalf("429s must not exhaust MaxRetries: %v", err) } if calls.Load() != 5 || len(*slept) == 0 || (*slept)[0] < 6*time.Second { t.Errorf("calls = %d, waits = %v; want 5 calls, first wait about 7s (Retry-After)", calls.Load(), *slept) } } func TestRateLimitBudget(t *testing.T) { var calls atomic.Int32 c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) w.Header().Set("Retry-After", "0") w.WriteHeader(http.StatusTooManyRequests) }, nil) if err := get(c, "/x"); atlassian.StatusOf(err) != 429 { t.Fatalf("err = %v, want 429 after the budget", err) } if got := calls.Load(); got != maxRateLimitRetries+1 { t.Errorf("calls = %d, want %d", got, maxRateLimitRetries+1) } } func TestDisableRateLimitRetry(t *testing.T) { var calls atomic.Int32 c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) w.WriteHeader(http.StatusTooManyRequests) }, func(o *atlassian.Options) { o.DisableRateLimitRetry = true }) if err := get(c, "/x"); atlassian.StatusOf(err) != 429 || calls.Load() != 1 { t.Fatalf("err = %v after %d calls, want one 429", err, calls.Load()) } } func TestAuthApplied(t *testing.T) { cases := []struct { name string auth atlassian.Auth check func(r *http.Request) bool }{ {"api token", atlassian.Auth{Type: atlassian.AuthAPIToken, Username: "e@x", Password: "tok"}, func(r *http.Request) bool { u, p, ok := r.BasicAuth() return ok && u == "e@x" && p == "tok" }}, {"basic", atlassian.Auth{Type: atlassian.AuthBasic, Username: "u", Password: "p"}, func(r *http.Request) bool { u, p, ok := r.BasicAuth() return ok && u == "u" && p == "p" }}, {"pat", atlassian.Auth{Type: atlassian.AuthPAT, Token: "pat"}, func(r *http.Request) bool { return r.Header.Get("Authorization") == "Bearer pat" }}, {"bearer", atlassian.Auth{Type: atlassian.AuthBearer, Token: "b"}, func(r *http.Request) bool { return r.Header.Get("Authorization") == "Bearer b" }}, {"cookie", atlassian.Auth{Type: atlassian.AuthCookie, Cookie: "s=1"}, func(r *http.Request) bool { return r.Header.Get("Cookie") == "s=1" && r.Header.Get("Authorization") == "" }}, {"auto prefers basic over cookie", atlassian.Auth{Username: "u", Password: "p", Cookie: "s=1"}, func(r *http.Request) bool { _, _, ok := r.BasicAuth() return ok && r.Header.Get("Cookie") == "" }}, {"api token without e-mail sends nothing", atlassian.Auth{Type: atlassian.AuthAPIToken, Password: "tok"}, func(r *http.Request) bool { return r.Header.Get("Authorization") == "" }}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { if !tc.check(r) { t.Errorf("headers = %v", r.Header) } fmt.Fprint(w, `{}`) }, func(o *atlassian.Options) { o.Auth = tc.auth }) if err := get(c, "/x"); err != nil { t.Fatal(err) } }) } } func TestCrossHostRedirectDropsCredentials(t *testing.T) { other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" { t.Error("credentials followed a cross-host redirect") } fmt.Fprint(w, `{}`) })) defer other.Close() c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, other.URL+"/elsewhere", http.StatusFound) }, nil) if err := get(c, "/x"); err != nil { t.Fatal(err) } } func TestNewRejectsBadCAFile(t *testing.T) { bad := filepath.Join(t.TempDir(), "ca.pem") if err := os.WriteFile(bad, []byte("not a certificate"), 0o600); err != nil { t.Fatal(err) } for _, f := range []string{bad, filepath.Join(t.TempDir(), "missing.pem")} { if _, err := New(atlassian.Options{TLS: atlassian.TLS{CAFile: f}}); !errors.Is(err, atlassian.ErrTLSConfig) { t.Errorf("CA file %s: err = %v, want ErrTLSConfig", f, err) } } if _, err := New(atlassian.Options{ProxyURL: "://bad"}); err == nil { t.Error("bad proxy URL must be an error") } } func TestMaxResponseBytes(t *testing.T) { c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"a":"`+strings.Repeat("x", 100)+`"}`) }, func(o *atlassian.Options) { o.MaxResponseBytes = 50 }) if err := get(c, "/x"); !errors.Is(err, atlassian.ErrResponseTooLarge) { t.Fatalf("err = %v, want ErrResponseTooLarge", err) } } func TestTokenNeverInError(t *testing.T) { c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) }, nil) err := get(c, "/x") if atlassian.StatusOf(err) != 401 || strings.Contains(err.Error(), "secret-token") { t.Fatalf("err = %v", err) } } func TestContextCancelStopsBackoff(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer srv.Close() c, err := New(atlassian.Options{BaseURL: srv.URL, MaxRetries: 5, Logger: quietLogger()}) if err != nil { t.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() start := time.Now() _, err = c.Do(ctx, http.MethodGet, "/x", nil, nil) if !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("err = %v, want deadline exceeded", err) } if time.Since(start) > 2*time.Second { t.Errorf("backoff ignored the context: %s", time.Since(start)) } } func TestPaginateAdvancesByItemsReturned(t *testing.T) { var starts []string c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { start := r.URL.Query().Get("startAt") starts = append(starts, start) switch start { case "0": fmt.Fprint(w, `{"total":3,"values":[{"key":"A"},{"key":"B"}]}`) // server capped at 2 case "2": fmt.Fprint(w, `{"total":3,"values":[{"key":"C"}]}`) default: t.Errorf("unexpected startAt %s", start) } }, nil) items, err := c.Paginate(context.Background(), "/x", nil, "values", 50) if err != nil || len(items) != 3 { t.Fatalf("items = %d, err = %v", len(items), err) } if strings.Join(starts, ",") != "0,2" { t.Errorf("startAt sequence = %v", starts) } } func TestPaginateStopsOnIsLast(t *testing.T) { var calls atomic.Int32 c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { if calls.Add(1) == 1 { fmt.Fprint(w, `{"isLast":false,"values":[{"id":"1"}]}`) return } fmt.Fprint(w, `{"isLast":true,"values":[{"id":"2"}]}`) }, nil) items, err := c.Paginate(context.Background(), "/x", nil, "values", 1) if err != nil || len(items) != 2 || calls.Load() != 2 { t.Fatalf("items = %d after %d calls, err = %v", len(items), calls.Load(), err) } } func TestDownloadFile(t *testing.T) { var calls atomic.Int32 c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { switch calls.Add(1) { case 1: w.Header().Set("Retry-After", "0") w.WriteHeader(http.StatusTooManyRequests) case 2: w.WriteHeader(http.StatusBadGateway) default: if _, _, ok := r.BasicAuth(); !ok { t.Error("same-host download without credentials") } fmt.Fprint(w, "payload") } }, func(o *atlassian.Options) { o.MaxRetries = 2 }) dest := filepath.Join(t.TempDir(), "sub", "f") if err := c.DownloadFile(context.Background(), "/att/1", dest); err != nil { t.Fatal(err) } if b, _ := os.ReadFile(dest); string(b) != "payload" { t.Errorf("downloaded %q", b) } } func TestDownloadFileRedirectToOtherHostDropsCredentials(t *testing.T) { other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "" { t.Error("credentials followed a redirect to a foreign host") } fmt.Fprint(w, "x") })) defer other.Close() c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { if _, _, ok := r.BasicAuth(); !ok { t.Error("site request without credentials") } http.Redirect(w, r, other.URL+"/media?token=s", http.StatusFound) }, nil) dest := filepath.Join(t.TempDir(), "f") if err := c.DownloadFile(context.Background(), "/rest/api/3/attachment/content/1", dest); err != nil { t.Fatal(err) } if b, _ := os.ReadFile(dest); string(b) != "x" { t.Errorf("downloaded %q", b) } } func TestDownloadFileFailureRemovesPartial(t *testing.T) { c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) }, nil) dest := filepath.Join(t.TempDir(), "f") err := c.DownloadFile(context.Background(), "/att/1?sig=secret", dest) if err == nil || strings.Contains(err.Error(), "secret") { t.Fatalf("err = %v (want an error without the query)", err) } if _, statErr := os.Stat(dest); !os.IsNotExist(statErr) { t.Error("partial file left behind") } }