-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathrbac-po.ts
More file actions
559 lines (495 loc) · 18.6 KB
/
rbac-po.ts
File metadata and controls
559 lines (495 loc) · 18.6 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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import { expect, Locator, Page } from "@playwright/test";
import { PageObject, PagesUrl } from "./page";
import {
DELETE_ROLE_COMPONENTS,
SEARCH_OBJECTS_COMPONENTS,
ROLES_PAGE_COMPONENTS,
} from "./page-obj";
import { type RoleBasedPolicy } from "@backstage-community/plugin-rbac-common";
import { RhdhAuthApiHack } from "../api/rhdh-auth-api-hack";
import RhdhRbacApi from "../api/rbac-api";
type PermissionPolicyType = "anyOf" | "not";
export class RbacPo extends PageObject {
private article: Locator;
private updateMemberButton: Locator;
// roles
private roleName: Locator;
private roleDescription: Locator;
private roleOwner: Locator;
private usersAndGroupsField: Locator;
private addPermissionPolicy: Locator;
private configureAccess: Locator;
private notButton: Locator;
private rulesSideBar: Locator;
private hasSpecButton: Locator;
private hasAnnotationButton: Locator;
private key: Locator;
private annotation: Locator;
private saveConditions: Locator;
private anyOfButton: Locator;
private isEntityKindButton: Locator;
private isOwnerButton: Locator;
private addRuleButton: Locator = this.page.getByRole("button", {
name: "Add rule",
});
private addNestedConditionButton: Locator = this.page.getByRole("button", {
name: "Add Nested Condition",
});
private hasLabel: Locator;
private label: Locator;
static rbacTestUsers = {
guest: "Guest User",
tara: "Tara MacGovern",
backstage: "Backstage",
rhdhqe: "rhdh-qe",
rhdhqe6: "rhdh-qe-6",
};
public selectPluginsCombobox: Locator = this.page.getByRole("combobox", {
name: "Select plugins",
});
private stringForRegexUsersAndGroups = (
numUsers: number,
numGroups: number,
): string => {
const usersText =
numUsers === 0 ? "" : `${numUsers} ${numUsers === 1 ? "user" : "users"}`;
const groupsText =
numGroups === 0
? ""
: `${numGroups} ${numGroups === 1 ? "group" : "groups"}`;
return `(${groupsText}${numGroups === 0 ? "" : ", "}${usersText}|${usersText}${numUsers === 0 ? "" : ", "}${groupsText})`;
};
public regexpShortUsersAndGroups = (
numUsers: number,
numGroups: number,
): RegExp => {
return new RegExp(this.stringForRegexUsersAndGroups(numUsers, numGroups));
};
public regexpLongUsersAndGroups = (
numUsers: number,
numGroups: number,
): RegExp => {
return new RegExp(
`Users and groups \\(${this.stringForRegexUsersAndGroups(numUsers, numGroups)}\\)`,
);
};
selectMember(label: string): string {
return `span[data-testid="${label}"]`;
}
public selectPermissionPolicyPlugin(row: number): string {
return `input[name="permissionPoliciesRows[${row}].plugin"]`;
}
selectPermissionPolicyPermission(row: number): string {
return `input[name="permissionPoliciesRows[${row}].permission"]`;
}
private selectPolicy(
row: number,
policy: number,
policyName = "Delete",
): string {
return `input[name="permissionPoliciesRows[${row}].policies[${policy}].policy-${policyName}"]`;
}
constructor(page: Page, url: PagesUrl = PagesUrl.RBAC) {
super(page, url);
this.article = this.page.getByRole("article");
this.updateMemberButton = this.page
.getByTestId("update-members")
.getByLabel("Update");
this.roleName = this.page.locator('input[name="name"]');
this.roleDescription = this.page.locator('textarea[name="description"]');
this.roleOwner = this.page.locator('textarea[name="owner"]');
this.usersAndGroupsField = this.page.locator(
'input[name="add-users-and-groups"]',
);
this.addPermissionPolicy = this.page.locator(
'button[name="add-permission-policy"]',
);
this.configureAccess = this.page.getByLabel("configure-access");
this.notButton = this.page.getByRole("button", { name: "Not" });
this.rulesSideBar = this.page.getByTestId("rules-sidebar");
this.hasSpecButton = this.page.getByText("HAS_SPEC");
this.hasAnnotationButton = this.page.getByText("HAS_ANNOTATION");
this.key = this.page.getByLabel("key *");
this.annotation = this.page.getByLabel("annotation *");
this.saveConditions = this.page.getByTestId("save-conditions");
this.anyOfButton = this.page.getByRole("button", { name: "AnyOf" });
this.isEntityKindButton = this.page.getByText("IS_ENTITY_KIND");
this.isOwnerButton = this.page.getByText("IS_OWNER");
this.hasLabel = this.page.getByText("HAS_LABEL");
this.label = this.page.getByLabel("label *");
}
public async clickAddPermissionPolicy() {
await this.addPermissionPolicy.click();
}
private async verifyGeneralRbacViewHeading() {
await this.uiHelper.verifyHeading(/All roles \(\d+\)/);
}
private async verifyUserRoleViewHeading(role: string) {
await this.uiHelper.verifyHeading(role);
}
private async verifyRoleIsListed(role: string) {
await this.uiHelper.verifyLink(role);
}
private async clickOnRoleLink(role: string) {
await this.uiHelper.clickLink(role);
}
private async switchToOverView() {
await this.uiHelper.clickTab("Overview");
}
private async verifyOverviewHeading(groups: number) {
await this.uiHelper.verifyHeading(`${groups} group`);
}
private async verifyPermissionPoliciesHeader(policies: number) {
await this.uiHelper.verifyText(`Permission policies (${policies})`);
}
private async verifyArticle() {
await expect(this.article).toContainText("catalog-entity");
await expect(this.article).toContainText("Read, Update");
await expect(this.article).toContainText("Delete");
}
private async updateMember(member: string) {
await this.updateMemberButton.click();
await this.verifyATextIsVisible(member);
}
private async next() {
await this.uiHelper.clickButton("Next");
}
private async create() {
await this.uiHelper.clickButton("Create");
}
public async selectOption(
option:
| "catalog"
| "kubernetes"
| "catalog.entity.read"
| "scaffolder"
| "scaffolder-template.read"
| "permission",
) {
const optionSelector = `li[role="option"]:has-text("${option}")`;
await this.page.waitForSelector(optionSelector);
await this.page.click(optionSelector);
}
private async clickOpenSidebar() {
await this.rulesSideBar.getByLabel("Open").click();
}
private async verifyConfigureAccessNumber(rules: number) {
await this.uiHelper.verifyText(
`Configure access (${rules} ${rules > 1 ? "rules" : "rule"})`,
);
}
async addUsersAndGroups(userOrRole: string) {
await this.usersAndGroupsField.fill(userOrRole);
}
async selectPermissionCheckbox(name: string) {
await this.page
.getByRole("cell", { name: name })
.getByRole("checkbox")
.click();
}
async pluginRuleCount(number: string) {
await expect(
this.page
.locator('span[class*="MuiBadge-badge"]')
.filter({ hasText: number }),
).toBeVisible();
}
private async createRoleUsers(
name: string,
users: string[],
groups: string[],
owner?: string,
) {
if (!this.page.url().includes("rbac")) await this.goto();
await this.uiHelper.clickButton("Create");
await this.uiHelper.verifyHeading("Create role");
await this.roleName.fill(name);
if (owner) {
await this.roleOwner.fill(owner);
}
await this.uiHelper.clickButton("Next");
await this.usersAndGroupsField.click();
for (const userOrGroup of users.concat(groups)) {
await this.page.click(this.selectMember(userOrGroup));
}
// Close dropdown after selecting users and groups
await this.page.getByTestId("ArrowDropDownIcon").click();
// Dynamically verify the heading based on users and groups added
await this.uiHelper.verifyHeading(
this.regexpShortUsersAndGroups(users.length, groups.length),
);
await this.next();
}
async createRole(
name: string,
users: string[],
groups: string[],
policies: RoleBasedPolicy[],
pluginId: "catalog" | "kubernetes" | "scaffolder" = "catalog",
owner?: string,
) {
await this.createRoleUsers(name, users, groups, owner);
// select permissions
await this.selectPluginsCombobox.click();
await this.selectOption(pluginId);
await this.page.getByText("Select...").click();
for (const policy of policies) {
await this.selectPermissionCheckbox(policy.permission!);
}
await this.next();
await this.uiHelper.verifyHeading("Review and create");
await this.uiHelper.verifyText(
this.regexpLongUsersAndGroups(users.length, groups.length),
);
await this.verifyPermissionPoliciesHeader(policies.length);
await this.create();
// Wait for either success message or error alert.
// Wrap both waitFor calls so the losing promise cannot reject unhandled.
const successLocator = this.page
.getByText(`Role role:default/${name} created successfully`, {
exact: true,
})
.first();
const errorAlert = this.page
.getByRole("alert")
.filter({ hasText: /error/i });
const outcome = await Promise.race([
successLocator
.waitFor({ state: "visible", timeout: 30000 })
.then(() => "success" as const)
.catch(() => "success_timeout" as const),
errorAlert
.waitFor({ state: "visible", timeout: 30000 })
.then(() => "error" as const)
.catch(() => "error_timeout" as const),
]);
if (outcome === "error") {
const errorMessage = await errorAlert.textContent();
throw new Error(
`Failed to create role: ${errorMessage}. This may indicate insufficient permissions or a leftover role from a previous test run.`,
);
}
if (outcome !== "success") {
throw new Error(
`Role creation timed out: neither success message nor error alert appeared within 30s.`,
);
}
// Now we should be on the roles list page
await this.page.getByPlaceholder("Filter").waitFor({ state: "visible" });
await this.page.getByPlaceholder("Filter").fill(name);
await this.uiHelper.verifyHeading("All roles (1)");
}
async createConditionalRole(
name: string,
users: string[],
groups: string[],
permissionPolicyType: PermissionPolicyType,
pluginId: "catalog" | "kubernetes" | "scaffolder" = "catalog",
owner?: string,
) {
await this.createRoleUsers(name, users, groups, owner);
// select permissions
await this.selectPluginsCombobox.click();
await this.selectOption(pluginId);
await this.page.getByText("Select...").click();
if (permissionPolicyType === "anyOf") {
// Conditional Scenario 1: Permission policies using AnyOf
await this.selectPermissionCheckbox("catalog.entity.read");
await this.page
.getByRole("row", { name: "catalog.entity.read" })
.getByLabel("remove")
.click();
await this.anyOfButton.click();
await this.clickOpenSidebar();
await this.isEntityKindButton.click();
await this.page.getByPlaceholder("string, string").click();
await this.page
.getByPlaceholder("string, string")
.fill("component,template,user,group");
await this.addRuleButton.click();
await this.page.getByLabel("Open").nth(2).click();
await this.hasSpecButton.click();
await this.key.click();
await this.key.fill("lifecycle");
await this.key.press("Tab");
await this.key.fill("experimental");
await this.addRuleButton.click();
await this.page.getByLabel("Open").nth(3).click();
await this.hasLabel.click();
await this.label.click();
await this.label.fill("partner");
// Add nested condition
await this.addNestedConditionButton.click();
await this.page.getByLabel("Open").nth(4).click();
await this.hasAnnotationButton.click();
await this.annotation.click();
await this.annotation.fill("test");
await this.saveConditions.click();
await this.pluginRuleCount("4");
await this.next();
await this.uiHelper.verifyHeading("Review and create");
await this.uiHelper.verifyText(
this.regexpLongUsersAndGroups(users.length, groups.length),
);
await this.verifyPermissionPoliciesHeader(1);
await this.uiHelper.verifyText("4 rules");
await this.uiHelper.clickButton("Create");
await this.uiHelper.verifyText(
`Role role:default/${name} created successfully`,
true,
15000,
);
} else if (permissionPolicyType === "not") {
// Conditional Scenario 2: Permission policies using Not
await this.selectPermissionCheckbox("catalog.entity.read");
await this.page
.getByRole("row", { name: "catalog.entity.read" })
.getByLabel("remove")
.click();
await this.notButton.click();
await this.clickOpenSidebar();
await this.hasSpecButton.click();
await this.key.click();
await this.key.fill("lifecycle");
await this.key.press("Tab");
await this.key.fill("experimental");
await this.saveConditions.click();
await this.pluginRuleCount("1");
await this.next();
await this.uiHelper.verifyHeading("Review and create");
await this.verifyPermissionPoliciesHeader(1);
await this.uiHelper.verifyText("1 rule");
await this.uiHelper.clickButton("Create");
await this.uiHelper.verifyText(`role:default/${name}`);
}
}
async tryDeleteRole(name: string): Promise<void> {
// Use the RBAC REST API for reliable cleanup — the UI-based approach
// can silently fail if the page hasn't fully loaded or the filter
// doesn't match, leaving a leftover role that blocks recreation.
try {
const token = await RhdhAuthApiHack.getToken(this.page);
const rbacApi = await RhdhRbacApi.build(token);
// name is fully qualified like "role:default/test-role1"
// The API expects just "default/test-role1"
const apiRoleName = name.replace(/^role:/, "");
// Delete policies associated with the role first
const policiesResponse = await rbacApi.getPoliciesByRole(apiRoleName);
if (policiesResponse.ok()) {
const policies = await policiesResponse.json();
if (policies.length > 0) {
await rbacApi.deletePolicy(apiRoleName, policies);
console.log(
`Deleted ${policies.length} leftover policies for ${name} via API`,
);
}
}
// Delete conditions associated with the role
const conditionsResponse = await rbacApi.getConditionByQuery({
roleEntityRef: name,
});
if (conditionsResponse.ok()) {
const conditions = await conditionsResponse.json();
for (const condition of conditions) {
const delResponse = await rbacApi.deleteConditionById(condition.id);
if (delResponse.ok()) {
console.log(
`Deleted leftover condition ${condition.id} for ${name} via API`,
);
}
}
}
// Delete the role itself
const response = await rbacApi.deleteRole(apiRoleName);
if (response.ok()) {
console.log(`Successfully deleted leftover role ${name} via API`);
} else if (response.status() === 404) {
console.log(`Role ${name} does not exist, no cleanup needed`);
} else {
console.warn(
`Unexpected status ${response.status()} when deleting role ${name} via API`,
);
}
} catch (error) {
console.warn(`API cleanup of role ${name} failed: ${error}`);
}
// Navigate to RBAC page for the subsequent test steps
await this.page.goto("/rbac");
}
async deleteRole(name: string, header: string = "All roles (0)") {
await this.page.goto("/rbac");
await this.uiHelper.searchInputAriaLabel(name);
const button = this.page.locator(ROLES_PAGE_COMPONENTS.deleteRole(name));
await button.waitFor({ state: "visible" });
await button.click();
await this.uiHelper.verifyHeading("Delete this role?");
await this.page.locator(DELETE_ROLE_COMPONENTS.roleName).click();
await this.page.fill(DELETE_ROLE_COMPONENTS.roleName, name);
await this.uiHelper.clickButton("Delete");
await this.uiHelper.verifyText(`Role ${name} deleted successfully`);
await this.page
.locator(SEARCH_OBJECTS_COMPONENTS.ariaLabelSearch)
.fill(name);
await this.uiHelper.verifyHeading(header);
}
private async createRBACConditions(owner: string) {
const permissions = [
"policy.entity.read",
"policy.entity.update",
"policy.entity.delete",
];
for (const permission of permissions) {
await this.selectPermissionCheckbox(permission);
await this.page
.getByRole("row", { name: permission })
.getByLabel("remove")
.click();
await this.clickOpenSidebar();
await this.isOwnerButton.click();
await this.page.getByPlaceholder("string, string").click();
await this.page.getByPlaceholder("string, string").fill(owner);
await this.saveConditions.click();
}
}
async createRBACConditionRole(name: string, users: string[], owner: string) {
if (!this.page.url().includes("rbac")) await this.goto();
await this.uiHelper.clickButton("Create");
await this.uiHelper.verifyHeading("Create role");
await this.roleName.fill(name);
await this.uiHelper.clickButton("Next");
await this.usersAndGroupsField.click();
for (const user of users) {
await this.page.click(this.selectMember(user));
}
// Close dropdown after selecting users and groups
await this.page.getByTestId("ArrowDropDownIcon").click();
// Dynamically verify the heading based on users and groups added
const numUsers = users.length;
await this.uiHelper.verifyHeading(
this.regexpShortUsersAndGroups(numUsers, 0),
);
await this.next();
await this.selectPluginsCombobox.click();
await this.selectOption("catalog");
await this.page.getByText("Select...").click();
await this.selectPermissionCheckbox("catalog.entity.read");
await this.page.getByTestId("expand-row-catalog").click();
await this.selectPluginsCombobox.click();
await this.selectOption("permission");
await this.page.getByText("Select...").click();
await this.selectPermissionCheckbox("policy.entity.create");
await this.createRBACConditions(owner);
await this.next();
await this.uiHelper.verifyHeading("Review and create");
await this.uiHelper.verifyText(this.regexpLongUsersAndGroups(numUsers, 0));
await this.verifyPermissionPoliciesHeader(5);
await this.create();
await this.page
.locator(SEARCH_OBJECTS_COMPONENTS.ariaLabelSearch)
.waitFor();
await this.page
.locator(SEARCH_OBJECTS_COMPONENTS.ariaLabelSearch)
.fill(name);
await this.uiHelper.verifyHeading("All roles (1)");
}
}