# 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