Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle invalid token when adding redirection headers #1945

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions lib/shopify_app/controller_concerns/login_protection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,7 @@ def add_top_level_redirection_headers(url: nil, ignore_response_code: false)
# Make sure the shop is set in the redirection URL
unless params[:shop]
ShopifyApp::Logger.debug("Setting current shop session")
params[:shop] = if current_shopify_session
current_shopify_session.shop

elsif shopify_id_token
jwt_payload = ShopifyAPI::Auth::JwtPayload.new(shopify_id_token)
jwt_payload.shop
end
params[:shop] = current_shopify_session&.shop || parse_shop_from_jwt
end

url ||= login_url_with_optional_shop
Expand Down Expand Up @@ -279,5 +273,15 @@ def requested_by_javascript?
request.media_type == "text/javascript" ||
request.media_type == "application/javascript"
end

def parse_shop_from_jwt
return nil unless shopify_id_token

jwt_payload = ShopifyAPI::Auth::JwtPayload.new(shopify_id_token)
jwt_payload.shop
rescue ShopifyAPI::Errors::InvalidJwtTokenError
ShopifyApp::Logger.warn("Invalid JWT token for current Shopify session")
nil
end
end
end
14 changes: 14 additions & 0 deletions test/shopify_app/controller_concerns/login_protection_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,20 @@ class LoginProtectionControllerTest < ActionController::TestCase
end
end

test "#activate_shopify_session when not enough scope and rescuing from invalid JWT token, breaks out of iframe in XHR requests" do
ShopifyAPI::Context.stubs(:scope).returns(ShopifyAPI::Auth::AuthScopes.new(["scope1", "scope2"]))
ShopifyAPI::Utils::SessionUtils.stubs(:current_session_id).returns(nil)

cookies.encrypted[ShopifyAPI::Auth::Oauth::SessionCookie::SESSION_COOKIE_NAME] = "cookie"
request.headers["HTTP_AUTHORIZATION"] = "Bearer token"

with_application_test_routes do
get :index, xhr: true

assert_equal "/login", response.headers["X-Shopify-API-Request-Failure-Reauthorize-Url"]
end
end

test "#activate_shopify_session when rescuing from non 401 errors, does not close session" do
with_application_test_routes do
cookies.encrypted[ShopifyAPI::Auth::Oauth::SessionCookie::SESSION_COOKIE_NAME] = "cookie"
Expand Down