1package server 2 3import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "net/http" 9 "net/http/httptest" 10 "os" 11 "path/filepath" 12 "strconv" 13 "strings" 14 "testing" 15 16 "tinyadventure/internal/model" 17) 18 19const testPlayer = "0123456789abcdef0123456789abcdef" 20 21type client struct { 22 t *testing.T 23 ts *httptest.Server 24 player string 25} 26 27func open(t *testing.T, seed model.Seed, dir string) (*Server, client) { 28 srv, err := New(seed, t.TempDir(), dir) 29 if err != nil { 30 t.Fatal(err) 31 } 32 ts := httptest.NewServer(srv) 33 t.Cleanup(ts.Close) 34 return srv, client{t, ts, testPlayer} 35} 36 37func (c client) raw(method, path string, body any) (*http.Response, []byte) { 38 c.t.Helper() 39 b, _ := json.Marshal(body) 40 req, _ := http.NewRequest(method, c.ts.URL+path, bytes.NewReader(b)) 41 req.Header.Set("X-Player", c.player) 42 res, err := http.DefaultClient.Do(req) 43 if err != nil { 44 c.t.Fatal(err) 45 } 46 defer res.Body.Close() 47 out, _ := io.ReadAll(res.Body) 48 return res, out 49} 50 51func (c client) call(method, path string, body any, want int) model.GameState { 52 c.t.Helper() 53 res, b := c.raw(method, path, body) 54 if res.StatusCode != want { 55 c.t.Fatalf("%s %s: status %d, want %d: %s", method, path, res.StatusCode, want, b) 56 } 57 var st model.GameState 58 json.Unmarshal(b, &st) 59 return st 60} 61 62func firstFight(t *testing.T, c client) model.GameState { 63 st := c.call("GET", "/api/state", nil, 200) 64 p := (&game{state: st}).poi(st.Campaign.Main.Steps[0].POI) 65 c.call("POST", "/api/move", model.Action{X: p.X, Y: p.Y}, 200) 66 return c.call("POST", "/api/interact", model.Action{ID: p.ID}, 200) 67} 68 69func TestHTTPFlow(t *testing.T) { 70 _, c := open(t, 7, "") 71 st := c.call("GET", "/api/state", nil, 200) 72 if st.Phase != "explore" || st.Shop == nil || st.Clock.Day != 1 || st.Feedback { 73 t.Fatalf("bad start: %s shop %v clock %+v feedback %v", st.Phase, st.Shop, st.Clock, st.Feedback) 74 } 75 c.call("POST", "/api/rest", nil, 400) 76 if st = c.call("POST", "/api/buy", model.Action{Item: "potion"}, 200); st.Party.Potions != 1 { 77 t.Fatalf("potions %d", st.Party.Potions) 78 } 79 st = firstFight(t, c) 80 if len(st.Log) == 0 || st.Encounter == nil || st.Summary.Battles != 1 || st.Summary.Dealt == 0 { 81 t.Fatalf("fight without log, encounter or tally: %+v", st.Summary) 82 } 83 c.call("POST", "/api/sell", model.Action{Item: "nope"}, 400) 84 c.call("POST", "/api/nope", nil, 404) 85} 86 87func TestRejections(t *testing.T) { 88 _, c := open(t, 3, "") 89 c.call("POST", "/api/move", model.Action{X: -1, Y: 0}, 400) 90 c.call("POST", "/api/interact", model.Action{ID: "nope"}, 400) 91 c.call("POST", "/api/equip", model.Action{Unit: "u1", Item: "nope"}, 400) 92 res, _ := c.raw("POST", "/api/feedback", model.Action{Text: strings.Repeat("a", maxBody)}) 93 if res.StatusCode != 400 { 94 t.Fatalf("oversized body gave %d", res.StatusCode) 95 } 96} 97 98func TestPlayersGetTheirOwnBoards(t *testing.T) { 99 _, a := open(t, 11, "") 100 b := a 101 b.player = strings.Repeat("f", 32) 102 sp := a.call("GET", "/api/state", nil, 200).Map.Spawns[1] 103 a.call("POST", "/api/move", model.Action{X: sp.X, Y: sp.Y}, 200) 104 if st := b.call("GET", "/api/state", nil, 200); st.Clock.Time != 0 || st.Game == a.call("GET", "/api/state", nil, 200).Game { 105 t.Fatalf("second player shares the first board: %+v", st.Clock) 106 } 107 res, _ := http.Get(a.ts.URL + "/api/state") 108 if c := res.Cookies(); len(c) != 1 || c[0].Name != cookieName || !c[0].HttpOnly || !playerID.MatchString(c[0].Value) { 109 t.Fatalf("cookie %+v", c) 110 } 111} 112 113func TestNewCampaign(t *testing.T) { 114 _, c := open(t, 11, "") 115 a := c.call("GET", "/api/state", nil, 200) 116 sp := a.Map.Spawns[1] 117 c.call("POST", "/api/move", model.Action{X: sp.X, Y: sp.Y}, 200) 118 b := c.call("POST", "/api/new", nil, 200) 119 if b.Seed == a.Seed || b.Game == a.Game || b.Clock.Time != 0 || b.Phase != "explore" { 120 t.Fatalf("not fresh: %d vs %d %+v", a.Seed, b.Seed, b.Clock) 121 } 122 if d := c.call("POST", "/api/new", map[string]int{"seed": 99}, 200); d.Seed != 99 { 123 t.Fatalf("seed %d", d.Seed) 124 } 125} 126 127func TestFinishedCampaignRejectsActions(t *testing.T) { 128 srv, c := open(t, 7, "") 129 g, _ := srv.game(testPlayer) 130 g.state.Phase = "defeat" 131 c.call("POST", "/api/move", model.Action{X: 1, Y: 1}, 400) 132 c.call("POST", "/api/rest", nil, 400) 133 if st := c.call("GET", "/api/state", nil, 200); st.Phase != "defeat" { 134 t.Fatalf("phase %s", st.Phase) 135 } 136 c.call("POST", "/api/new", nil, 200) 137} 138 139func TestPathPreviewMatchesTheWalk(t *testing.T) { 140 srv, c := open(t, 7, "") 141 g, _ := srv.game(testPlayer) 142 tx, ty := g.state.Party.X+3, g.state.Party.Y 143 for !g.state.Map.Walkable(tx, ty) || g.blocker(tx, ty) != "" { 144 tx++ 145 } 146 res, b := c.raw("GET", "/api/path?x="+strconv.Itoa(tx)+"&y="+strconv.Itoa(ty), nil) 147 var route model.Route 148 json.Unmarshal(b, &route) 149 want, _ := g.path(tx, ty) 150 if res.StatusCode != 200 || len(route.Path) == 0 || route.Time <= 0 || route.Path[len(route.Path)-1] != want[len(route.Path)-1] { 151 t.Fatalf("route %+v want %v", route, want) 152 } 153 if res, _ := c.raw("GET", "/api/path?x=a&y=1", nil); res.StatusCode != 400 { 154 t.Fatalf("bad query gave %d", res.StatusCode) 155 } 156} 157 158func TestPathPreviewCountsTheHazardHp(t *testing.T) { 159 for seed := model.Seed(1); seed <= 20; seed++ { 160 srv, c := open(t, seed, "") 161 g, _ := srv.game(testPlayer) 162 hp := func() int { 163 n := 0 164 for _, u := range g.state.Party.Units { 165 n += u.Stats.HP 166 } 167 return n 168 } 169 for dx := -6; dx <= 6; dx++ { 170 for dy := -6; dy <= 6; dy++ { 171 tx, ty := g.state.Party.X+dx, g.state.Party.Y+dy 172 route, err := g.route(tx, ty) 173 if err != nil || route.Hazard == 0 || route.Blocked != "" { 174 continue 175 } 176 before := hp() 177 c.call("POST", "/api/move", model.Action{X: tx, Y: ty}, 200) 178 if g.state.Party.X != tx || g.state.Party.Y != ty { 179 t.Skipf("seed %d: a band cut the walk short", seed) 180 } 181 if lost := before - hp(); lost != route.Hazard { 182 t.Fatalf("seed %d: preview %d hp, walk cost %d", seed, route.Hazard, lost) 183 } 184 return 185 } 186 } 187 } 188 t.Fatal("no route with a hazard near any spawn") 189} 190 191func TestTheLogReplaysToTheSameGame(t *testing.T) { 192 dir := t.TempDir() 193 srv, c := open(t, 7, dir) 194 c.call("POST", "/api/buy", model.Action{Item: "potion"}, 200) 195 c.call("POST", "/api/rest", nil, 400) 196 live := firstFight(t, c) 197 for _, it := range live.Party.Inventory { 198 c.call("POST", "/api/equip", model.Action{Unit: live.Party.Units[0].ID, Item: it.ID}, 200) 199 } 200 live = c.call("GET", "/api/state", nil, 200) 201 srv.seats = map[string]*seat{} 202 again := c.call("GET", "/api/state", nil, 200) 203 again.Summary.Seconds, live.Summary.Seconds = 0, 0 204 a, _ := json.Marshal(live) 205 b, _ := json.Marshal(again) 206 if !bytes.Equal(a, b) { 207 t.Fatalf("replay differs from the live game") 208 } 209 log, _ := os.ReadFile(filepath.Join(dir, "games", live.Game+".jsonl")) 210 if n := bytes.Count(log, []byte("\n")); n < 4 || bytes.Contains(log, []byte(testPlayer)) || !bytes.Contains(log, []byte(`"err"`)) { 211 t.Fatalf("log has %d lines or names the player:\n%s", n, log) 212 } 213} 214 215func TestBoardsThatNoLongerReplayStartOver(t *testing.T) { 216 for name, edit := range map[string]func([]byte) []byte{ 217 "older rules": func(b []byte) []byte { 218 return bytes.Replace(b, []byte(fmt.Sprintf(`"version":%d`, model.Version)), []byte(`"version":0`), 1) 219 }, 220 "a rejected step": func(b []byte) []byte { 221 return append(b, []byte(`{"kind":"equip","t":1,"unit":"u1","item":"gone"}`+"\n")...) 222 }, 223 } { 224 dir := t.TempDir() 225 srv, c := open(t, 7, dir) 226 old := firstFight(t, c) 227 file := filepath.Join(dir, "games", old.Game+".jsonl") 228 b, _ := os.ReadFile(file) 229 os.WriteFile(file, edit(b), 0o644) 230 srv.seats = map[string]*seat{} 231 st := c.call("GET", "/api/state", nil, 200) 232 if st.Game == old.Game || st.Summary.Battles != 0 { 233 t.Fatalf("%s: got game %s with %d battles", name, st.Game, st.Summary.Battles) 234 } 235 after, _ := os.ReadFile(file) 236 if !bytes.Equal(after, edit(b)) { 237 t.Fatalf("%s: the old log changed", name) 238 } 239 } 240} 241 242func TestFeedbackOpensAfterAFightAndAGearChange(t *testing.T) { 243 dir := t.TempDir() 244 srv, c := open(t, 7, dir) 245 c.call("POST", "/api/feedback", model.Action{Text: "hello there"}, 400) 246 st := firstFight(t, c) 247 g, _ := srv.game(testPlayer) 248 if st.Feedback || len(st.Party.Inventory) == 0 { 249 g.state.Party.Inventory = append(g.state.Party.Inventory, model.Item{ID: "t1", Name: "Test Ring", Slot: model.SlotTrinket, Rarity: "common"}) 250 } 251 id := g.state.Party.Inventory[0].ID 252 if st = c.call("POST", "/api/equip", model.Action{Unit: st.Party.Units[0].ID, Item: id}, 200); !st.Feedback { 253 t.Fatal("feedback stays closed after a fight and a gear change") 254 } 255 c.call("POST", "/api/feedback", model.Action{Text: " "}, 400) 256 c.call("POST", "/api/feedback", model.Action{Text: "The boss was hard"}, 200) 257 b, _ := os.ReadFile(filepath.Join(dir, "feedback.jsonl")) 258 if !bytes.Contains(b, []byte("The boss was hard")) || !bytes.Contains(b, []byte(st.Game)) { 259 t.Fatalf("feedback file: %s", b) 260 } 261} 262 263func TestFinishedRunsAreShareable(t *testing.T) { 264 dir := t.TempDir() 265 srv, c := open(t, 7, dir) 266 os.WriteFile(filepath.Join(srv.web, "index.html"), []byte("<head>\n<title>Tiny Adventure</title><meta name=\"description\" content=\"x\">\n</head>"), 0o644) 267 st := firstFight(t, c) 268 if res, _ := c.raw("GET", "/api/run/"+st.Game, nil); res.StatusCode != 404 { 269 t.Fatalf("unfinished run gave %d", res.StatusCode) 270 } 271 g, _ := srv.game(testPlayer) 272 g.state.Phase = "victory" 273 res, b := c.raw("GET", "/api/run/"+st.Game, nil) 274 var run model.Run 275 json.Unmarshal(b, &run) 276 if res.StatusCode != 200 || run.Seed != 7 || len(run.Party) != 4 || run.Boss == "" || run.KeysOf == 0 { 277 t.Fatalf("run %d %+v", res.StatusCode, run) 278 } 279 if _, page := c.raw("GET", "/r/"+st.Game, nil); !bytes.Contains(page, []byte(`og:image" content="http://`)) || !bytes.Contains(page, []byte("Victory on day")) || bytes.Contains(page, []byte(`content="x"`)) { 280 t.Fatalf("share page: %s", page) 281 } 282 res, png := c.raw("GET", "/r/"+st.Game+"/card.png", nil) 283 if res.StatusCode != 200 || !bytes.HasPrefix(png, []byte("\x89PNG")) { 284 t.Fatalf("card %d, %d bytes", res.StatusCode, len(png)) 285 } 286 if res, _ := c.raw("GET", "/api/run/../../etc", nil); res.StatusCode == 200 { 287 t.Fatal("path traversal answered") 288 } 289} 290 291func TestProxiedClientsAreRateLimited(t *testing.T) { 292 _, c := open(t, 7, "") 293 status := 0 294 for range 30 { 295 req, _ := http.NewRequest("POST", c.ts.URL+"/api/new", nil) 296 req.Header.Set("X-Forwarded-For", "203.0.113.9") 297 res, err := http.DefaultClient.Do(req) 298 if err != nil { 299 t.Fatal(err) 300 } 301 res.Body.Close() 302 status = res.StatusCode 303 } 304 if status != http.StatusTooManyRequests { 305 t.Fatalf("thirty new games in a row gave %d", status) 306 } 307 c.call("POST", "/api/new", nil, 200) 308}