Skip to content

Commit

Permalink
Merge pull request #1089 from NickLaMuro/fail-fast-with-missing-api-t…
Browse files Browse the repository at this point in the history
…oken

[BaseController::Authentication] raise on missing AUTH_TOKEN

(cherry picked from commit 4d3d917)
  • Loading branch information
Fryguy committed Oct 26, 2021
1 parent 7b3d7af commit d336a96
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
20 changes: 20 additions & 0 deletions app/controllers/api/base_controller/authentication.rb
Expand Up @@ -107,6 +107,26 @@ def auth_user(userid)
end

def authenticate_with_user_token(auth_token)
# Using `.nil?` + `.empty?` to avoid a REGEXP on `.blank?` valid
# tokens, which can be expensive on every request:
#
# http://tmm1.net/ruby21-profiling/
#
# We only care about empty? and not whitespace anyway since the reason
# for this check is because Dalli checks for `nil`, or specifically a
# zero length string to raise an error with:
#
# # lib/dalli/client.rb:380
#
# def validate_key(key)
# raise ArgumentError, "key cannot be blank" if !key || key.length == 0
#
# # ...
# end
#
raise AuthenticationError, "Missing Authentication Token (#{HttpHeaders::AUTH_TOKEN})" if auth_token.nil?
raise AuthenticationError, "Empty Authentication Token (#{HttpHeaders::AUTH_TOKEN})" if auth_token.length == 0

if !api_token_mgr.token_valid?(auth_token)
raise AuthenticationError, "Invalid Authentication Token #{auth_token} specified"
else
Expand Down
11 changes: 10 additions & 1 deletion spec/requests/authentication_spec.rb
Expand Up @@ -240,7 +240,7 @@
end

context "Token Based Authentication" do
%w(sql memory).each do |session_store|
%w(sql memory cache).each do |session_store|
context "when using a #{session_store} session store" do
before { stub_settings_merge(:server => {:session_store => session_store}) }

Expand All @@ -253,6 +253,15 @@
expect_result_to_have_keys(%w(auth_token token_ttl expires_on))
end

it "authentication using a blank token" do
get api_entrypoint_url, :headers => {Api::HttpHeaders::AUTH_TOKEN => ""}

expected_msg = "Empty Authentication Token (HTTP_X_AUTH_TOKEN)"

expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["error"]["message"]).to eq(expected_msg)
end

it "authentication using a bad token" do
get api_entrypoint_url, :headers => {Api::HttpHeaders::AUTH_TOKEN => "badtoken"}

Expand Down

0 comments on commit d336a96

Please sign in to comment.