The personal finance app for everyone (by everyone)
Ruby
fix(yahoo): don't send cookie/crumb on the chart endpoint (fixes persistent 429 price outages) (#3795)
joaocbatista63beb87065fa
diff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rbindex abf8cd9bf1..d867943dc3 100644--- a/app/models/provider/yahoo_finance.rb+++ b/app/models/provider/yahoo_finance.rb@@ -833,19 +833,37 @@ class Provider::YahooFinance < Provider# If Yahoo returns a stale-crumb error (200 OK with Unauthorized body),# clears the crumb cache and retries once with fresh credentials.def fetch_authenticated_chart(symbol, params)- cookie, crumb = fetch_cookie_and_crumb- response = authenticated_client(cookie).get("#{base_url}/v8/finance/chart/#{symbol}") do |req|- params.each { |k, v| req.params[k] = v }- req.params["crumb"] = crumb+ # The /v8/finance/chart endpoint does NOT require cookie/crumb auth, and+ # Yahoo rate-limits AUTHENTICATED chart requests far more aggressively than+ # anonymous ones (verified live: cookie+crumb => 429, same symbol/IP with+ # no auth => 200). Use the plain client for price/chart data. Cookie+crumb+ # remains scoped to quoteSummary (fetch_security_info), which needs it.+ begin+ response = client.get("#{base_url}/v8/finance/chart/#{symbol}") do |req|+ params.each { |k, v| req.params[k] = v }+ end+ data = JSON.parse(response.body)+ needs_auth = data.dig("chart", "error", "code") == "Unauthorized"+ rescue Faraday::UnauthorizedError+ # Hard HTTP 401 (raised by client's :raise_error) -- fall through to the+ # authenticated retry below, same as a soft Unauthorized body code.+ needs_auth = trueend- data = JSON.parse(response.body)- if data.dig("chart", "error", "code") == "Unauthorized"+ # Rare fallback: if Yahoo demands auth for a specific symbol (a hard 401+ # or a 200 OK with an Unauthorized body), retry once with FRESH cookie++ # crumb. Clear any cached crumb first so a stale-but-shape-valid one+ # isn't reused.+ if needs_authclear_crumb_cachecookie, crumb = fetch_cookie_and_crumb- response = authenticated_client(cookie).get("#{base_url}/v8/finance/chart/#{symbol}") do |req|- params.each { |k, v| req.params[k] = v }- req.params["crumb"] = crumb+ begin+ response = authenticated_client(cookie).get("#{base_url}/v8/finance/chart/#{symbol}") do |req|+ params.each { |k, v| req.params[k] = v }+ req.params["crumb"] = crumb+ end+ rescue Faraday::UnauthorizedError+ raise AuthenticationError, "Yahoo Finance authentication failed after crumb refresh"enddata = JSON.parse(response.body)if data.dig("chart", "error", "code") == "Unauthorized"diff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rbindex 3693ce9e1a..a3b65395b8 100644--- a/test/models/provider/yahoo_finance_test.rb+++ b/test/models/provider/yahoo_finance_test.rb@@ -516,8 +516,6 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCasetest "search_securities falls back to a direct chart lookup when the search index has no results" doempty_search_response = mockempty_search_response.stubs(:body).returns('{"quotes":[]}')- @provider.stubs(:client).returns(mock_client = mock)- mock_client.stubs(:get).returns(empty_search_response)chart_response = mockchart_response.stubs(:body).returns({@@ -532,10 +530,11 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase} ]}}.to_json)- chart_client = mock- chart_client.expects(:get).with(regexp_matches(%r{/v8/finance/chart/VAN0111AU\.AX$})).returns(chart_response)- @provider.stubs(:fetch_cookie_and_crumb).returns([ "cookie", "crumb" ])- @provider.stubs(:authenticated_client).with("cookie").returns(chart_client)++ mock_client = mock+ mock_client.stubs(:get).with(regexp_matches(%r{/v1/finance/search})).returns(empty_search_response)+ mock_client.expects(:get).with(regexp_matches(%r{/v8/finance/chart/VAN0111AU\.AX$})).returns(chart_response)+ @provider.stubs(:client).returns(mock_client)@provider.stubs(:throttle_request)response = @provider.search_securities("VAN0111AU.AX")@@ -555,15 +554,14 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCasetest "search_securities direct chart fallback returns no results when the symbol doesn't exist" doempty_search_response = mockempty_search_response.stubs(:body).returns('{"quotes":[]}')- @provider.stubs(:client).returns(mock_client = mock)- mock_client.stubs(:get).returns(empty_search_response)not_found_response = mocknot_found_response.stubs(:body).returns({ chart: { result: nil, error: { code: "Not Found" } } }.to_json)- chart_client = mock- chart_client.stubs(:get).returns(not_found_response)- @provider.stubs(:fetch_cookie_and_crumb).returns([ "cookie", "crumb" ])- @provider.stubs(:authenticated_client).with("cookie").returns(chart_client)++ mock_client = mock+ mock_client.stubs(:get).with(regexp_matches(%r{/v1/finance/search})).returns(empty_search_response)+ mock_client.stubs(:get).with(regexp_matches(%r{/v8/finance/chart/})).returns(not_found_response)+ @provider.stubs(:client).returns(mock_client)@provider.stubs(:throttle_request)response = @provider.search_securities("NOTAREAL.XX")@@ -650,8 +648,7 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase}.to_json)chart_client = mockchart_client.expects(:get).with(regexp_matches(%r{/v8/finance/chart/CIBEST\.CL$})).twice.returns(chart_response)- @provider.stubs(:fetch_cookie_and_crumb).returns([ "cookie", "crumb" ])- @provider.stubs(:authenticated_client).with("cookie").returns(chart_client)+ @provider.stubs(:client).returns(chart_client)@provider.stubs(:throttle_request)responses = [ "CIBEST", "CIBEST.CL" ].map do |symbol|@@ -676,6 +673,50 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase# Caching Tests# ================================+ test "fetch_authenticated_chart refreshes credentials after an Unauthorized body" do+ anonymous_response = mock+ anonymous_response.stubs(:body).returns('{"chart":{"error":{"code":"Unauthorized"}}}')+ retry_response = mock+ retry_response.stubs(:body).returns('{"chart":{"result":[{}]}}')+ anonymous_client = mock+ anonymous_client.expects(:get).once.returns(anonymous_response)+ retry_request = OpenStruct.new(params: {})+ authenticated_client = mock+ authenticated_client.expects(:get).once.yields(retry_request).returns(retry_response)++ @provider.stubs(:client).returns(anonymous_client)+ @provider.expects(:clear_crumb_cache).once+ @provider.expects(:fetch_cookie_and_crumb).once.returns([ "fresh-cookie", "fresh-crumb" ])+ @provider.expects(:authenticated_client).with("fresh-cookie").returns(authenticated_client)++ result = @provider.send(:fetch_authenticated_chart, "AAPL", {})++ assert_equal [ {} ], result.dig("chart", "result")+ assert_equal "fresh-crumb", retry_request.params["crumb"]+ end++ test "fetch_authenticated_chart refreshes credentials after an HTTP 401" do+ anonymous_client = mock+ anonymous_client.expects(:get).once.raises(+ Faraday::UnauthorizedError.new("Unauthorized", { body: "Invalid Crumb" })+ )+ retry_response = mock+ retry_response.stubs(:body).returns('{"chart":{"result":[{}]}}')+ retry_request = OpenStruct.new(params: {})+ authenticated_client = mock+ authenticated_client.expects(:get).once.yields(retry_request).returns(retry_response)++ @provider.stubs(:client).returns(anonymous_client)+ @provider.expects(:clear_crumb_cache).once+ @provider.expects(:fetch_cookie_and_crumb).once.returns([ "fresh-cookie", "fresh-crumb" ])+ @provider.expects(:authenticated_client).with("fresh-cookie").returns(authenticated_client)++ result = @provider.send(:fetch_authenticated_chart, "AAPL", {})++ assert_equal [ {} ], result.dig("chart", "result")+ assert_equal "fresh-crumb", retry_request.params["crumb"]+ end+# Note: Caching tests are skipped as Rails.cache may not be properly configured in test environment# and caching functionality is not the focus of the validation fixes