Files
browser/plugins/examples/scum-server-plugin/companion/adapters_e2e_test.go
T

230 lines
12 KiB
Go

package companion
import (
"context"
"errors"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
"time"
)
// isolatedAdapterPort is a non-production typed-port fixture. It records only
// the adapter's typed inputs and never opens a connection or accepts a raw
// game command.
type isolatedAdapterPort struct {
configFields map[string]string
configErr error
patchErr error
patches []ConfigFieldPatch
notifications []ue4SSPlayerNotification
notifyErr error
notifyAccept bool
spawns []ue4SSVehicleSpawn
spawnReceipts []UE4SSVehicleSpawnReceipt
spawnErrors []error
}
func (port *isolatedAdapterPort) ReadConfig(context.Context) (map[string]string, error) {
return port.configFields, port.configErr
}
func (port *isolatedAdapterPort) ApplyConfigPatch(_ context.Context, _ string, fields []ConfigFieldPatch) (map[string]string, error) {
port.patches = append(port.patches, fields...)
if port.patchErr != nil {
return nil, port.patchErr
}
return map[string]string{"ServerName": "Moonlight", "hostPath": "C:/private/server.ini"}, nil
}
func (port *isolatedAdapterPort) SendPlayerNotification(_ context.Context, notification ue4SSPlayerNotification) (UE4SSNotificationReceipt, error) {
port.notifications = append(port.notifications, notification)
return UE4SSNotificationReceipt{Accepted: port.notifyAccept}, port.notifyErr
}
func (port *isolatedAdapterPort) SpawnVehicle(_ context.Context, spawn ue4SSVehicleSpawn) (UE4SSVehicleSpawnReceipt, error) {
port.spawns = append(port.spawns, spawn)
index := len(port.spawns) - 1
if index >= len(port.spawnReceipts) {
return UE4SSVehicleSpawnReceipt{Outcome: UE4SSVehicleSpawnUnknown}, nil
}
return port.spawnReceipts[index], port.spawnErrors[index]
}
type isolatedDispatchGateway struct {
commands []ClaimedCommand
acks []string
completed map[string][]CommandResult
}
func (gateway *isolatedDispatchGateway) ClaimCommands(context.Context, int) ([]ClaimedCommand, error) {
return append([]ClaimedCommand(nil), gateway.commands...), nil
}
func (gateway *isolatedDispatchGateway) AckCommand(_ context.Context, id string, _ uint64) (CommandAck, error) {
gateway.acks = append(gateway.acks, id)
return CommandAck{CommandID: id, State: "claimed", FencingToken: 1}, nil
}
func (gateway *isolatedDispatchGateway) CompleteCommand(_ context.Context, id string, _ uint64, result CommandResult) (CompletedCommand, error) {
if gateway.completed == nil {
gateway.completed = map[string][]CommandResult{}
}
gateway.completed[id] = append(gateway.completed[id], result)
return CompletedCommand{State: "completed"}, nil
}
func e2eClaim(id, commandType string, payload map[string]any, stamp time.Time) ClaimedCommand {
return ClaimedCommand{ID: id, ProfileKey: ProfileKey, CommandType: commandType, Payload: payload, FencingToken: 1, LeaseExpiresAt: stamp.Add(time.Minute), ExpiresAt: stamp.Add(time.Minute)}
}
func TestSupportedAdaptersDispatchThroughIsolatedTypedPorts(t *testing.T) {
stamp := time.Now().UTC()
port := &isolatedAdapterPort{
configFields: map[string]string{"ServerName": "Moonlight", "Password": "never-return", "hostPath": "C:/private/server.ini"},
notifyAccept: true,
spawnReceipts: []UE4SSVehicleSpawnReceipt{{Outcome: UE4SSVehicleSpawnAccepted}, {Outcome: UE4SSVehicleSpawnRejected}, {Outcome: UE4SSVehicleSpawnUnknown}},
spawnErrors: []error{nil, nil, errors.New("receipt unavailable")},
}
adapter := RuntimeAdapter{BoundServerID: "server-1", Config: port, Notification: port, VehicleSpawn: port}
registry := NewHandlerRegistry(HandlerAvailability{BoundServerID: "server-1", Approved: true, Capabilities: map[string]bool{"config.read": true, "config.patch": true, "player.notify": true, "vehicle.spawn": true}}, adapter)
gateway := &isolatedDispatchGateway{commands: []ClaimedCommand{
e2eClaim("config-read", "config.read", map[string]any{}, stamp),
e2eClaim("config-patch", "config.patch", map[string]any{"revision": "r1", "fields": []any{map[string]any{"key": "ServerName", "value": "Moonlight"}}}, stamp),
e2eClaim("notify", "player.notify", map[string]any{"playerId": "76561198000000001", "message": "Moonlight ready"}, stamp),
e2eClaim("notify", "player.notify", map[string]any{"playerId": "76561198000000001", "message": "Moonlight ready"}, stamp),
e2eClaim("spawn-success", "vehicle.spawn", map[string]any{"vehicleCode": "BPC_Laika_C"}, stamp),
e2eClaim("spawn-failed", "vehicle.spawn", map[string]any{"vehicleCode": "BPC_WolfsWagen_C"}, stamp),
e2eClaim("spawn-unknown", "vehicle.spawn", map[string]any{"vehicleCode": "BPC_Laika_C"}, stamp),
e2eClaim("spawn-unknown", "vehicle.spawn", map[string]any{"vehicleCode": "BPC_Laika_C"}, stamp),
}}
dispatcher := Dispatcher{Client: gateway, Registry: registry, Now: func() time.Time { return stamp }}
if err := dispatcher.DispatchOnce(context.Background()); err != nil {
t.Fatalf("dispatch supported adapters: %v", err)
}
if len(port.notifications) != 1 || port.notifications[0].ServerID != "server-1" || port.notifications[0].localCommandPreview == "" {
t.Fatalf("notification did not remain server-bound and idempotent: %+v", port.notifications)
}
if len(port.patches) != 1 || gateway.completed["config-read"][0].Payload["fields"].(map[string]string)["ServerName"] != "Moonlight" || gateway.completed["config-patch"][0].Payload["appliedFields"].(map[string]string)["ServerName"] != "Moonlight" || gateway.completed["notify"][0].Payload["accepted"] != true {
t.Fatalf("supported adapters did not return their bounded successful results: patches=%+v completed=%+v", port.patches, gateway.completed)
}
if len(port.spawns) != 3 || port.spawns[0].localCommandPreview != "#spawnvehicle BPC_Laika_C" || port.spawns[1].localCommandPreview != "#spawnvehicle BPC_WolfsWagen_C" || port.spawns[2].localCommandPreview != "#spawnvehicle BPC_Laika_C" {
t.Fatalf("vehicle adapter did not use only fixed private templates: %+v", port.spawns)
}
if gateway.completed["spawn-success"][0].Payload["outcome"] != "succeeded" || gateway.completed["spawn-failed"][0].Payload["outcome"] != "failed" || gateway.completed["spawn-unknown"][0].Payload["outcome"] != "unknown" {
t.Fatalf("unexpected bounded vehicle outcomes: %+v", gateway.completed)
}
for id, results := range gateway.completed {
for _, result := range results {
serialized := result.Summary + " " + stringifyPayload(result.Payload)
for _, secret := range []string{"C:/private/server.ini", "never-return", "#spawnvehicle", "SendChat"} {
if strings.Contains(serialized, secret) {
t.Fatalf("%s exposed protected adapter output %q: %+v", id, secret, result)
}
}
}
}
}
func TestSupportedAdaptersFailClosedForBindingApprovalAndCapability(t *testing.T) {
stamp := time.Now().UTC()
for name, testCase := range map[string]struct {
availability HandlerAvailability
adapter RuntimeAdapter
}{
"binding": {availability: HandlerAvailability{BoundServerID: "server-1", Approved: true, Capabilities: map[string]bool{"vehicle.spawn": true}}, adapter: RuntimeAdapter{BoundServerID: "server-2"}},
"approval": {availability: HandlerAvailability{BoundServerID: "server-1", Approved: false, Capabilities: map[string]bool{"vehicle.spawn": true}}, adapter: RuntimeAdapter{BoundServerID: "server-1"}},
"capability": {availability: HandlerAvailability{BoundServerID: "server-1", Approved: true, Capabilities: map[string]bool{}}, adapter: RuntimeAdapter{BoundServerID: "server-1"}},
} {
t.Run(name, func(t *testing.T) {
port := &isolatedAdapterPort{}
testCase.adapter.VehicleSpawn = port
gateway := &isolatedDispatchGateway{commands: []ClaimedCommand{e2eClaim(name, "vehicle.spawn", map[string]any{"vehicleCode": "BPC_Laika_C"}, stamp)}}
dispatcher := Dispatcher{Client: gateway, Registry: NewHandlerRegistry(testCase.availability, testCase.adapter), Now: func() time.Time { return stamp }}
if err := dispatcher.DispatchOnce(context.Background()); err != nil {
t.Fatalf("dispatch fail-closed case: %v", err)
}
result := gateway.completed[name][0]
if result.Payload["result"] != "unsupported" || len(port.spawns) != 0 {
t.Fatalf("unsafe adapter reached transport: result=%+v spawns=%+v", result, port.spawns)
}
})
}
}
func TestSupportedAdapterTransportFailuresCompleteWithoutProtectedOutput(t *testing.T) {
stamp := time.Now().UTC()
port := &isolatedAdapterPort{patchErr: errors.New("private port failed"), notifyErr: errors.New("private notification failed")}
adapter := RuntimeAdapter{BoundServerID: "server-1", Config: port, Notification: port}
gateway := &isolatedDispatchGateway{commands: []ClaimedCommand{
e2eClaim("patch-failure", "config.patch", map[string]any{"revision": "r1", "fields": []any{map[string]any{"key": "ServerName", "value": "Moonlight"}}}, stamp),
e2eClaim("notification-failure", "player.notify", map[string]any{"playerId": "76561198000000001", "message": "Moonlight ready"}, stamp),
}}
dispatcher := Dispatcher{Client: gateway, Registry: NewHandlerRegistry(HandlerAvailability{BoundServerID: "server-1", Approved: true, Capabilities: map[string]bool{"config.patch": true, "player.notify": true}}, adapter), Now: func() time.Time { return stamp }}
if err := dispatcher.DispatchOnce(context.Background()); err != nil {
t.Fatalf("dispatch adapter failures: %v", err)
}
for id, results := range gateway.completed {
result := results[0]
if result.Payload["result"] != "failed" || strings.Contains(stringifyPayload(result.Payload), "private") || strings.Contains(result.Summary, "private") {
t.Fatalf("%s did not redact failed typed-port output: %+v", id, result)
}
}
if len(port.notifications) != 1 || port.notifications[0].localCommandPreview == "" {
t.Fatalf("notification fixture did not receive one typed request: %+v", port.notifications)
}
}
func stringifyPayload(payload map[string]any) string {
parts := make([]string, 0, len(payload))
for key, value := range payload {
parts = append(parts, key+"="+strings.TrimSpace(strings.ReplaceAll(strings.TrimSpace(toText(value)), "\n", " ")))
}
return strings.Join(parts, " ")
}
func toText(value any) string {
if text, ok := value.(string); ok {
return text
}
return ""
}
func TestCompanionProductionSourceHasNoForbiddenAdapterPaths(t *testing.T) {
_, currentFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("resolve companion source directory")
}
forbidden := map[string]*regexp.Regexp{
"raw SQL or direct database access": regexp.MustCompile(`(?im)"(?:database/sql|github\.com/(?:mattn/go-sqlite3|go-sql-driver/mysql)|gorm\.io/gorm)"|\b(?:sql|db|database)\.(?:Open|Exec(?:Context)?|Query(?:Context)?|Prepare(?:Context)?)\s*\(`),
"unrestricted RCON or command execution": regexp.MustCompile(`(?i)\b(?:send|execute|run|dispatch)[a-z0-9_]*(?:rcon|rawcommand|command)\s*\(`),
"desktop automation or screen capture": regexp.MustCompile(`(?i)\b(?:tesseract|gosseract|screenshot|robotgo|autogui|keybd_event|mouse_event|sendinput)\b`),
"direct socket transport": regexp.MustCompile(`\bnet\.(?:Dial|DialTimeout)\s*\(`),
}
root := filepath.Dir(currentFile)
err := filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() || filepath.Ext(path) != ".go" || strings.HasSuffix(path, "_test.go") {
return nil
}
source, err := os.ReadFile(path)
if err != nil {
return err
}
for name, pattern := range forbidden {
if match := pattern.FindString(string(source)); match != "" {
t.Fatalf("%s contains forbidden %s: %q", filepath.Base(path), name, match)
}
}
return nil
})
if err != nil {
t.Fatalf("scan production companion source: %v", err)
}
}