|
| 1 | +package paypal |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "sync/atomic" |
| 9 | + "testing" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/plutov/paypal/v4/limiter" |
| 13 | + "github.com/stretchr/testify/assert" |
| 14 | +) |
| 15 | + |
| 16 | +type okResp struct { |
| 17 | + OK bool `json:"ok"` |
| 18 | +} |
| 19 | + |
| 20 | +func newTestServer() (*httptest.Server, *int32, *int32) { |
| 21 | + tokenHits := new(int32) |
| 22 | + apiHits := new(int32) |
| 23 | + mux := http.NewServeMux() |
| 24 | + mux.HandleFunc("/v1/oauth2/token", func(w http.ResponseWriter, r *http.Request) { |
| 25 | + atomic.AddInt32(tokenHits, 1) |
| 26 | + w.Header().Set("Content-Type", "application/json") |
| 27 | + _ = json.NewEncoder(w).Encode(map[string]any{ |
| 28 | + "access_token": "test-token", |
| 29 | + "token_type": "Bearer", |
| 30 | + "expires_in": 3600, |
| 31 | + }) |
| 32 | + }) |
| 33 | + mux.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) { |
| 34 | + atomic.AddInt32(apiHits, 1) |
| 35 | + if r.Header.Get("Authorization") == "" { |
| 36 | + w.WriteHeader(http.StatusUnauthorized) |
| 37 | + return |
| 38 | + } |
| 39 | + w.Header().Set("Content-Type", "application/json") |
| 40 | + _ = json.NewEncoder(w).Encode(okResp{OK: true}) |
| 41 | + }) |
| 42 | + return httptest.NewServer(mux), tokenHits, apiHits |
| 43 | +} |
| 44 | + |
| 45 | +func newClientForServer(t *testing.T, s *httptest.Server) *Client { |
| 46 | + t.Helper() |
| 47 | + c, err := NewClient("id", "secret", s.URL) |
| 48 | + if err != nil { |
| 49 | + t.Fatalf("new client: %v", err) |
| 50 | + } |
| 51 | + c.SetHTTPClient(s.Client()) |
| 52 | + return c |
| 53 | +} |
| 54 | + |
| 55 | +func TestClientLimiter_BlocksWhenInsufficientPermitsForTokenAndRequest(t *testing.T) { |
| 56 | + s, tokenHits, apiHits := newTestServer() |
| 57 | + defer s.Close() |
| 58 | + c := newClientForServer(t, s) |
| 59 | + |
| 60 | + // limiter allows only 1 request, but we need 2 (token + api) |
| 61 | + lim := limiter.NewFixedWindowLimiter(limiter.NewMemoryStorage(), limiter.FixedWindowConfig{Window: time.Minute, Limit: 1}) |
| 62 | + c.SetLimiter(lim, "test-key") |
| 63 | + |
| 64 | + req, _ := c.NewRequest(context.Background(), http.MethodGet, s.URL+"/api", nil) |
| 65 | + var out okResp |
| 66 | + err := c.SendWithAuth(req, &out) |
| 67 | + assert.Error(t, err) |
| 68 | + assert.Equal(t, ErrRateLimited, err) |
| 69 | + // should have short-circuited before hitting network |
| 70 | + assert.Equal(t, int32(0), atomic.LoadInt32(tokenHits)) |
| 71 | + assert.Equal(t, int32(0), atomic.LoadInt32(apiHits)) |
| 72 | +} |
| 73 | + |
| 74 | +func TestClientLimiter_AllowsWithSufficientPermitsForTokenAndRequest(t *testing.T) { |
| 75 | + s, tokenHits, apiHits := newTestServer() |
| 76 | + defer s.Close() |
| 77 | + c := newClientForServer(t, s) |
| 78 | + |
| 79 | + // need 2 permits and we have 2 |
| 80 | + lim := limiter.NewFixedWindowLimiter(limiter.NewMemoryStorage(), limiter.FixedWindowConfig{Window: time.Minute, Limit: 2}) |
| 81 | + c.SetLimiter(lim, "test-key") |
| 82 | + |
| 83 | + req, _ := c.NewRequest(context.Background(), http.MethodGet, s.URL+"/api", nil) |
| 84 | + var out okResp |
| 85 | + err := c.SendWithAuth(req, &out) |
| 86 | + assert.NoError(t, err) |
| 87 | + assert.True(t, out.OK) |
| 88 | + assert.Equal(t, int32(1), atomic.LoadInt32(tokenHits)) |
| 89 | + assert.Equal(t, int32(1), atomic.LoadInt32(apiHits)) |
| 90 | +} |
| 91 | + |
| 92 | +func TestClientLimiter_ConsumesOnePermitWhenTokenAlreadySet(t *testing.T) { |
| 93 | + s, tokenHits, apiHits := newTestServer() |
| 94 | + defer s.Close() |
| 95 | + c := newClientForServer(t, s) |
| 96 | + |
| 97 | + // set token so we don't need refresh |
| 98 | + c.SetAccessToken("preset") |
| 99 | + // allow only 1 permit |
| 100 | + lim := limiter.NewFixedWindowLimiter(limiter.NewMemoryStorage(), limiter.FixedWindowConfig{Window: time.Minute, Limit: 1}) |
| 101 | + c.SetLimiter(lim, "test-key") |
| 102 | + |
| 103 | + req, _ := c.NewRequest(context.Background(), http.MethodGet, s.URL+"/api", nil) |
| 104 | + var out okResp |
| 105 | + err := c.SendWithAuth(req, &out) |
| 106 | + assert.NoError(t, err) |
| 107 | + assert.True(t, out.OK) |
| 108 | + assert.Equal(t, int32(0), atomic.LoadInt32(*&tokenHits)) |
| 109 | + assert.Equal(t, int32(1), atomic.LoadInt32(apiHits)) |
| 110 | +} |
| 111 | + |
| 112 | +func TestClientLimiter_TokenSoonToExpire_ConsumesTwoPermits(t *testing.T) { |
| 113 | + s, tokenHits, apiHits := newTestServer() |
| 114 | + defer s.Close() |
| 115 | + c := newClientForServer(t, s) |
| 116 | + |
| 117 | + // pre-existing token but expiring soon (< 60s) |
| 118 | + c.Token = &TokenResponse{Token: "old"} |
| 119 | + c.tokenExpiresAt = time.Now().Add(5 * time.Second) |
| 120 | + |
| 121 | + // need 2 permits; provide exactly 2 |
| 122 | + lim := limiter.NewFixedWindowLimiter(limiter.NewMemoryStorage(), limiter.FixedWindowConfig{Window: time.Minute, Limit: 2}) |
| 123 | + c.SetLimiter(lim, "test-key") |
| 124 | + |
| 125 | + req, _ := c.NewRequest(context.Background(), http.MethodGet, s.URL+"/api", nil) |
| 126 | + var out okResp |
| 127 | + err := c.SendWithAuth(req, &out) |
| 128 | + assert.NoError(t, err) |
| 129 | + assert.True(t, out.OK) |
| 130 | + assert.Equal(t, int32(1), atomic.LoadInt32(tokenHits)) |
| 131 | + assert.Equal(t, int32(1), atomic.LoadInt32(apiHits)) |
| 132 | +} |
0 commit comments