aorecomp

Anarchy Online classic in the browser

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


server/browser_profile_test.go (6248B)


      1 package main
      2 
      3 import (
      4 	"net/http"
      5 	"net/http/httptest"
      6 	"os"
      7 	"strings"
      8 	"testing"
      9 )
     10 
     11 func TestBrowserProfileAdministratorBoundary(t *testing.T) {
     12 	for _, baseURL := range []string{"/", "/share/demo/"} {
     13 		t.Run(baseURL, func(t *testing.T) {
     14 			world := newAdminTestServer(t)
     15 			world.baseURL = baseURL
     16 			handler := world.httpHandler()
     17 			login := adminRequest(handler, "POST", baseURL+"admin/login", "username=Operator&password=admin&password_confirm=admin", nil)
     18 			if login.Code != http.StatusSeeOther {
     19 				t.Fatal(login.Code, login.Body)
     20 			}
     21 			cookie := login.Result().Cookies()[0]
     22 			path := baseURL + "admin/browser-profile/12345678-1234-1234-1234-123456789abc"
     23 
     24 			for _, scenario := range []struct {
     25 				name, path, origin string
     26 				cookie             *http.Cookie
     27 				status             int
     28 			}{
     29 				{"anonymous", path, "", nil, http.StatusUnauthorized},
     30 				{"player cookie", path, "", &http.Cookie{Name: "ao_client", Value: cookie.Value}, http.StatusUnauthorized},
     31 				{"cross origin", path, "https://attacker.test", cookie, http.StatusForbidden},
     32 				{"removed public route", baseURL + "browser-profile/12345678-1234-1234-1234-123456789abc", "", nil, http.StatusNotFound},
     33 			} {
     34 				t.Run(scenario.name, func(t *testing.T) {
     35 					request := httptest.NewRequest("POST", "https://example.test"+scenario.path, strings.NewReader(`{"sequence":0}`))
     36 					request.Header.Set("Content-Type", "application/json")
     37 					if scenario.origin != "" {
     38 						request.Header.Set("Origin", scenario.origin)
     39 					}
     40 					if scenario.cookie != nil {
     41 						request.AddCookie(scenario.cookie)
     42 					}
     43 					response := httptest.NewRecorder()
     44 					handler.ServeHTTP(response, request)
     45 
     46 					if response.Code != scenario.status {
     47 						t.Fatal(response.Code, response.Body)
     48 					}
     49 					if _, err := os.Stat("logs/profiles"); !os.IsNotExist(err) {
     50 						t.Fatal("rejected upload created profile storage", err)
     51 					}
     52 				})
     53 			}
     54 
     55 			accepted := adminRequest(handler, "POST", path, `{"sequence":1}`, cookie)
     56 
     57 			if accepted.Code != http.StatusNoContent {
     58 				t.Fatal(accepted.Code, accepted.Body)
     59 			}
     60 			contents, err := os.ReadFile("logs/profiles/12345678-1234-1234-1234-123456789abc.ndjson")
     61 			if err != nil || string(contents) != "{\"sequence\":1}\n" {
     62 				t.Fatal("administrator upload", string(contents), err)
     63 			}
     64 		})
     65 	}
     66 }
     67 
     68 func TestBrowserProfileAppendsJSONLines(t *testing.T) {
     69 	t.Chdir(t.TempDir())
     70 	writer := newProfileWriter()
     71 	defer writer.stop()
     72 	mux := http.NewServeMux()
     73 	mux.Handle("POST /browser-profile/{session}", writer)
     74 	url := "/browser-profile/12345678-1234-1234-1234-123456789abc"
     75 
     76 	for _, body := range []string{"{\n \"sequence\": 0\n}", `{"sequence":1}`} {
     77 		response := httptest.NewRecorder()
     78 		mux.ServeHTTP(response, httptest.NewRequest("POST", url, strings.NewReader(body)))
     79 		if response.Code != http.StatusNoContent {
     80 			t.Fatalf("upload: %d %s", response.Code, response.Body.String())
     81 		}
     82 	}
     83 
     84 	body, err := os.ReadFile("logs/profiles/12345678-1234-1234-1234-123456789abc.ndjson")
     85 	if err != nil || string(body) != "{\"sequence\":0}\n{\"sequence\":1}\n" {
     86 		t.Fatalf("profile: %q %v", body, err)
     87 	}
     88 }
     89 
     90 func TestBrowserProfileRejectsInvalidUploads(t *testing.T) {
     91 	for _, test := range []struct {
     92 		name, session, body string
     93 		status              int
     94 	}{
     95 		{"path", "../../outside", `{}`, http.StatusBadRequest},
     96 		{"json", "12345678-1234-1234-1234-123456789abc", `{`, http.StatusBadRequest},
     97 		{"size", "12345678-1234-1234-1234-123456789abc", strings.Repeat(" ", 2*1024*1024+1), http.StatusRequestEntityTooLarge},
     98 	} {
     99 		t.Run(test.name, func(t *testing.T) {
    100 			t.Chdir(t.TempDir())
    101 			writer := newProfileWriter()
    102 			defer writer.stop()
    103 			request := httptest.NewRequest("POST", "/", strings.NewReader(test.body))
    104 			request.SetPathValue("session", test.session)
    105 			response := httptest.NewRecorder()
    106 
    107 			writer.ServeHTTP(response, request)
    108 
    109 			if response.Code != test.status {
    110 				t.Fatalf("response: %d", response.Code)
    111 			}
    112 			if _, err := os.Stat("logs"); !os.IsNotExist(err) {
    113 				t.Fatalf("invalid request created profile storage: %v", err)
    114 			}
    115 		})
    116 	}
    117 }
    118 
    119 func TestBrowserProfileSessionLimit(t *testing.T) {
    120 	t.Chdir(t.TempDir())
    121 	writer := newProfileWriter()
    122 	defer writer.stop()
    123 	if err := os.MkdirAll("logs/profiles", 0755); err != nil {
    124 		t.Fatal(err)
    125 	}
    126 	path := "logs/profiles/12345678-1234-1234-1234-123456789abc.ndjson"
    127 	file, err := os.Create(path)
    128 	if err != nil {
    129 		t.Fatal(err)
    130 	}
    131 	if err := file.Truncate(128 * 1024 * 1024); err != nil {
    132 		t.Fatal(err)
    133 	}
    134 	file.Close()
    135 	request := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
    136 	request.SetPathValue("session", "12345678-1234-1234-1234-123456789abc")
    137 	response := httptest.NewRecorder()
    138 
    139 	writer.ServeHTTP(response, request)
    140 
    141 	if response.Code != http.StatusRequestEntityTooLarge {
    142 		t.Fatal(response.Code)
    143 	}
    144 	info, err := os.Stat(path)
    145 	if err != nil || info.Size() != 128*1024*1024 {
    146 		t.Fatalf("size: %v %v", info, err)
    147 	}
    148 }
    149 
    150 func TestBrowserProfileConcurrentUploadsCannotExceedSessionLimit(t *testing.T) {
    151 	t.Chdir(t.TempDir())
    152 	writer := newProfileWriter()
    153 	defer writer.stop()
    154 	if err := os.MkdirAll("logs/profiles", 0755); err != nil {
    155 		t.Fatal(err)
    156 	}
    157 	path := "logs/profiles/12345678-1234-1234-1234-123456789abc.ndjson"
    158 	file, err := os.Create(path)
    159 	if err != nil {
    160 		t.Fatal(err)
    161 	}
    162 	if err := file.Truncate(128*1024*1024 - 3); err != nil {
    163 		file.Close()
    164 		t.Fatal(err)
    165 	}
    166 	file.Close()
    167 	statuses := make(chan int, 16)
    168 	for range 16 {
    169 		go func() {
    170 			request := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
    171 			request.SetPathValue("session", "12345678-1234-1234-1234-123456789abc")
    172 			response := httptest.NewRecorder()
    173 			writer.ServeHTTP(response, request)
    174 			statuses <- response.Code
    175 		}()
    176 	}
    177 
    178 	accepted, full := 0, 0
    179 	for range 16 {
    180 		switch status := <-statuses; status {
    181 		case http.StatusNoContent:
    182 			accepted++
    183 		case http.StatusRequestEntityTooLarge:
    184 			full++
    185 		default:
    186 			t.Errorf("unexpected upload status %d", status)
    187 		}
    188 	}
    189 	if accepted != 1 || full != 15 {
    190 		t.Fatal("concurrent batches did not share one size decision", accepted, full)
    191 	}
    192 	info, err := os.Stat(path)
    193 	if err != nil || info.Size() != 128*1024*1024 {
    194 		t.Fatal("concurrent appends exceeded the session limit", info, err)
    195 	}
    196 }