package mainserver import ( "context" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" "runtime" "strconv" "sync/atomic" "testing" "time" ) const testSecret = "test-secret-key-base" // The vectors are shared with the main-server (Ruby) test suite via // contracts/test_signature_vectors.json — the single source of truth for the // wire format. Do not change the formula without updating both sides. func signatureVectorsPath(t *testing.T) string { t.Helper() _, file, _, ok := runtime.Caller(0) if !ok { t.Fatal("cannot locate the test file") } return filepath.Join(filepath.Dir(file), "..", "..", "..", "contracts", "test_signature_vectors.json") } type signatureVector struct { Name string `json:"name"` Secret string `json:"secret"` Timestamp int64 `json:"timestamp"` Path string `json:"path"` Body string `json:"body"` SignatureHex string `json:"signature_hex"` } func loadSignatureVectors(t *testing.T) []signatureVector { t.Helper() data, err := os.ReadFile(signatureVectorsPath(t)) if err != nil { t.Fatalf("read signature vectors: %v", err) } var doc struct { Vectors []signatureVector `json:"vectors"` } if err := json.Unmarshal(data, &doc); err != nil { t.Fatalf("parse signature vectors: %v", err) } if len(doc.Vectors) == 0 { t.Fatal("no signature vectors found") } return doc.Vectors } func TestSignMatchesSharedVectors(t *testing.T) { for _, v := range loadSignatureVectors(t) { got := Sign(v.Timestamp, v.Path, []byte(v.Body), []byte(v.Secret)) if got != v.SignatureHex { t.Errorf("vector %q: Sign = %q, want %q", v.Name, got, v.SignatureHex) } } } func newTestReporter(t *testing.T, baseURL string) *Reporter { t.Helper() rep, err := NewReporter(baseURL, []byte(testSecret), slog.New(slog.DiscardHandler)) if err != nil { t.Fatalf("NewReporter: %v", err) } return rep } func TestReportMatchResult(t *testing.T) { var gotPath, gotTS, gotSig, gotBody string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { data, _ := io.ReadAll(r.Body) gotPath = r.URL.Path gotTS = r.Header.Get("X-Request-Timestamp") gotSig = r.Header.Get("X-Request-Signature") gotBody = string(data) w.WriteHeader(http.StatusOK) })) defer srv.Close() rep := newTestReporter(t, srv.URL) err := rep.ReportMatchResult(context.Background(), Result{ MatchID: "abc", Status: StatusPlayer1Won, DurationSeconds: 42, }) if err != nil { t.Fatalf("ReportMatchResult: %v", err) } if gotPath != "/api/internal/matches/abc/result" { t.Fatalf("path = %q", gotPath) } if gotBody != `{"status":"player1_won","duration_seconds":42}` { t.Fatalf("body = %q", gotBody) } ts, err := strconv.ParseInt(gotTS, 10, 64) if err != nil { t.Fatalf("timestamp header = %q: %v", gotTS, err) } if now := time.Now().Unix(); ts < now-60 || ts > now+60 { t.Fatalf("timestamp = %d, want close to %d", ts, now) } want := "sha256=" + Sign(ts, gotPath, []byte(gotBody), []byte(testSecret)) if gotSig != want { t.Fatalf("signature = %q, want %q", gotSig, want) } } func TestReportMatchResultRetriesUntilSuccess(t *testing.T) { var attempts atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if attempts.Add(1) < 3 { w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) })) defer srv.Close() rep := newTestReporter(t, srv.URL) err := rep.ReportMatchResult(context.Background(), Result{MatchID: "abc", Status: StatusDraw}) if err != nil { t.Fatalf("ReportMatchResult: %v", err) } if got := attempts.Load(); got != 3 { t.Fatalf("attempts = %d, want 3", got) } } func TestReportMatchResultFailsAfterRetries(t *testing.T) { var attempts atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { attempts.Add(1) w.WriteHeader(http.StatusConflict) })) defer srv.Close() rep := newTestReporter(t, srv.URL) err := rep.ReportMatchResult(context.Background(), Result{MatchID: "abc", Status: StatusAbandoned}) if err == nil { t.Fatal("expected an error after all attempts failed") } if got := attempts.Load(); got != 3 { t.Fatalf("attempts = %d, want 3", got) } } func TestNewReporterRejectsInvalidURL(t *testing.T) { for _, url := range []string{"", "localhost:3000", "http://", "::", "ftp://example.com", "http://example.com/?a=b"} { if _, err := NewReporter(url, []byte(testSecret), nil); err == nil { t.Fatalf("NewReporter(%q): expected an error", url) } } } func TestReportMatchResultWithPathPrefix(t *testing.T) { var gotPath string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotPath = r.URL.Path w.WriteHeader(http.StatusOK) })) defer srv.Close() rep := newTestReporter(t, srv.URL+"/main/") err := rep.ReportMatchResult(context.Background(), Result{ MatchID: "abc", Status: StatusPlayer1Won, DurationSeconds: 1, }) if err != nil { t.Fatalf("ReportMatchResult: %v", err) } if gotPath != "/main/api/internal/matches/abc/result" { t.Fatalf("path = %q, want /main/api/internal/matches/abc/result", gotPath) } }