http_test.go341 lines, 11 KB
| 1 | package wallet_test |
| 2 | |
| 3 | import ( |
| 4 | "crypto/ed25519" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/fiston-user/payments/internal/auth" |
| 15 | "github.com/fiston-user/payments/internal/platform/authn" |
| 16 | "github.com/fiston-user/payments/internal/platform/idempotency" |
| 17 | "github.com/fiston-user/payments/internal/wallet" |
| 18 | "github.com/google/uuid" |
| 19 | ) |
| 20 | |
| 21 | // testAPI is the wallet API on the test database, behind authn.Require, and |
| 22 | // without the Redis cache: Postgres alone must get idempotency right. |
| 23 | type testAPI struct { |
| 24 | api http.Handler |
| 25 | signer *auth.Signer |
| 26 | } |
| 27 | |
| 28 | func newAPI(t *testing.T) testAPI { |
| 29 | t.Helper() |
| 30 | pool := newPool(t) |
| 31 | svc := wallet.NewService(wallet.NewStore(pool)) |
| 32 | mux := http.NewServeMux() |
| 33 | wallet.NewHandler(svc, idempotency.NewStore(pool, nil)).Register(mux) |
| 34 | pub, key, _ := ed25519.GenerateKey(nil) |
| 35 | return testAPI{authn.NewVerifier(pub).Require(mux), auth.NewSigner(key, time.Minute)} |
| 36 | } |
| 37 | |
| 38 | // user returns the API as a new user sees it, with their access token. |
| 39 | func (a testAPI) user(t *testing.T) http.Handler { |
| 40 | t.Helper() |
| 41 | token, err := a.signer.Issue(uuid.New(), time.Now()) |
| 42 | if err != nil { |
| 43 | t.Fatalf("issue token: %v", err) |
| 44 | } |
| 45 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 46 | r.Header.Set("Authorization", "Bearer "+token) |
| 47 | a.api.ServeHTTP(w, r) |
| 48 | }) |
| 49 | } |
| 50 | |
| 51 | // call sends one request to api, and returns the recorded response. Each call |
| 52 | // has a fresh idempotency key, like a new request from a well-behaved client. |
| 53 | func call(api http.Handler, method, path, body string) *httptest.ResponseRecorder { |
| 54 | return callWithKey(api, method, path, uuid.NewString(), body) |
| 55 | } |
| 56 | |
| 57 | // callWithKey sends a request with the idempotency key we pick: the same key |
| 58 | // again is a retry. |
| 59 | func callWithKey(api http.Handler, method, path, key, body string) *httptest.ResponseRecorder { |
| 60 | req := httptest.NewRequest(method, path, strings.NewReader(body)) |
| 61 | req.Header.Set(idempotency.KeyHeader, key) |
| 62 | rr := httptest.NewRecorder() |
| 63 | api.ServeHTTP(rr, req) |
| 64 | return rr |
| 65 | } |
| 66 | |
| 67 | // decode reads a JSON response into a T, the way a client would. |
| 68 | func decode[T any](t *testing.T, rr *httptest.ResponseRecorder) T { |
| 69 | t.Helper() |
| 70 | var v T |
| 71 | if err := json.Unmarshal(rr.Body.Bytes(), &v); err != nil { |
| 72 | t.Fatalf("decode %s: %v", rr.Body, err) |
| 73 | } |
| 74 | return v |
| 75 | } |
| 76 | |
| 77 | // The parts of our responses the tests look at. |
| 78 | type ( |
| 79 | walletJSON struct { |
| 80 | ID string `json:"id"` |
| 81 | } |
| 82 | balanceJSON struct { |
| 83 | Balance wallet.Money `json:"balance"` |
| 84 | } |
| 85 | entriesJSON struct { |
| 86 | Entries []struct { |
| 87 | Amount wallet.Money `json:"amount"` |
| 88 | } `json:"entries"` |
| 89 | NextCursor string `json:"next_cursor"` |
| 90 | } |
| 91 | errorJSON struct { |
| 92 | Error struct { |
| 93 | Code string `json:"code"` |
| 94 | } `json:"error"` |
| 95 | } |
| 96 | ) |
| 97 | |
| 98 | func walletBody(currency string) string { |
| 99 | return fmt.Sprintf(`{"currency": %q}`, currency) |
| 100 | } |
| 101 | |
| 102 | // createWallet opens a wallet for the user, and returns its ID. |
| 103 | func createWallet(t *testing.T, api http.Handler, currency string) string { |
| 104 | t.Helper() |
| 105 | rr := call(api, "POST", "/v1/wallets", walletBody(currency)) |
| 106 | if rr.Code != http.StatusCreated { |
| 107 | t.Fatalf("create wallet: status %d: %s", rr.Code, rr.Body) |
| 108 | } |
| 109 | return decode[walletJSON](t, rr).ID |
| 110 | } |
| 111 | |
| 112 | func TestCreateWallet(t *testing.T) { |
| 113 | t.Parallel() |
| 114 | api := newAPI(t).user(t) |
| 115 | |
| 116 | // The rows run in order: the duplicate needs the wallet from the first. |
| 117 | tests := []struct { |
| 118 | name string |
| 119 | body string |
| 120 | status int |
| 121 | code string |
| 122 | }{ |
| 123 | {"created", walletBody("USD"), 201, ""}, |
| 124 | {"one per currency", walletBody("USD"), 409, "conflict"}, |
| 125 | {"another currency", walletBody("JPY"), 201, ""}, |
| 126 | {"lowercase currency", walletBody("usd"), 422, "invalid_input"}, |
| 127 | {"unsupported currency", walletBody("XYZ"), 422, "invalid_input"}, |
| 128 | {"owner in the body", `{"owner_id": "alice", "currency": "EUR"}`, 400, "bad_request"}, |
| 129 | {"unknown field", `{"currency": "USD", "balance": 100}`, 400, "bad_request"}, |
| 130 | } |
| 131 | for _, tt := range tests { |
| 132 | t.Run(tt.name, func(t *testing.T) { |
| 133 | rr := call(api, "POST", "/v1/wallets", tt.body) |
| 134 | if rr.Code != tt.status { |
| 135 | t.Fatalf("status = %d, want %d: %s", rr.Code, tt.status, rr.Body) |
| 136 | } |
| 137 | // A success has no error object, so its code is empty. |
| 138 | if got := decode[errorJSON](t, rr).Error.Code; got != tt.code { |
| 139 | t.Errorf("code = %q, want %q", got, tt.code) |
| 140 | } |
| 141 | }) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | func TestDeposit(t *testing.T) { |
| 146 | t.Parallel() |
| 147 | env := newAPI(t) |
| 148 | api := env.user(t) |
| 149 | id, theirs := createWallet(t, api, "USD"), createWallet(t, env.user(t), "USD") |
| 150 | |
| 151 | tests := []struct { |
| 152 | name string |
| 153 | wallet string |
| 154 | body string |
| 155 | status int |
| 156 | }{ |
| 157 | {"deposited", id, `{"amount": 2500, "currency": "USD"}`, 201}, |
| 158 | {"zero", id, `{"amount": 0, "currency": "USD"}`, 422}, |
| 159 | {"negative", id, `{"amount": -2500, "currency": "USD"}`, 422}, |
| 160 | {"over the maximum", id, `{"amount": 100000001, "currency": "USD"}`, 422}, |
| 161 | {"wrong currency", id, `{"amount": 2500, "currency": "EUR"}`, 422}, |
| 162 | {"decimal amount", id, `{"amount": 25.00, "currency": "USD"}`, 400}, |
| 163 | {"amount as a string", id, `{"amount": "2500", "currency": "USD"}`, 400}, |
| 164 | {"unknown wallet", uuid.NewString(), `{"amount": 2500, "currency": "USD"}`, 404}, |
| 165 | {"malformed wallet ID", "42", `{"amount": 2500, "currency": "USD"}`, 404}, |
| 166 | {"someone else's wallet", theirs, `{"amount": 2500, "currency": "USD"}`, 404}, |
| 167 | } |
| 168 | for _, tt := range tests { |
| 169 | t.Run(tt.name, func(t *testing.T) { |
| 170 | rr := call(api, "POST", "/v1/wallets/"+tt.wallet+"/deposits", tt.body) |
| 171 | if rr.Code != tt.status { |
| 172 | t.Errorf("status = %d, want %d: %s", rr.Code, tt.status, rr.Body) |
| 173 | } |
| 174 | }) |
| 175 | } |
| 176 | |
| 177 | // Only the first deposit was valid, so only it may have moved money. |
| 178 | rr := call(api, "GET", "/v1/wallets/"+id+"/balance", "") |
| 179 | if got := decode[balanceJSON](t, rr).Balance; got != (wallet.Money{Amount: 2500, Currency: "USD"}) { |
| 180 | t.Errorf("balance = %+v, want 2500 USD", got) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func TestEntriesPagination(t *testing.T) { |
| 185 | t.Parallel() |
| 186 | api := newAPI(t).user(t) |
| 187 | id := createWallet(t, api, "EUR") |
| 188 | for _, amount := range []int{100, 200, 300} { |
| 189 | body := fmt.Sprintf(`{"amount": %d, "currency": "EUR"}`, amount) |
| 190 | if rr := call(api, "POST", "/v1/wallets/"+id+"/deposits", body); rr.Code != http.StatusCreated { |
| 191 | t.Fatalf("deposit %d: status %d: %s", amount, rr.Code, rr.Body) |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | // Follow the cursors, two entries per page, and collect every amount. |
| 196 | var amounts []int64 |
| 197 | pages, cursor := 0, "" |
| 198 | for pages < 5 { |
| 199 | rr := call(api, "GET", "/v1/wallets/"+id+"/entries?limit=2&cursor="+cursor, "") |
| 200 | if rr.Code != http.StatusOK { |
| 201 | t.Fatalf("status = %d: %s", rr.Code, rr.Body) |
| 202 | } |
| 203 | page := decode[entriesJSON](t, rr) |
| 204 | for _, e := range page.Entries { |
| 205 | amounts = append(amounts, e.Amount.Amount) |
| 206 | } |
| 207 | pages++ |
| 208 | if cursor = page.NextCursor; cursor == "" { |
| 209 | break |
| 210 | } |
| 211 | } |
| 212 | // Newest first, and every entry exactly once. |
| 213 | if want := []int64{300, 200, 100}; !slices.Equal(amounts, want) || pages != 2 { |
| 214 | t.Errorf("got %v in %d pages, want %v in 2", amounts, pages, want) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | func TestEntriesRejectsBadQueries(t *testing.T) { |
| 219 | t.Parallel() |
| 220 | api := newAPI(t).user(t) |
| 221 | id := createWallet(t, api, "USD") |
| 222 | |
| 223 | for _, query := range []string{"limit=0", "limit=101", "limit=ten", "cursor=not-a-cursor"} { |
| 224 | t.Run(query, func(t *testing.T) { |
| 225 | rr := call(api, "GET", "/v1/wallets/"+id+"/entries?"+query, "") |
| 226 | if rr.Code != http.StatusUnprocessableEntity { |
| 227 | t.Errorf("status = %d, want 422: %s", rr.Code, rr.Body) |
| 228 | } |
| 229 | }) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | func TestTransferEndpoint(t *testing.T) { |
| 234 | t.Parallel() |
| 235 | env := newAPI(t) |
| 236 | api, bobs := env.user(t), env.user(t) |
| 237 | alice, euros := createWallet(t, api, "USD"), createWallet(t, api, "EUR") |
| 238 | bob := createWallet(t, bobs, "USD") |
| 239 | if rr := call(api, "POST", "/v1/wallets/"+alice+"/deposits", `{"amount": 1000, "currency": "USD"}`); rr.Code != http.StatusCreated { |
| 240 | t.Fatalf("deposit: status %d: %s", rr.Code, rr.Body) |
| 241 | } |
| 242 | |
| 243 | // The rows run in order: the second transfer needs the money the first one spent. |
| 244 | tests := []struct { |
| 245 | name string |
| 246 | from, to string |
| 247 | amount int64 |
| 248 | currency string |
| 249 | status int |
| 250 | code string |
| 251 | }{ |
| 252 | {"transferred", alice, bob, 600, "USD", 201, ""}, |
| 253 | {"insufficient funds", alice, bob, 600, "USD", 422, "insufficient_funds"}, |
| 254 | {"to the same wallet", alice, alice, 100, "USD", 422, "invalid_input"}, |
| 255 | {"to another currency", alice, euros, 100, "USD", 422, "invalid_input"}, |
| 256 | {"wrong currency", alice, bob, 100, "EUR", 422, "invalid_input"}, |
| 257 | {"unknown wallet", alice, uuid.NewString(), 100, "USD", 422, "invalid_input"}, |
| 258 | {"from someone else's wallet", bob, alice, 100, "USD", 422, "invalid_input"}, |
| 259 | {"zero", alice, bob, 0, "USD", 422, "invalid_input"}, |
| 260 | } |
| 261 | for _, tt := range tests { |
| 262 | t.Run(tt.name, func(t *testing.T) { |
| 263 | body := fmt.Sprintf(`{"from": %q, "to": %q, "amount": %d, "currency": %q}`, tt.from, tt.to, tt.amount, tt.currency) |
| 264 | rr := call(api, "POST", "/v1/transfers", body) |
| 265 | if rr.Code != tt.status { |
| 266 | t.Fatalf("status = %d, want %d: %s", rr.Code, tt.status, rr.Body) |
| 267 | } |
| 268 | if got := decode[errorJSON](t, rr).Error.Code; got != tt.code { |
| 269 | t.Errorf("code = %q, want %q", got, tt.code) |
| 270 | } |
| 271 | }) |
| 272 | } |
| 273 | |
| 274 | // Six dollars moved, exactly once. |
| 275 | expectBalance(t, api, alice, 400) |
| 276 | expectBalance(t, bobs, bob, 600) |
| 277 | } |
| 278 | |
| 279 | // expectBalance checks a wallet's balance, as its owner sees it. |
| 280 | func expectBalance(t *testing.T, api http.Handler, id string, want int64) { |
| 281 | t.Helper() |
| 282 | rr := call(api, "GET", "/v1/wallets/"+id+"/balance", "") |
| 283 | if got := decode[balanceJSON](t, rr).Balance.Amount; got != want { |
| 284 | t.Errorf("balance of %s = %d, want %d", id, got, want) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | func TestTransferRetryStorm(t *testing.T) { |
| 289 | t.Parallel() |
| 290 | env := newAPI(t) |
| 291 | api, bobs := env.user(t), env.user(t) |
| 292 | alice, bob := createWallet(t, api, "USD"), createWallet(t, bobs, "USD") |
| 293 | deposit := call(api, "POST", "/v1/wallets/"+alice+"/deposits", `{"amount": 1000, "currency": "USD"}`) |
| 294 | if deposit.Code != http.StatusCreated { |
| 295 | t.Fatalf("deposit: status %d: %s", deposit.Code, deposit.Body) |
| 296 | } |
| 297 | |
| 298 | // One transfer, sent twenty times at once with the same key: a client that |
| 299 | // retries in a panic. Collect every response. |
| 300 | key := uuid.NewString() |
| 301 | body := fmt.Sprintf(`{"from": %q, "to": %q, "amount": 100, "currency": "USD"}`, alice, bob) |
| 302 | responses := make(chan *httptest.ResponseRecorder, 20) |
| 303 | concurrently(20, func() error { |
| 304 | responses <- callWithKey(api, "POST", "/v1/transfers", key, body) |
| 305 | return nil |
| 306 | }) |
| 307 | close(responses) |
| 308 | |
| 309 | // Exactly one ran. The rest were refused while it was running, or got its |
| 310 | // response replayed, byte for byte. |
| 311 | ran, replayed, refused := 0, 0, 0 |
| 312 | bodies := make(map[string]bool) |
| 313 | for rr := range responses { |
| 314 | switch { |
| 315 | case rr.Code == http.StatusConflict: |
| 316 | refused++ |
| 317 | continue |
| 318 | case rr.Code != http.StatusCreated: |
| 319 | t.Fatalf("status = %d: %s", rr.Code, rr.Body) |
| 320 | case rr.Header().Get(idempotency.ReplayedHeader) == "true": |
| 321 | replayed++ |
| 322 | default: |
| 323 | ran++ |
| 324 | } |
| 325 | bodies[rr.Body.String()] = true |
| 326 | } |
| 327 | t.Logf("%d ran, %d replayed, %d refused as in progress", ran, replayed, refused) |
| 328 | if ran != 1 || len(bodies) != 1 { |
| 329 | t.Errorf("%d requests ran, with %d different bodies; want exactly 1 of each", ran, len(bodies)) |
| 330 | } |
| 331 | |
| 332 | // Now that it's done, a retry gets the stored response. |
| 333 | rr := callWithKey(api, "POST", "/v1/transfers", key, body) |
| 334 | if rr.Header().Get(idempotency.ReplayedHeader) != "true" || !bodies[rr.Body.String()] { |
| 335 | t.Errorf("retry: status %d, not the stored response: %s", rr.Code, rr.Body) |
| 336 | } |
| 337 | |
| 338 | // And the money moved once: one dollar, not twenty. |
| 339 | expectBalance(t, api, alice, 900) |
| 340 | expectBalance(t, bobs, bob, 100) |
| 341 | } |