From d6429a8190856f8400ff8be388ac732b9489705f Mon Sep 17 00:00:00 2001 From: Mark Burns Date: Thu, 14 May 2015 15:24:50 +0900 Subject: [PATCH] add request validation --- lib/slanger/request_validation.rb | 25 +++++++++++++++++++++++ spec/unit/request_validation_spec.rb | 30 ++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 lib/slanger/request_validation.rb create mode 100644 spec/unit/request_validation_spec.rb diff --git a/lib/slanger/request_validation.rb b/lib/slanger/request_validation.rb new file mode 100644 index 00000000..5ff13f4e --- /dev/null +++ b/lib/slanger/request_validation.rb @@ -0,0 +1,25 @@ +module Slanger + class RequestValidation < Struct.new :body + def socket_id + validate_socket_id!(data["socket_id"]) + end + + def data + @data ||= JSON.parse(body.tap{ |s| s.force_encoding('utf-8')}) + end + + private + + def validate_socket_id!(socket_id) + unless valid_socket_id?(socket_id) + raise Signature::AuthenticationError.new("Invalid socket_id: #{socket_id}") + end + + socket_id + end + + def valid_socket_id?(socket_id) + socket_id =~ /\A[\da-fA-F]{8}\-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}\z/ + end + end +end diff --git a/spec/unit/request_validation_spec.rb b/spec/unit/request_validation_spec.rb new file mode 100644 index 00000000..8d2f4d27 --- /dev/null +++ b/spec/unit/request_validation_spec.rb @@ -0,0 +1,30 @@ +#encoding: utf-8 +require 'spec_helper' + +describe Slanger::RequestValidation do + describe '#socket_id' do + it 'validation' do + socket_id = "POST\n/apps/99759/events\nauth_key=840543d97de9803651b1&auth_timestamp=123&auth_version=1.0&body_md5=some_md5&dummy=" + + expect {validate(socket_id) }.to raise_error Signature::AuthenticationError + expect {validate("something 123")}.to raise_error Signature::AuthenticationError + expect {validate("335e6070-96fc-4950-a94a-a9032d85ae26") }.not_to raise_error Signature::AuthenticationError + + expect {validate("335e6070-96fc-4950-a94a-a9032d85ae26 ") }.to raise_error Signature::AuthenticationError + expect {validate(" 335e6070-96fc-4950-a94a-a9032d85ae26") }.to raise_error Signature::AuthenticationError + expect {validate("hello\n35e6070-96fc-4950-a94a-a9032d85ae26\nhomakov") }.to raise_error Signature::AuthenticationError + expect {validate("35e6070-96fc-4950-a94a-a9032d85ae26") }.to raise_error Signature::AuthenticationError + expect {validate("335e6070-96fc-4950-a94aa9032d85ae26") }.to raise_error Signature::AuthenticationError + end + end + + def validate(socket_id) + Slanger::RequestValidation.new(body(socket_id)).socket_id + end + + def body(socket_id) + {socket_id: socket_id}.to_json + end + +end +