diff --git a/web/tests/e2e/environment/test.ts b/web/tests/e2e/environment/test.ts index f0df3d829d1..94e91266e98 100644 --- a/web/tests/e2e/environment/test.ts +++ b/web/tests/e2e/environment/test.ts @@ -46,6 +46,12 @@ export const test = base.extend<{ } } + // Runs after each test has finished + if (config.keycloak && (config.mfa || config.vaultMode) && adminUser) { + await api.keycloak.setAccessTokenForKeycloakUser(adminUser) + await api.keycloak.deleteUserTotpCredentials({ user: adminUser }) + } + await cleanUpUser(store.createdUserStore, adminUser) await cleanUpGroup(adminUser) await cleanUpSpaces(adminUser) @@ -80,6 +86,14 @@ export const test = base.extend<{ } } } + + // Runs before each test, but after the world has been initialized. + const adminUser = world.usersEnvironment.getUser({ key: config.keycloakAdminUser }) + if (config.keycloak && (config.mfa || config.vaultMode) && adminUser) { + await api.keycloak.setAccessTokenForKeycloakUser(adminUser) + await api.keycloak.deleteUserTotpCredentials({ user: adminUser }) + } + await use() }, { auto: true } diff --git a/web/tests/e2e/support/api/keycloak/user.ts b/web/tests/e2e/support/api/keycloak/user.ts index 71947f943e3..a7035abbff5 100644 --- a/web/tests/e2e/support/api/keycloak/user.ts +++ b/web/tests/e2e/support/api/keycloak/user.ts @@ -168,3 +168,57 @@ export const getRealmRole = async (role: string, admin: User): Promise => { + const username = user.originalId + + const response = await request({ + method: 'GET', + path: `${join(realmBasePath, 'users')}?username=${encodeURIComponent(username)}&exact=true`, + user + }) + checkResponseStatus(response, 'Failed while finding Keycloak user') + + const keycloakUsers = (await response.json()) as Array<{ + id: string + username: string + }> + + if (keycloakUsers.length === 0) { + throw new Error(`Keycloak user with username '${username}' not found`) + } + + return keycloakUsers[0].id +} + +export const deleteUserTotpCredentials = async ({ user }: { user: User }): Promise => { + const keycloakUserId = await getKeycloakUserId({ user }) + + const response = await request({ + method: 'GET', + path: join(realmBasePath, 'users', keycloakUserId, 'credentials'), + user + }) + checkResponseStatus(response, 'Failed while listing Keycloak user credentials') + + const credentials = (await response.json()) as Array<{ + id: string + type: string + }> + + for (const credential of credentials) { + if (['otp', 'totp'].includes(credential.type)) { + const deleteResponse = await request({ + method: 'DELETE', + path: join(realmBasePath, 'users', keycloakUserId, 'credentials', credential.id), + user + }) + + if (deleteResponse.status !== 204) { + throw new Error( + `Failed to delete OTP/TOTP credential for user: ${user.id}, Status: ${deleteResponse.status}` + ) + } + } + } +}