diff --git a/engines/dfc_provider/app/services/dfc_request.rb b/engines/dfc_provider/app/services/dfc_request.rb index 949ec23bad..a24b5d95f3 100644 --- a/engines/dfc_provider/app/services/dfc_request.rb +++ b/engines/dfc_provider/app/services/dfc_request.rb @@ -14,9 +14,12 @@ class DfcRequest end def call(url, data = nil) - response = request(url, data) + begin + response = request(url, data) + rescue Faraday::UnauthorizedError, Faraday::ForbiddenError + raise unless token_stale? - if response.status >= 400 && token_stale? + # If access was denied and our token is stale then refresh and retry: refresh_access_token! response = request(url, data) end @@ -47,7 +50,10 @@ class DfcRequest 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{@user.oidc_account.token}", } - ) + ) do |f| + # Configure Faraday to raise errors on status 4xx and 5xx responses. + f.response :raise_error + end end def only_public_connections(&) diff --git a/engines/dfc_provider/spec/services/dfc_request_spec.rb b/engines/dfc_provider/spec/services/dfc_request_spec.rb index 0de024b670..0e6fbfb8d3 100644 --- a/engines/dfc_provider/spec/services/dfc_request_spec.rb +++ b/engines/dfc_provider/spec/services/dfc_request_spec.rb @@ -40,11 +40,13 @@ RSpec.describe DfcRequest do expect { api.call("http://example.net/api") - }.to change { - account.token - }.and change { - account.refresh_token } + .to raise_error(Faraday::UnauthorizedError) + .and change { + account.token + }.and change { + account.refresh_token + } end it "doesn't try to refresh the token when it's still fresh" do @@ -53,7 +55,8 @@ RSpec.describe DfcRequest do user.oidc_account.updated_at = 1.minute.ago - expect(api.call("http://example.net/api")).to eq "" + expect { api.call("http://example.net/api") } + .to raise_error(Faraday::UnauthorizedError) # Trying to reach the OIDC server via network request to refresh the token # would raise errors because we didn't setup Webmock or VCR.