add private endpoint for match reporting
This commit is contained in:
+174
-2
@@ -325,6 +325,176 @@ Action Cable использует формат JSON-сообщений чере
|
||||
|
||||
---
|
||||
|
||||
### Детали матча
|
||||
|
||||
Возвращает подробную информацию о матче: итог, длительность и дельту рейтинга
|
||||
текущего игрока. Матч доступен **только его участникам** — для остальных
|
||||
пользователей (и для неизвестного `uuid`) возвращается `404`, чтобы не раскрывать
|
||||
чужие матчи.
|
||||
|
||||
Эндпоинт можно вызывать сразу после получения клиентом сообщения `END` от
|
||||
`game-server`: `game-server` сообщает итоги на main-server **до** рассылки `END`.
|
||||
Для незавершённого матча возвращается его текущее состояние (`status: "ongoing"`,
|
||||
`finished_at` и `duration_seconds` равны `null`).
|
||||
|
||||
**URL:** `GET /api/matches/:uuid`
|
||||
|
||||
**Auth:** требуется (JWT одного из игроков матча)
|
||||
|
||||
**Пример запроса:**
|
||||
|
||||
```bash
|
||||
curl -X GET http://localhost:3000/api/matches/145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e2f \
|
||||
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
|
||||
```
|
||||
|
||||
**Успешный ответ (200 OK):**
|
||||
|
||||
```json
|
||||
{
|
||||
"match": {
|
||||
"id": "145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e2f",
|
||||
"status": "player1_won",
|
||||
"game_server": "ws://localhost:8081/ws",
|
||||
"started_at": "2026-11-09T12:00:00.000Z",
|
||||
"finished_at": "2026-11-09T12:02:05.000Z",
|
||||
"duration_seconds": 125,
|
||||
"player1": {
|
||||
"id": 1,
|
||||
"nickname": "CaptainNemo",
|
||||
"rating_before": 100,
|
||||
"rating_change": 0
|
||||
},
|
||||
"player2": {
|
||||
"id": 2,
|
||||
"nickname": "CaptainHook",
|
||||
"rating_before": 100,
|
||||
"rating_change": 0
|
||||
},
|
||||
"your_rating_before": 100,
|
||||
"your_rating_change": 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Поля `your_rating_before` и `your_rating_change` — рейтинг и его дельта **для
|
||||
запрашивающего игрока** (каждому участнику возвращается своё значение).
|
||||
Пересчёт рейтинга пока не реализован, поэтому дельта временно всегда `0`.
|
||||
|
||||
Значения `status`:
|
||||
|
||||
| Значение | Описание |
|
||||
|----------|----------|
|
||||
| `ongoing` | матч ещё идёт |
|
||||
| `player1_won` | победа первого игрока |
|
||||
| `player2_won` | победа второго игрока |
|
||||
| `draw` | ничья |
|
||||
| `abandoned` | матч не состоялся / технический сбой (например, соперник не подключился) |
|
||||
|
||||
**Ошибки:**
|
||||
|
||||
| Код | Описание |
|
||||
|-----|----------|
|
||||
| `401` | отсутствует/невалиден токен |
|
||||
| `404` | матч не найден или пользователь не является его участником |
|
||||
|
||||
---
|
||||
|
||||
### Итоги матча (внутренний endpoint)
|
||||
|
||||
Приватный endpoint, предназначенный **только для `game-server`**. Вызывается
|
||||
перед рассылкой игрокам сообщения `END`, чтобы к моменту запроса деталей матча
|
||||
(см. выше) итоги уже были сохранены.
|
||||
|
||||
**URL:** `POST /api/internal/matches/:uuid/result`
|
||||
|
||||
**Auth:** HMAC-подпись общим секретом (`SECRET_KEY_BASE`), JWT не используется.
|
||||
|
||||
**Content-Type:** `application/json`
|
||||
|
||||
**Параметры (JSON):**
|
||||
|
||||
| Параметр | Тип | Обязательный | Описание |
|
||||
|----------|-----|--------------|----------|
|
||||
| `status` | string | ✅ | Итог: `player1_won`, `player2_won`, `draw` или `abandoned` |
|
||||
| `duration_seconds` | integer | ✅ | Длительность матча в секундах (`>= 0`) |
|
||||
|
||||
`finished_at` устанавливается сервером в момент обработки отчёта. Пересчёт
|
||||
рейтинга пока не выполняется — поля `rating_change` остаются нулевыми.
|
||||
|
||||
#### Аутентификация через HMAC
|
||||
|
||||
Секрет (тот же, что используется для подписи JWT) **не передаётся** в запросе.
|
||||
Вместо этого клиент подписывает запрос:
|
||||
|
||||
```
|
||||
подписываемая строка = "<timestamp>.<path>.<raw body>"
|
||||
signature = hex(HMAC-SHA256(SECRET_KEY_BASE, подписываемая строка))
|
||||
```
|
||||
|
||||
- `<timestamp>` — unix-время в секундах (заголовок `X-Request-Timestamp`);
|
||||
- `<path>` — путь запроса без query string, например
|
||||
`/api/internal/matches/<uuid>/result`;
|
||||
- `<raw body>` — точное тело запроса в байтах.
|
||||
|
||||
Заголовки запроса:
|
||||
|
||||
| Заголовок | Значение |
|
||||
|-----------|----------|
|
||||
| `X-Request-Timestamp` | unix-время в секундах |
|
||||
| `X-Request-Signature` | `sha256=<hex-дайджест>` |
|
||||
|
||||
Подпись привязана к методу-пути и телу запроса, а `timestamp` ограничивает
|
||||
окно повторного использования: запросы с расхождением времени больше
|
||||
**5 минут** отклоняются. Сравнение подписи выполняется за постоянное время.
|
||||
|
||||
**Пример запроса:**
|
||||
|
||||
```bash
|
||||
UUID=145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e2f
|
||||
BODY='{"status":"player1_won","duration_seconds":125}'
|
||||
TS=$(date +%s)
|
||||
SIG=$(printf '%s.%s.%s' "$TS" "/api/internal/matches/$UUID/result" "$BODY" \
|
||||
| openssl dgst -sha256 -hmac "$SECRET_KEY_BASE" -hex | sed 's/^.* //')
|
||||
|
||||
curl -X POST "http://localhost:3000/api/internal/matches/$UUID/result" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Request-Timestamp: $TS" \
|
||||
-H "X-Request-Signature: sha256=$SIG" \
|
||||
-d "$BODY"
|
||||
```
|
||||
|
||||
**Успешный ответ (200 OK):**
|
||||
|
||||
```json
|
||||
{
|
||||
"match": {
|
||||
"id": "145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e2f",
|
||||
"status": "player1_won",
|
||||
"game_server": "ws://localhost:8081/ws",
|
||||
"started_at": "2026-11-09T12:00:00.000Z",
|
||||
"finished_at": "2026-11-09T12:02:05.000Z",
|
||||
"duration_seconds": 125,
|
||||
"player1": { "id": 1, "nickname": "CaptainNemo", "rating_before": 100, "rating_change": 0 },
|
||||
"player2": { "id": 2, "nickname": "CaptainHook", "rating_before": 100, "rating_change": 0 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Ошибки:**
|
||||
|
||||
| Код | Описание |
|
||||
|-----|----------|
|
||||
| `401` | отсутствует/неверная подпись или устаревший `timestamp` |
|
||||
| `404` | матч с таким `uuid` не найден |
|
||||
| `409` | матч уже завершён с другим итогом |
|
||||
| `422` | невалидный `status` или `duration_seconds` |
|
||||
|
||||
Отчёт идемпотентен: повторная отправка того же итога для уже завершённого
|
||||
матча возвращает `200` без изменения данных.
|
||||
|
||||
---
|
||||
|
||||
## Health Check
|
||||
|
||||
Проверка доступности сервера.
|
||||
@@ -347,7 +517,9 @@ Action Cable использует формат JSON-сообщений чере
|
||||
|-----|----------|
|
||||
| `200` | Успешный запрос |
|
||||
| `201` | Ресурс создан (регистрация) |
|
||||
| `401` | Неавторизован (отсутствует/невалиден токен) |
|
||||
| `401` | Неавторизован (отсутствует/невалиден токен или HMAC-подпись) |
|
||||
| `404` | Ресурс не найден (или недоступен пользователю) |
|
||||
| `409` | Конфликт состояния (матч уже завершён с другим итогом) |
|
||||
| `422` | Ошибка валидации |
|
||||
| `500` | Внутренняя ошибка сервера |
|
||||
|
||||
@@ -368,7 +540,7 @@ Action Cable использует формат JSON-сообщений чере
|
||||
| `MATCHMAKING_MAX_RANGE` | `1000` | Максимальный допуск по рейтингу |
|
||||
| `MATCHMAKING_SWEEP_INTERVAL` | `2` | Периодичность фоновой сверки очереди, сек |
|
||||
| `CORS_ORIGINS` | `*` | Разрешённые origins для CORS (через запятую) |
|
||||
| `SECRET_KEY_BASE` | из `credentials.yml.enc` | Секретный ключ для JWT |
|
||||
| `SECRET_KEY_BASE` | из `credentials.yml.enc` | Секретный ключ для JWT, а также для HMAC-подписи внутренних запросов `game-server` (общий с ним секрет) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
module Api
|
||||
module Internal
|
||||
# Base class for endpoints intended for the game-server only (never for
|
||||
# browsers). Authenticated via HMAC of the request body instead of a JWT:
|
||||
# see InternalSignatureService.
|
||||
class BaseController < ApplicationController
|
||||
skip_before_action :authenticate_request!
|
||||
before_action :authenticate_internal_request!
|
||||
|
||||
private
|
||||
|
||||
def authenticate_internal_request!
|
||||
unless InternalSignatureService.valid?(request)
|
||||
render json: { error: "Unauthorized" }, status: :unauthorized
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,53 @@
|
||||
module Api
|
||||
module Internal
|
||||
# Receives match results reported by the game-server when a match ends.
|
||||
#
|
||||
# Transitions a match from `ongoing` to its final status and stores the
|
||||
# duration. Rating recalculation is not implemented yet, so the
|
||||
# rating_change fields stay as they are (0).
|
||||
#
|
||||
# The report is idempotent: re-reporting the same outcome for an already
|
||||
# finished match returns 200, a different one returns 409.
|
||||
class MatchResultsController < Api::Internal::BaseController
|
||||
FINAL_STATUSES = %w[player1_won player2_won draw abandoned].freeze
|
||||
|
||||
def create
|
||||
match = Match.find_by(uuid: params[:uuid])
|
||||
return render json: { error: "Match not found" }, status: :not_found unless match
|
||||
|
||||
status_param = params[:status].to_s
|
||||
unless FINAL_STATUSES.include?(status_param)
|
||||
return render json: { error: "status must be one of: #{FINAL_STATUSES.join(', ')}" },
|
||||
status: :unprocessable_content
|
||||
end
|
||||
|
||||
duration = parse_duration
|
||||
return render json: { error: "duration_seconds must be a non-negative integer" },
|
||||
status: :unprocessable_content if duration.nil?
|
||||
|
||||
unless match.ongoing?
|
||||
if match.status == status_param
|
||||
# Idempotent re-report of the same outcome.
|
||||
return render json: { match: MatchSerializer.as_json(match) }
|
||||
end
|
||||
|
||||
return render json: { error: "Match already finished" }, status: :conflict
|
||||
end
|
||||
|
||||
match.update!(status: status_param, duration_seconds: duration, finished_at: Time.current)
|
||||
render json: { match: MatchSerializer.as_json(match) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Accepts an integer or a string of digits; nil/floats/garbage are invalid.
|
||||
def parse_duration
|
||||
value = params[:duration_seconds]
|
||||
value = value.to_s if value.is_a?(Numeric)
|
||||
return nil unless value.is_a?(String) && value.match?(/\A\d+\z/)
|
||||
|
||||
value.to_i
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,11 @@
|
||||
# Player-facing match details. Only participants of a match can view it:
|
||||
# a non-participant (or an unknown uuid) gets 404 to avoid leaking
|
||||
# information about other players' matches.
|
||||
class Api::MatchesController < ApplicationController
|
||||
def show
|
||||
match = Match.for_user(current_user).find_by(uuid: params[:uuid])
|
||||
return render json: { error: "Match not found" }, status: :not_found unless match
|
||||
|
||||
render json: { match: MatchSerializer.as_json(match, viewer: current_user) }
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
# Serializes a Match as the JSON representation shared by the internal
|
||||
# (game-server facing) and the player-facing endpoints. When `viewer` is
|
||||
# given, the viewer's own rating delta is included under `your_rating_before`
|
||||
# and `your_rating_change`.
|
||||
class MatchSerializer
|
||||
def self.as_json(match, viewer: nil)
|
||||
match_json = {
|
||||
id: match.uuid,
|
||||
status: match.status,
|
||||
game_server: match.game_server,
|
||||
started_at: match.started_at,
|
||||
finished_at: match.finished_at,
|
||||
duration_seconds: match.duration_seconds,
|
||||
player1: player_json(match.player1, match.player1_rating_before, match.player1_rating_change),
|
||||
player2: player_json(match.player2, match.player2_rating_before, match.player2_rating_change)
|
||||
}
|
||||
|
||||
if viewer
|
||||
if viewer.id == match.player1_id
|
||||
match_json[:your_rating_before] = match.player1_rating_before
|
||||
match_json[:your_rating_change] = match.player1_rating_change
|
||||
elsif viewer.id == match.player2_id
|
||||
match_json[:your_rating_before] = match.player2_rating_before
|
||||
match_json[:your_rating_change] = match.player2_rating_change
|
||||
end
|
||||
end
|
||||
|
||||
match_json
|
||||
end
|
||||
|
||||
def self.player_json(user, rating_before, rating_change)
|
||||
{
|
||||
id: user.id,
|
||||
nickname: user.nickname,
|
||||
rating_before: rating_before,
|
||||
rating_change: rating_change
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,47 @@
|
||||
# HMAC authentication for the internal (game-server facing) endpoints.
|
||||
#
|
||||
# The game-server signs every request with the same shared secret that is
|
||||
# used for JWTs (Rails.application.secret_key_base), but the secret itself is
|
||||
# never transmitted. The signature proves the sender knows the secret and
|
||||
# binds the request to a specific method path, timestamp and body.
|
||||
#
|
||||
# Signed payload:
|
||||
# "#{timestamp}.#{path}.#{raw_body}"
|
||||
# where `path` is the request path without the query string.
|
||||
#
|
||||
# Headers (sent by the client):
|
||||
# X-Request-Timestamp: unix time in seconds
|
||||
# X-Request-Signature: "sha256=" + hex(HMAC-SHA256(secret, signed payload))
|
||||
#
|
||||
# The timestamp must be within TOLERANCE of the server time to mitigate
|
||||
# replay attacks.
|
||||
class InternalSignatureService
|
||||
TIMESTAMP_HEADER = "X-Request-Timestamp"
|
||||
SIGNATURE_HEADER = "X-Request-Signature"
|
||||
SIGNATURE_PREFIX = "sha256="
|
||||
TOLERANCE = 5.minutes
|
||||
|
||||
def self.sign(body, path, secret: Rails.application.secret_key_base, timestamp: Time.current.to_i)
|
||||
OpenSSL::HMAC.hexdigest("SHA256", secret, signed_payload(timestamp, path, body))
|
||||
end
|
||||
|
||||
def self.valid?(request, secret: Rails.application.secret_key_base)
|
||||
timestamp = request.headers[TIMESTAMP_HEADER]
|
||||
signature = request.headers[SIGNATURE_HEADER]
|
||||
return false if timestamp.blank? || signature.blank?
|
||||
|
||||
ts = Integer(timestamp, exception: false)
|
||||
return false unless ts
|
||||
return false if (Time.current.to_i - ts).abs > TOLERANCE
|
||||
|
||||
provided = signature.start_with?(SIGNATURE_PREFIX) ? signature[SIGNATURE_PREFIX.length..] : signature
|
||||
expected = sign(request.raw_post, request.path, secret: secret, timestamp: ts)
|
||||
return false unless provided.is_a?(String) && provided.bytesize == expected.bytesize
|
||||
|
||||
ActiveSupport::SecurityUtils.secure_compare(provided, expected)
|
||||
end
|
||||
|
||||
def self.signed_payload(timestamp, path, body)
|
||||
"#{timestamp}.#{path}.#{body}"
|
||||
end
|
||||
end
|
||||
@@ -9,6 +9,15 @@ Rails.application.routes.draw do
|
||||
|
||||
# Matchmaking starts and stops over the MatchmakingChannel WebSocket
|
||||
# (see app/channels/matchmaking_channel.rb).
|
||||
|
||||
# Match details for the participants of the match.
|
||||
get "matches/:uuid", to: "matches#show"
|
||||
|
||||
# Intended for the game-server only; authenticated via HMAC (see
|
||||
# InternalSignatureService), not via a user JWT.
|
||||
namespace :internal do
|
||||
post "matches/:uuid/result", to: "match_results#create"
|
||||
end
|
||||
end
|
||||
|
||||
# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
|
||||
|
||||
@@ -52,15 +52,23 @@ app/
|
||||
│ └── api/
|
||||
│ ├── registrations_controller.rb # Регистрация и загрузка аватара
|
||||
│ ├── sessions_controller.rb # Вход, выход, профиль (/api/me)
|
||||
│ └── matchmaking_controller.rb # HTTP-отмена поиска
|
||||
│ ├── matchmaking_controller.rb # HTTP-отмена поиска
|
||||
│ ├── matches_controller.rb # Детали матча для участников (GET /api/matches/:uuid)
|
||||
│ └── internal/
|
||||
│ ├── base_controller.rb # HMAC-аутентификация запросов game-server
|
||||
│ └── match_results_controller.rb # Приём итогов матча от game-server
|
||||
├── jobs/
|
||||
│ ├── application_job.rb # Базовый класс фоновых задач
|
||||
│ └── matchmaking_sweep_job.rb # Периодическая проверка очереди (Solid Queue)
|
||||
├── models/
|
||||
│ ├── application_record.rb # Базовый класс моделей
|
||||
│ └── user.rb # Модель игрока (никнейм, пароль, рейтинг, аватар)
|
||||
│ ├── user.rb # Модель игрока (никнейм, пароль, рейтинг, аватар)
|
||||
│ └── match.rb # Матч: участники, статус, длительность, дельты рейтинга
|
||||
├── serializers/
|
||||
│ └── match_serializer.rb # Общий JSON-формат матча для API и внутреннего endpoint
|
||||
└── services/
|
||||
├── jwt_service.rb # Кодирование и валидация JWT
|
||||
├── internal_signature_service.rb # HMAC-подпись/проверка внутренних запросов game-server
|
||||
└── matchmaking_service.rb # Логика очереди и вызовы Lua в Redis
|
||||
```
|
||||
|
||||
@@ -105,6 +113,12 @@ app/
|
||||
- Секретный ключ: `Rails.application.secret_key_base`.
|
||||
- Стандартный срок действия токена авторизации: 7 дней.
|
||||
- Обработка исключений `JWT::DecodeError` и `JWT::ExpiredSignature` с возвратом `nil`.
|
||||
- **`InternalSignatureService`:**
|
||||
- HMAC-аутентификация запросов от `game-server` к внутренним endpoint'ам
|
||||
(`/api/internal/...`): подписывается строка `"<timestamp>.<path>.<body>"`.
|
||||
- Использует тот же общий секрет, что и JWT (`secret_key_base`), поэтому
|
||||
новых переменных окружения не требуется; сам секрет по сети не передаётся.
|
||||
- Отклоняет запросы с расхождением времени больше 5 минут (защита от replay).
|
||||
- **`MatchmakingService`:**
|
||||
- Инкапсулирует вызовы Redis Lua-скриптов (`PAIR_SCRIPT`, `FINALIZE_SCRIPT`, `CANCEL_SCRIPT`).
|
||||
- Выполняет создание матчей, подписание игровых токенов и бродкаст уведомлений через `MatchmakingChannel`.
|
||||
@@ -128,8 +142,36 @@ app/
|
||||
| **Секрет подписи** | `SECRET_KEY_BASE` | `SECRET_KEY_BASE` (общий для Rails и Go) |
|
||||
| **Алгоритм** | HS256 | HS256 |
|
||||
|
||||
Тот же секрет используется и для третьего механизма — **HMAC-подписи внутренних
|
||||
запросов** `game-server → main-server` (см. `InternalSignatureService`): отдельно
|
||||
подписанного JWT нет, секрет по сети не передаётся.
|
||||
|
||||
### Безопасность делегирования на Game Server:
|
||||
1. Игровой сервер Go не имеет прямого доступа к базе данных пользователей Main Server.
|
||||
2. При подключении к Game Server игрок предъявляет `game_token`.
|
||||
3. Game Server валидирует подпись токена тем же общим секретом `SECRET_KEY_BASE`, сверяет `match_id` и идентификатор подключившегося игрока (`player1_id` или `player2_id`).
|
||||
4. Токен действует всего 120 секунд, что исключает возможность повторного использования после начала игры.
|
||||
|
||||
### Взаимодействие Game Server → Main Server (итоги матча)
|
||||
|
||||
Когда партия завершается на `game-server` (победа одного из игроков, таймаут
|
||||
подключения соперника или технический сбой), он **до рассылки игрокам сообщения
|
||||
`END`** отправляет отчёт на внутренний endpoint:
|
||||
|
||||
```
|
||||
POST /api/internal/matches/:uuid/result
|
||||
```
|
||||
|
||||
с телом `{ "status": "player1_won" | "player2_won" | "draw" | "abandoned",
|
||||
"duration_seconds": N }` и HMAC-подписью (см. `InternalSignatureService`).
|
||||
|
||||
Порядок важен: получив `END`, клиент сразу запрашивает подробности матча через
|
||||
`GET /api/matches/:uuid`, поэтому итоги должны быть уже сохранены. Отчёт
|
||||
best-effort: при недоступности main-server `game-server` делает несколько
|
||||
попыток, после чего всё равно рассылает `END` (ошибка логируется).
|
||||
|
||||
Main-server переводит матч из статуса `ongoing` в финальный
|
||||
(`player1_won` / `player2_won` / `draw` / `abandoned`), сохраняет
|
||||
`duration_seconds` и `finished_at`. Пересчёт рейтинга пока не реализован:
|
||||
поля `rating_change` остаются нулевыми. Повторный отчёт того же итога
|
||||
идемпотентен (`200`), отчёт иного итога для завершённого матча — `409`.
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe "Internal match results API", type: :request do
|
||||
let(:player1) { User.create!(nickname: "player_one", password: "secret123") }
|
||||
let(:player2) { User.create!(nickname: "player_two", password: "secret123") }
|
||||
|
||||
let(:match) do
|
||||
Match.create!(
|
||||
player1: player1,
|
||||
player2: player2,
|
||||
status: :ongoing,
|
||||
game_server: "ws://game-server:8080/ws",
|
||||
started_at: Time.current,
|
||||
player1_rating_before: 100,
|
||||
player2_rating_before: 100,
|
||||
player1_rating_change: 0,
|
||||
player2_rating_change: 0
|
||||
)
|
||||
end
|
||||
|
||||
let(:path) { "/api/internal/matches/#{match.uuid}/result" }
|
||||
let(:payload) { { status: "player1_won", duration_seconds: 125 } }
|
||||
let(:body) { payload.to_json }
|
||||
|
||||
def signed_headers(body:, path:, timestamp: Time.current.to_i, secret: Rails.application.secret_key_base)
|
||||
signature = InternalSignatureService.sign(body, path, secret: secret, timestamp: timestamp)
|
||||
{
|
||||
"Content-Type" => "application/json",
|
||||
"X-Request-Timestamp" => timestamp.to_s,
|
||||
"X-Request-Signature" => "sha256=#{signature}"
|
||||
}
|
||||
end
|
||||
|
||||
describe "POST /api/internal/matches/:uuid/result" do
|
||||
it "marks an ongoing match as finished with the reported outcome" do
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
|
||||
match.reload
|
||||
expect(match.status).to eq("player1_won")
|
||||
expect(match.duration_seconds).to eq(125)
|
||||
expect(match.finished_at).to be_present
|
||||
|
||||
json = JSON.parse(response.body)
|
||||
expect(json.dig("match", "id")).to eq(match.uuid)
|
||||
expect(json.dig("match", "status")).to eq("player1_won")
|
||||
expect(json.dig("match", "duration_seconds")).to eq(125)
|
||||
expect(json.dig("match", "player1", "rating_change")).to eq(0)
|
||||
expect(json.dig("match", "player2", "rating_change")).to eq(0)
|
||||
end
|
||||
|
||||
%w[player2_won draw abandoned].each do |status|
|
||||
it "accepts the #{status} outcome" do
|
||||
body = { status: status, duration_seconds: 5 }.to_json
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(match.reload.status).to eq(status)
|
||||
expect(match.duration_seconds).to eq(5)
|
||||
end
|
||||
end
|
||||
|
||||
it "rejects an invalid signature" do
|
||||
headers = signed_headers(body: body, path: path)
|
||||
headers["X-Request-Signature"] = "sha256=deadbeef"
|
||||
|
||||
post path, params: body, headers: headers
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
expect(match.reload.status).to eq("ongoing")
|
||||
end
|
||||
|
||||
it "rejects a signature made with a different secret" do
|
||||
headers = signed_headers(body: body, path: path, secret: "wrong-secret")
|
||||
|
||||
post path, params: body, headers: headers
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
expect(match.reload.status).to eq("ongoing")
|
||||
end
|
||||
|
||||
it "rejects a signature bound to a different path" do
|
||||
headers = signed_headers(body: body, path: "/api/internal/matches/other/result")
|
||||
|
||||
post path, params: body, headers: headers
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it "rejects a tampered body" do
|
||||
headers = signed_headers(body: body, path: path)
|
||||
tampered = { status: "player2_won", duration_seconds: 125 }.to_json
|
||||
|
||||
post path, params: tampered, headers: headers
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
expect(match.reload.status).to eq("ongoing")
|
||||
end
|
||||
|
||||
it "rejects a stale timestamp" do
|
||||
headers = signed_headers(body: body, path: path, timestamp: 10.minutes.ago.to_i)
|
||||
|
||||
post path, params: body, headers: headers
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it "rejects a request without signature headers" do
|
||||
post path, params: body, headers: { "Content-Type" => "application/json" }
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it "returns 404 for an unknown match" do
|
||||
missing_path = "/api/internal/matches/00000000-0000-0000-0000-000000000000/result"
|
||||
post missing_path, params: body, headers: signed_headers(body: body, path: missing_path)
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
it "rejects an invalid status" do
|
||||
body = { status: "ongoing", duration_seconds: 10 }.to_json
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_content)
|
||||
expect(match.reload.status).to eq("ongoing")
|
||||
end
|
||||
|
||||
it "rejects a missing duration" do
|
||||
body = { status: "draw" }.to_json
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_content)
|
||||
expect(match.reload.status).to eq("ongoing")
|
||||
end
|
||||
|
||||
it "rejects a negative duration" do
|
||||
body = { status: "draw", duration_seconds: -1 }.to_json
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_content)
|
||||
end
|
||||
|
||||
it "rejects a non-integer duration" do
|
||||
body = { status: "draw", duration_seconds: "soon" }.to_json
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_content)
|
||||
end
|
||||
|
||||
it "is idempotent for a repeated report of the same outcome" do
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
finished_at = match.reload.finished_at
|
||||
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(match.reload.finished_at).to eq(finished_at)
|
||||
expect(match.status).to eq("player1_won")
|
||||
end
|
||||
|
||||
it "rejects a report that conflicts with an already recorded outcome" do
|
||||
match.update!(status: :player1_won, duration_seconds: 10, finished_at: Time.current)
|
||||
body = { status: "player2_won", duration_seconds: 10 }.to_json
|
||||
|
||||
post path, params: body, headers: signed_headers(body: body, path: path)
|
||||
|
||||
expect(response).to have_http_status(:conflict)
|
||||
expect(match.reload.status).to eq("player1_won")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,94 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe "Match details API", type: :request do
|
||||
let(:player1) { User.create!(nickname: "player_one", password: "secret123") }
|
||||
let(:player2) { User.create!(nickname: "player_two", password: "secret123") }
|
||||
let(:outsider) { User.create!(nickname: "outsider", password: "secret123") }
|
||||
|
||||
let(:match) do
|
||||
Match.create!(
|
||||
player1: player1,
|
||||
player2: player2,
|
||||
status: :player1_won,
|
||||
game_server: "ws://game-server:8080/ws",
|
||||
started_at: 10.minutes.ago,
|
||||
finished_at: Time.current,
|
||||
duration_seconds: 600,
|
||||
player1_rating_before: player1.rating,
|
||||
player2_rating_before: player2.rating,
|
||||
player1_rating_change: 12,
|
||||
player2_rating_change: -12
|
||||
)
|
||||
end
|
||||
|
||||
def token_for(user)
|
||||
JwtService.encode(user_id: user.id)
|
||||
end
|
||||
|
||||
describe "GET /api/matches/:uuid" do
|
||||
it "returns match details with player1's rating delta for player1" do
|
||||
get "/api/matches/#{match.uuid}", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json = JSON.parse(response.body)
|
||||
expect(json["match"]["id"]).to eq(match.uuid)
|
||||
expect(json["match"]["status"]).to eq("player1_won")
|
||||
expect(json["match"]["duration_seconds"]).to eq(600)
|
||||
expect(json["match"]["game_server"]).to eq("ws://game-server:8080/ws")
|
||||
expect(json["match"]["your_rating_change"]).to eq(12)
|
||||
expect(json["match"]["your_rating_before"]).to eq(player1.rating)
|
||||
expect(json["match"]["player1"]["nickname"]).to eq("player_one")
|
||||
expect(json["match"]["player2"]["rating_change"]).to eq(-12)
|
||||
end
|
||||
|
||||
it "returns player2's own rating delta for player2" do
|
||||
get "/api/matches/#{match.uuid}", headers: { "Authorization" => "Bearer #{token_for(player2)}" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json = JSON.parse(response.body)
|
||||
expect(json["match"]["your_rating_change"]).to eq(-12)
|
||||
expect(json["match"]["your_rating_before"]).to eq(player2.rating)
|
||||
end
|
||||
|
||||
it "returns 404 for a user who is not a participant" do
|
||||
get "/api/matches/#{match.uuid}", headers: { "Authorization" => "Bearer #{token_for(outsider)}" }
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
it "returns 404 for an unknown match uuid" do
|
||||
get "/api/matches/00000000-0000-0000-0000-000000000000",
|
||||
headers: { "Authorization" => "Bearer #{token_for(player1)}" }
|
||||
|
||||
expect(response).to have_http_status(:not_found)
|
||||
end
|
||||
|
||||
it "returns 401 without a token" do
|
||||
get "/api/matches/#{match.uuid}"
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it "returns the current state for an ongoing match" do
|
||||
ongoing = Match.create!(
|
||||
player1: player1,
|
||||
player2: player2,
|
||||
status: :ongoing,
|
||||
game_server: "ws://game-server:8080/ws",
|
||||
started_at: Time.current,
|
||||
player1_rating_before: player1.rating,
|
||||
player2_rating_before: player2.rating,
|
||||
player1_rating_change: 0,
|
||||
player2_rating_change: 0
|
||||
)
|
||||
|
||||
get "/api/matches/#{ongoing.uuid}", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json = JSON.parse(response.body)
|
||||
expect(json["match"]["status"]).to eq("ongoing")
|
||||
expect(json["match"]["finished_at"]).to be_nil
|
||||
expect(json["match"]["duration_seconds"]).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,75 @@
|
||||
require "rails_helper"
|
||||
|
||||
RSpec.describe InternalSignatureService do
|
||||
let(:secret) { "test-secret-key-base" }
|
||||
let(:body) { '{"status":"player1_won","duration_seconds":42}' }
|
||||
let(:path) { "/api/internal/matches/abc/result" }
|
||||
let(:timestamp) { 1_700_000_000 }
|
||||
|
||||
it "produces a stable, cross-implementation signature" do
|
||||
# Vector shared with the game-server (Go) test suite. Do not change the
|
||||
# formula without updating both sides.
|
||||
expect(described_class.sign(body, path, secret: secret, timestamp: timestamp))
|
||||
.to eq("e0a7f8b5508639b1afe604b41f00070dd282d02b6444db5b4856959f175e8361")
|
||||
end
|
||||
|
||||
describe ".valid?" do
|
||||
def request_double(path: "/api/internal/matches/abc/result",
|
||||
body: '{"status":"player1_won","duration_seconds":42}',
|
||||
headers: {})
|
||||
request = instance_double("ActionDispatch::Http::Request")
|
||||
allow(request).to receive(:path).and_return(path)
|
||||
allow(request).to receive(:raw_post).and_return(body)
|
||||
allow(request).to receive(:headers).and_return(headers)
|
||||
request
|
||||
end
|
||||
|
||||
def valid_headers(secret: "test-secret-key-base", path: "/api/internal/matches/abc/result",
|
||||
body: '{"status":"player1_won","duration_seconds":42}', timestamp: Time.current.to_i)
|
||||
signature = described_class.sign(body, path, secret: secret, timestamp: timestamp)
|
||||
{
|
||||
"X-Request-Timestamp" => timestamp.to_s,
|
||||
"X-Request-Signature" => "sha256=#{signature}"
|
||||
}
|
||||
end
|
||||
|
||||
it "accepts a correctly signed request" do
|
||||
headers = valid_headers
|
||||
expect(described_class.valid?(request_double(headers: headers), secret: secret)).to be(true)
|
||||
end
|
||||
|
||||
it "accepts a signature without the sha256= prefix" do
|
||||
headers = valid_headers
|
||||
headers["X-Request-Signature"] = headers["X-Request-Signature"].delete_prefix("sha256=")
|
||||
expect(described_class.valid?(request_double(headers: headers), secret: secret)).to be(true)
|
||||
end
|
||||
|
||||
it "rejects missing headers" do
|
||||
expect(described_class.valid?(request_double(headers: {}), secret: secret)).to be(false)
|
||||
end
|
||||
|
||||
it "rejects a non-numeric timestamp" do
|
||||
headers = valid_headers
|
||||
headers["X-Request-Timestamp"] = "not-a-number"
|
||||
expect(described_class.valid?(request_double(headers: headers), secret: secret)).to be(false)
|
||||
end
|
||||
|
||||
it "rejects a wrong signature" do
|
||||
headers = valid_headers
|
||||
headers["X-Request-Signature"] = "sha256=#{"a" * 64}"
|
||||
expect(described_class.valid?(request_double(headers: headers), secret: secret)).to be(false)
|
||||
end
|
||||
|
||||
it "rejects a timestamp too far in the past" do
|
||||
timestamp = (Time.current - described_class::TOLERANCE - 60).to_i
|
||||
headers = valid_headers(timestamp: timestamp)
|
||||
expect(described_class.valid?(request_double(headers: headers), secret: secret)).to be(false)
|
||||
end
|
||||
|
||||
it "rejects a timestamp too far in the future" do
|
||||
timestamp = (Time.current + described_class::TOLERANCE + 60).to_i
|
||||
headers = valid_headers(timestamp: timestamp)
|
||||
expect(described_class.valid?(request_double(headers: headers), secret: secret)).to be(false)
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user