Skip to content

Commit

Permalink
Correctly handle Amazon GW forbidden errors
Browse files Browse the repository at this point in the history
The Amazon API gateway used by the Easee API seems to route some requests to a blackhole, possibly because we keep trying to login with outdated credentials. However, such responses should result in a Forbidden error to make sure they're dealt with correctly upstream.

This PR adds a Faraday middleware that detects the Amazon Forbidden response header and changes the response status code to 403.
  • Loading branch information
martijnversluis committed Jun 10, 2024
1 parent 6dfe564 commit 070c451
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/easee/amazon_gw_middleware.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module Easee
class AmazonGwMiddleware < Faraday::Middleware
def on_complete(env)
return unless env.response_headers["X-Amzn-Errortype"] == "ForbiddenException"

response_values = Faraday::Response::RaiseError.new.response_values(env)
raise(Faraday::ForbiddenError, response_values)
end
end
end
1 change: 1 addition & 0 deletions lib/easee/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ def connection
Faraday.new(url: BASE_URL) do |conn|
conn.request :json
conn.response :raise_error
conn.use AmazonGwMiddleware
conn.response :json, content_type: /\bjson$/
end
end
Expand Down
1 change: 1 addition & 0 deletions lib/stekker_easee.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
require_relative "easee/site"
require_relative "easee/state"
require_relative "easee/charger"
require_relative "easee/amazon_gw_middleware"

module Easee
end
29 changes: 29 additions & 0 deletions spec/easee/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,35 @@
expect { client.login }
.to raise_error(Easee::Errors::InvalidCredentials)
end

it "raises Forbidden errors when the request is rerouted with X-Amzn-Errortype: ForbiddenException" do
user_name = "test"
password = "old"

stub_request(:post, "https://api.easee.cloud/api/accounts/login")
.with(
body: { userName: user_name, password: }.to_json,
)
.to_return(
status: 301,
headers: {
Date: "Fri, 07 Jun 2024 07:30:02 GMT",
"Content-Type": "application/json",
"Content-Length": "0",
Connection: "keep-alive",
"X-Amzn-Requestid": "aaa0a000-000a-0000-a0a0-00000a00aa00",
"X-Amzn-Errortype": "ForbiddenException",
"X-Amz-Apigw-Id": "A_AAAAa0aaAAAaa=",
"X-Easee-Key": "a00a0000-0a0a-0a0a-aa00-0a0000a0a0a0",
Location: "https://blackhole.easee.com",
},
)

client = Easee::Client.new(user_name:, password:)

expect { client.login }
.to raise_error(Easee::Errors::Forbidden)
end
end

describe "#pair" do
Expand Down

0 comments on commit 070c451

Please sign in to comment.