add private endpoint for match reporting

This commit is contained in:
2026-11-09 23:17:55 +03:00
parent f0616c7c51
commit dcb76fa570
11 changed files with 738 additions and 4 deletions
@@ -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