Skip to content

Commit

Permalink
add websocket acceptance tests
Browse files Browse the repository at this point in the history
  • Loading branch information
GrantBirki committed Oct 17, 2024
1 parent e8852ee commit dac62e1
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
13 changes: 12 additions & 1 deletion script/acceptance_tests/server.cr
Original file line number Diff line number Diff line change
@@ -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?
Expand Down Expand Up @@ -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
63 changes: 63 additions & 0 deletions script/acceptance_tests/tests.cr
Original file line number Diff line number Diff line change
@@ -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
Expand Down

0 comments on commit dac62e1

Please sign in to comment.