Skip to content
This repository has been archived by the owner on Jul 23, 2023. It is now read-only.

Commit

Permalink
add request validation
Browse files Browse the repository at this point in the history
  • Loading branch information
markburns committed May 14, 2015
1 parent 92c49b1 commit d6429a8
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
25 changes: 25 additions & 0 deletions 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
30 changes: 30 additions & 0 deletions 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

0 comments on commit d6429a8

Please sign in to comment.