cy.origin() and multiple origins in the same domain - cypress

I am trying to add login flow to my cypress tests.
I want to get it running on my machine, in the following environment:
both app and OAuth server are running in docker containers
both containers have their ports mapped to localhost:
app is available at baseUrl: 'https://localhost:8888'
OAuth Server is available at 'http://localhost:9081'
As you can see, there are 2 origins on the localhost.
If I try the simple code:
cy.visit('/mysecuredpage'); // this redirects to http://localhost:9081
cy.contains('Please log in');
cy.get('input#username').type('user1');
cy.get('input#password').type('password1');
cy.get('button#password-submit').click();
I get an error about conflicting origins:
The command was expected to run against origin `http://localhost:9081` but the application is at origin `https://localhost:8888`.
I was trying to follow SSO login custom command
cy.visit('/mysecuredpage'); // this redirects to http://localhost:9081
cy.origin('http://localhost:9081', () => {
cy.contains('Please log in');
cy.get('input#username').type('user1');
cy.get('input#password').type('password1');
cy.get('button#password-submit').click();
});
Unfortunately, this fails with an error about wrong domain:
CypressError: `cy.origin()` requires the first argument to be a different domain than top. You passed `http://localhost:9081` to the origin command, while top is at `http://localhost:9081`.
Either the intended page was not visited prior to running the cy.origin block or the cy.origin block may not be needed at all.
Am I running against some known limitation or doing sth wrong?
I am not even sure if multiple origins in the same domain is the root cause of the problem, or is it caused by some usage pattern of my app (all pages are private and redirect immediately to Oauth - there is no login button on the app side)
Cypress: 11.0.1
Browser: Chrome 107 (headless)
Node Version: v18.6.0

Related

Request to Google OAuth endpoint redirects to a blank page in Firefox

I have a React (CRA) + Node JS application already deployed locally (using the create-react-app build script), I've implemented Google OAuth signin with passportjs and cookieSession for persistence.
The login works fine but there is a strange bug when I Logout and then try to log in again with google OAuth, it just redirects me to a blank page.
This is how I make the request to my google oauth endpoint:
window.open('https://localhost:3000/auth/google', "_self")
That endpoint then is taken by my API:
app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
Doing some troubleshooting it seemed at first the culprit were the cookies because when I delete the site data before trying to login again... then the login works just fine.
However if I delete the cookies only (through the storage panel -> cookies -> delete all, in firefox) the bug still persists, it only disappears when I delete the site data entirely.
Moreover, The second time I try to login the request don't event reach my server.
What I've alredy tried:
Wrapping my login button inside an anchor tag and setting the anchor's tag href to the endpoint url.
Creating an anchor tag and assigning an href with the endpoint url and then clicking that new element programmatically.
None of this worked, the issue still persists.
Fresh firefox profile: this is even weird, the bug appears the very first time I try to login with google in a newly created profile. Again I have to first click the clear cookies and site data button for it to work.
Incognito mode: The issue persists, again the first time I login it works but the second time it redirects me to a blank page and the request is not even reaching my server.
What could be the problem here?
The issue was the service worker that cames with the creat-react-app template, however I didn't want to disable it completely as I want my app to be a PWA, so the next best thing was to disable the service-worker caching specifically for the page from which the user initiates the Google login (the page where the google button is).
For this I had to install the sw-precache package which allows you to modify the default service-worker that came with the create-react-app template (as you cannot directly modify it).
Then you have to create a config file at the root of your project and add these lines, in this case I call it sw-precache-config.js:
module.exports = {
runtimeCaching: [
{
urlPattern: /<the route to ignore>/,
handler: 'networkOnly'
}
]
};
and then in the build script from your package json:
"build": "react-scripts build && sw-precache --config=sw-precache-config.js"

Socket hang up error with Cypress (tried 5.4 and 6.0.1)

I'm trying to use cypress to test an app running on my local linux box. If I manually browse to the test URL (https://localhost:8443) it works fine. If I create a test in Cypress that simply contains nothing more than
describe('my app tests', function () {
it('does very little', function () {
cy.visit('https://localhost:8443')
})
})
Then it fails after a few seconds with:
cy.visit() failed trying to load:
https://localhost:8443/
We attempted to make an http request to this URL but the request failed without a response.
We received this error at the network level:
> Error: socket hang up
Common situations why this would fail:
- you don't have internet access
- you forgot to run / boot your web server
- your web server isn't accessible
- you have weird network configuration settings on your computer
Looking in DevTools there are no apparent requests to the test server - just 3 requests (1 document with a 304 status, and 2 xhr requests each with a 200 status) all of which apparently loading the cypress test and support files. Nothing else - no logged request to the test URL.
Can anyone offer any suggestions why I'm seeing this 'dead' test?

slash command "dispatch_failed"

I have went through creating the custom slash command configuration via slack and installed it on workspace. However when I run it I get this
/testing failed with the error "dispatch_failed"
I tried multiple workspaces but same issue. Anyone experienced this?
So after a few tests, I found out that this is just a generic message of anything that fails at slack at this point. I have first my endpoint that was unreachable. So it was returning this message. I fixed that, used ngrok for tunnel so that I could debug and that is how I found this issue.
Also, this error can occur due to the following reasons as well.
Errors in code
Unreachable backend or Invalidly configured slash command in the app
While the documentation tells you:
"use the Request URL is your base server link + "/slashcommand" after it"
This is incorrect. The request URL should be: "/slack/events"
Of course the command needs to match whats in the 'edit command' window and in the method '.command' in your app.js:
app.command('/flash-card', async ({ ack, body, client })
If you're using ngrok http <port> to test in your localhost, be aware that a new ngrok public URL is created every time you run this command. So in https://api.slack.com/apps, in your app's Features, you may have to update your Slash Command' request URL with the current ngrok URL generated for you.
You need to set the Method in the Integration Settings to GET, is default to POST
This is also the error for a 404 Not Found.
If you're developing offline with ngrok, the 404 error can be seen in the terminal.
If you're deploying with serverless, ensure that you're handling the new endpoint /slack/command. One solution is to create a separate handler, i.e. /command.js
functions:
slack:
handler: app.handler
events:
- http:
path: slack/events
method: post
command:
handler: command.handler
events:
- http:
path: slack/command
method: post
[If your code is executing and u still have this error]
In my case using Slackbolt with js I forgot to add
await ack();
in called function so Slack api throw error.

Trying to set up CAS with my Laravel project

I am using subfission/cas for my application. I have followed all installation steps. I am using windows, if that matters. More precisely, I have configured the following:
I ran the following in my terminal
composer require "subfission/cas" "dev-master"
I configured my Kernel.php accordingly, adding the following:
'cas.auth' => 'Subfission\Cas\Middleware\CASAuth',
'cas.guest' => 'Subfission\Cas\Middleware\RedirectCASAuthenticated',
I ran the following command:
php artisan vendor:publish
I also set up my cas server in my cas.php config file:
'cas_hostname' => env('CAS_HOSTNAME', 'cas.myserver.me'),
'cas_real_hosts' => env('CAS_REAL_HOSTS', 'cas.myserver.me'),
What I want is a middleware for all my routes, so I added the following route rule in my routes:
Route::middleware(['cas.auth'])->group(function ()
{
Route::get('/', function ()
{
return view('welcome');
});
});
Basically, I want to redirect everyone who is not logged in to the login page whenever I access the main page (for now, I will add more routes in the future). What happens is that the users are redirected to the login page when they are not logged in, but after the login I receive the following error:
ErrorException (E_WARNING)
DOMDocument::loadXML(): Opening and ending tag mismatch: hr line 1 and body in Entity, line: 1
No matter what view I'm redirecting the user to. I tried the default welcome page as well as an empty view, but I still get the same error.
EDIT: I have used the dev-master branch from subfission/cas for the above error and after switching to 2.1.1, I get a different error:
session_name(): Cannot change session name when headers already sent
EDIT 2: I did some more digging and I enabled internal errors in my cas client class with:
libxml_use_internal_errors(true);
And now I get the following:
Authentication failure: SA not validated Reason: bad response from the CAS server
And the cas response is:
The thing is that I use the same cas server for another 2 projects and it works well for those (but those aren't laravel projects.
I know it's been a while, but for anyone else having issues like this, the issue is the protocol selected for which your web service communicates with your CAS(Central Authentication Service) provider. There are two main protocols used for SSO/CAS in this package:
SAML(Security Assertion Markup Language) version 1.1 & 2
CAS Protocol v3.0
[Confusingly enough, CAS protocol shares the same namespace as the service.]
The idea is to match the protocol and version with your identity provider. It sounds like your provider is using CASv3.0, which is why disabling SAML worked.
Also, if you enable debug mode, you will see further error details in your log file to help your troubleshoot.
Best of luck!
I managed to solve the issue by disabling the SAML in the cas configure file:
'cas_enable_saml' => env('CAS_ENABLE_SAML', true),
change to
'cas_enable_saml' => env('CAS_ENABLE_SAML', false),

Cache internal routes with sw-precache

I'm creating a SPA using vanilla JavaScript and currently setting up sw-precache to handle the caching of resources. The service worker is generated as part of a gulp build and installed successfully. When I navigate to the root url (http://127.0.0.1:8080/) whilst offline the app shell displays, illustrating that resources are indeed cached.
I'm now attempting to get the SW to handle internal routing without failing. When navigating to http://127.0.0.1:8080/dashboard_index whilst offline I get the message 'Site can't be reached'.
The app handles this routing on the client side via a series of event listeners on the users actions or, in the case of using the back button, the url. When accessing one of these urls, no calls to the server should be made. As such, the service worker should allow these links to 'fall through' to the client side code.
I've tried a few things and expected this Q/A to solve the problem. I've included the current state of the generate-service-worker gulp task, and with this setup I'd expect to be able to access /dashboard_index offine. Once this is working I can adapt the solution to cover other routes.
Any help much appreciated.
gulp.task('generate-service-worker', function(callback) {
var rootDir = './public';
swPrecache.write(path.join(rootDir, 'sw.js'), {
staticFileGlobs: [rootDir + '/*/*.{js,html,png,jpg,gif,svg}',
rootDir + '/*.{js,html,png,jpg,gif,json}'],
stripPrefix: rootDir,
navigateFallback: '/',
navigateFallbackWhitelist: [/\/dashboard_index/],
runtimeCaching: [{
urlPattern: /^http:\/\/127\.0\.0\.1\:8080/getAllData, // Req returns all data the app needs
handler: 'networkFirst'
}],
verbose: true
}, callback);
});
update
The code to the application can be found here.
Removing the option navigateFallbackWhitelist does not chage the result.
Navigating to /dashboard_index whilst offline prints the following to the console.
GET http://127.0.0.1:8080/dashboard_index net::ERR_CONNECTION_REFUSED
sw.js:1 An unknown error occurred when fetching the script.
http://127.0.0.1:8080/sw.js Failed to load resource: net::ERR_CONNECTION_REFUSED
The same An unknown error occurred when fetching the script. is also duplicated in the 'application > service workers' tab of chrome debug tools.
It's also noted that the runtimeCaching option is not caching the json response returned from that route.
For the record, in case anyone else runs into this, I believe this answer from the comments should address the issue:
Can you switch from navigateFallback: '/' to navigateFallback:
'/index.html'? You don't have an entry for '/' in your list of
precached resources, but you do have an entry for '/index.html'.
There's some logic in place to automatically treat '/' and
'/index.html' as being equivalent, but that doesn't apply to what
navigateFallback is doing...

Resources