aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/browser_account_test.go (11391B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"crypto/sha256"
      6 	"fmt"
      7 	"net/http"
      8 	"net/http/httptest"
      9 	"net/url"
     10 	"reflect"
     11 	"strings"
     12 	"sync"
     13 	"testing"
     14 )
     15 
     16 func accountVisitor(t *testing.T, world *server) *http.Cookie {
     17 	t.Helper()
     18 	response := httptest.NewRecorder()
     19 	launchTestVisitor(t, world, response, httptest.NewRequest("POST", "https://example.test/browser-launch", nil))
     20 	if response.Code != 200 || len(response.Result().Cookies()) != 1 {
     21 		t.Fatalf("visitor launch: %d %s", response.Code, response.Body.String())
     22 	}
     23 	return response.Result().Cookies()[0]
     24 }
     25 
     26 func accountRequest(world *server, cookie *http.Cookie, action, name, password string) *httptest.ResponseRecorder {
     27 	request := httptest.NewRequest("POST", "https://example.test"+world.baseURL+"browser-account/"+action,
     28 		strings.NewReader(url.Values{"name": {name}, "password": {password}}.Encode()))
     29 	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
     30 	if cookie != nil {
     31 		request.AddCookie(cookie)
     32 	}
     33 	response := httptest.NewRecorder()
     34 	world.httpHandler().ServeHTTP(response, request)
     35 	return response
     36 }
     37 
     38 func TestBrowserAccountClaimPreservesCharacterAndSurvivesRestart(t *testing.T) {
     39 	world := newTestServer(t)
     40 	cookie := accountVisitor(t, world)
     41 	player := world.characters[1]
     42 	inventory := player.inventory
     43 	inventory.Credits = 123
     44 	if err := world.saveInventory(player, inventory); err != nil {
     45 		t.Fatal(err)
     46 	}
     47 	before := *player
     48 	world.clients[1] = &worldClient{id: 1, ready: true, conn: &combatInterestConn{}}
     49 
     50 	response := accountRequest(world, cookie, "claim", "Alice", "test password")
     51 	restored := newTestInventoryServer(t)
     52 	var salt, hash []byte
     53 	if err := restored.db.QueryRow("SELECT password_salt, password_hash FROM characters WHERE id=1").Scan(&salt, &hash); err != nil {
     54 		t.Fatal(err)
     55 	}
     56 
     57 	if response.Code != 204 || response.Header().Get("Cache-Control") != "no-store" || player.name != "Alice" || restored.characters[1].name != "Alice" ||
     58 		player.title != "" || restored.characters[1].title != "" ||
     59 		player.health != before.health || player.nano != before.nano || player.position != before.position || player.stats != before.stats ||
     60 		!reflect.DeepEqual(player.inventory, before.inventory) || !reflect.DeepEqual(restored.characters[1].inventory, before.inventory) || world.clients[1].ready {
     61 		t.Fatalf("claim lost the existing player or session: %d %s", response.Code, response.Body.String())
     62 	}
     63 	if len(salt) != 16 || len(hash) != 32 || bytes.Contains(hash, []byte("test password")) ||
     64 		!bytes.Equal(world.browserPassword("test password", salt), hash) || bytes.Equal(world.browserPassword("wrong password", salt), hash) {
     65 		t.Fatal("password was not stored as a salted Argon2id hash")
     66 	}
     67 	claimedCookie := response.Result().Cookies()[0]
     68 	if claimedCookie.Value == cookie.Value || !claimedCookie.HttpOnly || !claimedCookie.Secure || claimedCookie.SameSite != http.SameSiteLaxMode {
     69 		t.Fatal("claim did not rotate a protected browser credential")
     70 	}
     71 	request := httptest.NewRequest("GET", "/", nil)
     72 	request.AddCookie(cookie)
     73 	if restored.browserCharacter(request) != nil {
     74 		t.Fatal("old visitor credential remained valid")
     75 	}
     76 	request = httptest.NewRequest("GET", "/", nil)
     77 	request.AddCookie(claimedCookie)
     78 	if restored.browserCharacter(request) != restored.characters[1] || player.savedProfile.Name != "Alice" {
     79 		t.Fatal("claimed browser ownership did not survive restart")
     80 	}
     81 }
     82 
     83 func TestBrowserAccountLoginSwitchesOnlyAfterCorrectPassword(t *testing.T) {
     84 	world := newTestServer(t)
     85 	first := accountVisitor(t, world)
     86 	claimed := accountRequest(world, first, "claim", "Alice", "test password")
     87 	if claimed.Code != 204 {
     88 		t.Fatal(claimed.Body.String())
     89 	}
     90 	first = claimed.Result().Cookies()[0]
     91 	visitor := accountVisitor(t, world)
     92 	before := *world.characters[2]
     93 	firstHash, visitorHash := world.characters[1].browserTokenHash, before.browserTokenHash
     94 
     95 	rejected := accountRequest(world, visitor, "login", "Alice", "wrong")
     96 
     97 	if rejected.Code != 401 || len(rejected.Result().Cookies()) != 0 || world.characters[1].browserTokenHash != firstHash ||
     98 		world.characters[2].browserTokenHash != visitorHash || !reflect.DeepEqual(*world.characters[2], before) {
     99 		t.Fatal("failed login changed either player")
    100 	}
    101 
    102 	response := accountRequest(world, visitor, "login", "aLiCe", "test password")
    103 	restored := newTestInventoryServer(t)
    104 
    105 	if response.Code != 204 || len(response.Result().Cookies()) != 1 || world.characters[1].browserTokenHash == firstHash || world.characters[2].browserTokenHash == visitorHash ||
    106 		world.characters[1].name != "Alice" || world.characters[2].name != before.name || world.characters[2].position != before.position {
    107 		t.Fatalf("login did not replace the credentials without moving players: %d %s", response.Code, response.Body.String())
    108 	}
    109 	request := httptest.NewRequest("GET", "/", nil)
    110 	request.AddCookie(response.Result().Cookies()[0])
    111 	if restored.browserCharacter(request) != restored.characters[1] {
    112 		t.Fatal("new login did not survive restart")
    113 	}
    114 	for _, stale := range []*http.Cookie{first, visitor} {
    115 		request := httptest.NewRequest("GET", "/", nil)
    116 		request.AddCookie(stale)
    117 		if restored.browserCharacter(request) != nil {
    118 			t.Fatal("replaced credential remained valid")
    119 		}
    120 	}
    121 }
    122 
    123 func TestBrowserAccountRejectsInvalidClaimsWithoutChangingVisitor(t *testing.T) {
    124 	for _, scenario := range []struct{ name, password string }{
    125 		{"", "password"}, {"123Alice", "password"}, {"Abc", "password"}, {"Al\x00ice", "password"}, {"Ali1ce", "password"},
    126 		{strings.Repeat("a", 255), "password"}, {"Alice", ""}, {"Alice", "abcd"}, {"Alice", "\u00e9\u00e9\u00e9\u00e9"}, {"Alice", strings.Repeat("a", 1025)},
    127 	} {
    128 		t.Run(fmt.Sprintf("name=%q/length=%d", scenario.name, len(scenario.password)), func(t *testing.T) {
    129 			world := newTestServer(t)
    130 			cookie := accountVisitor(t, world)
    131 			before := *world.characters[1]
    132 
    133 			response := accountRequest(world, cookie, "claim", scenario.name, scenario.password)
    134 
    135 			if response.Code != 400 || len(response.Result().Cookies()) != 0 || !reflect.DeepEqual(*world.characters[1], before) {
    136 				t.Fatalf("invalid claim changed visitor: %d %s", response.Code, response.Body.String())
    137 			}
    138 		})
    139 	}
    140 }
    141 
    142 func TestBrowserAccountDuplicateNamesAndRepeatedClaim(t *testing.T) {
    143 	world := newTestServer(t)
    144 	first := accountVisitor(t, world)
    145 	firstClaim := accountRequest(world, first, "claim", "Alice", "password")
    146 	if firstClaim.Code != 204 {
    147 		t.Fatal(firstClaim.Body.String())
    148 	}
    149 	second := accountVisitor(t, world)
    150 	secondName := world.characters[2].name
    151 
    152 	duplicate := accountRequest(world, second, "claim", "ALICE", "other password")
    153 	repeated := accountRequest(world, firstClaim.Result().Cookies()[0], "claim", "Bobby", "replacement password")
    154 	login := accountRequest(world, second, "login", "Alice", "password")
    155 
    156 	if duplicate.Code != 409 || repeated.Code != 409 || login.Code != 204 || world.characters[1].name != "Alice" || world.characters[2].name != secondName {
    157 		t.Fatalf("name collision changed accounts: %d %d %d", duplicate.Code, repeated.Code, login.Code)
    158 	}
    159 }
    160 
    161 func TestBrowserAccountConcurrentClaimCommitsOnce(t *testing.T) {
    162 	world := newTestServer(t)
    163 	cookie := accountVisitor(t, world)
    164 	shutdown := startTestService(t, world)
    165 	var requests sync.WaitGroup
    166 	responses := make([]*httptest.ResponseRecorder, 8)
    167 
    168 	for index := range responses {
    169 		requests.Add(1)
    170 		go func() {
    171 			defer requests.Done()
    172 			responses[index] = accountRequest(world, cookie, "claim", "Alice", "password")
    173 		}()
    174 	}
    175 	requests.Wait()
    176 
    177 	committed := 0
    178 	for _, response := range responses {
    179 		if response.Code == 204 {
    180 			committed++
    181 		} else if response.Code != 401 {
    182 			t.Fatalf("unexpected concurrent claim: %d %s", response.Code, response.Body.String())
    183 		}
    184 	}
    185 	if err := shutdown(); err != nil {
    186 		t.Fatal(err)
    187 	}
    188 	if committed != 1 || newTestInventoryServer(t).characters[1].name != "Alice" {
    189 		t.Fatalf("concurrent claim committed %d times", committed)
    190 	}
    191 }
    192 
    193 func TestBrowserAccountFailureLeavesBothCredentialsAndPasswordUnchanged(t *testing.T) {
    194 	for _, action := range []string{"claim", "login"} {
    195 		for _, failure := range []struct{ name, statement string }{
    196 			{"update", "CREATE TRIGGER reject_account BEFORE UPDATE OF browser_token_hash ON characters BEGIN SELECT RAISE(ABORT, 'account'); END"},
    197 			{"ignored update", "CREATE TRIGGER reject_account BEFORE UPDATE OF browser_token_hash ON characters BEGIN SELECT RAISE(IGNORE); END"},
    198 			{"commit", "CREATE TABLE pending_account (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_account AFTER UPDATE OF browser_token_hash ON characters BEGIN INSERT INTO pending_account VALUES (999999); END"},
    199 		} {
    200 			t.Run(action+"/"+failure.name, func(t *testing.T) {
    201 				world := newTestServer(t)
    202 				cookie := accountVisitor(t, world)
    203 				if action == "login" {
    204 					if response := accountRequest(world, cookie, "claim", "Alice", "password"); response.Code != 204 {
    205 						t.Fatal(response.Body.String())
    206 					}
    207 					cookie = accountVisitor(t, world)
    208 				}
    209 				before := newTestInventoryServer(t)
    210 				if _, err := world.db.Exec(failure.statement); err != nil {
    211 					t.Fatal(err)
    212 				}
    213 
    214 				response := accountRequest(world, cookie, action, "Alice", "password")
    215 				restored := newTestInventoryServer(t)
    216 
    217 				if response.Code != 500 || len(response.Result().Cookies()) != 0 {
    218 					t.Fatalf("failed persistence reported success: %d %s", response.Code, response.Body.String())
    219 				}
    220 				for id, player := range before.characters {
    221 					if player.npc {
    222 						continue
    223 					}
    224 					if restored.characters[id].name != player.name || restored.characters[id].browserTokenHash != player.browserTokenHash ||
    225 						world.characters[id].browserTokenHash != player.browserTokenHash || world.characters[id].name != player.name {
    226 						t.Fatal("failed transaction published a name or credential")
    227 					}
    228 				}
    229 				if action == "claim" {
    230 					var hash []byte
    231 					if err := world.db.QueryRow("SELECT password_hash FROM characters WHERE id=1").Scan(&hash); err != nil || len(hash) != 0 {
    232 						t.Fatal("failed claim retained a password hash", err)
    233 					}
    234 				}
    235 				if _, err := world.db.Exec("DROP TRIGGER reject_account"); err != nil {
    236 					t.Fatal(err)
    237 				}
    238 
    239 				response = accountRequest(world, cookie, action, "Alice", "password")
    240 
    241 				if response.Code != 204 {
    242 					t.Fatalf("retry failed: %d %s", response.Code, response.Body.String())
    243 				}
    244 			})
    245 		}
    246 	}
    247 }
    248 
    249 func TestBrowserAccountRoutesProtectOriginAndMountCookie(t *testing.T) {
    250 	world := newTestServer(t)
    251 	world.baseURL = "/game/"
    252 	cookie := accountVisitor(t, world)
    253 	request := httptest.NewRequest("POST", "https://example.test/game/browser-account/claim", strings.NewReader("name=Alice&password=password"))
    254 	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    255 	request.Header.Set("Origin", "https://other.test")
    256 	request.AddCookie(cookie)
    257 	response := httptest.NewRecorder()
    258 
    259 	world.httpHandler().ServeHTTP(response, request)
    260 	claimed := accountRequest(world, cookie, "claim", "Alice", "password")
    261 
    262 	if response.Code != 403 || claimed.Code != 204 || claimed.Result().Cookies()[0].Path != "/game/" {
    263 		t.Fatalf("origin or mounted cookie: %d %d", response.Code, claimed.Code)
    264 	}
    265 	wanted := fmt.Sprintf("%x", sha256.Sum256([]byte(claimed.Result().Cookies()[0].Value)))
    266 	if world.characters[1].browserTokenHash != wanted {
    267 		t.Fatal("mounted claim lost browser ownership")
    268 	}
    269 }