Files
aeternalis/server/internal/transport/housing_test.go
T

81 lines
2.2 KiB
Go

package transport
import (
"aeternalis/server/content"
"aeternalis/server/internal/game"
"aeternalis/server/internal/store"
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
)
func TestHousingHTTPAuthorization(t *testing.T) {
ctx := context.Background()
db, e := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "house.db")))
if e != nil {
t.Fatal(e)
}
defer db.Close()
b, _ := content.Load()
w := game.New("house-auth", 1, time.Now(), b)
c, _ := w.Join("owner", "Owner")
c.WorldsSurvived = 1
_ = w.Connect(c.View.Entity.ID)
w.Kind = "hub"
w.Phase = "hub"
l, _, e := db.Acquire(ctx, w)
if e != nil {
t.Fatal(e)
}
if e = l.Save(ctx, w, ""); e != nil {
t.Fatal(e)
}
auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "")
out := httptest.NewRecorder()
if e = auth.session(out, httptest.NewRequest("POST", auth.base+"/auth/dev", nil), "owner"); e != nil {
t.Fatal(e)
}
cookie := out.Result().Cookies()[0]
s := NewService(w, l)
h := NewHTTP(s, auth, t.TempDir(), nil).Handler()
request := func(method, origin, body string, cookie *http.Cookie) int {
r := httptest.NewRequest(method, auth.base+"/api/housing", strings.NewReader(body))
r.RemoteAddr = "127.0.0.1:1234"
if origin != "" {
r.Header.Set("Origin", origin)
}
if cookie != nil {
r.AddCookie(cookie)
}
out := httptest.NewRecorder()
h.ServeHTTP(out, r)
return out.Code
}
body := `{"requestId":"` + game.ID() + `","op":"create","name":"Home"}`
if code := request("GET", "", "", nil); code != 401 {
t.Fatal("anonymous directory", code)
}
if code := request("POST", auth.base, body, nil); code != 401 {
t.Fatal("anonymous mutation", code)
}
if code := request("POST", "https://evil.example", body, cookie); code != 403 {
t.Fatal("cross-origin mutation", code)
}
if code := request("POST", auth.base, body, cookie); code != 200 {
t.Fatal("authorized create", code)
}
if code := request("GET", "", "", cookie); code != 200 {
t.Fatal("authorized directory", code)
}
if code := request("POST", auth.base, `{"requestId":"`+game.ID()+`","op":"create","account":"other"}`, cookie); code != 400 {
t.Fatal("actor spoofing", code)
}
if !s.ready.Load() {
t.Fatal("ordinary rejection froze world")
}
}