package agones import ( "context" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/cosmic-clash/cosmic-clash/server/domain" "github.com/cosmic-clash/cosmic-clash/server/workload" ) func request() domain.AllocationRequest { return domain.AllocationRequest{AllocationID: "allocation-1", MatchID: "match-1", Region: "EU", Build: "build-1", Protocol: 1, Transport: "enet"} } func TestAllocateBuildsStrictGameServerAllocationAndEndpoint(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost || r.URL.Path != "/apis/allocation.agones.dev/v1/namespaces/games/gameserverallocations" { t.Fatalf("request=%s %s", r.Method, r.URL.Path) } var body allocationRequest if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Fatal(err) } if body.APIVersion != "allocation.agones.dev/v1" || body.Kind != "GameServerAllocation" || len(body.Spec.Selectors) != 1 || body.Spec.Selectors[0].MatchLabels["cosmic-clash/region"] != "EU" { t.Fatalf("body=%+v", body) } if body.Spec.Metadata.Annotations["cosmic-clash.io/match-id"] != "match-1" || body.Spec.Metadata.Annotations["cosmic-clash.io/allocation-id"] != "allocation-1" { t.Fatalf("allocation did not request match/allocation ID annotations on the GameServer: %+v", body.Spec.Metadata.Annotations) } want := map[string]string{"cosmic-clash.io/region": "EU", "cosmic-clash.io/build": "build-1", "cosmic-clash.io/protocol": "1", "cosmic-clash.io/transport": "enet"} for key, value := range want { if body.Spec.Metadata.Annotations[key] != value { t.Fatalf("annotation %s = %q, want %q", key, body.Spec.Metadata.Annotations[key], value) } } w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"status":{"state":"Allocated","gameServerName":"gs-a","address":"2001:db8::1","ports":[{"name":"default","port":7777}]}}`)) })) defer server.Close() got, err := (Client{BaseURL: server.URL, Namespace: "games", HTTP: server.Client()}).Allocate(context.Background(), request(), map[string]string{"cosmic-clash/region": "EU", "cosmic-clash/build": "build-1"}, time.Unix(1000, 0)) if err != nil { t.Fatal(err) } if got.GameServer != "gs-a" || got.Endpoint != "[2001:db8::1]:7777" || got.Allocation.State != domain.ServerAllocated { t.Fatalf("allocation=%+v", got) } } // TestAllocateRequestsAWorkloadTokenAnnotationWhenConfigured proves the // delivery-channel wiring for the control-plane's self-issued signed token // (server/workload/signed_token.go): with WorkloadSecret set, Allocate // requests a cosmic-clash.io/workload-token annotation whose value actually // parses and verifies against that same secret and names this allocation's // ID -- the exact thing supervisor.Supervisor.workloadToken() reads back // and cmd/control-plane's WorkloadVerify checks. With WorkloadSecret unset // (the default), no such annotation is requested at all, leaving deployments // not yet using this delivery path unaffected. func TestAllocateRequestsAWorkloadTokenAnnotationWhenConfigured(t *testing.T) { secret := []byte("agones-integration-secret") var gotAnnotations map[string]string server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var body allocationRequest if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Fatal(err) } gotAnnotations = body.Spec.Metadata.Annotations w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"status":{"state":"Allocated","gameServerName":"gs-a","address":"203.0.113.9","ports":[{"name":"default","port":7777}]}}`)) })) defer server.Close() now := time.Unix(1000, 0) client := Client{BaseURL: server.URL, Namespace: "games", HTTP: server.Client(), WorkloadSecret: secret} if _, err := client.Allocate(context.Background(), request(), map[string]string{"cosmic-clash/region": "EU"}, now); err != nil { t.Fatal(err) } token := gotAnnotations["cosmic-clash.io/workload-token"] if token == "" { t.Fatal("Allocate did not request a cosmic-clash.io/workload-token annotation with WorkloadSecret configured") } claims, err := workload.ParseSignedWorkloadToken(secret, token, now.Add(time.Second)) if err != nil { t.Fatalf("minted token does not verify against the same secret: %v", err) } if claims.AllocationID != "allocation-1" { t.Fatalf("token names allocation %q, want %q", claims.AllocationID, "allocation-1") } gotAnnotations = nil unsigned := Client{BaseURL: server.URL, Namespace: "games", HTTP: server.Client()} if _, err := unsigned.Allocate(context.Background(), request(), map[string]string{"cosmic-clash/region": "EU"}, now); err != nil { t.Fatal(err) } if _, ok := gotAnnotations["cosmic-clash.io/workload-token"]; ok { t.Fatal("Allocate requested a workload-token annotation with no WorkloadSecret configured") } } func TestAllocateFailsClosedOnMalformedProviderResponses(t *testing.T) { cases := []string{ `{"status":{"state":"UnAllocated","gameServerName":"gs","address":"127.0.0.1","ports":[{"name":"default","port":7777}]}}`, `{"status":{"state":"Allocated","gameServerName":"gs","address":"127.0.0.1","ports":[]}}`, `{"status":{"state":"Allocated","gameServerName":"gs","address":"127.0.0.1","ports":[{"name":"default","port":70000}]}}`, } for _, payload := range cases { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(payload)) })) _, err := (Client{BaseURL: server.URL, Namespace: "games", HTTP: server.Client()}).Allocate(context.Background(), request(), map[string]string{"region": "EU"}, time.Unix(1000, 0)) server.Close() if err == nil { t.Fatalf("malformed response accepted: %s", payload) } } } func TestAllocateRejectsUnsafeConfigurationAndProviderFailure(t *testing.T) { for _, client := range []Client{{BaseURL: "http://127.0.0.1:1/path", Namespace: "games"}, {BaseURL: "http://127.0.0.1:1", Namespace: "games/other"}} { if _, err := client.Allocate(context.Background(), request(), map[string]string{"region": "EU"}, time.Unix(1000, 0)); err == nil { t.Fatal("unsafe client configuration accepted") } } server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "no capacity", http.StatusConflict) })) defer server.Close() _, err := (Client{BaseURL: server.URL, Namespace: "games", HTTP: server.Client()}).Allocate(context.Background(), request(), map[string]string{"region": "EU"}, time.Unix(1000, 0)) if err == nil || !strings.Contains(err.Error(), "409") { t.Fatalf("provider failure err=%v", err) } } func TestListReadyServersProjectsOnlyStrictReadyFleetMembers(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet || r.URL.Path != "/apis/agones.dev/v1/namespaces/games/gameservers" { t.Fatalf("request=%s %s", r.Method, r.URL.Path) } _, _ = w.Write([]byte(`{"items":[{"metadata":{"name":"ready-a","labels":{"cosmic-clash.io/region":"EU","cosmic-clash.io/build":"build-1","cosmic-clash.io/protocol":"1","cosmic-clash.io/transport":"enet"}},"status":{"state":"Ready"}},{"metadata":{"name":"allocated-a","labels":{}},"status":{"state":"Allocated"}}]}`)) })) defer server.Close() ready, err := (Client{BaseURL: server.URL, Namespace: "games", HTTP: server.Client()}).ListReadyServers(context.Background()) if err != nil || len(ready) != 1 || ready[0] != (domain.ReadyServer{ServerID: "ready-a", Region: "EU", Build: "build-1", Protocol: 1, Transport: "enet", State: domain.ServerReady}) { t.Fatalf("ready=%+v err=%v", ready, err) } } func TestListReadyServersFailsClosedOnInvalidReadyCompatibility(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"items":[{"metadata":{"name":"ready-a","labels":{"cosmic-clash.io/region":"EU","cosmic-clash.io/build":"build-1","cosmic-clash.io/protocol":"bad","cosmic-clash.io/transport":"enet"}},"status":{"state":"Ready"}}]}`)) })) defer server.Close() if _, err := (Client{BaseURL: server.URL, Namespace: "games", HTTP: server.Client()}).ListReadyServers(context.Background()); err == nil { t.Fatal("invalid Ready GameServer accepted") } }