8000 Migrate AuthAttachmentRegisterTest by vaceksimon · Pull Request #52032 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,11 @@ protected void registerUser(String username, String password, String email, Stri

registerPage.assertCurrent();
registerPage.register("firstName", "lastName", email, username, password, password);
webAuthnRegisterPage.assertCurrent();
String userId = AdminApiUtil.findUserByUsername(managedRealm.admin(), username).getId();
managedRealm.cleanup().add(r -> r.users().get(userId).remove());
Comment thread
vaceksimon marked this conversation as resolved.
Resolved

// User was registered. Now he needs to register WebAuthn credential
webAuthnRegisterPage.assertCurrent();
webAuthnRegisterPage.clickRegister();

if (shouldSuccess) {
Expand Down Expand Up @@ -521,9 +523,6 @@ public RealmBuilder configure(RealmBuilder builder) {

builder.browserFlow("browser-webauthn");

builder.users(UserBuilder.create(USERNAME).password(PASSWORD).name("WebAuthn", "User")
.email("webauthn-user@localhost").emailVerified(true));

builder.users(UserBuilder.create("test-user@localhost")
Comment thread
vaceksimon marked this conversation as resolved.
Resolved
.enabled(true)
.email("test-user@localhost")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import org.keycloak.representations.idm.User 8000 Representation;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.events.EventAssertion;
import org.keycloak.testframework.realm.UserBuilder;
import org.keycloak.testframework.remote.runonserver.InjectRunOnServer;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.ui.annotations.InjectPage;
Expand Down Expand Up @@ -188,9 +189,8 @@ public void webAuthnPasswordlessAlternativeWithWebAuthnAndPassword() {
final String WEBAUTHN_LABEL = "webauthn";
final String PASSWORDLESS_LABEL = "passwordless";

managedRealm.addUser(UserBuilder.create(USERNAME).password(PASSWORD).name("WebAuthn", "User") .email("webauthn-user@localhost").emailVerified(true));
managedRealm.updateWithCleanup(r -> r.browserFlow(webAuthnTogetherPasswordlessFlow()));
final UserRepresentation cleanupUser = AdminApiUtil.findUserByUsername(managedRealm.admin(), USERNAME);
managedRealm.cleanup().add(r -> r.users().get(cleanupUser.getId()).update(cleanupUser));

UserRepresentation user = AdminApiUtil.findUserByUsername(managedRealm.admin(), USERNAME);

Expand Down Expand Up @@ -420,6 +420,7 @@ public void webAuthnPasswordlessShouldFailIfUserIsDeletedInBetween() {
public void webAuthnTwoFactorAndWebAuthnPasswordlessTogether() {
// Change binding to browser-webauthn-passwordless. This is flow, which contains both "webauthn" and "webauthn-passwordless" authenticator
managedRealm.updateWithCleanup(r -> r.browserFlow("browser-webauthn-passwordless"));
managedRealm.addUser(UserBuilder.create(USERNAME).password(PASSWORD).name("WebAuthn", "User") .email("webauthn-user@localhost").emailVerified(true));
// Login as webauthn-user with password
oAuthClient.openLoginForm();
loginPage.fillLogin(USERNAME, PASSWORD);
Expand Down
8000
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@
import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.realm.RealmBuilder;
import org.keycloak.testframework.realm.UserBuilder;
import org.keycloak.tests.webauthn.authenticators.DefaultVirtualAuthOptions;
import org.keycloak.tests.webauthn.page.WebAuthnLoginPage;

Expand Down Expand Up @@ -57,6 +61,9 @@ public class WebAuthnTransportLocaleTest extends AbstractWebAuthnVirtualTest {

private static final Logger log = LoggerFactory.getLogger(WebAuthnTransportLocaleTest.class);

@InjectRealm(ref = "webauthn", config = WebAuthnTransportLocaleRealmConfig.class)
protected ManagedRealm managedRealm;

@BeforeEach
public void setupLocale() {
// Clear cookies to reset locale from any previous test
Expand Down Expand Up @@ -282,4 +289,19 @@ private int getUserCredentialsCount() {
private void setUpWebAuthnFlow() {
managedRealm.updateWithCleanup(r -> r.browserFlow("browser-webauthn"));
}

private static class WebAuthnTransportLocaleRealmConfig extends WebAuthnRealmConfig {

@Override
public RealmBuilder configure(RealmBuilder builder) {
super.configure(builder);
return builder.users(
UserBuilder.create(USERNAME)
.password(PASSWORD)
.name("WebAuthn", "User")
.email("webauthn-user@localhost")
.emailVerified(true)
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.tests.webauthn.registration;
Comment thread
vaceksimon marked this conversation as resolved.
Resolved

import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.tests.webauthn.AbstractWebAuthnVirtualTest;

import com.webauthn4j.data.AuthenticatorAttachment;
import com.webauthn4j.data.UserVerificationRequirement;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

import static org.keycloak.tests.webauthn.authenticators.DefaultVirtualAuthOptions.DEFAULT_BLE;
import static org.keycloak.tests.webauthn.authenticators.DefaultVirtualAuthOptions.DEFAULT_INTERNAL;
import static org.keycloak.tests.webauthn.authenticators.DefaultVirtualAuthOptions.DEFAULT_USB;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

/**
* @author <a href="mailto:mabartos@redhat.com">Martin Bartos</a>
*/
@KeycloakIntegrationTest
// This test should be ignored on Firefox: See https://github.com/keycloak/keycloak/issues/10368
public class AuthAttachmentRegisterTest extends AbstractWebAuthnVirtualTest {
Comment thread
vaceksimon marked this conversation as resolved.
Resolved
Comment thread
vaceksimon marked this conversation as resolved.
Resolved

@Test
public void authenticatorAttachmentCrossPlatform() {
getVirtualAuthManager().useAuthenticator(DEFAULT_USB.getOptions());
assertAuthenticatorAttachment(true, AuthenticatorAttachment.CROSS_PLATFORM);
}

@Test
@Disabled
public void authenticatorAttachmentCrossPlatformInternal() {
getVirtualAuthManager().useAuthenticator(DEFAULT_INTERNAL.getOptions());
assertAuthenticatorAttachment(true, AuthenticatorAttachment.CROSS_PLATFORM);
}

@Test
public void authenticatorAttachmentPlatform() {
managedRealm.updateWithCleanup(r -> {
if (isPasswordless()) {
r.webAuthnPolicyPasswordlessAuthenticatorAttachment(AuthenticatorAttachment.PLATFORM.getValue());
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that the getWebAuthnRealmUpdater in its current form will not have a future in the new testsuite.

But IMO it's very useful here as we need to check the normal webauthn, and passwordless one.

Would it be possible to update the realm updater for webauthn that would accept the realm? Otherwise, we'll have so many duplications like this:

if (isPasswordless()) {
            assertEquals(AuthenticatorAttachment.PLATFORM.getValue(), rep.getWebAuthnPolicyPasswordlessAuthenticatorAttachment());
            assertEquals(UserVerificationRequirement.DISCOURAGED.getValue(), rep.getWebAuthnPolicyPasswordlessUserVerificationRequirement());
        } else {
            assertEquals(AuthenticatorAttachment.PLATFORM.getValue(), rep.getWebAuthnPolicyAuthenticatorAttachment());
            assertEquals(UserVerificationRequirement.DISCOURAGED.getValue(), rep.getWebAuthnPolicyUserVerificationRequirement());
        }

WDYT?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely right. ServerResourceUpdater and other classes are not moved, but AbstractWebAuthnRealmUpdater and its subclasses are definitely beneficial for reducing boilerplate.

I will create a follow-up PR to create the WebAuthn realm updater, which can be used with RealmBuilder and in the configs too. And I will update the WebAuthn test classes that will benefit from it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, thanks!

r.webAuthnPolicyPasswordlessUserVerificationRequirement(UserVerificationRequirement.DISCOURAGED.getValue());
r.webAuthnPolicyPasswordlessCreateTimeout(3);
} else {
r.webAuthnPolicyAuthenticatorAttachment(AuthenticatorAttachment.PLATFORM.getValue());
r.webAuthnPolicyUserVerificationRequirement(UserVerificationRequirement.DISCOURAGED.getValue());
r.webAuthnPolicyCreateTimeout(3);
}
return r;
}
);

// It shouldn't be possible to register the authenticator
getVirtualAuthManager().useAuthenticator(DEFAULT_BLE.getOptions());

RealmRepresentation rep = managedRealm.admin().toRepresentation();
if (isPasswordless()) {
assertEquals(AuthenticatorAttachment.PLATFORM.getValue(), rep.getWebAuthnPolicyPasswordlessAuthenticatorAttachment());
assertEquals(UserVerificationRequirement.DISCOURAGED.getValue(), rep.getWebAuthnPolicyPasswordlessUserVerificationRequirement());
} else {
assertEquals(AuthenticatorAttachment.PLATFORM.getValue(), rep.getWebAuthnPolicyAuthenticatorAttachment());
assertEquals(UserVerificationRequirement.DISCOURAGED.getValue(), rep.getWebAuthnPolicyUserVerificationRequirement());
}

registerDefaultUser(false);

// Instead of returning an error it seems that selenium webauthn just hangs
// So we cannot test this correctly
webAuthnRegisterPage.assertCurrent();

// click authentication again does nothing
webAuthnRegisterPage.clickRegister();
webAuthnRegisterPage.clickRegister();
webAuthnRegisterPage.assertCurrent();

// it timeouts after create timeout
webAuthnErrorPage.assertCurrent();
assertThat(webAuthnErrorPage.getError(), containsString("The Passkey operation was not allowed or timed out."));
}

@Test
public void authenticatorAttachmentPlatformInternal() {
getVirtualAuthManager().useAuthenticator(DEFAULT_INTERNAL.getOptions());
assertAuthenticatorAttachment(true, AuthenticatorAttachment.PLATFORM);
}

private void assertAuthenticatorAttachment(boolean shouldSuccess, AuthenticatorAttachment attachment) {
managedRealm.updateWithCleanup(r -> isPasswordless()
? r.webAuthnPolicyPasswordlessAuthenticatorAttachment(attachment.getValue())
: r.webAuthnPolicyAuthenticatorAttachment(attachment.getValue())
);
RealmRepresentation rep = managedRealm.admin().toRepresentation();
assertEquals(attachment.getValue(), isPasswordless()
? rep.getWebAuthnPolicyPasswordlessAuthenticatorAttachment()
: rep.getWebAuthnPolicyAuthenticatorAttachment()
);

registerDefaultUser(shouldSuccess);

Assertions.assertTrue(oAuthClient.parseLoginResponse().isSuccess());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,6 @@ public class WebAuthnOtherSettingsTest extends AbstractWebAuthnVirtualTest {

@Test
public void defaultValues() {
removeDefaultUser();

registerDefaultUser("webauthn");

Assertions.assertTrue(oAuthClient.parseLoginResponse().isSuccess());
Expand Down Expand Up @@ -124,9 +122,6 @@ public void defaultValues() {
public void timeout() {
final int timeout = 3; // seconds


removeDefaultUser();

getVirtualAuthManager().removeAuthenticator();
setWebAuthnPolicyCreateTimeout(timeout);

Expand All @@ -136,8 +131,10 @@ public void timeout() {
oAuthClient.openRegistrationForm();
registerPage.assertCurrent();
registerPage.register("firstName", "lastName", EMAIL, USERNAME, PASSWORD);

webAuthnRegisterPage.assertCurrent();
String userId = AdminApiUtil.findUserByUsername(managedRealm.admin(), USERNAME).getId();
managedRealm.cleanup().add(r -> r.users().get(userId).remove());

webAuthnRegisterPage.clickRegister();


Expand All @@ -159,8 +156,6 @@ public void acceptableAaguidsShouldBeEmptyOrNullByDefault() {

@Test
public void excludeCredentials() {
removeDefaultUser();

setAcceptableAaguidsWithDirectAttestation(List.of(ALL_ZERO_AAGUID));

disableTruststoreSpi();
Expand All @@ -178,8 +173,6 @@ public void excludeCredentials() {

@Test
public void excludeCredentialsSuccess() {
removeDefaultUser();

setAcceptableAaguidsWithDirectAttestation(List.of(CHROME_AAGUID));

disableTruststoreSpi();
Expand All @@ -196,8 +189,6 @@ public void excludeCredentialsSuccess() {

@Test
public void excludeCredentialsUsingNone() {
removeDefaultUser();

// Acceptable AAGUIDs restricted, but attestation left at the default (none): registration must be rejected
setAcceptableAaguids(List.of(ALL_ZERO_AAGUID));

Expand All @@ -218,9 +209,6 @@ public void apiNotAllowedErrorMessage() {

@Test
public void apiInvalidStateErrorMessage() {

removeDefaultUser();

registerDefaultUser();
UserRepresentation user = userResource().toRepresentation();
logout();
Expand All @@ -245,26 +233,22 @@ public void apiInvalidStateErrorMessage() {

@Test
public void apiSecurityErrorMessage() {

removeDefaultUser();

setWebAuthnPolicyRpId("invalid.example.com");

oAuthClient.openRegistrationForm();
registerPage.assertCurrent();
registerPage.register("firstName", "lastName", EMAIL, USERNAME, PASSWORD);

webAuthnRegisterPage.assertCurrent();
String userId = AdminApiUtil.findUserByUsername(managedRealm.admin(), USERNAME).getId();
managedRealm.cleanup().add(r -> r.users().get(userId).remove());

Comment thread
vaceksimon marked this conversation as resolved.
Resolved
webAuthnRegisterPage.clickRegister();

webAuthnErrorPage.assertCurrent();
assertThat(webAuthnErrorPage.getError(), containsString("A security error occurred during the Passkey operation. Please ensure you are on the correct site and try again."));
}

private void assertBrowserApiErrorMessage(Consumer<VirtualAuthenticatorOptions> optionsConsumer, String expectedMessage) {
// remove the pre-created default user to register it fresh
removeDefaultUser();

getVirtualAuthManager().removeAuthenticator();
VirtualAuthenticatorOptions options = getDefaultAuthenticatorOptions();
optionsConsumer.accept(options);
Expand All @@ -273,8 +257,10 @@ private void assertBrowserApiErrorMessage(Consumer<VirtualAuthenticatorOptions>
oAuthClient.openRegistrationForm();
registerPage.assertCurrent();
registerPage.register("firstName", "lastName", EMAIL, USERNAME, PASSWORD);

webAuthnRegisterPage.assertCurrent();
String userId = AdminApiUtil.findUserByUsername(managedRealm.admin(), USERNAME).getId();
managedRealm.cleanup().add(r -> r.users().get(userId).remove());

webAuthnRegisterPage.clickRegister();


Expand All @@ -286,13 +272,6 @@ private String registerProviderId() {
return isPasswordless() ? WebAuthnPasswordlessRegisterFactory.PROVIDER_ID : WebAuthnRegisterFactory.PROVIDER_ID;
}

private void removeDefaultUser() {
UserRepresentation defaultUser = AdminApiUtil.findUserByUsername(managedRealm.admin(), USERNAME);
if (defaultUser != null) {
managedRealm.admin().users().delete(defaultUser.getId());
}
}

private List<String> getAcceptableAaguids() {
RealmRepresentation realmRep = managedRealm.admin().toRepresentation();
return isPasswordless() ? realmRep.getWebAuthnPolicyPasswordlessAcceptableAaguids() : realmRep.getWebAuthnPolicyAcceptableAaguids();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,15 @@
* limitations under the License.
*/

package org.keycloak.testsuite.webauthn.registration.passwordless;
package org.keycloak.tests.webauthn.registration.passwordless;

import org.keycloak.testsuite.arquillian.annotation.IgnoreBrowserDriver;
import org.keycloak.testsuite.webauthn.registration.AuthAttachmentRegisterTest;

import org.openqa.selenium.firefox.FirefoxDriver;
import org.keycloak.tests.webauthn.registration.AuthAttachmentRegisterTest;

/**
* @author <a href="mailto:mabartos@redhat.com">Martin Bartos</a>
*/
@IgnoreBrowserDriver(FirefoxDriver.class) // See https://github.com/keycloak/keycloak/issues/10368
// This test should be ignored on Firefox: See https://github.com/keycloak/keycloak/issues/10368
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned offline, we don't need to specify the Firefox issue.

public class PwdLessAuthAttachmentRegTest extends AuthAttachmentRegisterTest {

@Override
Expand Down
Loading
Loading
0