Files

206 lines
7.6 KiB
Go

package transport
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"aeternalis/server/content"
"aeternalis/server/internal/game"
"aeternalis/server/internal/store"
)
func TestControlAuthorizationAndExecution(t *testing.T) {
ctx := context.Background()
db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "control.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, _ := content.Load()
w := game.New("control-test", 1, time.Now(), b)
lease, _, err := db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
svc := NewService(w, lease)
auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "")
assets := t.TempDir()
for _, f := range []string{"index.html", "game.html", "control.html"} {
if err = os.WriteFile(filepath.Join(assets, f), []byte("<!doctype html><title>"+f+"</title>"), 0600); err != nil {
t.Fatal(err)
}
}
server := httptest.NewServer(NewHTTP(svc, auth, assets, nil).Handler())
defer server.Close()
auth.base = server.URL
request := func(method, path, body, token, origin string) int {
t.Helper()
r, _ := http.NewRequest(method, server.URL+path, strings.NewReader(body))
if token != "" {
r.AddCookie(&http.Cookie{Name: auth.cookieName(), Value: token})
}
r.Header.Set("Origin", origin)
response, err := server.Client().Do(r)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
return response.StatusCode
}
for _, path := range []string{"/", "/game", "/control", "/worlds/control-test/api/config"} {
if status := request("GET", path, "", "", ""); status != 200 {
t.Fatal(path, status)
}
}
if status := request("GET", "/worlds/another/api/config", "", "", ""); status != 404 {
t.Fatal("wrong world routed", status)
}
if request("GET", "/api/control", "", "", "") != 401 {
t.Fatal("anonymous admin access")
}
if request("POST", "/api/control/catalog/preview", "{}", "", server.URL) != 401 {
t.Fatal("anonymous preview access")
}
token := game.ID() + game.ID()
_ = db.CreateSession(ctx, hash(token), "operator")
if request("GET", "/api/control", "", token, "") != 403 {
t.Fatal("player has admin access")
}
if request("POST", "/api/control/catalog/preview", "{}", token, server.URL) != 403 {
t.Fatal("player preview access")
}
_ = db.GrantAdmin(ctx, hash(token), 600)
if request("GET", "/api/control", "", token, "") != 200 {
t.Fatal("admin denied")
}
previewBody := `{"id":"` + game.ID() + `","expectedVersion":1,"op":"create-effect-set","reason":"Preview effects","effectSet":{"name":"Test effect","description":"","modifiers":[{"stat":"strength","flat":2,"percent":0}]}}`
for _, path := range []string{"/api/control/catalog", "/api/control/catalog/preview"} {
if request("POST", path, strings.Replace(previewBody, `"effectSet":{`, `"effectSet":{"id":"client_chosen",`, 1), token, server.URL) != 400 {
t.Fatal("client selected a permanent content ID")
}
}
if request("POST", "/api/control/catalog/preview", previewBody, token, "https://evil.example") != 403 {
t.Fatal("cross-origin preview")
}
if request("POST", "/api/control/catalog/preview", previewBody, token, server.URL) != 200 {
t.Fatal("valid preview rejected")
}
if request("POST", "/api/control/catalog/preview", strings.Replace(previewBody, `"flat":2`, `"flat":2,"script":"bad"`, 1), token, server.URL) != 400 {
t.Fatal("unknown nested field accepted")
}
if request("POST", "/api/control/catalog/preview", previewBody+` {}`, token, server.URL) != 400 {
t.Fatal("trailing JSON accepted")
}
previewCatalog, err := db.Catalog(ctx)
if err != nil || previewCatalog.Version != 1 || len(previewCatalog.EffectSets) != 0 {
t.Fatal("preview changed catalog", err)
}
body := `{"id":"` + game.ID() + `","worldId":"control-test","op":"close-admissions","reason":"maintenance window"}`
if request("POST", "/api/control/commands", body, token, "https://evil.example") != 403 {
t.Fatal("cross-origin admin command")
}
if request("POST", "/api/control/commands", body, token, server.URL) != 202 {
t.Fatal("command not queued")
}
if err = svc.controls(ctx); err != nil {
t.Fatal(err)
}
if !w.AdmissionsClosed {
t.Fatal("command not applied by world owner")
}
commands, _ := db.Commands(ctx, w.ID, false)
if len(commands) != 1 || commands[0].Status != "completed" {
t.Fatal("command not audited")
}
spawn := `{"id":"` + game.ID() + `","worldId":"control-test","op":"spawn-mobs","target":"ash_guard","value":"2,30,30","reason":"Combat playtest"}`
before := len(w.Mobs)
for i := 0; i < 2; i++ {
if request("POST", "/api/control/commands", spawn, token, server.URL) != 202 {
t.Fatal("spawn command/retry not accepted")
}
if err = svc.controls(ctx); err != nil {
t.Fatal(err)
}
if len(w.Mobs) != before+2 {
t.Fatal("spawn retry duplicated mobs")
}
}
if err = lease.Release(ctx); err != nil {
t.Fatal(err)
}
nextLease, snapshot, err := db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
defer nextLease.Release(ctx)
var restarted game.World
if err = json.Unmarshal(snapshot, &restarted); err != nil {
t.Fatal(err)
}
if err = restarted.Restore(time.Now()); err != nil {
t.Fatal(err)
}
if err = NewService(&restarted, nextLease).controls(ctx); err != nil || len(restarted.Mobs) != before+2 {
t.Fatal("spawn execution was not durable/retry safe", err)
}
commands, err = db.Commands(ctx, w.ID, false)
if err != nil || len(commands) != 2 || commands[0].Status != "completed" || commands[1].Status != "completed" {
t.Fatal("spawn audit not committed with world", err)
}
bad := `{"id":"` + game.ID() + `","worldId":"control-test","op":"end-world","reason":"maintenance window"}`
if request("POST", "/api/control/commands", bad, token, server.URL) != 400 {
t.Fatal("destructive action without confirmation")
}
_ = db.DeleteSession(ctx, hash(token))
if request("GET", "/api/control", "", token, "") != 401 {
t.Fatal("revoked admin session accepted")
}
}
func TestKeycloakRolesAndReturnURL(t *testing.T) {
var claims roleClaims
_ = json.Unmarshal([]byte(`{"realm_access":{"roles":["player"]},"resource_access":{"game":{"roles":["aeternalis-admin"]},"other":{"roles":["foreign-admin"]}}}`), &claims)
if !claims.admin("aeternalis-admin", "game") || claims.admin("foreign-admin", "game") || claims.admin("", "game") {
t.Fatal("role scope validation")
}
for _, raw := range []string{"https://evil.example", "//evil.example/game", "/\\evil", "/game#fragment", "/control?next=https://evil"} {
if result := safeReturn(raw); result != "/" && result != "/control" {
t.Fatal("unsafe return", raw, result)
}
}
if safeReturn("/game?world=world-002&evil=value") != "/game?world=world-002" {
t.Fatal("game return lost or untrusted query retained")
}
}
func TestAdminRoleClaimsMatchExactlyAndOnlyOwnClient(t *testing.T) {
for _, tc := range []struct {
name, raw string
want bool
}{
{"realm role", `{"realm_access":{"roles":["aeternalis-admin"]}}`, true},
{"client role", `{"resource_access":{"game":{"roles":["aeternalis-admin"]}}}`, true},
{"other client", `{"resource_access":{"other":{"roles":["aeternalis-admin"]}}}`, false},
{"player", `{"realm_access":{"roles":["player"]}}`, false},
{"case mismatch", `{"realm_access":{"roles":["Aeternalis-admin"]}}`, false},
{"substring", `{"realm_access":{"roles":["not-aeternalis-admin"]}}`, false},
{"missing", `{}`, false},
} {
t.Run(tc.name, func(t *testing.T) {
var claims roleClaims
if err := json.Unmarshal([]byte(tc.raw), &claims); err != nil {
t.Fatal(err)
}
if claims.admin("aeternalis-admin", "game") != tc.want {
t.Fatal("incorrect role access")
}
})
}
}