@appsemble/e2e 0.40.4 → 0.40.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import { expect, authenticatedTest as test } from '../../../index.js';
2
2
  import pkg from '../../../package.json' with { type: 'json' };
3
- const { KEYCLOAK_ADMIN_PASSWORD = 'password', KEYCLOAK_ADMIN_USERNAME = 'admin', KEYCLOAK_BASE_URL, KEYCLOAK_REALM = 'appsemble-e2e', } = process.env;
3
+ import { createGroup, createRealm, createUser, getAdminToken, joinGroup, requestKc, } from '../../../utils/keycloak-admin.js';
4
+ const { KEYCLOAK_BASE_URL, KEYCLOAK_REALM = 'appsemble-e2e' } = process.env;
4
5
  const clientId = 'appsemble-oidc';
5
6
  const clientSecret = 'appsemble-oidc-secret';
6
7
  const userEmail = 'keycloak-user@appsemble.com';
@@ -8,99 +9,12 @@ const userPassword = 'password';
8
9
  let app;
9
10
  let organizationId;
10
11
  let secret;
11
- async function requestKc(path, { body, expectedStatuses, method, token, }) {
12
- const response = await fetch(`${KEYCLOAK_BASE_URL}${path}`, {
13
- body,
14
- headers: {
15
- authorization: `Bearer ${token}`,
16
- 'content-type': 'application/json',
17
- },
18
- method,
19
- });
20
- if (!expectedStatuses.includes(response.status)) {
21
- throw new Error(`${method} ${path} returned ${response.status}: ${await response.text()}`);
22
- }
23
- return response;
24
- }
25
- async function getAdminToken() {
26
- for (let attempt = 0; attempt < 60; attempt += 1) {
27
- try {
28
- const response = await fetch(`${KEYCLOAK_BASE_URL}/realms/master/protocol/openid-connect/token`, {
29
- body: new URLSearchParams({
30
- client_id: 'admin-cli',
31
- grant_type: 'password',
32
- password: KEYCLOAK_ADMIN_PASSWORD,
33
- username: KEYCLOAK_ADMIN_USERNAME,
34
- }),
35
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
36
- method: 'POST',
37
- });
38
- if (response.ok) {
39
- const { access_token: token } = (await response.json());
40
- return token;
41
- }
42
- }
43
- catch {
44
- // The service may still be starting.
45
- }
46
- await new Promise((resolve) => {
47
- setTimeout(resolve, 1000);
48
- });
49
- }
50
- throw new Error('Could not obtain Keycloak admin token');
51
- }
52
- async function createGroup(token, name, parentGroupId) {
53
- const path = parentGroupId
54
- ? `/admin/realms/${KEYCLOAK_REALM}/groups/${parentGroupId}/children`
55
- : `/admin/realms/${KEYCLOAK_REALM}/groups`;
56
- const response = await requestKc(path, {
57
- body: JSON.stringify({ name }),
58
- expectedStatuses: [201],
59
- method: 'POST',
60
- token,
61
- });
62
- return response.headers.get('location').split('/').pop();
63
- }
64
- async function createUser(token) {
65
- const response = await requestKc(`/admin/realms/${KEYCLOAK_REALM}/users`, {
66
- body: JSON.stringify({
67
- credentials: [{ temporary: false, type: 'password', value: userPassword }],
68
- email: userEmail,
69
- emailVerified: true,
70
- enabled: true,
71
- firstName: 'Keycloak',
72
- lastName: 'User',
73
- username: userEmail,
74
- }),
75
- expectedStatuses: [201],
76
- method: 'POST',
77
- token,
78
- });
79
- return response.headers.get('location').split('/').pop();
80
- }
81
- async function joinGroup(token, userId, groupId) {
82
- await requestKc(`/admin/realms/${KEYCLOAK_REALM}/users/${userId}/groups/${groupId}`, {
83
- expectedStatuses: [204],
84
- method: 'PUT',
85
- token,
86
- });
87
- }
88
12
  async function configureRealm() {
89
13
  const token = await getAdminToken();
90
- await requestKc(`/admin/realms/${KEYCLOAK_REALM}`, {
91
- expectedStatuses: [204, 404],
92
- method: 'DELETE',
93
- token,
94
- });
95
- await requestKc('/admin/realms', {
96
- body: JSON.stringify({ enabled: true, realm: KEYCLOAK_REALM }),
97
- expectedStatuses: [201],
98
- method: 'POST',
99
- token,
100
- });
101
- const parentGroupId = await createGroup(token, 'Appsemble');
102
- const managersGroupId = await createGroup(token, 'Managers', parentGroupId);
103
- const editorsGroupId = await createGroup(token, 'Editors', parentGroupId);
14
+ await createRealm(token, KEYCLOAK_REALM);
15
+ const parentGroupId = await createGroup(token, KEYCLOAK_REALM, 'Appsemble');
16
+ const managersGroupId = await createGroup(token, KEYCLOAK_REALM, 'Managers', parentGroupId);
17
+ const editorsGroupId = await createGroup(token, KEYCLOAK_REALM, 'Editors', parentGroupId);
104
18
  await requestKc(`/admin/realms/${KEYCLOAK_REALM}/clients`, {
105
19
  body: JSON.stringify({
106
20
  clientAuthenticatorType: 'client-secret',
@@ -132,9 +46,14 @@ async function configureRealm() {
132
46
  method: 'POST',
133
47
  token,
134
48
  });
135
- const userId = await createUser(token);
136
- await joinGroup(token, userId, managersGroupId);
137
- await joinGroup(token, userId, editorsGroupId);
49
+ const userId = await createUser(token, KEYCLOAK_REALM, {
50
+ email: userEmail,
51
+ firstName: 'Keycloak',
52
+ lastName: 'User',
53
+ password: userPassword,
54
+ });
55
+ await joinGroup(token, KEYCLOAK_REALM, userId, managersGroupId);
56
+ await joinGroup(token, KEYCLOAK_REALM, userId, editorsGroupId);
138
57
  }
139
58
  test.describe('App Keycloak OIDC login', () => {
140
59
  test.skip(!KEYCLOAK_BASE_URL, 'Keycloak OIDC login requires KEYCLOAK_BASE_URL');
@@ -210,9 +129,9 @@ test.describe('App Keycloak OIDC login', () => {
210
129
  const appUrl = await visitApp(app.id);
211
130
  await page.goto(`${appUrl}/Login`);
212
131
  await page.getByRole('button', { name: `Login with ${secret.name}` }).click();
213
- await page.locator('#username').fill(userEmail);
214
- await page.locator('#password').fill(userPassword);
215
- await page.locator('#kc-login').click();
132
+ await page.getByRole('textbox', { name: /username or email/i }).fill(userEmail);
133
+ await page.getByRole('textbox', { exact: true, name: 'Password' }).fill(userPassword);
134
+ await page.getByRole('button', { name: /sign in/i }).click();
216
135
  await expect(page.getByRole('heading', { name: 'Manager content' })).toBeVisible();
217
136
  await expect(page.getByRole('link', { name: 'Manager Page' })).toBeVisible();
218
137
  await expect(page.getByRole('link', { name: 'Editor Page' })).toBeVisible();
@@ -1,6 +1,7 @@
1
1
  import { expect, authenticatedTest as test } from '../../../index.js';
2
2
  import pkg from '../../../package.json' with { type: 'json' };
3
- const { KEYCLOAK_ADMIN_PASSWORD = 'password', KEYCLOAK_ADMIN_USERNAME = 'admin', KEYCLOAK_BASE_URL, KEYCLOAK_REALM = 'appsemble-e2e', } = process.env;
3
+ import { createGroup, createRealm, createUser, getAdminToken, getSigningCertificate, joinGroup, requestKc, } from '../../../utils/keycloak-admin.js';
4
+ const { KEYCLOAK_BASE_URL, KEYCLOAK_REALM = 'appsemble-e2e' } = process.env;
4
5
  const appsembleBaseUrl = 'http://appsemble:9999';
5
6
  const samlAttributeNameFormat = 'attribute.nameformat';
6
7
  const samlAssertionConsumerUrlPostAttribute = 'saml_assertion_consumer_url_post';
@@ -13,123 +14,21 @@ let idpCertificate;
13
14
  let organizationId;
14
15
  let secret;
15
16
  test.use({ timezoneId: 'Europe/Amsterdam' });
16
- async function requestKc(path, { body, expectedStatuses, method, token, }) {
17
- const response = await fetch(`${KEYCLOAK_BASE_URL}${path}`, {
18
- body,
19
- headers: {
20
- authorization: `Bearer ${token}`,
21
- 'content-type': 'application/json',
22
- },
23
- method,
24
- });
25
- if (!expectedStatuses.includes(response.status)) {
26
- throw new Error(`${method} ${path} returned ${response.status}: ${await response.text()}`);
27
- }
28
- return response;
29
- }
30
- async function getAdminToken() {
31
- for (let attempt = 0; attempt < 60; attempt += 1) {
32
- try {
33
- const response = await fetch(`${KEYCLOAK_BASE_URL}/realms/master/protocol/openid-connect/token`, {
34
- body: new URLSearchParams({
35
- client_id: 'admin-cli',
36
- grant_type: 'password',
37
- password: KEYCLOAK_ADMIN_PASSWORD,
38
- username: KEYCLOAK_ADMIN_USERNAME,
39
- }),
40
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
41
- method: 'POST',
42
- });
43
- if (response.ok) {
44
- const { access_token: token } = (await response.json());
45
- return token;
46
- }
47
- }
48
- catch {
49
- // The service may still be starting.
50
- }
51
- await new Promise((resolve) => {
52
- setTimeout(resolve, 1000);
53
- });
54
- }
55
- throw new Error('Could not obtain Keycloak admin token');
56
- }
57
- async function createGroup(token, name, parentGroupId) {
58
- const path = parentGroupId
59
- ? `/admin/realms/${KEYCLOAK_REALM}/groups/${parentGroupId}/children`
60
- : `/admin/realms/${KEYCLOAK_REALM}/groups`;
61
- const response = await requestKc(path, {
62
- body: JSON.stringify({ name }),
63
- expectedStatuses: [201],
64
- method: 'POST',
65
- token,
66
- });
67
- return response.headers.get('location').split('/').pop();
68
- }
69
- async function createUser(token) {
70
- const response = await requestKc(`/admin/realms/${KEYCLOAK_REALM}/users`, {
71
- body: JSON.stringify({
72
- credentials: [{ temporary: false, type: 'password', value: userPassword }],
73
- email: userEmail,
74
- emailVerified: true,
75
- enabled: true,
76
- firstName: 'Keycloak',
77
- lastName: 'SAML User',
78
- username: userEmail,
79
- }),
80
- expectedStatuses: [201],
81
- method: 'POST',
82
- token,
83
- });
84
- return response.headers.get('location').split('/').pop();
85
- }
86
- function wrapCertificate(certificate) {
87
- const lines = certificate.match(/.{1,64}/g);
88
- if (!lines) {
89
- throw new Error('Could not wrap Keycloak signing certificate');
90
- }
91
- return `-----BEGIN CERTIFICATE-----\n${lines.join('\n')}\n-----END CERTIFICATE-----`;
92
- }
93
- async function getSigningCertificate(token) {
94
- const response = await requestKc(`/admin/realms/${KEYCLOAK_REALM}/keys`, {
95
- expectedStatuses: [200],
96
- method: 'GET',
97
- token,
98
- });
99
- const { keys } = (await response.json());
100
- const certificate = keys.find((key) => key.use === 'SIG' && key.status === 'ACTIVE' && key.certificate)?.certificate;
101
- if (!certificate) {
102
- throw new Error('Could not find Keycloak signing certificate');
103
- }
104
- return wrapCertificate(certificate);
105
- }
106
- async function joinGroup(token, userId, groupId) {
107
- await requestKc(`/admin/realms/${KEYCLOAK_REALM}/users/${userId}/groups/${groupId}`, {
108
- expectedStatuses: [204],
109
- method: 'PUT',
110
- token,
111
- });
112
- }
113
17
  async function configureRealm() {
114
18
  const token = await getAdminToken();
115
- await requestKc(`/admin/realms/${KEYCLOAK_REALM}`, {
116
- expectedStatuses: [204, 404],
117
- method: 'DELETE',
118
- token,
119
- });
120
- await requestKc('/admin/realms', {
121
- body: JSON.stringify({ enabled: true, realm: KEYCLOAK_REALM }),
122
- expectedStatuses: [201],
123
- method: 'POST',
124
- token,
19
+ await createRealm(token, KEYCLOAK_REALM);
20
+ idpCertificate = await getSigningCertificate(token, KEYCLOAK_REALM);
21
+ const parentGroupId = await createGroup(token, KEYCLOAK_REALM, 'Appsemble');
22
+ const managersGroupId = await createGroup(token, KEYCLOAK_REALM, 'Managers', parentGroupId);
23
+ const editorsGroupId = await createGroup(token, KEYCLOAK_REALM, 'Editors', parentGroupId);
24
+ const userId = await createUser(token, KEYCLOAK_REALM, {
25
+ email: userEmail,
26
+ firstName: 'Keycloak',
27
+ lastName: 'SAML User',
28
+ password: userPassword,
125
29
  });
126
- idpCertificate = await getSigningCertificate(token);
127
- const parentGroupId = await createGroup(token, 'Appsemble');
128
- const managersGroupId = await createGroup(token, 'Managers', parentGroupId);
129
- const editorsGroupId = await createGroup(token, 'Editors', parentGroupId);
130
- const userId = await createUser(token);
131
- await joinGroup(token, userId, managersGroupId);
132
- await joinGroup(token, userId, editorsGroupId);
30
+ await joinGroup(token, KEYCLOAK_REALM, userId, managersGroupId);
31
+ await joinGroup(token, KEYCLOAK_REALM, userId, editorsGroupId);
133
32
  }
134
33
  async function createSamlClient(token, appId, secretId) {
135
34
  const samlBaseUrl = `${appsembleBaseUrl}/api/apps/${appId}/saml/${secretId}`;
@@ -278,9 +177,9 @@ test.describe('App Keycloak SAML login', () => {
278
177
  const appUrl = await visitApp(app.id);
279
178
  await page.goto(`${appUrl}/Login`);
280
179
  await page.getByRole('button', { name: `Login with ${secret.name}` }).click();
281
- await page.locator('#username').fill(userEmail);
282
- await page.locator('#password').fill(userPassword);
283
- await page.locator('#kc-login').click();
180
+ await page.getByRole('textbox', { name: /username or email/i }).fill(userEmail);
181
+ await page.getByRole('textbox', { exact: true, name: 'Password' }).fill(userPassword);
182
+ await page.getByRole('button', { name: /sign in/i }).click();
284
183
  await expect(page.getByRole('heading', { name: 'Manager content' })).toBeVisible();
285
184
  await expect(page.getByRole('link', { name: 'Manager Page' })).toBeVisible();
286
185
  await expect(page.getByRole('link', { name: 'Editor Page' })).toBeVisible();
@@ -17,6 +17,8 @@ test.describe('Organizations', () => {
17
17
  await page.getByRole('button', { name: 'Add members' }).click();
18
18
  await page.getByRole('textbox', { name: 'Email' }).fill(email);
19
19
  await page.locator('form').getByRole('button', { name: 'Add members' }).click();
20
+ // The page can be used while the dialog transitions out, so wait until it's gone.
21
+ await expect(page.getByRole('dialog')).toBeHidden();
20
22
  const memberRow = page.getByRole('row', { name: email });
21
23
  await expect(memberRow).toBeVisible();
22
24
  await memberRow.getByRole('button', { name: '' }).click();
@@ -29,6 +31,8 @@ test.describe('Organizations', () => {
29
31
  await page.getByRole('button', { name: 'Add members' }).click();
30
32
  await page.getByRole('textbox', { name: 'Email' }).fill(email);
31
33
  await page.locator('form').getByRole('button', { name: 'Add members' }).click();
34
+ // The page can be used while the dialog transitions out, so wait until it's gone.
35
+ await expect(page.getByRole('dialog')).toBeHidden();
32
36
  const memberRow = page.getByRole('row', { name: email });
33
37
  await expect(memberRow).toBeVisible();
34
38
  await memberRow.getByRole('button', { name: '' }).click();
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Perform an authenticated request against the Keycloak admin REST API.
3
+ *
4
+ * @param path The path relative to `KEYCLOAK_BASE_URL`.
5
+ * @param options The request options: a serialized `body`, the `expectedStatuses` treated as
6
+ * successful, the HTTP `method`, and a Keycloak admin bearer `token`.
7
+ * @returns The raw fetch response.
8
+ */
9
+ export declare function requestKc(path: string, { body, expectedStatuses, method, token, }: {
10
+ body?: string;
11
+ expectedStatuses: number[];
12
+ method: 'DELETE' | 'GET' | 'POST' | 'PUT';
13
+ token: string;
14
+ }): Promise<Response>;
15
+ /**
16
+ * Obtain a Keycloak admin token from the `master` realm.
17
+ *
18
+ * The Keycloak service may still be starting when the tests begin, so this retries for a while.
19
+ *
20
+ * @returns The `admin-cli` access token.
21
+ */
22
+ export declare function getAdminToken(): Promise<string>;
23
+ /**
24
+ * Recreate a realm from scratch by deleting any existing realm and creating an empty one.
25
+ *
26
+ * @param token A Keycloak admin bearer token.
27
+ * @param realm The realm name.
28
+ */
29
+ export declare function createRealm(token: string, realm: string): Promise<void>;
30
+ /**
31
+ * Create a group, optionally nested under a parent group.
32
+ *
33
+ * @param token A Keycloak admin bearer token.
34
+ * @param realm The realm name.
35
+ * @param name The group name.
36
+ * @param parentGroupId The id of the parent group, when creating a nested group.
37
+ * @returns The id of the created group.
38
+ */
39
+ export declare function createGroup(token: string, realm: string, name: string, parentGroupId?: string): Promise<string>;
40
+ /**
41
+ * Create an enabled user with a permanent password.
42
+ *
43
+ * @param token A Keycloak admin bearer token.
44
+ * @param realm The realm name.
45
+ * @param user The user to create: `email` (also used as the username), `firstName`, `lastName`,
46
+ * and `password`.
47
+ * @returns The id of the created user.
48
+ */
49
+ export declare function createUser(token: string, realm: string, { email, firstName, lastName, password, }: {
50
+ email: string;
51
+ firstName: string;
52
+ lastName: string;
53
+ password: string;
54
+ }): Promise<string>;
55
+ /**
56
+ * Add a user to a group.
57
+ *
58
+ * @param token A Keycloak admin bearer token.
59
+ * @param realm The realm name.
60
+ * @param userId The user id.
61
+ * @param groupId The group id.
62
+ */
63
+ export declare function joinGroup(token: string, realm: string, userId: string, groupId: string): Promise<void>;
64
+ /**
65
+ * Fetch the active PEM-wrapped signing certificate of a realm.
66
+ *
67
+ * @param token A Keycloak admin bearer token.
68
+ * @param realm The realm name.
69
+ * @returns The PEM-wrapped signing certificate.
70
+ */
71
+ export declare function getSigningCertificate(token: string, realm: string): Promise<string>;
72
+ /**
73
+ * Create a confidential OIDC client whose tokens carry group memberships as a `groups` claim.
74
+ *
75
+ * This mirrors the client the plain OIDC login test uses, but points its redirect URI at a
76
+ * Keycloak identity broker endpoint so a broker realm can federate to this realm.
77
+ *
78
+ * @param token A Keycloak admin bearer token.
79
+ * @param realm The upstream realm name.
80
+ * @param client The client to create: `clientId`, `clientSecret`, and the allowed `redirectUris`
81
+ * (typically the broker endpoint).
82
+ */
83
+ export declare function createUpstreamOidcClient(token: string, realm: string, { clientId, clientSecret, redirectUris, }: {
84
+ clientId: string;
85
+ clientSecret: string;
86
+ redirectUris: string[];
87
+ }): Promise<void>;
88
+ /**
89
+ * Create an OIDC identity provider that federates a broker realm to an upstream realm.
90
+ *
91
+ * @param token A Keycloak admin bearer token.
92
+ * @param realm The broker realm name.
93
+ * @param config The identity provider configuration: the `alias`, the `displayName` shown on the
94
+ * broker login page, the upstream `authorizationUrl`, `tokenUrl`, `userInfoUrl`, and `jwksUrl`
95
+ * endpoints, and the `clientId` and `clientSecret` registered in the upstream realm.
96
+ */
97
+ export declare function createOidcIdentityProvider(token: string, realm: string, { alias, authorizationUrl, clientId, clientSecret, displayName, jwksUrl, tokenUrl, userInfoUrl, }: {
98
+ alias: string;
99
+ authorizationUrl: string;
100
+ clientId: string;
101
+ clientSecret: string;
102
+ displayName: string;
103
+ jwksUrl: string;
104
+ tokenUrl: string;
105
+ userInfoUrl: string;
106
+ }): Promise<void>;
107
+ /**
108
+ * Add a mapper that imports the upstream `groups` claim into a `groups` attribute on brokered
109
+ * users, so a downstream client in the broker realm can re-emit it as a `groups` claim.
110
+ *
111
+ * @param token A Keycloak admin bearer token.
112
+ * @param realm The broker realm name.
113
+ * @param alias The identity provider alias.
114
+ */
115
+ export declare function createIdpGroupMapper(token: string, realm: string, alias: string): Promise<void>;