From fec4f9167261ace044fb256f1f8c278c84dcaec5 Mon Sep 17 00:00:00 2001 From: Josh Creek <8179928+jcreek@users.noreply.github.com> Date: Tue, 1 Sep 2026 08:10:05 +0100 Subject: [PATCH] feat: bind signed rosters to assignments --- multiplayer-todo.md | 2 +- server/store/assignment_sql.go | 35 +++++++++++++++++++++++++++++ server/store/assignment_sql_test.go | 5 +++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/multiplayer-todo.md b/multiplayer-todo.md index 1e0a6afe..48bb35fe 100644 --- a/multiplayer-todo.md +++ b/multiplayer-todo.md @@ -1228,7 +1228,7 @@ the local/CI/community transport, not a silent production fallback. |---|---|---| | 8.39 `[D:8.3,8.14,8.17]` | **IN PROGRESS.** `MatchmakingState` now projects queue → proposal → allocation/process-ready/assignment-ready/connect/live plus terminal failure states; autoload `ControlPlaneClient` provides authenticated queue create/recovery/heartbeat/cancel and proposal response requests with idempotency/revision headers; `matchmaking.tscn`/`matchmaking.gd` expose the state and authoritative actions from the main menu; authenticated proposal recovery now reconciles missed proposal events and expires them at read time; the Go API publishes targeted authenticated revisioned queue/proposal/assignment events and the Godot client consumes state/proposal/assignment events, fetching the authoritative assignment after assignment readiness; the API can now use the durable participant-scoped proposal provider for both recovery and accept/decline mutations | `test_matchmaking_state.gd`, `test_control_plane_client.gd`, `test_matchmaking_ui.gd`, `TestProposalRecoveryIsParticipantScopedAndExpiresAtReadBoundary`, `TestAuthenticatedWebSocketDeliversOnlyTargetedRevisionedEvents`, `TestStateChangingAPIActionsPublishTargetedEvents`, `TestProposalRecoveryUsesDurableBackendAndRemainsParticipantScoped` and store proposal SQL tests reject stale/gapped/conflicting updates, validate endpoint/token/payload normalization, preserve idempotent duplicates, and guarantee visible phase/terminal copy; wiring durable allocation events into the outbox, wait/latency explanations and Godot runtime verification remain | | 8.40 `[D:8.3,8.14]` | **IN PROGRESS.** Pure Go revisioned replica reducer rejects gaps for REST resync, makes duplicate/out-of-order events idempotent, and resumes from the authoritative snapshot revision; authenticated queue-ticket recovery now has an owner-checked REST read; Godot client projection persists non-secret ticket/proposal state, forces authoritative recovery after restart, and can replay a lost queue-create response with the original ticket/idempotency key; the Go API now exposes an authenticated `/v1/events` WebSocket with bounded per-player queues, strict upgrade/vocabulary validation and REST-resync-safe slow-client failure; Godot `ControlPlaneClient` can connect to the stream, consume validated events, automatically reconnect with bounded backoff, and trigger REST recovery on projection gaps and stream return | `server/domain/sync.go`, `server/api/events.go`, `server/api/service.go`, `service_test.go`, `matchmaking_state.gd` and `control_plane_client.gd` cover gap, snapshot, replay, same-revision conflict, owner-only ticket recovery, expired-ticket terminal handling, malformed restart snapshots, API-level duplicate-create replay/conflict, authenticated handshake/key rejection, targeted event delivery, exactly-once slow-subscriber closure and invalid-event rejection; durable outbox fan-out and live Godot verification remain | -| 8.41 `[D:7.8,8.9,8.31,8.40]` | **IN PROGRESS.** Authenticated `GET /v1/assignments/{matchId}` now exposes only a validated, player-scoped assignment view; Godot `AssignmentState`/`ControlPlaneClient.fetch_assignment()` bind the response to the authenticated player, recheck expiry, preserve explicit transport/slot/join authorisation and do not connect before assignment-ready; migration 0002 and the Go store adapter now persist/recover the complete player-scoped assignment projection with conflict-safe identical replay; `AssignmentProviderFromStore` wires that durable projection into the API injection point; `SaveAssignments` publishes a complete signed roster atomically instead of allowing partial player visibility | `server/api/service.go`, `store_adapters.go`, `service_test.go`, `assignment_state.gd`, `test_assignment_state.gd`, `server/migrations/0002_assignments.sql` and `server/store/assignment_sql.go` cover participant/identity/expiry/shape/transport boundaries, player-scoped schema keys, expiry-filtered reads, assignment upsert conflict handling, atomic batch validation and nil-store fail-closed behavior; signed manifest-to-player caller wiring, SDR relay-ticket installation, `hello` join-authorisation wiring, fencing integration and live Godot/PostgreSQL verification remain | +| 8.41 `[D:7.8,8.9,8.31,8.40]` | **IN PROGRESS.** Authenticated `GET /v1/assignments/{matchId}` now exposes only a validated, player-scoped assignment view; Godot `AssignmentState`/`ControlPlaneClient.fetch_assignment()` bind the response to the authenticated player, recheck expiry, preserve explicit transport/slot/join authorisation and do not connect before assignment-ready; migration 0002 and the Go store adapter now persist/recover the complete player-scoped assignment projection with conflict-safe identical replay; `AssignmentProviderFromStore` wires that durable projection into the API injection point; `SaveAssignments` publishes a complete signed roster atomically instead of allowing partial player visibility; `SaveVerifiedAssignmentRoster` rechecks signed claims before deriving player rows | `server/api/service.go`, `store_adapters.go`, `service_test.go`, `assignment_state.gd`, `test_assignment_state.gd`, `server/migrations/0002_assignments.sql` and `server/store/assignment_sql.go` cover participant/identity/expiry/shape/transport boundaries, player-scoped schema keys, expiry-filtered reads, assignment upsert conflict handling, atomic batch validation and signed-claim binding; direct API caller wiring, SDR relay-ticket installation, `hello` join-authorisation wiring, fencing integration and live Godot/PostgreSQL verification remain | | 8.42 `[D:8.22,8.23,8.24,8.40]` | **IN PROGRESS.** `RankedProfileState` and `ControlPlaneClient.fetch_ranked_profile()` expose the backend-authoritative rating/RD/volatility/games/tier/provisional/season view; matchmaking UI displays provisional/tier status without client-side rating math | `test_control_plane_client.gd` validates profile shape, numeric safety and provisional display; ranked profile fetch/display, committed revision after reconnect, abandon status and season countdown remain dependent on live auth/backend events and Godot runtime verification | | 8.43 `[D:8.39,8.40,8.41]` | **IN PROGRESS.** Matchmaking client now distinguishes expired queue recovery, session expiry, missing records and retryable control-plane outages; a 401 clears the in-memory token, emits `session_expired` and disables retry until a new session is configured; terminal messages remain visible and active searches are not falsely failed on transient errors | `MatchmakingState` and `ControlPlaneClient` tests cover explicit expiry and the existing terminal/retry-safe state paths; decline, version mismatch, regional outage retry UI, failed reconnect, duplicate-action recovery and live Godot verification remain | diff --git a/server/store/assignment_sql.go b/server/store/assignment_sql.go index 3a82dcbe..d64c20eb 100644 --- a/server/store/assignment_sql.go +++ b/server/store/assignment_sql.go @@ -3,8 +3,13 @@ package store import ( "context" "database/sql" + "encoding/base64" + "encoding/json" "fmt" + "strconv" "time" + + "github.com/cosmic-clash/cosmic-clash/server/domain" ) // DurableAssignment is the persistence form of a verified assignment-ready @@ -124,6 +129,36 @@ func SaveAssignments(ctx context.Context, db *sql.DB, assignments []DurableAssig return tx.Commit() } +// SaveVerifiedAssignmentRoster converts the backend-verified signed roster to +// player-scoped rows. It rechecks the claims at this persistence boundary so a +// caller cannot accidentally publish a token for another match or slot. +func SaveVerifiedAssignmentRoster(ctx context.Context, db *sql.DB, assignment domain.Assignment, roster []domain.SignedJoinAuthorisation) error { + if assignment.Allocation.State != domain.ServerAllocated || len(roster) == 0 { + return fmt.Errorf("invalid verified assignment roster") + } + digest := domain.ManifestDigest(assignment.Manifest) + rows := make([]DurableAssignment, 0, len(roster)) + for _, signed := range roster { + auth := signed.Authorisation + if len(signed.Signature) == 0 || auth.MatchID != assignment.Allocation.MatchID || auth.ServerID != assignment.Allocation.ServerID || auth.Protocol != strconv.Itoa(assignment.Allocation.Protocol) || auth.PlayerID == "" || auth.Slot < 0 || auth.Slot > 5 || auth.ExpiresAt.IsZero() { + return fmt.Errorf("invalid signed assignment roster") + } + envelope, err := json.Marshal(signed) + if err != nil { + return fmt.Errorf("encode signed assignment roster: %w", err) + } + rows = append(rows, DurableAssignment{ + MatchID: assignment.Allocation.MatchID, PlayerID: auth.PlayerID, + AllocationID: assignment.Allocation.AllocationID, ServerID: assignment.Allocation.ServerID, + Slot: auth.Slot, Region: assignment.Allocation.Region, ClientBuild: assignment.Allocation.Build, + ProtocolVersion: assignment.Allocation.Protocol, Transport: assignment.Allocation.Transport, + Endpoint: assignment.Endpoint, JoinAuthorisation: base64.RawURLEncoding.EncodeToString(envelope), + ManifestDigest: digest[:], ExpiresAt: auth.ExpiresAt, Revision: 1, + }) + } + return SaveAssignments(ctx, db, rows) +} + func GetAssignment(ctx context.Context, db *sql.DB, playerID, matchID string, now time.Time) (DurableAssignment, error) { if db == nil || playerID == "" || matchID == "" || now.IsZero() { return DurableAssignment{}, fmt.Errorf("invalid assignment recovery arguments") diff --git a/server/store/assignment_sql_test.go b/server/store/assignment_sql_test.go index 6efd6ec1..2d781e47 100644 --- a/server/store/assignment_sql_test.go +++ b/server/store/assignment_sql_test.go @@ -3,6 +3,8 @@ package store import ( "testing" "time" + + "github.com/cosmic-clash/cosmic-clash/server/domain" ) func TestAssignmentSQLBindsPlayerAndPreservesIdenticalReplay(t *testing.T) { @@ -37,4 +39,7 @@ func TestAssignmentStoreRejectsInvalidBatches(t *testing.T) { if err := SaveAssignments(nil, nil, []DurableAssignment{{MatchID: "match-1", PlayerID: "player-1"}}); err == nil { t.Fatal("invalid assignment batch accepted") } + if err := SaveVerifiedAssignmentRoster(nil, nil, domain.Assignment{}, nil); err == nil { + t.Fatal("empty verified roster accepted") + } }