forked from redhat-developer/rhdh-e2e-test-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.ts
More file actions
429 lines (378 loc) · 14.1 KB
/
Copy pathcommon.ts
File metadata and controls
429 lines (378 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import { UIhelper } from "./ui-helper.js";
import { authenticator } from "otplib";
import { test, expect } from "@playwright/test";
import type { Browser, Page, TestInfo } from "@playwright/test";
import { SETTINGS_PAGE_COMPONENTS } from "../page-objects/page-obj.js";
import * as path from "path";
import * as fs from "fs";
import { DEFAULT_USERS } from "../../deployment/keycloak/constants.js";
export class LoginHelper {
page: Page;
uiHelper: UIhelper;
constructor(page: Page) {
this.page = page;
this.uiHelper = new UIhelper(page);
}
async loginAsGuest() {
await this.page.goto("/");
await this.uiHelper.waitForLoad(240000);
// TODO - Remove it after https://issues.redhat.com/browse/RHIDP-2043. A Dynamic plugin for Guest Authentication Provider needs to be created
this.page.on("dialog", async (dialog) => {
console.log(`Dialog message: ${dialog.message()}`);
await dialog.accept();
});
await this.uiHelper.verifyHeading("Select a sign-in method");
await this.uiHelper.clickButton("Enter");
await this.page.waitForSelector("nav a", { timeout: 10_000 });
}
async signOut() {
await this.page.click(SETTINGS_PAGE_COMPONENTS.userSettingsMenu);
await this.page.click(SETTINGS_PAGE_COMPONENTS.signOut);
await this.uiHelper.verifyHeading("Select a sign-in method");
}
private async logintoGithub(userid: string) {
await this.page.goto("https://github.com/login");
await this.page.waitForSelector("#login_field");
await this.page.fill("#login_field", userid);
switch (userid) {
case process.env.VAULT_GH_USER_ID:
await this.page.fill(
"#password",
process.env.VAULT_GH_USER_PASS as string,
);
break;
case process.env.VAULT_GH_USER2_ID:
await this.page.fill(
"#password",
process.env.VAULT_GH_USER2_PASS as string,
);
break;
default:
throw new Error("Invalid User ID");
}
await this.page.click('[value="Sign in"]');
await this.page.fill("#app_totp", this.getGitHub2FAOTP(userid));
test.setTimeout(260_000);
if (
(await this.uiHelper.isTextVisible(
"The two-factor code you entered has already been used",
)) ||
(await this.uiHelper.isTextVisible(
"too many codes have been submitted",
3000,
))
) {
await this.page.waitForTimeout(60000);
await this.page.fill("#app_totp", this.getGitHub2FAOTP(userid));
}
await this.page
.getByRole("heading", { name: "Home" })
.waitFor({ timeout: 30_000 });
}
async logintoKeycloak(popup: Page, userid: string, password: string) {
await popup.waitForLoadState();
await popup.locator("#username").fill(userid);
await popup.locator("#password").fill(password);
await popup.locator("#kc-login").click();
}
async loginAsKeycloakUser(
userid: string = DEFAULT_USERS[0].username,
password: string = DEFAULT_USERS[0].password,
) {
await this.page.goto("/");
await this.uiHelper.waitForLoad(240000);
const popupPromise = this.page.waitForEvent("popup");
await this.uiHelper.clickButton("Sign In");
const popup = await popupPromise;
await this.logintoKeycloak(popup, userid, password);
await this.page.waitForSelector("nav a", { timeout: 10_000 });
}
async loginAsGithubUser(
userid: string = process.env.VAULT_GH_USER_ID as string,
) {
const sessionFileName = `authState_${userid}.json`;
// Check if a session file for this specific user already exists
if (fs.existsSync(sessionFileName)) {
// Load and reuse existing authentication state
const cookies = JSON.parse(
fs.readFileSync(sessionFileName, "utf-8"),
).cookies;
await this.page.context().addCookies(cookies);
console.log(`Reusing existing authentication state for user: ${userid}`);
await this.page.goto("/");
await this.uiHelper.waitForLoad(12000);
await this.uiHelper.clickButton("Sign In");
// Wait for either: sidebar appears (auto-login) or popup opens (needs auth)
const navPromise = this.page
.waitForSelector("nav a", { timeout: 15_000 })
.then(() => "nav" as const)
.catch(() => null);
const popupPromise = this.page
.waitForEvent("popup", { timeout: 15_000 })
.then((popup) => ({ popup }))
.catch(() => null);
const result = await Promise.race([navPromise, popupPromise]);
if (result === null) {
throw new Error(
"GitHub login failed: neither sidebar nor popup appeared after Sign In — session file may be stale",
);
}
if (typeof result === "object" && "popup" in result) {
// Popup opened — handle reauthorization
await this.handleGithubPopupReauth(result.popup);
}
} else {
// Perform login if no session file exists, then save the state
await this.logintoGithub(userid);
await this.page.goto("/");
await this.uiHelper.waitForLoad(240000);
await this.uiHelper.clickButton("Sign In");
await this.checkAndReauthorizeGithubApp();
await this.page.waitForSelector("nav a", { timeout: 10_000 });
await this.page.context().storageState({ path: sessionFileName });
console.log(`Authentication state saved for user: ${userid}`);
}
}
async checkAndReauthorizeGithubApp() {
await new Promise<void>((resolve) => {
this.page.once("popup", async (popup) => {
await this.handleGithubPopupReauth(popup);
resolve();
});
});
}
private async handleGithubPopupReauth(popup: Page) {
await popup.waitForLoadState();
// Check for popup closure for up to 10 seconds before proceeding
for (let attempts = 0; attempts < 10 && !popup.isClosed(); attempts++) {
await this.page.waitForTimeout(1000); // Using page here because if the popup closes automatically, it throws an error during the wait
}
const locator = popup.locator("button.js-oauth-authorize-btn");
if (!popup.isClosed() && (await locator.isVisible())) {
await popup.locator("body").click();
await locator.waitFor();
await locator.click();
}
}
async googleSignIn(email: string) {
await new Promise<void>((resolve) => {
this.page.once("popup", async (popup) => {
await popup.waitForLoadState();
const locator = popup
.getByRole("link", { name: email, exact: false })
.first();
await popup.waitForTimeout(3000);
await locator.waitFor({ state: "visible" });
await locator.click({ force: true });
await popup.waitForTimeout(3000);
await popup
.locator("[name=Passwd]")
.fill(process.env.GOOGLE_USER_PASS as string);
await popup.locator("[name=Passwd]").press("Enter");
await popup.waitForTimeout(3500);
await popup.locator("[name=totpPin]").fill(this.getGoogle2FAOTP());
await popup.locator("[name=totpPin]").press("Enter");
await popup
.getByRole("button", { name: /Continue|Weiter/ })
.click({ timeout: 60000 });
resolve();
});
});
}
async checkAndClickOnGHloginPopup(force = false) {
const frameLocator = this.page.getByLabel("Login Required");
try {
await frameLocator.waitFor({ state: "visible", timeout: 2000 });
await this.clickOnGHloginPopup();
} catch (error) {
if (force) throw error;
}
}
getLoginBtnSelector(): string {
return 'MuiListItem-root li.MuiListItem-root button.MuiButton-root:has(span.MuiButton-label:text("Log in"))';
}
async clickOnGHloginPopup() {
const isLoginRequiredVisible = await this.uiHelper.isTextVisible("Sign in");
if (isLoginRequiredVisible) {
await this.uiHelper.clickButton("Sign in");
await this.uiHelper.clickButton("Log in");
await this.checkAndReauthorizeGithubApp();
await this.page.waitForSelector(this.getLoginBtnSelector(), {
state: "detached",
});
} else {
console.log(
'"Log in" button is not visible. Skipping login popup actions.',
);
}
}
getGitHub2FAOTP(userid: string): string {
const secrets: { [key: string]: string | undefined } = {
[process.env.VAULT_GH_USER_ID as string]: process.env.VAULT_GH_2FA_SECRET,
[process.env.VAULT_GH_USER2_ID as string]:
process.env.VAULT_GH_USER2_2FA_SECRET,
};
const secret = secrets[userid];
if (!secret) {
throw new Error("Invalid User ID");
}
return authenticator.generate(secret);
}
getGoogle2FAOTP(): string {
const secret = process.env.GOOGLE_2FA_SECRET as string;
return authenticator.generate(secret);
}
async keycloakLogin(username: string, password: string) {
await this.page.goto("/");
await this.page.waitForSelector('p:has-text("Sign in using OIDC")');
const [popup] = await Promise.all([
this.page.waitForEvent("popup"),
this.uiHelper.clickButton("Sign In"),
]);
await popup.waitForLoadState("domcontentloaded");
// Check if popup closes automatically (already logged in)
try {
await popup.waitForEvent("close", { timeout: 5000 });
return "Already logged in";
} catch {
// Popup didn't close, proceed with login
}
try {
await popup.locator("#username").click();
await popup.locator("#username").fill(username);
await popup.locator("#password").fill(password);
await popup.locator("[name=login]").click({ timeout: 5000 });
await popup.waitForEvent("close", { timeout: 2000 });
return "Login successful";
} catch (e) {
const usernameError = popup.locator("id=input-error");
if (await usernameError.isVisible()) {
await popup.close();
return "User does not exist";
} else {
throw e;
}
}
}
private async handleGitHubPopupLogin(
popup: Page,
username: string,
password: string,
twofactor: string,
): Promise<string> {
await expect(async () => {
await popup.waitForLoadState("domcontentloaded");
expect(popup).toBeTruthy();
}).toPass({
intervals: [5_000, 10_000],
timeout: 20 * 1000,
});
// Check if popup closes automatically
try {
await popup.waitForEvent("close", { timeout: 5000 });
return "Already logged in";
} catch {
// Popup didn't close, proceed with login
}
try {
await popup.locator("#login_field").click({ timeout: 5000 });
await popup.locator("#login_field").fill(username, { timeout: 5000 });
const cookieLocator = popup.locator("#wcpConsentBannerCtrl");
if (await cookieLocator.isVisible()) {
await popup.click('button:has-text("Reject")', { timeout: 5000 });
}
await popup.locator("#password").click({ timeout: 5000 });
await popup.locator("#password").fill(password, { timeout: 5000 });
await popup
.locator("[type='submit'][value='Sign in']:not(webauthn-status *)")
.first()
.click({ timeout: 5000 });
const twofactorcode = authenticator.generate(twofactor);
await popup.locator("#app_totp").click({ timeout: 5000 });
await popup.locator("#app_totp").fill(twofactorcode, { timeout: 5000 });
await popup.waitForEvent("close", { timeout: 20000 });
return "Login successful";
} catch (e) {
const authorization = popup.locator("button.js-oauth-authorize-btn");
if (await authorization.isVisible()) {
await authorization.click();
return "Login successful";
} else {
throw e;
}
}
}
async githubLogin(username: string, password: string, twofactor: string) {
await this.page.goto("/");
await this.page.waitForSelector('p:has-text("Sign in using GitHub")');
const [popup] = await Promise.all([
this.page.waitForEvent("popup"),
this.uiHelper.clickButton("Sign In"),
]);
return this.handleGitHubPopupLogin(popup, username, password, twofactor);
}
async githubLoginFromSettingsPage(
username: string,
password: string,
twofactor: string,
) {
await this.page.goto("/settings/auth-providers");
const [popup] = await Promise.all([
this.page.waitForEvent("popup"),
this.page.getByTitle("Sign in to GitHub").click(),
this.uiHelper.clickButton("Log in"),
]);
return this.handleGitHubPopupLogin(popup, username, password, twofactor);
}
async microsoftAzureLogin(username: string, password: string) {
await this.page.goto("/");
await this.page.waitForSelector('p:has-text("Sign in using Microsoft")');
const [popup] = await Promise.all([
this.page.waitForEvent("popup"),
this.uiHelper.clickButton("Sign In"),
]);
await popup.waitForLoadState("domcontentloaded");
if (popup.url().startsWith(process.env.RHDH_BASE_URL as string)) {
// an active microsoft session is already logged in and the popup will automatically close
return "Already logged in";
} else {
try {
await popup.locator("[name=loginfmt]").click();
await popup
.locator("[name=loginfmt]")
.fill(username, { timeout: 5000 });
await popup
.locator('[type=submit]:has-text("Next")')
.click({ timeout: 5000 });
await popup.locator("[name=passwd]").click();
await popup.locator("[name=passwd]").fill(password, { timeout: 5000 });
await popup
.locator('[type=submit]:has-text("Sign in")')
.click({ timeout: 5000 });
await popup
.locator('[type=button]:has-text("No")')
.click({ timeout: 15000 });
return "Login successful";
} catch (e) {
const usernameError = popup.locator("id=usernameError");
if (await usernameError.isVisible()) {
return "User does not exist";
} else {
throw e;
}
}
}
}
}
export async function setupBrowser(browser: Browser, testInfo: TestInfo) {
const context = await browser.newContext({
recordVideo: {
dir: `test-results/${path
.parse(testInfo.file)
.name.replace(".spec", "")}/${testInfo.titlePath[1]}`,
size: { width: 1920, height: 1080 },
},
});
const page = await context.newPage();
return { page, context };
}