Rails Integration Testing - How to Simulate bad CSRF token and Expired Session - session

I just changed exception handling code in my application_controller.rb to correctly capture ActionController::InvalidAuthenticityToken.
I was previously doing a rescue_from Exception that was defined after the recuse_from ActionController::InvalidAuthenticityToken. This was taking priority and my intended rescue_from code was not being executed.
I'd like to write an integration test to verify this behavior. How can I create an object that will allow me to send a bad CSRF token to a post request to simulate this behavior?
I'd also like to have an object that will allow me to simulate an expired session to make a get request. How would I implement these integration tests?

A bad CSRF token can be simulated with:
with_forgery_protection do
post user_session_path, {:authenticity_token => 'foo'}
assert redirected_to_new_user_session_path
end
An expired session can be simulated using the TimeCop gem:
Timecop.travel 2.days.from.now do
get some_authorized_path
assert_redirect_to new_user_session_path
end

Related

How to mock OAuth2 authentication flow in RSpec?

I am quite new to using RSpec but would like to start testing the (thus far, quite basic) API that I have created, but I am absolutely stumped as to how I can go about mocking the authorization flow of OAuth2, using the oauth and quickbooks-ruby gems. I have researched into this quite extensively today, and am coming up empty handed on any results. Any resources or suggestions would be hugely appreciated.
I am unsure how to even begin approaching actually writing tests, so I don't have any RSpec stuff written yet, but below is shown the two endpoints that I would like to somehow mock, to give an idea of my aim.
get '/callback' do
redirect_uri = "http://localhost:4567/callback"
resp = qbo_client.auth_code.get_token(params[:code], redirect_uri: redirect_uri)
redirect to("/")
end
get '/auth' do
redirect_uri = 'http://localhost:4567/callback'
code_url = qbo_client.auth_code.authorize_url(redirect_uri: redirect_uri, response_type: "code", state: SecureRandom.hex(12), scope: "com.intuit.quickbooks.accounting")
redirect code_url
end
Basically, for a user to authenticate, they hit the /auth endpoint which redirects to Quickbooks for OAuth authorization, this sends the authorization code to the callback endpoint which is then traded for an access token.
I am unsure how to simulate obtaining and exchanging the authorization code, primarily. My best guess at this point is to use a fixture representing the auth-code, mock the exchange with webmock or some comparable tool, but I am very unsure if this is the right approach.
To test the OAuth2 flow in your API, you will need to simulate the responses from the authorization server and ensure that your code handles them correctly. One way to do this is by using a library like VCR or WebMock to record and replay HTTP interactions between your API and the authorization server.
Here is an example of how you could use VCR to record and replay requests to the Quickbooks API:
Install VCR gem() and configure VCR in your spec_helper.rb file:
require 'vcr'
VCR.configure do |config|
config.cassette_library_dir = 'spec/vcr_cassettes'
config.hook_into :webmock
end
RSpec.configure do |config|
config.around(:each) do |example|
VCR.use_cassette("#{example.full_description.parameterize.underscore}") do
example.run
end
end
end
Use the VCR.use_cassette block to wrap your API requests in your test:
describe 'GET /auth' do
it 'redirects to Quickbooks for OAuth authorization' do
VCR.use_cassette('quickbooks_oauth_authorize') do
get '/auth'
expect(last_response).to be_redirect
end
end
end
describe 'GET /callback' do
it 'trades the authorization code for an access token' do
VCR.use_cassette('quickbooks_oauth_token') do
get '/callback', code: '123456'
expect(last_response).to be_redirect
end
end
end
When you run your tests, VCR will record the HTTP interactions and save them to a YAML file in the spec/vcr_cassettes directory. On subsequent test runs, VCR will replay the interactions from the cassette file instead of making real HTTP requests to the authorization server. This allows you to test the OAuth2 flow in a predictable and repeatable way.
In the example above, I used quickbooks_oauth_authorize and quickbooks_oauth_token as the names of the cassette files, but you can use any name that makes sense for your test. You can also pass additional options to the VCR.use_cassette block to customize how VCR records and replays the interactions, such as record: :new_episodes to append new interactions to an existing cassette file.
I hope this helps you get started with testing the OAuth2 flow in your API using RSpec and VCR. Good luck!

Why route throws 401 when Cypress test clicks on link but it is OK when tested manually?

I'm aware this sounds like a back-end issue at first but I suspect Cypress causing this route to throw 401 for some reason.
When I test logout route manually it gives me 200 status code back and UI changes accordingly.
However when Cypress tests the logout route back-end returns 401 and rest of the test fail as well because other tests depend on logout route returning 200.
Backend isn't giving me any error outputs besides status code 401 on that route.
I'm using token authentication. Tokens are stored in browser's local storage but that
should have no effect on how Cypress tests routes.
If you need any info ask away.
Any suggestions ?

I am getting token error which is not matching with session in the request

I am getting below error in jmeter performance testing
ERROR:
The token in the request does not match the one in the session!
Scenarios:
user logs into the appln
click on the modify user from the menu
search for the user
select the user
adding roles to the user
6.click submit
7.click on return to search button.
8.click on logout.
I am getting the csrf token in the post method and i captured the csrf token in 2 samples before in the GET method.I added regular expression in GET method and i used that regular expression variable in the Post method token.
Please let me know how to fix the token error.
Thanks,
It's hard to provide a comprehensive response without seeing network dump of requests from the real browser and from JMeter, most probably you need to extract the CSRF token from every response, not "2 samples before", try moving your Regular Expression Extractor to the same level as HTTP Request samplers - this way it will be applied to all of them and will extract the "fresh" CSRF token from each response. See JMeter Scoping Rules - The Ultimate Guide article for more information
As per Cross-Site Request Forgery Prevention Cheat Sheet
The site then requires that every transaction request include this pseudorandom value as a hidden form value (or other request parameter/header)`
The following guidance will demonstrate how to create overrides in JavaScript libraries to have CSRF tokens included automatically with every AJAX request for the state changing methods mentioned above.
CSRF tokens should be generated on the server-side. They can be generated once per user session or for each request.

403 error response from IIS on almost alternate request while load testing api

I have a web api which is deployed on IIS.
Api's are going through load test using load runner and almost on all alternative api call, getting 403 error response code, struggling to identify the issue, call is not going to the API, its returned back from IIS
I am doing bearer token authorization, somehow token which were incoming with each request were not valid, that is why the issue was occurring, to overcome this we have increased the lifetime of token to 1 hour and request load test team to generate the token once and send that token only with each request so that we can now see the proper execution time for each end point.
403 error indicates that access to the requested URL by the client is Forbidden for some reason. you need to provide detailed error message snapshot and what is the sub status code. and check that you assign this permission to the site folder:1) IIS_IUSRS,2)NETWORK SERVICE,3)IUSR

Why does Mechanize raise "undefined method 'any?'" when it sees bad OAuth credentials?

I'm testing some Ruby code that uses Mechanize under the covers. I found that when I pass a bad OAuth token in a request, Mechanize throws an unexpected exception.
I make my call with the bad token, and the call raises the following exception:
#<NoMethodError: undefined method `any?' for nil:NilClass>
I've got some additional analysis that I'll post as an answer, but if anyone has additional insight it would be appreciated.
I tried putting this question on the mechanize-users mailing list, but the moderator didn't post it.
If you look here you can see than Mechanize::HTTP::WWWAuthenticateParser#parse can return nil under certain conditions (line 83 as of this post) I'm not sure why this might be useful but there's your answer.
The initial response contains a WWW-AUTHENTICATE header with the error information:
response-header: www-authenticate => Bearer realm=api.att.com,error=invalid_token, error_description=the token is not valid
From my reading of the OAuth spec this is correct usage. However, tracing through the Mechanize code, I see that Mechanize assumes the WWW-AUTHENTICATE header will contain one or more challenges, describing how to retry the request with authentication. I specifically find myself at agent.rb:702 in #response_authenticate, where it checks for credentials with:
#auth_store.credentials?
And that method in turn calls #any? on a nil object, since it didn't manage to parse any challenges out of the header:
def credentials? uri, challenges
challenges.any? do |challenge|
credentials_for uri, challenge.realm_name
end
end

Resources