Files
CosmicClash/server/agones/allocation_test.go
T
Josh Creek 544f76c502 feat(multiplayer): deliver signed workload tokens via Agones allocation annotation
Closes the remaining gap the previous two commits left open: WorkloadVerify
itself worked, but nothing minted a real token at allocation time or handed
it to a running pod, so it had no real caller yet.

agones.Client gains WorkloadSecret/WorkloadTokenTTL. When set, Allocate
mints a signed workload token for the allocation (allocation_id is known at
request-construction time, before Agones has picked a server -- see the
previous commit for why that's the only identifier the token can bind) and
requests it as a third cosmic-clash.io/workload-token annotation, alongside
the existing match-id/allocation-id ones. Left unset (the default), Allocate
requests no such annotation, so a deployment not yet using this path is
unaffected. cmd/allocator wires it from a new --workload-secret /
COSMIC_CLASH_WORKLOAD_SECRET flag (must match cmd/control-plane's own), with
a startup warning if left unset.

supervisor.Supervisor.workloadToken() resolves the bearer credential for
control-plane registration: an explicitly configured --workload-token-path
always wins (kept for a future Kubernetes-projected-JWT WorkloadVerify path,
not yet wired server-side), otherwise it falls back to the
cosmic-clash.io/workload-token annotation on the allocated GameServer --
the same annotation-fallback pattern matchID already used for
cosmic-clash.io/match-id. WorkloadTokenPath is accordingly no longer
required at construction time when ControlPlaneURL is set.

Verified: new agones test proves the annotation is requested (and parses/
verifies against the same secret, naming the right allocation) when
WorkloadSecret is configured, and that it's absent when it isn't; new
supervisor tests prove the annotation-sourced token is what's actually sent
as the Authorization bearer, and that Start fails closed with neither a
configured path nor an annotation present. Full
`go build ./... && go vet ./... && gofmt -l . && go test ./... -race` and
`go test -tags integration ./... -race` both clean.
2026-09-01 14:57:45 +01:00

151 lines
7.8 KiB
Go

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)
}
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")
}
}