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

Can't reach to redirected page by the cy.origin() or by 3rd party authentication request when using Chrome browser #23814

Closed
idanElitzur opened this issue Sep 13, 2022 · 13 comments · Fixed by #23885
Assignees

Comments

@idanElitzur
Copy link

idanElitzur commented Sep 13, 2022

Current behavior

I can't reach the elements in the redirected page of google accounts.
I've already tried by cy.origin() and by the auth API request.
but both of them are not solving this use case.

Please your help soon, I really stuck in this problem and tried all the related posts I;ve found by the net and nothing succeed :/

Desired behavior

No response

Test code to reproduce

My custom login command:

export const login = (user: string) => {
  cy.session([user], () => {
    cy.visit('/');
    cy.fixture('testUsers').then((user) => {
      cy.get(loc.login.emailField).should('be.visible').type(user.user.email);
      cy.get(loc.login.emailField)
        .should('be.visible')
        .and('have.attr', 'value', user.user.email);
      cy.get(loc.login.submitEmail).should('be.enabled').click();
      cy.get(loc.sideNavBar.buyersPipeline).should('be.visible');
      cy.window().then((win) => {
        win.localStorage.removeItem('BACKOFFICE_TOKEN');
        win.localStorage.removeItem('BACKOFFICE_REFRESH_TOKEN');
      });
    });
  });
  cy.visit('/');
};

The authentication API request:

Cypress.Commands.add('loginByGoogleApi', () => {
	cy.log('Logging in to Google')
	cy.request({
		method: 'POST',
		url: 'https://www.googleapis.com/oauth2/v4/token',
		body: {
			grant_type: 'refresh_token',
			client_id: Cypress.env('googleClientId'),
			client_secret: Cypress.env('googleClientSecret'),
			refresh_token: Cypress.env('googleRefreshToken'),
		},
	}).then(({ body }) => {
		const { access_token, id_token } = body

		cy.request({
			method: 'GET',
			url: 'https://www.googleapis.com/oauth2/v3/userinfo',
			headers: { Authorization: `Bearer ${access_token}` },
		}).then(({ body }) => {
			const userItem = {
				token: id_token,
				user: {
					googleId: body.sub,
					email: body.email,
					givenName: body.given_name,
					familyName: body.family_name,
					imageUrl: body.picture,
				},
			}
			cy.log(JSON.stringify(userItem));
			window.localStorage.setItem('googleCypress', JSON.stringify(userItem))
			cy.visit('/')
		})
	})
})

The test file with both of the ways :

    it.only('Send email to a user by google account connect ' , () => {
      cy.loginByGoogleApi();
      cy.get(loc.sideNavBar.buyersPipeline).should('be.visible').click();
      cy.get(loc.pipelineBuyer.nameColumn)
        .eq(4)
        .should('be.visible')
        .click({force: true});
      cy.get(loc.buyerDetails.basicCard).should('be.visible');
      cy.get(loc.buyerDetails.timelineSendEmailIcon)
        .should('be.visible')
        .click();
        cy.get('div[role="dialog"]').find('button.MuiButton-root').should('be.visible').click();
        cy.origin('https://accounts.google.com', () => {
                   cy.visit('https://accounts.google.com/o/oauth2/v2/auth');
                   cy.get('input[name="identifier"]').should('be.visible');
        })
        cy.visit('/')
        })
    });
Cypress conf:
	e2e: {
		chromeWebSecurity: false,
		experimentalSourceRewriting: false,
		numTestsKeptInMemory: 1,
		defaultCommandTimeout: 30000,
		requestTimeout: 30000,
		responseTimeout: 30000,
		taskTimeout: 30000,
		pageLoadTimeout: 30000,
		screenshotOnRunFailure: true,
		video: false,
		viewportHeight: 1080,
		viewportWidth: 1920,
		waitForAnimations: true,
		}
		
		-----
		
	on('before:browser:launch', (browser, launchOptions) => {
		if (browser.name === 'chrome') {
			launchOptions.args.push(
				'--disable-gpu',
				'--no-sandbox',
				'--start-maximized',
				'--enable-automation',
				'--safebrowsing-disable-auto-update',
					'--disable-dev-shm-usage',
				'--window-size=1920,1080'
			)
			return launchOptions;
		}
	});
e2e file:
   Cypress.on('window:before:load', function (window) {
	const original = window.EventTarget.prototype.addEventListener

	window.EventTarget.prototype.addEventListener = function () {
		if (arguments && arguments[0] === 'beforeunload') {
			return
		}
		return original.apply(this, arguments)
	}

	Object.defineProperty(window, 'onbeforeunload', {
		get: function () { },
		set: function () { }
	})

Actually the error is about the page load time, even I've increased it to 90sec and it seems like he doesn't do anything, just reached to origin timeout and then the page timeout.

I really tried everything and posted few times here, please your assistance.
Thanks!

Chrome driver v105

Cypress Version

10.7.0

Node version

v14.19.1

Operating System

macOs 12

Debug Logs

`
cypress:server:remote-states getting remote state: { auth: undefined, origin: 'https://google.com', strategy: 'http', fileServer: null, domainName: 'google.com', props: { port: '443', tld: 'com', domain: 'google' } } for: https://google.com +0ms
  cypress:network:cors Parsed URL { port: '443', tld: 'com', domain: 'appdomain' } +0ms
  cypress:network:cors Parsed URL { port: '443', tld: 'com', domain: 'appdomain' } +0ms
  cypress:network:cors Parsed URL { port: '443', tld: 'com', domain: 'appdomain' } +0ms
  cypress:server:remote-states getting remote state: { auth: undefined, origin: 'https://google.com', strategy: 'http', fileServer: null, domainName: 'google.com', props: { port: '443', tld: 'com', domain: 'google' } } for: https://google.com +0ms
POST /nyc/backoffice-api 200 1753.644 ms - -
  cypress:network:cors Parsed URL { port: '443', tld: 'com', domain: 'google' } +175ms
POST /nyc/backoffice-api - - ms - -
  cypress:server:request aborting { requestId: 'request19311' } +238ms
  cypress:server:util:socket_allowed allowed socket closed, removing { localPort: 60383 } +731ms
GET /o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fmail.google.com&include_granted_scopes=true&state=%7B%22redirectUri%22%3A%22https%3A%2F%2Fbackoffice.appdomain.com%2Fapp%2Fpipeline%2F9cc6ea5c-56743-431e-8994-b96b5343424ac%3Ftab%3Doverview%22%2C%22clientToken%22%3A%22wuu236seupt3g2nrpa6dsl7rlrnshhlbxq3981z1jodbzcdh8n3ss8czcovpdhdw6%22%7D&prompt=consent&response_type=code&client_id=843969890362-aehhht36f7a01d38bmsvvpjrh915i86v.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fng.appdomain.com%2FusersManagerSrvGoogleLogin 200 716.465 ms - -
  cypress:server:browsers:chrome continueRequest: { requestId: 'interception-job-1647.0' } +770ms

After close cypress is crashed with the error:

Error: write EPIPE
    at afterWriteDispatched (node:internal/stream_base_commons:160:15)
    at writeGeneric (node:internal/stream_base_commons:151:3)
    at Socket._writeGeneric (node:net:795:11)
    at Socket._write (node:net:807:8)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Socket.Writable.write (node:internal/streams/writable:334:10)
    at Function.log (/Users/idanelitzur/Library/Caches/Cypress/10.7.0/Cypress.app/Contents/Resources/app/node_modules/debug/src/node.js:194:24)
    at debug (/Users/idanelitzur/Library/Caches/Cypress/10.7.0/Cypress.app/Contents/Resources/app/node_modules/debug/src/common.js:113:10)
    at parseUrlIntoDomainTldPort (/Users/idanelitzur/Library/Caches/Cypress/10.7.0/Cypress.app/Contents/Resources/app/packages/network/lib/cors.js:50:5)
    at getSuperDomain (/Users/idanelitzur/Library/Caches/Cypress/10.7.0/Cypress.app/Contents/Resources/app/packages/network/lib/cors.js:13:20)
    at Object.getOriginPolicy (/Users/idanelitzur/Library/Caches/Cypress/10.7.0/Cypress.app/Contents/Resources/app/packages/network/lib/cors.js:93:54)
    at RemoteStates.get (/Users/idanelitzur/Library/Caches/Cypress/10.7.0/Cypress.app/Contents/Resources/app/packages/server/lib/remote_states.js:51:60)
    at Object.MaybeSetBasicAuthHeaders (/Users/idanelitzur/Library/Caches/Cypress/10.7.0/Cypress.app/Contents/Resources/app/packages/proxy/lib/http/request-middleware.js:130:43)

Other

JS error from console that always return when using cy.origin() even i tried to solve this out by some configuration in the e2e.ts file:

error?authError=Cg9pbnZhbGlkX3JlcXVlc3QSLFJlcXVpcmVkIHBhcmFtZXRlciBpcyBtaXNzaW5nOiByZXNwb25zZV90eXBlGjdodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pZGVudGl0eS9wcm90b2NvbHMvb2F1dGgyIJAD:1 Uncaught TypeError: Cannot read properties of undefined (reading 'removeAllListeners')
    at ./injection/cross-origin.js (error?authError=Cg9pbnZhbGlkX3JlcXVlc3QSLFJlcXVpcmVkIHBhcmFtZXRlciBpcyBtaXNzaW5nOiByZXNwb25zZV90eXBlGjdodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pZGVudGl0eS9wcm90b2NvbHMvb2F1dGgyIJAD:1:2344)
    at r (error?authError=Cg9pbnZhbGlkX3JlcXVlc3QSLFJlcXVpcmVkIHBhcmFtZXRlciBpcyBtaXNzaW5nOiByZXNwb25zZV90eXBlGjdodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pZGVudGl0eS9wcm90b2NvbHMvb2F1dGgyIJAD:1:222)
    at 0 (error?authError=Cg9pbnZhbGlkX3JlcXVlc3QSLFJlcXVpcmVkIHBhcmFtZXRlciBpcyBtaXNzaW5nOiByZXNwb25zZV90eXBlGjdodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pZGVudGl0eS9wcm90b2NvbHMvb2F1dGgyIJAD:1:2570)
    at r (error?authError=Cg9pbnZhbGlkX3JlcXVlc3QSLFJlcXVpcmVkIHBhcmFtZXRlciBpcyBtaXNzaW5nOiByZXNwb25zZV90eXBlGjdodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pZGVudGl0eS9wcm90b2NvbHMvb2F1dGgyIJAD:1:222)
    at error?authError=Cg9pbnZhbGlkX3JlcXVlc3QSLFJlcXVpcmVkIHBhcmFtZXRlciBpcyBtaXNzaW5nOiByZXNwb25zZV90eXBlGjdodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pZGVudGl0eS9wcm90b2NvbHMvb2F1dGgyIJAD:1:1014
    at error?authError=Cg9pbnZhbGlkX3JlcXVlc3QSLFJlcXVpcmVkIHBhcmFtZXRlciBpcyBtaXNzaW5nOiByZXNwb25zZV90eXBlGjdodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pZGVudGl0eS9wcm90b2NvbHMvb2F1dGgyIJAD:1:1023

Screen Shot 2022-09-13 at 20 25 40

Screen Shot 2022-09-13 at 20 34 54

@idanElitzur
Copy link
Author

Actually this is happen only by Chrome browser (latest).
When i using Electron instead it cross the cy.origin() and not stuck under 'loading pages but it doesn't pass the session cookies inside it and can't complete the flow :/

any solutions for cookies handling inside cy.origin() after page redirecting?

@idanElitzur idanElitzur changed the title Can't reach to redirected page by the cy.origin() or by 3rd party authentication request Can't reach to redirected page by the cy.origin() or by 3rd party authentication request when using Chrome broser Sep 14, 2022
@idanElitzur idanElitzur changed the title Can't reach to redirected page by the cy.origin() or by 3rd party authentication request when using Chrome broser Can't reach to redirected page by the cy.origin() or by 3rd party authentication request when using Chrome browser Sep 14, 2022
@chrisbreiding
Copy link
Contributor

Sorry you're encountering this problem. Thanks for creating an issue and for the thorough reproduction information. It's very helpful.

There are currently some known issues with logging in through Google in the Chrome browser that we're actively looking into. Hopefully we'll have a solution in the near future.

@idanElitzur
Copy link
Author

Thanks a lot, This issue is really blocking my project in these days.
Do you have any solution how to deal with session cookies inside origin() by Electron?
I would like to it as a "plaster" until the problem with chrome broswer will solved out.
@chrisbreiding

Thanks

@AtofStryker
Copy link
Contributor

Hey @idanElitzur. I can at least provide an update with the issues you are seeing with cy.origin for https://accounts.google.com. I posted an update here. A solution is hopefully coming soon!

@idanElitzur
Copy link
Author

idanElitzur commented Sep 14, 2022

Thanks, but you don't have any kind of temporary solution for the use case of cross-origin?
Any hack to cross this redirection by some API?
I've tried to use your google authentication login best practice guide lines and it doesn't effect about this use case, I saw it logged in ok by the API but there is no any new cookies in the session and the app didn't know that I've already logged in by google auth request and the dialog to connect by google accounts still pops up.

@AtofStryker

@AtofStryker
Copy link
Contributor

My guess is that there aren't new cookies set because the programmatic request doesn't set any cookies unless they are third party because it doesn't have the ability to do so as it is a cross-site request. It looks like the cy.request method is more of a bearer token approach and likely wouldnt work for something that is expecting cookies set for some type of oauth2 flow.

For the case of cy.origin, if Electron does work for you in the meantime, I would recommend using that if you application is dependent on google oauth2 flow and trying the experimentalModifyObstructiveThirdPartyCode flag. However in the current state it might result in recaptchas and possible missing cookies from document.cookie. API approach is likely the most stable until we are able to get some of our cookie fixes out in #23551 and #23531.

@idanElitzur
Copy link
Author

idanElitzur commented Sep 14, 2022

OK thanks, I'll try this solution.
Just to be clearly, Should I do the following steps?

  • add the conf flags of experimentalModifyObstructiveThirdPartyCode and set it true.
  • Add the login by google API login according to your best practice guide as below:
export const login = (user: string) => {
  cy.session([user], () => {
    cy.visit('/');
    cy.loginByGoogleApi();
    cy.fixture('testUsers').then((user) => {
      cy.get(loc.login.emailField).should('be.visible').type(user.user.email);
      //wait for typed value will be complete
      cy.get(loc.login.emailField)
        .should('be.visible')
        .and('have.attr', 'value', user.user.email);
      cy.get(loc.login.submitEmail).should('be.enabled').click();
      //wait for some element in the landing page will be visible
      cy.get(loc.sideNavBar.buyersPipeline).should('be.visible');
      // Remove session data we don't want to cache
      cy.window().then((win) => {
        win.localStorage.setItem('cypress.item','BACKOFFICE_TOKEN');
        win.sessionStorage.setItem('cypress.item','BACKOFFICE_TOKEN');
        win.localStorage.setItem('cypress.item', 'BACKOFFICE_REFRESH_TOKEN');
        win.sessionStorage.setItem('cypress.item', 'BACKOFFICE_REFRESH_TOKEN');
      });
    });
    cy.setCookie('cypress.item', 'BACKOFFICE_TOKEN').then((print: any) => {
      cy.log(JSON.stringify(print));
    })
  });
  cy.visit('/');
};
  • then call this login function by the test case before the redirect it happens:
    it.only('Send email to a user - is shown in the activity', () => {
        cy.loginByGoogleApi();
        cy.get(loc.sideNavBar.buyersPipeline).should('be.visible').click();
      cy.get(loc.pipelineBuyer.nameColumn)
        .eq(4)
        .should('be.visible')
        .click({force: true});
      cy.get(loc.buyerDetails.basicCard).should('be.visible');
      cy.get(loc.buyerDetails.timelineSendEmailIcon)
        .should('be.visible')
        .click();
        cy.get('div[role="dialog"]').find('button.MuiButton-root').should('be.visible').click();
        cy.get('input[name="identifier"]').should('be.visible').type('[email protected]');
        cy.get('button#identifierNext').should('be.enabled').click();
    });

and is it should work ok?
@AtofStryker
 Because it's not :/
 probably I missing something here..

@idanElitzur
Copy link
Author

Hey @chrisbreiding
Is this fixed already as part of v10.9.0?

@chrisbreiding
Copy link
Contributor

No, I don't believe so. The work in #23872 and #23643 may address this issue and will hopefully be out in the next release, though I can't promise anything at this time.

@AtofStryker
Copy link
Contributor

This should be fixed by #23885

@AtofStryker
Copy link
Contributor

related to #24085

@cypress-bot
Copy link
Contributor

cypress-bot bot commented Oct 4, 2022

The code for this is done in cypress-io/cypress#23885, but has yet to be released.
We'll update this issue and reference the changelog when it's released.

@cypress-bot
Copy link
Contributor

cypress-bot bot commented Oct 11, 2022

Released in 10.10.0.

This comment thread has been locked. If you are still experiencing this issue after upgrading to
Cypress v10.10.0, please open a new issue.

@cypress-bot cypress-bot bot locked as resolved and limited conversation to collaborators Oct 11, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants