diff --git a/script/acceptance_tests/server.cr b/script/acceptance_tests/server.cr index 8f3eb2d..1645d41 100644 --- a/script/acceptance_tests/server.cr +++ b/script/acceptance_tests/server.cr @@ -1,7 +1,13 @@ require "kemal" require "../../src/kemal-hmac" -hmac_auth({"my_crest_client" => ["my_secret"], "my_standard_client" => ["my_secret_1", "my_secret_2"]}) +hmac_auth( + { + "my_crest_client" => ["my_secret"], + "my_standard_client" => ["my_secret_1", "my_secret_2"], + "my_ws_client" => ["my_secret_3"], + } +) get "/" do |env| "Hi, %s! You sent a request that was successfully verified with HMAC auth" % env.kemal_authorized_client? @@ -45,4 +51,9 @@ options "/catch-all" do |env| "Hi, %s! Welcome to catch-all" % env.kemal_authorized_client? end +ws "/websocket" do |socket| + socket.send "websocket success" + socket.close +end + Kemal.run diff --git a/script/acceptance_tests/tests.cr b/script/acceptance_tests/tests.cr index 7c812aa..85e2b7c 100644 --- a/script/acceptance_tests/tests.cr +++ b/script/acceptance_tests/tests.cr @@ -1,8 +1,71 @@ require "../../src/kemal-hmac" require "crest" require "http/client" +require "http/web_socket" require "spec" +describe "websocket" do + it "successfully sends a websocket request to the server with HMAC auth" do + hmac_client = Kemal::Hmac::Client.new("my_ws_client", "my_secret_3") + + path = "/websocket" + + headers = HTTP::Headers.new + hmac_client.generate_headers(path).each do |key, value| + headers.add(key, value) + end + + # Open websocket connection + ws = HTTP::WebSocket.new( + URI.parse("ws://localhost:3000/websocket"), + headers: headers + ) + + response = "" + + # Set callback + ws.on_message do |msg| + response = msg + end + + ws.run + ws.close + + response.should eq "websocket success" + end + + it "does not provide HMAC headers and fails the websocket request" do + hmac_client = Kemal::Hmac::Client.new("my_ws_client", "invalid_secret") + + path = "/websocket" + + headers = HTTP::Headers.new + hmac_client.generate_headers(path).each do |key, value| + headers.add(key, value) + end + + begin + ws = HTTP::WebSocket.new( + URI.parse("ws://localhost:3000/websocket"), + headers: headers + ) + rescue ex : Socket::Error + ex.message.not_nil!.should contain "Handshake got denied. Status code was 401." + end + end + + it "does not provide the correct HMAC headers and fails the websocket request" do + begin + ws = HTTP::WebSocket.new( + URI.parse("ws://localhost:3000/websocket"), + headers: HTTP::Headers.new + ) + rescue ex : Socket::Error + ex.message.not_nil!.should contain "Handshake got denied. Status code was 401." + end + end +end + describe "All HTTP Methods" do ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].each do |method| it "successfully validates a #{method} request" do