From 547e45923c3bb033d9b9b213919b8f80e995565a Mon Sep 17 00:00:00 2001 From: Prince Mathew Date: Tue, 10 Nov 2026 10:49:35 +0530 Subject: [PATCH] feat(Embedded): Add passkey login support to embedded API --- EXAMPLES.md | 1 + .../android/embedded/EmbeddedAuthClient.kt | 43 +++- .../android/embedded/EmbeddedAuthError.kt | 9 + .../authorize/EmbeddedAuthAdapters.kt | 7 +- .../embedded/authorize/EmbeddedCapability.kt | 1 + .../android/embedded/authorize/NextAction.kt | 20 ++ .../embedded/authorize/NextActionMapper.kt | 34 +++ .../embedded/passkey/PasskeyAssertion.kt | 90 ++++++++ .../embedded/passkey/PasskeyRequestOptions.kt | 33 +++ .../embedded/passkey/UserVerification.kt | 17 ++ .../embedded/EmbeddedAuthClientTest.kt | 124 +++++++++- .../authorize/NextActionMapperTest.kt | 160 +++++++++++++ .../embedded/passkey/PasskeyAssertionTest.kt | 211 ++++++++++++++++++ .../android/util/EmbeddedAuthMockServer.kt | 13 ++ examples/embedded-auth/authorize.md | 3 +- examples/embedded-auth/passkey.md | 124 ++++++++++ sample-embedded/build.gradle | 3 + .../auth0/sample/embedded/AuthorizeScreen.kt | 8 + .../sample/embedded/EmbeddedViewModel.kt | 7 + .../com/auth0/sample/embedded/PasskeyCard.kt | 102 +++++++++ .../src/main/res/values/strings.xml | 5 + 21 files changed, 1010 insertions(+), 5 deletions(-) create mode 100644 auth0/src/main/java/com/auth0/android/embedded/passkey/PasskeyAssertion.kt create mode 100644 auth0/src/main/java/com/auth0/android/embedded/passkey/PasskeyRequestOptions.kt create mode 100644 auth0/src/main/java/com/auth0/android/embedded/passkey/UserVerification.kt create mode 100644 auth0/src/test/java/com/auth0/android/embedded/passkey/PasskeyAssertionTest.kt create mode 100644 examples/embedded-auth/passkey.md create mode 100644 sample-embedded/src/main/java/com/auth0/sample/embedded/PasskeyCard.kt diff --git a/EXAMPLES.md b/EXAMPLES.md index fdf2131f4..669e0fd03 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -33,6 +33,7 @@ Each topic lives in its own file under [`examples/`](examples). - [Email OTP — first-factor & MFA second-factor](examples/embedded-auth/authorize.md) - [Username & Password — first-factor](examples/embedded-auth/password-authorize.md) +- [Passkey — first-factor](examples/embedded-auth/passkey.md) - [Phone OTP (SMS/Voice) — first-factor & MFA second-factor](examples/embedded-auth/phone-authorize.md) - [Push Notification Polling (OOB)](examples/embedded-auth/push-oob-polling.md) - [Recovery Code](examples/embedded-auth/recovery-code.md) diff --git a/auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthClient.kt b/auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthClient.kt index e1eda9e72..bf70adaa2 100644 --- a/auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthClient.kt +++ b/auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthClient.kt @@ -13,6 +13,8 @@ import com.auth0.android.embedded.authorize.PhoneDeliveryMethod import com.auth0.android.embedded.authorize.StepRequest import com.auth0.android.embedded.authorize.authorizeCodeAdapter import com.auth0.android.embedded.authorize.embeddedAuthErrorAdapter +import com.auth0.android.embedded.passkey.InvalidPasskeyResponseException +import com.auth0.android.embedded.passkey.passkeyAuthnResponse import com.auth0.android.request.Request import com.auth0.android.request.internal.GsonAdapter import com.auth0.android.request.internal.GsonProvider @@ -58,7 +60,8 @@ public class EmbeddedAuthClient(private val auth0: Auth0) { * @param scope space-separated scopes to request. Must include `openid` for the terminal token * exchange to return an ID token; defaults to `"openid profile email offline_access"`. * @param audience optional API audience to request an access token for. - * @param capabilities the set of steps this client can handle in the flow. + * @param capabilities the set of steps this client can handle in the flow. Defaults to every step the + * SDK models. */ @JvmOverloads public fun authorize( @@ -145,6 +148,38 @@ public class EmbeddedAuthClient(private val auth0: Auth0) { addParameter(PASSWORD_KEY, password) } + /** + * Signs the user in with a passkey. Completes the flow when no further factor is required. + * + * Call it with the `authenticationResponseJson` of the credential the platform returned after + * running the ceremony for [NextAction.VerifyPasskey.requestJson]. Only the fields the server + * accepts are sent. The passkey must be discoverable, so the response must carry a `userHandle`. + * + * On success, it yields the [Credentials]. If the passkey is rejected, the request completes through + * [EmbeddedAuthException] with [EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_PASSKEY] + * and a new [NextAction.VerifyPasskey] that carries a fresh challenge. If the server requires further + * steps, [EmbeddedAuthError.InsufficientAuthorization.nextActions] carry them. + * + * A response that doesn't match the server's schema completes with [EmbeddedAuthError.InvalidInput] + * without sending a request; the flow is unchanged. + */ + public fun verifyPasskey(authenticationResponseJson: String): Request { + val authnResponse = try { + passkeyAuthnResponse(authenticationResponseJson) + } catch (e: InvalidPasskeyResponseException) { + return FailedRequest( + EmbeddedAuthException( + INVALID_INPUT_ERROR, + e.message ?: DEFAULT_INVALID_INPUT_DESCRIPTION, + error = EmbeddedAuthError.InvalidInput + ) + ) + } + return terminalStep(EmbeddedCapability.VERIFY_PASSKEY) { + addParameter(AUTHN_RESPONSE_KEY, authnResponse) + } + } + /** * Continues the flow by requesting a phone challenge for the authenticator at [index]. * @@ -367,6 +402,7 @@ public class EmbeddedAuthClient(private val auth0: Auth0) { private const val PHONE_KEY = "phone" private const val USERNAME_KEY = "username" private const val PASSWORD_KEY = "password" + private const val AUTHN_RESPONSE_KEY = "authn_response" private const val DELIVERY_METHOD_KEY = "delivery_method" private const val OTP_KEY = "otp" private const val INDEX_KEY = "index" @@ -375,6 +411,8 @@ public class EmbeddedAuthClient(private val auth0: Auth0) { private const val CODE_KEY = "code" private const val GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code" private const val NO_ACTIVE_SESSION_ERROR = "no_active_session" + private const val INVALID_INPUT_ERROR = "invalid_input" + private const val DEFAULT_INVALID_INPUT_DESCRIPTION = "The input was rejected." private const val DEFAULT_SCOPE = "openid profile email offline_access" @@ -391,7 +429,8 @@ public class EmbeddedAuthClient(private val auth0: Auth0) { EmbeddedCapability.VERIFY_RECOVERY_CODE, EmbeddedCapability.CONFIRM_RECOVERY_CODE, EmbeddedCapability.SIGNUP, - EmbeddedCapability.CONFIRM_SIGNUP + EmbeddedCapability.CONFIRM_SIGNUP, + EmbeddedCapability.VERIFY_PASSKEY ) } diff --git a/auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthError.kt b/auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthError.kt index 2d6328fe6..49ddedee3 100644 --- a/auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthError.kt +++ b/auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthError.kt @@ -31,6 +31,9 @@ public sealed interface EmbeddedAuthError { /** The username or the password was invalid; the server does not say which. */ INVALID_IDENTIFIER_OR_PASSWORD, + /** The submitted passkey was rejected. The new [NextAction.VerifyPasskey] carries a fresh challenge. */ + INVALID_PASSKEY, + /** Authorization is pending (e.g., push notification awaiting user approval). Retry after a delay. */ AUTHORIZATION_PENDING, @@ -97,6 +100,12 @@ public sealed interface EmbeddedAuthError { */ public data object Network : EmbeddedAuthError + /** + * Client-side guard: the input was rejected before any request was sent, so the flow is unchanged. + * Read [EmbeddedAuthException.description] for which field was rejected, and retry the step. + */ + public data object InvalidInput : EmbeddedAuthError + /** Client-side guard: no flow is in progress. Call [EmbeddedAuthClient.authorize] first. */ public data object NoActiveSession : EmbeddedAuthError diff --git a/auth0/src/main/java/com/auth0/android/embedded/authorize/EmbeddedAuthAdapters.kt b/auth0/src/main/java/com/auth0/android/embedded/authorize/EmbeddedAuthAdapters.kt index b1bd199cc..83c26dd59 100644 --- a/auth0/src/main/java/com/auth0/android/embedded/authorize/EmbeddedAuthAdapters.kt +++ b/auth0/src/main/java/com/auth0/android/embedded/authorize/EmbeddedAuthAdapters.kt @@ -11,6 +11,7 @@ import com.auth0.android.request.internal.GsonAdapter.Companion.forMap import com.auth0.android.request.internal.GsonProvider import com.auth0.android.request.internal.ResponseUtils.isNetworkError import com.google.gson.Gson +import com.google.gson.ToNumberPolicy import java.io.IOException import java.io.Reader @@ -32,6 +33,7 @@ private const val IP_BLOCKED = "ip_blocked" private const val INVALID_CODE = "invalid_code" private const val INVALID_IDENTIFIER_OR_CODE = "invalid_identifier_or_code" private const val INVALID_IDENTIFIER_OR_PASSWORD = "invalid_identifier_or_password" +private const val INVALID_PASSKEY = "invalid_passkey" private const val INVALID_GRANT = "invalid_grant" private const val INVALID_REQUEST = "invalid_request" private const val TOO_MANY_REQUESTS_STATUS = 429 @@ -51,7 +53,9 @@ internal fun authorizeCodeAdapter(gson: Gson): JsonAdapter = * Translates every embedded-authentication error response into an [EmbeddedAuthException]. */ internal fun embeddedAuthErrorAdapter(): ErrorAdapter { - val mapAdapter = forMap(GsonProvider.gson) + val mapAdapter = forMap( + GsonProvider.gson.newBuilder().setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE).create() + ) return object : ErrorAdapter { override fun fromRawResponse( @@ -136,6 +140,7 @@ internal fun embeddedAuthErrorAdapter(): ErrorAdapter { EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_IDENTIFIER_OR_CODE INVALID_IDENTIFIER_OR_PASSWORD -> EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_IDENTIFIER_OR_PASSWORD + INVALID_PASSKEY -> EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_PASSKEY AUTHORIZATION_PENDING -> EmbeddedAuthError.InsufficientAuthorization.Reason.AUTHORIZATION_PENDING SLOW_DOWN -> EmbeddedAuthError.InsufficientAuthorization.Reason.SLOW_DOWN diff --git a/auth0/src/main/java/com/auth0/android/embedded/authorize/EmbeddedCapability.kt b/auth0/src/main/java/com/auth0/android/embedded/authorize/EmbeddedCapability.kt index 4ca396b0e..3ee3010f5 100644 --- a/auth0/src/main/java/com/auth0/android/embedded/authorize/EmbeddedCapability.kt +++ b/auth0/src/main/java/com/auth0/android/embedded/authorize/EmbeddedCapability.kt @@ -10,6 +10,7 @@ public enum class EmbeddedCapability(public val value: String) { CHALLENGE_PUSH("action:challenge:push:v1"), VERIFY_OTP("action:verify:otp:v1"), VERIFY_PASSWORD("action:verify:password:v1"), + VERIFY_PASSKEY("action:verify:passkey:v1"), VERIFY_OOB("action:verify:oob:v1"), VERIFY_RECOVERY_CODE("action:verify:recovery-code:v1"), CONFIRM_RECOVERY_CODE("action:confirm:recovery-code:v1"), diff --git a/auth0/src/main/java/com/auth0/android/embedded/authorize/NextAction.kt b/auth0/src/main/java/com/auth0/android/embedded/authorize/NextAction.kt index 435ca9767..aa5f5809a 100644 --- a/auth0/src/main/java/com/auth0/android/embedded/authorize/NextAction.kt +++ b/auth0/src/main/java/com/auth0/android/embedded/authorize/NextAction.kt @@ -2,6 +2,7 @@ package com.auth0.android.embedded.authorize import com.auth0.android.embedded.EmbeddedAuthClient import com.auth0.android.embedded.EmbeddedAuthException +import com.auth0.android.embedded.passkey.PasskeyRequestOptions /** One way to continue the embedded authentication flow, as reported on [EmbeddedAuthException.nextActions]. */ public sealed interface NextAction { @@ -28,6 +29,25 @@ public sealed interface NextAction { override val capability: EmbeddedCapability = EmbeddedCapability.VERIFY_PASSWORD } + /** + * Continue by signing in with a passkey. Run the platform's passkey ceremony with [requestJson], then + * submit the result with [EmbeddedAuthClient.verifyPasskey]. + * + * [options] exposes the main WebAuthn options. [requestJson] is the complete options object the + * server sent, ready to use as the request JSON of a Credential Manager `GetPublicKeyCredentialOption`. + * The challenge is single-use: after a failed attempt the server offers a new [VerifyPasskey] with a + * fresh one. + */ + @ConsistentCopyVisibility + public data class VerifyPasskey internal constructor( + public val options: PasskeyRequestOptions, + public val requestJson: String + ) : NextAction { + override val capability: EmbeddedCapability = EmbeddedCapability.VERIFY_PASSKEY + + override fun toString(): String = "VerifyPasskey(options=$options)" + } + /** Continue by requesting an email challenge. Act on it with [EmbeddedAuthClient.challengeEmail]. */ @ConsistentCopyVisibility public data class ChallengeEmail internal constructor( diff --git a/auth0/src/main/java/com/auth0/android/embedded/authorize/NextActionMapper.kt b/auth0/src/main/java/com/auth0/android/embedded/authorize/NextActionMapper.kt index 361e6cca5..d5fdd367f 100644 --- a/auth0/src/main/java/com/auth0/android/embedded/authorize/NextActionMapper.kt +++ b/auth0/src/main/java/com/auth0/android/embedded/authorize/NextActionMapper.kt @@ -1,6 +1,9 @@ package com.auth0.android.embedded.authorize import android.util.Log +import com.auth0.android.embedded.passkey.PasskeyRequestOptions +import com.auth0.android.embedded.passkey.UserVerification +import com.auth0.android.request.internal.GsonProvider private const val TAG = "NextActionMapper" @@ -16,6 +19,13 @@ private const val IDENTIFIERS_KEY = "identifiers" private const val EMAIL_KEY = "email" private const val PHONE_NUMBER_KEY = "phone_number" private const val REQUIRED_KEY = "required" +private const val AUTHN_PARAMS_PUBLIC_KEY_KEY = "authn_params_public_key" +private const val CHALLENGE_KEY = "challenge" +private const val TIMEOUT_KEY = "timeout" +private const val RP_ID_KEY = "rpId" +private const val USER_VERIFICATION_KEY = "userVerification" +private const val HINTS_KEY = "hints" +private const val ALLOW_CREDENTIALS_KEY = "allowCredentials" internal fun List>.toNextActions(): List = mapNotNull { it.toNextAction() } @@ -26,6 +36,27 @@ private fun Map.toNextAction(): NextAction? { EmbeddedCapability.IDENTIFY_PHONE -> NextAction.IdentifyPhone EmbeddedCapability.IDENTIFY_USERNAME -> NextAction.IdentifyUsername EmbeddedCapability.VERIFY_PASSWORD -> NextAction.VerifyPassword + EmbeddedCapability.VERIFY_PASSKEY -> { + val params = this[AUTHN_PARAMS_PUBLIC_KEY_KEY] as? Map<*, *> + ?: return dropped(raw, AUTHN_PARAMS_PUBLIC_KEY_KEY) + val challenge = params[CHALLENGE_KEY] as? String + ?: return dropped(raw, "$AUTHN_PARAMS_PUBLIC_KEY_KEY.$CHALLENGE_KEY") + val timeout = params[TIMEOUT_KEY] as? Long + ?: return dropped(raw, "$AUTHN_PARAMS_PUBLIC_KEY_KEY.$TIMEOUT_KEY") + val rpId = params[RP_ID_KEY] as? String + ?: return dropped(raw, "$AUTHN_PARAMS_PUBLIC_KEY_KEY.$RP_ID_KEY") + val userVerification = UserVerification.fromValue(params[USER_VERIFICATION_KEY] as? String) + ?: return dropped(raw, "$AUTHN_PARAMS_PUBLIC_KEY_KEY.$USER_VERIFICATION_KEY") + val hints = (params[HINTS_KEY] as? List<*>)?.filterIsInstance().orEmpty() + val allowCredentials = (params[ALLOW_CREDENTIALS_KEY] as? List<*>) + ?.filterIsInstance>() + ?.map { it.toStringKeyedMap() } + .orEmpty() + NextAction.VerifyPasskey( + options = PasskeyRequestOptions(challenge, timeout, rpId, userVerification, hints, allowCredentials), + requestJson = GsonProvider.gson.toJson(params) + ) + } EmbeddedCapability.CHALLENGE_EMAIL -> { val index = (this[INDEX_KEY] as? Number)?.toInt() ?: return dropped(raw, INDEX_KEY) val identifier = this[IDENTIFIER_KEY] as? String ?: return dropped(raw, IDENTIFIER_KEY) @@ -95,6 +126,9 @@ private val SIGNUP_IDENTIFIER_TYPES: List> = listOf PHONE_NUMBER_KEY to IdentifierType.PHONE ) +private fun Map<*, *>.toStringKeyedMap(): Map = + entries.mapNotNull { (key, value) -> if (key is String && value != null) key to value else null }.toMap() + /** * Logs and drops a recognized next action whose required [field] the server omitted or sent * malformed. Returns `null` so the entry is filtered out by [toNextActions]. diff --git a/auth0/src/main/java/com/auth0/android/embedded/passkey/PasskeyAssertion.kt b/auth0/src/main/java/com/auth0/android/embedded/passkey/PasskeyAssertion.kt new file mode 100644 index 000000000..16f6be35b --- /dev/null +++ b/auth0/src/main/java/com/auth0/android/embedded/passkey/PasskeyAssertion.kt @@ -0,0 +1,90 @@ +package com.auth0.android.embedded.passkey + +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonParseException +import com.google.gson.JsonParser + +private const val ID_KEY = "id" +private const val RAW_ID_KEY = "rawId" +private const val TYPE_KEY = "type" +private const val RESPONSE_KEY = "response" +private const val CLIENT_DATA_JSON_KEY = "clientDataJSON" +private const val AUTHENTICATOR_DATA_KEY = "authenticatorData" +private const val SIGNATURE_KEY = "signature" +private const val USER_HANDLE_KEY = "userHandle" +private const val AUTHENTICATOR_ATTACHMENT_KEY = "authenticatorAttachment" +private const val CLIENT_EXTENSION_RESULTS_KEY = "clientExtensionResults" + +private const val PUBLIC_KEY_TYPE = "public-key" +private const val MAX_CREDENTIAL_ID_LENGTH = 1364 +private const val MAX_CLIENT_DATA_JSON_LENGTH = 1000 +private const val MAX_AUTHENTICATOR_DATA_LENGTH = 750 +private const val MAX_SIGNATURE_LENGTH = 750 +private const val MAX_USER_HANDLE_LENGTH = 100 + +private val AUTHENTICATOR_ATTACHMENTS = setOf("platform", "cross-platform") + +/** The assertion was rejected locally; the message names the field and never includes its value. */ +internal class InvalidPasskeyResponseException(message: String) : IllegalArgumentException(message) + +/** + * Builds the `authn_response` object from the `authenticationResponseJson` the platform returns, + * keeping only the fields `/e/authorize` accepts and enforcing its required fields, `type` value and + * length limits. `authenticatorAttachment` is kept only when it is a known value; + * `clientExtensionResults` is forwarded unchanged when it is an object. + * + * @throws InvalidPasskeyResponseException if the assertion doesn't satisfy the schema. + */ +internal fun passkeyAuthnResponse(authenticationResponseJson: String): Map { + val root = try { + JsonParser.parseString(authenticationResponseJson) + } catch (e: JsonParseException) { + throw InvalidPasskeyResponseException("The passkey response is not valid JSON.") + } + val assertion = root as? JsonObject + ?: throw InvalidPasskeyResponseException("The passkey response must be a JSON object.") + val response = (assertion.get(RESPONSE_KEY) as? JsonObject) + ?: throw InvalidPasskeyResponseException("The passkey response is missing \"$RESPONSE_KEY\".") + + val type = assertion.requiredString(TYPE_KEY, PUBLIC_KEY_TYPE.length) + if (type != PUBLIC_KEY_TYPE) { + throw InvalidPasskeyResponseException("The passkey response \"$TYPE_KEY\" must be \"$PUBLIC_KEY_TYPE\".") + } + + return buildMap { + put(ID_KEY, assertion.requiredString(ID_KEY, MAX_CREDENTIAL_ID_LENGTH)) + put(RAW_ID_KEY, assertion.requiredString(RAW_ID_KEY, MAX_CREDENTIAL_ID_LENGTH)) + put(TYPE_KEY, type) + put( + RESPONSE_KEY, + mapOf( + CLIENT_DATA_JSON_KEY to response.requiredString(CLIENT_DATA_JSON_KEY, MAX_CLIENT_DATA_JSON_LENGTH, "$RESPONSE_KEY."), + AUTHENTICATOR_DATA_KEY to response.requiredString(AUTHENTICATOR_DATA_KEY, MAX_AUTHENTICATOR_DATA_LENGTH, "$RESPONSE_KEY."), + SIGNATURE_KEY to response.requiredString(SIGNATURE_KEY, MAX_SIGNATURE_LENGTH, "$RESPONSE_KEY."), + USER_HANDLE_KEY to response.requiredString(USER_HANDLE_KEY, MAX_USER_HANDLE_LENGTH, "$RESPONSE_KEY.") + ) + ) + assertion.stringOrNull(AUTHENTICATOR_ATTACHMENT_KEY) + ?.takeIf { it in AUTHENTICATOR_ATTACHMENTS } + ?.let { put(AUTHENTICATOR_ATTACHMENT_KEY, it) } + (assertion.get(CLIENT_EXTENSION_RESULTS_KEY) as? JsonObject) + ?.let { put(CLIENT_EXTENSION_RESULTS_KEY, it) } + } +} + +private fun JsonObject.requiredString(key: String, maxLength: Int, path: String = ""): String { + val value = stringOrNull(key) + if (value.isNullOrEmpty()) { + throw InvalidPasskeyResponseException("The passkey response is missing \"$path$key\".") + } + if (value.length > maxLength) { + throw InvalidPasskeyResponseException("The passkey response \"$path$key\" is longer than $maxLength characters.") + } + return value +} + +private fun JsonObject.stringOrNull(key: String): String? { + val element: JsonElement = get(key) ?: return null + return if (element.isJsonPrimitive && element.asJsonPrimitive.isString) element.asString else null +} diff --git a/auth0/src/main/java/com/auth0/android/embedded/passkey/PasskeyRequestOptions.kt b/auth0/src/main/java/com/auth0/android/embedded/passkey/PasskeyRequestOptions.kt new file mode 100644 index 000000000..dcc363df9 --- /dev/null +++ b/auth0/src/main/java/com/auth0/android/embedded/passkey/PasskeyRequestOptions.kt @@ -0,0 +1,33 @@ +package com.auth0.android.embedded.passkey + +/** + * The options the server offers for a passkey sign-in, as sent on [NextAction.VerifyPasskey]. + */ +@ConsistentCopyVisibility +public data class PasskeyRequestOptions internal constructor( + /** The single-use, base64url-encoded challenge the authenticator signs. */ + public val challenge: String, + + /** How long, in milliseconds, the ceremony may take. */ + public val timeout: Long, + + /** The relying party identifier the passkey is scoped to. */ + public val rpId: String, + + /** Whether the authenticator must verify the user. */ + public val userVerification: UserVerification, + + /** Hints about which kind of authenticator to prefer, in order. Empty when the server sent none. */ + public val hints: List, + + /** + * The credentials the server restricts the ceremony to, each as the server sent it. Empty when the + * server sent none. The API doesn't define an entry's fields, so they are not modelled here. + */ + public val allowCredentials: List> +) { + + override fun toString(): String = + "PasskeyRequestOptions(challenge='xxxxx', timeout=$timeout, rpId='$rpId', " + + "userVerification=$userVerification, hints=$hints, allowCredentials=${allowCredentials.size} entries)" +} diff --git a/auth0/src/main/java/com/auth0/android/embedded/passkey/UserVerification.kt b/auth0/src/main/java/com/auth0/android/embedded/passkey/UserVerification.kt new file mode 100644 index 000000000..719e26d1a --- /dev/null +++ b/auth0/src/main/java/com/auth0/android/embedded/passkey/UserVerification.kt @@ -0,0 +1,17 @@ +package com.auth0.android.embedded.passkey + +/** How strongly the authenticator must verify the user during a passkey ceremony. */ +public enum class UserVerification(internal val value: String) { + /** The ceremony fails unless the authenticator verifies the user. */ + REQUIRED("required"), + + /** The authenticator verifies the user when it can. */ + PREFERRED("preferred"), + + /** The authenticator should not verify the user. */ + DISCOURAGED("discouraged"); + + internal companion object { + fun fromValue(value: String?): UserVerification? = entries.firstOrNull { it.value == value } + } +} diff --git a/auth0/src/test/java/com/auth0/android/embedded/EmbeddedAuthClientTest.kt b/auth0/src/test/java/com/auth0/android/embedded/EmbeddedAuthClientTest.kt index 4cd8a2839..b15cd3068 100644 --- a/auth0/src/test/java/com/auth0/android/embedded/EmbeddedAuthClientTest.kt +++ b/auth0/src/test/java/com/auth0/android/embedded/EmbeddedAuthClientTest.kt @@ -10,11 +10,13 @@ import com.auth0.android.embedded.authorize.OtpType import com.auth0.android.embedded.authorize.PhoneDeliveryMethod import com.auth0.android.embedded.authorize.SignupIdentifier import com.auth0.android.embedded.authorize.embeddedAuthErrorAdapter +import com.auth0.android.embedded.passkey.UserVerification import com.auth0.android.util.EmbeddedAuthMockServer import com.auth0.android.util.SSLTestUtils.testClient import kotlinx.coroutines.test.runTest import okhttp3.mockwebserver.RecordedRequest import org.hamcrest.MatcherAssert.assertThat +import org.hamcrest.Matchers.containsString import org.hamcrest.Matchers.empty import org.hamcrest.Matchers.not import org.hamcrest.Matchers.hasSize @@ -120,7 +122,8 @@ public class EmbeddedAuthClientTest { "action:verify:recovery-code:v1", "action:confirm:recovery-code:v1", "action:signup:v1", - "action:signup:confirm:v1" + "action:signup:confirm:v1", + "action:verify:passkey:v1" ) ) ) @@ -1638,6 +1641,108 @@ public class EmbeddedAuthClientTest { assertThat(followOn.error, `is`(EmbeddedAuthError.NoActiveSession)) } + // ── verifyPasskey ──────────────────────────────────────────────────────────── + + @Test + public fun `authorize surfaces the passkey offer next to the other first factors`(): Unit = runTest { + mockAPI.willReturnContinuationWith( + EmbeddedAuthMockServer.NEXT_IDENTIFY_EMAIL, + EmbeddedAuthMockServer.NEXT_VERIFY_PASSKEY + ) + + val error = assertEmbeddedErrorSuspending { + client.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION).await() + } + + val offer = error.nextActions[1] as NextAction.VerifyPasskey + assertThat(error.nextActions[0], `is`(NextAction.IdentifyEmail as NextAction)) + assertThat(offer.options.challenge, `is`("Y2hhbGxlbmdl")) + assertThat(offer.options.timeout, `is`(900000L)) + assertThat(offer.options.rpId, `is`("login.example.com")) + assertThat(offer.options.userVerification, `is`(UserVerification.PREFERRED)) + val requestJson = JSONObject(offer.requestJson) + assertThat(requestJson.getString("challenge"), `is`("Y2hhbGxlbmdl")) + assertThat(offer.requestJson, containsString("\"timeout\":900000")) + assertThat(offer.requestJson, not(containsString("900000.0"))) + } + + @Test + public fun `verifyPasskey await POSTs exactly the schema fields and returns credentials`(): Unit = runTest { + establishSession() + mockAPI.willReturnAuthorizeCode() + mockAPI.willReturnTokens() + + val credentials = client.verifyPasskey(passkeyAssertion()).await() + + assertThat(credentials.accessToken, `is`(EmbeddedAuthMockServer.ACCESS_TOKEN)) + val authorize = mockAPI.takeRequest() + assertThat(authorize.requestUrl?.encodedPath, `is`("/e/authorize")) + val body = bodyOf(authorize) + assertThat(body.keys().asSequence().toSet(), `is`(setOf("auth_session", "action", "client_id", "authn_response"))) + assertThat(body.getString("auth_session"), `is`(EmbeddedAuthMockServer.AUTH_SESSION)) + assertThat(body.getString("action"), `is`("action:verify:passkey:v1")) + assertThat(body.getString("client_id"), `is`(CLIENT_ID)) + val response = body.getJSONObject("authn_response") + assertThat( + response.keys().asSequence().toSet(), + `is`(setOf("id", "rawId", "type", "response", "authenticatorAttachment", "clientExtensionResults")) + ) + assertThat(response.getString("id"), `is`("credential-id")) + assertThat(response.getString("type"), `is`("public-key")) + assertThat(response.getString("authenticatorAttachment"), `is`("platform")) + assertThat(response.getJSONObject("clientExtensionResults").getJSONObject("credProps").getBoolean("rk"), `is`(true)) + val inner = response.getJSONObject("response") + assertThat( + inner.keys().asSequence().toSet(), + `is`(setOf("clientDataJSON", "authenticatorData", "signature", "userHandle")) + ) + assertThat(inner.getString("userHandle"), `is`("user-handle")) + assertThat(mockAPI.takeRequest().requestUrl?.encodedPath, `is`("/oauth/token")) + + val followOn = assertEmbeddedErrorSuspending { client.verifyPasskey(passkeyAssertion()).await() } + assertThat(followOn.error, `is`(EmbeddedAuthError.NoActiveSession)) + } + + @Test + public fun `verifyPasskey await rejects an invalid assertion without sending a request and keeps the session`(): Unit = runTest { + establishSession() + val sentBefore = mockAPI.server.requestCount + + val error = assertEmbeddedErrorSuspending { client.verifyPasskey("""{"id":"a"}""").await() } + + assertThat(error.error, `is`(EmbeddedAuthError.InvalidInput)) + assertThat(error.code, `is`("invalid_input")) + assertThat(error.statusCode, `is`(0)) + assertThat(mockAPI.server.requestCount, `is`(sentBefore)) + + mockAPI.willReturnAuthorizeCode() + mockAPI.willReturnTokens() + client.verifyPasskey(passkeyAssertion()).await() + + assertThat(bodyOf(mockAPI.takeRequest()).getString("auth_session"), `is`(EmbeddedAuthMockServer.AUTH_SESSION)) + } + + @Test + public fun `verifyPasskey await surfaces invalid_passkey with a fresh offer and rotates the session`(): Unit = runTest { + establishSession() + mockAPI.willReturnInvalidPasskey() + + val error = assertEmbeddedErrorSuspending { client.verifyPasskey(passkeyAssertion()).await() } + mockAPI.takeRequest() + + val pending = error.error as EmbeddedAuthError.InsufficientAuthorization + assertThat(pending.reason, `is`(EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_PASSKEY)) + val offer = pending.nextActions[0] as NextAction.VerifyPasskey + assertThat(offer.options.challenge, `is`("ZnJlc2g")) + + mockAPI.willReturnAuthorizeCode() + mockAPI.willReturnTokens() + val credentials = client.verifyPasskey(passkeyAssertion()).await() + + assertThat(credentials.accessToken, `is`(EmbeddedAuthMockServer.ACCESS_TOKEN)) + assertThat(bodyOf(mockAPI.takeRequest()).getString("auth_session"), `is`(EmbeddedAuthMockServer.ROTATED_AUTH_SESSION)) + } + // ── Session preservation on MFA errors ─────────────────────────────────────── @Test @@ -1752,6 +1857,23 @@ public class EmbeddedAuthClientTest { return error!! } + private fun passkeyAssertion( + attachment: String? = "platform", + extensions: String? = """{"credProps":{"rk":true}}""", + userHandle: String? = "user-handle", + extraTop: String = "", + extraResponse: String = "" + ): String = buildString { + append("""{"id":"credential-id","rawId":"credential-raw-id","type":"public-key"""") + attachment?.let { append(""","authenticatorAttachment":"$it"""") } + extensions?.let { append(""","clientExtensionResults":$it""") } + append(extraTop) + append(""","response":{"clientDataJSON":"client-data","authenticatorData":"authenticator-data","signature":"the-signature"""") + userHandle?.let { append(""","userHandle":"$it"""") } + append(extraResponse) + append("}}") + } + private fun bodyOf(request: RecordedRequest): JSONObject = JSONObject(request.body.readUtf8()) diff --git a/auth0/src/test/java/com/auth0/android/embedded/authorize/NextActionMapperTest.kt b/auth0/src/test/java/com/auth0/android/embedded/authorize/NextActionMapperTest.kt index 656448c82..b482e1bd7 100644 --- a/auth0/src/test/java/com/auth0/android/embedded/authorize/NextActionMapperTest.kt +++ b/auth0/src/test/java/com/auth0/android/embedded/authorize/NextActionMapperTest.kt @@ -1,6 +1,12 @@ package com.auth0.android.embedded.authorize +import com.auth0.android.embedded.passkey.UserVerification +import com.google.gson.GsonBuilder +import com.google.gson.ToNumberPolicy +import com.google.gson.reflect.TypeToken import org.hamcrest.MatcherAssert.assertThat +import org.hamcrest.Matchers.containsString +import org.hamcrest.Matchers.not import org.hamcrest.Matchers.`is` import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.instanceOf @@ -179,4 +185,158 @@ public class NextActionMapperTest { action as NextAction.ConfirmRecoveryCode assertThat(action.newCode, `is`("NEW-CODE-123")) } + + @Test + public fun testVerifyPasskeyMapped() { + val action = passkeyOffer( + """{"challenge":"Y2hhbGxlbmdl","timeout":900000,"userVerification":"required","rpId":"login.example.com","hints":["client-device","hybrid"],"allowCredentials":[{"type":"public-key","id":"abc","transports":["internal"]},{"type":"public-key","id":"def"}]}""" + ).toNextActions().first() + + assertThat(action, instanceOf(NextAction.VerifyPasskey::class.java)) + action as NextAction.VerifyPasskey + assertThat(action.capability, `is`(EmbeddedCapability.VERIFY_PASSKEY)) + assertThat(action.options.challenge, `is`("Y2hhbGxlbmdl")) + assertThat(action.options.timeout, `is`(900000L)) + assertThat(action.options.rpId, `is`("login.example.com")) + assertThat(action.options.userVerification, `is`(UserVerification.REQUIRED)) + assertThat(action.options.hints, `is`(listOf("client-device", "hybrid"))) + assertThat( + action.options.allowCredentials, + `is`( + listOf( + mapOf("type" to "public-key", "id" to "abc", "transports" to listOf("internal")), + mapOf("type" to "public-key", "id" to "def") + ) + ) + ) + } + + @Test + public fun testVerifyPasskeyMapsEachUserVerificationValue() { + val expected = mapOf( + "required" to UserVerification.REQUIRED, + "preferred" to UserVerification.PREFERRED, + "discouraged" to UserVerification.DISCOURAGED + ) + for ((value, verification) in expected) { + val action = passkeyOffer( + """{"challenge":"c","timeout":1,"userVerification":"$value","rpId":"r"}""" + ).toNextActions().first() as NextAction.VerifyPasskey + assertThat(action.options.userVerification, `is`(verification)) + } + } + + @Test + public fun testVerifyPasskeyHintsAndAllowCredentialsDefaultToEmpty() { + val action = passkeyOffer( + """{"challenge":"c","timeout":1,"userVerification":"preferred","rpId":"r"}""" + ).toNextActions().first() as NextAction.VerifyPasskey + + assertThat(action.options.hints, `is`(emptyList())) + assertThat(action.options.allowCredentials, `is`(emptyList())) + } + + @Test + public fun testVerifyPasskeyRequestJsonKeepsEveryServerFieldAndIntegers() { + val action = passkeyOffer( + """{"challenge":"c","timeout":900000,"userVerification":"preferred","rpId":"r","hints":["hybrid"],"allowCredentials":[{"type":"public-key","id":"abc","transports":["internal"]}],"extensions":{"credProps":true,"count":3,"ratio":1.5}}""" + ).toNextActions().first() as NextAction.VerifyPasskey + + assertThat( + action.requestJson, + `is`( + """{"challenge":"c","timeout":900000,"userVerification":"preferred","rpId":"r","hints":["hybrid"],"allowCredentials":[{"type":"public-key","id":"abc","transports":["internal"]}],"extensions":{"credProps":true,"count":3,"ratio":1.5}}""" + ) + ) + assertThat(action.requestJson, not(containsString("900000.0"))) + } + + @Test + public fun testVerifyPasskeyDroppedWithoutAuthnParams() { + assertThat(listOf(mapOf(ACTION_KEY to "action:verify:passkey:v1")).toNextActions().isEmpty(), `is`(true)) + assertThat( + listOf(mapOf(ACTION_KEY to "action:verify:passkey:v1", "authn_params_public_key" to "text")).toNextActions().isEmpty(), + `is`(true) + ) + } + + @Test + public fun testVerifyPasskeyDroppedWhenARequiredFieldIsMissing() { + val complete = mapOf( + "challenge" to "c", + "timeout" to 1, + "userVerification" to "preferred", + "rpId" to "r" + ) + for (field in complete.keys) { + val offer = mapOf( + ACTION_KEY to "action:verify:passkey:v1", + "authn_params_public_key" to (complete - field) + ) + assertThat("without $field", listOf(offer).toNextActions().isEmpty(), `is`(true)) + } + } + + @Test + public fun testVerifyPasskeyDroppedWhenAFieldHasTheWrongType() { + val invalid = listOf( + """{"challenge":1,"timeout":1,"userVerification":"preferred","rpId":"r"}""", + """{"challenge":"c","timeout":"900000","userVerification":"preferred","rpId":"r"}""", + """{"challenge":"c","timeout":1.5,"userVerification":"preferred","rpId":"r"}""", + """{"challenge":"c","timeout":1,"userVerification":"preferred","rpId":2}""", + """{"challenge":"c","timeout":1,"userVerification":"always","rpId":"r"}""", + """{"challenge":"c","timeout":1,"userVerification":1,"rpId":"r"}""" + ) + for (params in invalid) { + assertThat(params, passkeyOffer(params).toNextActions().isEmpty(), `is`(true)) + } + } + + @Test + public fun testVerifyPasskeyKeepsTheOfferWhenOptionalFieldsHaveTheWrongType() { + val action = passkeyOffer( + """{"challenge":"c","timeout":1,"userVerification":"preferred","rpId":"r","hints":"hybrid","allowCredentials":"abc"}""" + ).toNextActions().first() as NextAction.VerifyPasskey + + assertThat(action.options.hints, `is`(emptyList())) + assertThat(action.options.allowCredentials, `is`(emptyList())) + } + + @Test + public fun testVerifyPasskeySkipsInvalidEntriesInTheOptionalLists() { + val action = passkeyOffer( + """{"challenge":"c","timeout":1,"userVerification":"preferred","rpId":"r","hints":["hybrid",1,null,"client-device"],"allowCredentials":[{"id":"x"},"text",5,null,{"id":"y","extra":null}]}""" + ).toNextActions().first() as NextAction.VerifyPasskey + + assertThat(action.options.hints, `is`(listOf("hybrid", "client-device"))) + assertThat(action.options.allowCredentials, `is`(listOf(mapOf("id" to "x"), mapOf("id" to "y")))) + } + + @Test + public fun testVerifyPasskeyKeepsTheOfferAndPassesOnFieldsItDoesNotModel() { + val action = passkeyOffer( + """{"challenge":"c","timeout":1,"userVerification":"preferred","rpId":"r","futureField":"value"}""" + ).toNextActions().first() as NextAction.VerifyPasskey + + assertThat(action.requestJson, containsString("\"futureField\":\"value\"")) + } + + @Test + public fun testVerifyPasskeyToStringHidesTheChallenge() { + val action = passkeyOffer( + """{"challenge":"SECRET-CHALLENGE","timeout":1,"userVerification":"preferred","rpId":"r"}""" + ).toNextActions().first() as NextAction.VerifyPasskey + + assertThat(action.options.toString(), not(containsString("SECRET-CHALLENGE"))) + assertThat(action.toString(), not(containsString("SECRET-CHALLENGE"))) + } + + /** Parses [authnParams] the way the SDK does, so whole JSON numbers arrive as `Long`. */ + private fun passkeyOffer(authnParams: String): List> { + val raw: Map = GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE).create().fromJson( + """{"action":"action:verify:passkey:v1","authn_params_public_key":$authnParams}""", + object : TypeToken>() {}.type + ) + return listOf(raw) + } } diff --git a/auth0/src/test/java/com/auth0/android/embedded/passkey/PasskeyAssertionTest.kt b/auth0/src/test/java/com/auth0/android/embedded/passkey/PasskeyAssertionTest.kt new file mode 100644 index 000000000..2e96c6577 --- /dev/null +++ b/auth0/src/test/java/com/auth0/android/embedded/passkey/PasskeyAssertionTest.kt @@ -0,0 +1,211 @@ +package com.auth0.android.embedded.passkey + +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import org.hamcrest.MatcherAssert.assertThat +import org.hamcrest.Matchers.containsString +import org.hamcrest.Matchers.`is` +import org.hamcrest.Matchers.not +import org.junit.Assert.fail +import org.junit.Test + +public class PasskeyAssertionTest { + + private val validAssertion = """ + { + "id": "credential-id", + "rawId": "credential-raw-id", + "type": "public-key", + "authenticatorAttachment": "platform", + "clientExtensionResults": {}, + "response": { + "clientDataJSON": "client-data", + "authenticatorData": "authenticator-data", + "signature": "the-signature", + "userHandle": "user-handle" + } + } + """.trimIndent() + + @Test + public fun `builds authn_response with exactly the allowed fields`() { + val result = passkeyAuthnResponse(validAssertion) + + assertThat( + result.keys, + `is`(setOf("id", "rawId", "type", "response", "authenticatorAttachment", "clientExtensionResults")) + ) + assertThat(result["id"], `is`("credential-id")) + assertThat(result["rawId"], `is`("credential-raw-id")) + assertThat(result["type"], `is`("public-key")) + @Suppress("UNCHECKED_CAST") + val response = result["response"] as Map + assertThat(response.keys, `is`(setOf("clientDataJSON", "authenticatorData", "signature", "userHandle"))) + assertThat(response["clientDataJSON"], `is`("client-data")) + assertThat(response["authenticatorData"], `is`("authenticator-data")) + assertThat(response["signature"], `is`("the-signature")) + assertThat(response["userHandle"], `is`("user-handle")) + } + + @Test + public fun `drops fields the schema does not allow`() { + val input = edit { + addProperty("unexpected", "value") + getAsJsonObject("response").apply { + addProperty("attestationObject", "attestation") + add("transports", JsonParser.parseString("""["internal"]""")) + addProperty("other", "value") + } + } + + val result = passkeyAuthnResponse(input) + + assertThat(result.containsKey("unexpected"), `is`(false)) + @Suppress("UNCHECKED_CAST") + val response = result["response"] as Map + assertThat(response.keys, `is`(setOf("clientDataJSON", "authenticatorData", "signature", "userHandle"))) + } + + @Test + public fun `keeps platform and cross-platform authenticatorAttachment`() { + for (attachment in listOf("platform", "cross-platform")) { + val result = passkeyAuthnResponse(edit { addProperty("authenticatorAttachment", attachment) }) + assertThat(result["authenticatorAttachment"], `is`(attachment)) + } + } + + @Test + public fun `leaves out authenticatorAttachment when missing, unknown, null or not a string`() { + val variants = listOf Unit>( + { remove("authenticatorAttachment") }, + { addProperty("authenticatorAttachment", "hybrid") }, + { add("authenticatorAttachment", com.google.gson.JsonNull.INSTANCE) }, + { addProperty("authenticatorAttachment", 1) } + ) + for (variant in variants) { + val result = passkeyAuthnResponse(edit(variant)) + assertThat(result.containsKey("authenticatorAttachment"), `is`(false)) + } + } + + @Test + public fun `keeps clientExtensionResults when it is an object`() { + val result = passkeyAuthnResponse( + edit { add("clientExtensionResults", JsonParser.parseString("""{"credProps":{"rk":true}}""")) } + ) + + assertThat(result["clientExtensionResults"].toString(), `is`("""{"credProps":{"rk":true}}""")) + } + + @Test + public fun `leaves out clientExtensionResults when missing or not an object`() { + val variants = listOf Unit>( + { remove("clientExtensionResults") }, + { add("clientExtensionResults", com.google.gson.JsonNull.INSTANCE) }, + { add("clientExtensionResults", JsonParser.parseString("[1]")) }, + { addProperty("clientExtensionResults", "x") } + ) + for (variant in variants) { + val result = passkeyAuthnResponse(edit(variant)) + assertThat(result.containsKey("clientExtensionResults"), `is`(false)) + } + } + + @Test + public fun `rejects input that is not a JSON object`() { + for (input in listOf("", " ", "null", "[1]", "\"text\"", "not json", """{"id":"a"} trailing""")) { + assertRejected(input) + } + } + + @Test + public fun `rejects a missing or non-object response`() { + assertRejected(edit { remove("response") }, "response") + assertRejected(edit { addProperty("response", "x") }, "response") + assertRejected(edit { add("response", JsonParser.parseString("[]")) }, "response") + } + + @Test + public fun `rejects each required field that is missing, empty, not a string or null`() { + val topLevel = listOf("id", "rawId", "type") + for (field in topLevel) { + assertRejected(edit { remove(field) }, field) + assertRejected(edit { addProperty(field, "") }, field) + assertRejected(edit { addProperty(field, 1) }, field) + assertRejected(edit { add(field, com.google.gson.JsonNull.INSTANCE) }, field) + } + for (field in RESPONSE_LIMITS.keys) { + assertRejected(edit { getAsJsonObject("response").remove(field) }, "response.$field") + assertRejected(edit { getAsJsonObject("response").addProperty(field, "") }, "response.$field") + assertRejected(edit { getAsJsonObject("response").addProperty(field, 1) }, "response.$field") + assertRejected( + edit { getAsJsonObject("response").add(field, com.google.gson.JsonNull.INSTANCE) }, + "response.$field" + ) + } + } + + @Test + public fun `rejects a type other than public-key`() { + assertRejected(edit { addProperty("type", "other") }, "type") + } + + @Test + public fun `accepts every field at its maximum length`() { + for (field in listOf("id", "rawId")) { + passkeyAuthnResponse(edit { addProperty(field, "a".repeat(1364)) }) + } + for ((field, max) in RESPONSE_LIMITS) { + passkeyAuthnResponse(edit { getAsJsonObject("response").addProperty(field, "a".repeat(max)) }) + } + } + + @Test + public fun `rejects every field one character over its maximum length`() { + for (field in listOf("id", "rawId")) { + assertRejected(edit { addProperty(field, "a".repeat(1365)) }, field) + } + for ((field, max) in RESPONSE_LIMITS) { + assertRejected( + edit { getAsJsonObject("response").addProperty(field, "a".repeat(max + 1)) }, + "response.$field" + ) + } + } + + @Test + public fun `error messages never include the rejected value`() { + val secret = "SECRET-VALUE-" + "a".repeat(1400) + + val tooLong = assertRejected(edit { addProperty("id", secret) }, "id") + val wrongType = assertRejected(edit { addProperty("type", "SECRET-TYPE") }, "type") + + assertThat(tooLong.message, not(containsString("SECRET-VALUE"))) + assertThat(wrongType.message, not(containsString("SECRET-TYPE"))) + } + + private fun edit(change: JsonObject.() -> Unit): String = + JsonParser.parseString(validAssertion).asJsonObject.apply(change).toString() + + private fun assertRejected(input: String, field: String? = null): InvalidPasskeyResponseException { + try { + passkeyAuthnResponse(input) + } catch (e: InvalidPasskeyResponseException) { + if (field != null) { + assertThat(e.message, containsString("\"$field\"")) + } + return e + } + fail("expected InvalidPasskeyResponseException") + throw AssertionError() + } + + private companion object { + private val RESPONSE_LIMITS = mapOf( + "clientDataJSON" to 1000, + "authenticatorData" to 750, + "signature" to 750, + "userHandle" to 100 + ) + } +} diff --git a/auth0/src/test/java/com/auth0/android/util/EmbeddedAuthMockServer.kt b/auth0/src/test/java/com/auth0/android/util/EmbeddedAuthMockServer.kt index a93376706..fa90bade5 100644 --- a/auth0/src/test/java/com/auth0/android/util/EmbeddedAuthMockServer.kt +++ b/auth0/src/test/java/com/auth0/android/util/EmbeddedAuthMockServer.kt @@ -84,6 +84,17 @@ $actionsJson return this } + /** The recoverable `403` after a rejected passkey: rotated session and a fresh passkey offer. */ + fun willReturnInvalidPasskey(): EmbeddedAuthMockServer { + server.enqueue( + responseWithJSON( + """{ "error": "insufficient_authorization", "error_description": "invalid_passkey", "auth_session": "$ROTATED_AUTH_SESSION", "next": [ $NEXT_VERIFY_PASSKEY_FRESH ] }""", + 403 + ) + ) + return this + } + fun willReturnTooManyWrongOtpAttempts(): EmbeddedAuthMockServer { server.enqueue(responseWithJSON("""{ "error": "access_denied", "error_description": "too_many_wrong_otp_attempts" }""", 403)) return this @@ -207,6 +218,8 @@ $actionsJson const val NEXT_SIGNUP_PHONE_NO_REQUIRED = """{ "action": "action:signup:v1", "identifiers": { "email": { "required": true }, "phone_number": {} } }""" const val NEXT_SIGNUP_EMAIL_NON_BOOLEAN_REQUIRED = """{ "action": "action:signup:v1", "identifiers": { "email": { "required": "true" }, "phone_number": { "required": false } } }""" const val NEXT_CONFIRM_SIGNUP = """{ "action": "action:signup:confirm:v1" }""" + const val NEXT_VERIFY_PASSKEY = """{ "action": "action:verify:passkey:v1", "authn_params_public_key": { "challenge": "Y2hhbGxlbmdl", "timeout": 900000, "userVerification": "preferred", "rpId": "login.example.com" } }""" + const val NEXT_VERIFY_PASSKEY_FRESH = """{ "action": "action:verify:passkey:v1", "authn_params_public_key": { "challenge": "ZnJlc2g", "timeout": 900000, "userVerification": "preferred", "rpId": "login.example.com" } }""" const val NEXT_UNKNOWN = """{ "action": "action:future:unknown:v1" }""" const val IDENTIFIER = "jane@example.com" const val AUTHORIZATION_CODE = "the-authorization-code" diff --git a/examples/embedded-auth/authorize.md b/examples/embedded-auth/authorize.md index cf14bc99c..34658ba79 100644 --- a/examples/embedded-auth/authorize.md +++ b/examples/embedded-auth/authorize.md @@ -62,6 +62,7 @@ if (error is EmbeddedAuthError.InsufficientAuthorization) { is NextAction.IdentifyPhone -> { /* show phone field, call identify(..., PHONE) */ } is NextAction.IdentifyUsername -> { /* show username field, call identify(..., USERNAME) */ } is NextAction.VerifyPassword -> { /* show password field, call verifyPassword() */ } + is NextAction.VerifyPasskey -> { /* run the passkey ceremony with action.requestJson, call verifyPasskey() */ } is NextAction.ChallengeEmail -> { /* send email code, call challengeEmail(action.index) */ } is NextAction.ChallengePhone -> { /* send SMS/voice code, call challengePhone(action.index, ...) */ } is NextAction.ChallengePush -> { /* trigger push, call challengePush(action.index) */ } @@ -75,7 +76,7 @@ if (error is EmbeddedAuthError.InsufficientAuthorization) { } ``` -See the dedicated examples for each factor: [Username & Password](password-authorize.md), [Phone OTP (SMS/Voice)](phone-authorize.md), [Push (OOB)](push-oob-polling.md), [TOTP](totp.md), and [Recovery Code](recovery-code.md). +See the dedicated examples for each factor: [Username & Password](password-authorize.md), [Passkey](passkey.md), [Phone OTP (SMS/Voice)](phone-authorize.md), [Push (OOB)](push-oob-polling.md), [TOTP](totp.md), and [Recovery Code](recovery-code.md). #### Identify the user diff --git a/examples/embedded-auth/passkey.md b/examples/embedded-auth/passkey.md new file mode 100644 index 000000000..d0847ff2c --- /dev/null +++ b/examples/embedded-auth/passkey.md @@ -0,0 +1,124 @@ +# Passkey — first factor + +Sign the user in with a passkey in the same `/e/authorize` flow used for the other first factors. +The sequence is `authorize` → platform passkey prompt → `verifyPasskey` (see +[authorize.md](authorize.md) for the next-action pattern). There is no identify step: the passkey +identifies the user. + +`authorize` completes by throwing an `EmbeddedAuthException` whose `error` is +`EmbeddedAuthError.InsufficientAuthorization`. When passkeys are available, its `nextActions` include a +`NextAction.VerifyPasskey` next to the other first factors. It carries the WebAuthn options as +`requestJson`, which you pass unchanged to the platform. `verifyPasskey` then returns `Credentials`. + +## Requirements + +- Passkeys are enabled on the connection, and the request is made on a [custom domain](https://auth0.com/docs/customize/custom-domains). Otherwise the server doesn't offer `VerifyPasskey`. +- Android 9 (API 28) or later, which Credential Manager requires. `authorize` asks for passkeys by default, so on earlier versions pass a `capabilities` set that leaves out `EmbeddedCapability.VERIFY_PASSKEY`. +- The user signs in with a **discoverable** passkey, one that stores the user handle. A response without a `userHandle` is rejected with `EmbeddedAuthError.InvalidInput`. +- Your app uses [Credential Manager](https://developer.android.com/identity/sign-in/credential-manager) to run the passkey ceremony. The SDK doesn't depend on it, so add it yourself: + +```groovy +dependencies { + implementation "androidx.credentials:credentials:1.3.0" + implementation "androidx.credentials:credentials-play-services-auth:1.3.0" +} +``` + +To keep passkeys out of your app, pass a `capabilities` set to `authorize` that leaves out +`EmbeddedCapability.VERIFY_PASSKEY`. + +```kotlin +val embedded = EmbeddedAuthClient(Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN")) + +// 1. Start the flow. When passkeys are available, the next actions include NextAction.VerifyPasskey. +val passkey = try { + embedded.authorize("Username-Password-Authentication").await() + null +} catch (e: EmbeddedAuthException) { + val nextActions = (e.error as? EmbeddedAuthError.InsufficientAuthorization)?.nextActions ?: throw e + nextActions.filterIsInstance().firstOrNull() +} +// passkey == null: passkeys aren't offered; show the other first factors. + +// 2. Run the passkey ceremony with the server's options, unchanged. +val assertionJson = try { + val result = CredentialManager.create(context).getCredential( + context, + GetCredentialRequest(listOf(GetPublicKeyCredentialOption(passkey.requestJson))) + ) + (result.credential as PublicKeyCredential).authenticationResponseJson +} catch (e: GetCredentialCancellationException) { + /* the user dismissed the sheet — nothing changed, offer it again or another option */ + return +} catch (e: NoCredentialException) { + /* no passkey for this site on the device — offer the other first factors */ + return +} + +// 3. Submit the assertion. Returns Credentials. +try { + val credentials = embedded.verifyPasskey(assertionJson).await() + // credentials.accessToken, credentials.idToken, ... +} catch (e: EmbeddedAuthException) { + when (val error = e.error) { + is EmbeddedAuthError.InsufficientAuthorization -> { + if (error.reason == EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_PASSKEY) { + /* rejected: error.nextActions has a new NextAction.VerifyPasskey with a fresh challenge — repeat step 2 with it */ + } + /* otherwise the tenant requires MFA — continue with error.nextActions */ + } + EmbeddedAuthError.InvalidInput -> { /* the assertion was malformed; nothing was sent and the flow is unchanged */ } + EmbeddedAuthError.Network -> { /* the request never reached the server — retry verifyPasskey */ } + else -> { /* other terminal error — restart with authorize() */ } + } +} +``` + +## Options + +`NextAction.VerifyPasskey` exposes the options the server sent: + +| Property | Description | +| --- | --- | +| `requestJson` | The complete options object, ready for `GetPublicKeyCredentialOption`. Use this to run the ceremony. | +| `options.challenge` | The single-use challenge. | +| `options.timeout` | How long, in milliseconds, the ceremony may take. | +| `options.rpId` | The relying party the passkey is scoped to. | +| `options.userVerification` | `REQUIRED`, `PREFERRED` or `DISCOURAGED`. | +| `options.hints` | Preferred authenticator hints. Empty when the server sent none. | +| `options.allowCredentials` | The credentials the server restricts the ceremony to, each as the server sent it. Empty when the server sent none. | + +Each challenge works once. After a rejected passkey, use the new `VerifyPasskey` from the error's +`nextActions`; don't reuse the previous `requestJson`. + +
+ Using callbacks + +```kotlin +embedded.verifyPasskey(assertionJson) + .start(object : Callback { + override fun onSuccess(result: Credentials) { /* signed in */ } + override fun onFailure(error: EmbeddedAuthException) { /* branch on error.error as in the coroutine sample */ } + }) +``` +
+ +
+ Using Java + +```java +Auth0 auth0 = Auth0.getInstance("YOUR_CLIENT_ID", "YOUR_DOMAIN"); +EmbeddedAuthClient embedded = new EmbeddedAuthClient(auth0); + +// assertionJson is PublicKeyCredential.getAuthenticationResponseJson() from Credential Manager. +embedded.verifyPasskey(assertionJson) + .start(new Callback() { + @Override public void onSuccess(Credentials credentials) { + // credentials.getAccessToken() + } + @Override public void onFailure(@NonNull EmbeddedAuthException e) { + // branch on e.getError() as in the coroutine sample + } + }); +``` +
diff --git a/sample-embedded/build.gradle b/sample-embedded/build.gradle index 45826c5c5..c9ff9c009 100644 --- a/sample-embedded/build.gradle +++ b/sample-embedded/build.gradle @@ -65,4 +65,7 @@ dependencies { implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.8.6' implementation 'androidx.lifecycle:lifecycle-runtime-compose:2.8.6' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.6' + + implementation 'androidx.credentials:credentials:1.3.0' + implementation 'androidx.credentials:credentials-play-services-auth:1.3.0' } diff --git a/sample-embedded/src/main/java/com/auth0/sample/embedded/AuthorizeScreen.kt b/sample-embedded/src/main/java/com/auth0/sample/embedded/AuthorizeScreen.kt index 6f1bf97e0..bd30d441e 100644 --- a/sample-embedded/src/main/java/com/auth0/sample/embedded/AuthorizeScreen.kt +++ b/sample-embedded/src/main/java/com/auth0/sample/embedded/AuthorizeScreen.kt @@ -197,6 +197,12 @@ private fun ActionsSection( onVerify = { viewModel.verifyPassword(it) }, ) + is NextAction.VerifyPasskey -> PasskeyCard( + rpId = action.options.rpId, + requestJson = action.requestJson, + onAssertion = { viewModel.verifyPasskey(it) }, + ) + is NextAction.ChallengeEmail -> ChallengeEmailCard( identifier = action.identifier, onChallenge = { viewModel.challengeEmail(action.index) }, @@ -561,6 +567,7 @@ private fun explain(error: EmbeddedAuthError): String = when (error) { EmbeddedAuthError.TooManyLogins, EmbeddedAuthError.IpBlocked -> "Rate limited — try again later." EmbeddedAuthError.Network -> "The request didn't reach the server — check your connection and retry." + EmbeddedAuthError.InvalidInput -> "The input was rejected before it was sent — start over." else -> "Authorize step failed." } @@ -568,5 +575,6 @@ private fun EmbeddedAuthError.InsufficientAuthorization.Reason.messageRes(): Int EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_IDENTIFIER_OR_PASSWORD -> R.string.error_invalid_identifier_or_password EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_CODE -> R.string.error_invalid_code EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_IDENTIFIER_OR_CODE -> R.string.error_invalid_identifier_or_code + EmbeddedAuthError.InsufficientAuthorization.Reason.INVALID_PASSKEY -> R.string.error_invalid_passkey else -> null } diff --git a/sample-embedded/src/main/java/com/auth0/sample/embedded/EmbeddedViewModel.kt b/sample-embedded/src/main/java/com/auth0/sample/embedded/EmbeddedViewModel.kt index e3a5c4f33..97aa2a549 100644 --- a/sample-embedded/src/main/java/com/auth0/sample/embedded/EmbeddedViewModel.kt +++ b/sample-embedded/src/main/java/com/auth0/sample/embedded/EmbeddedViewModel.kt @@ -75,6 +75,13 @@ class EmbeddedViewModel(application: Application) : AndroidViewModel(application /** Terminal step: yields credentials, or continues if the server requires a second factor. */ fun verifyPassword(password: String): Unit = runTerminalStep { client.verifyPassword(password).await() } + /** + * Terminal step: submits the passkey assertion. Yields credentials, or continues with a fresh + * [NextAction.VerifyPasskey] if the passkey was rejected, or with MFA if the tenant requires it. + */ + fun verifyPasskey(authenticationResponseJson: String): Unit = + runTerminalStep { client.verifyPasskey(authenticationResponseJson).await() } + /** Terminal step: acknowledges the rotated recovery code. */ fun confirmRecoveryCode(): Unit = runTerminalStep { client.confirmRecoveryCode().await() } diff --git a/sample-embedded/src/main/java/com/auth0/sample/embedded/PasskeyCard.kt b/sample-embedded/src/main/java/com/auth0/sample/embedded/PasskeyCard.kt new file mode 100644 index 000000000..b240b74c7 --- /dev/null +++ b/sample-embedded/src/main/java/com/auth0/sample/embedded/PasskeyCard.kt @@ -0,0 +1,102 @@ +package com.auth0.sample.embedded + +import android.content.Context +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedCard +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.credentials.CredentialManager +import androidx.credentials.GetCredentialRequest +import androidx.credentials.GetPublicKeyCredentialOption +import androidx.credentials.PublicKeyCredential +import androidx.credentials.exceptions.GetCredentialCancellationException +import androidx.credentials.exceptions.GetCredentialException +import androidx.credentials.exceptions.GetCredentialUnknownException +import androidx.credentials.exceptions.NoCredentialException +import kotlinx.coroutines.launch + +/** + * Offers passkey sign-in. Runs the Credential Manager ceremony with the server's [requestJson] and + * hands the resulting `authenticationResponseJson` to [onAssertion]. A canceled or failed ceremony + * leaves the flow unchanged, so the user can retry or pick another action. + */ +@Composable +internal fun PasskeyCard( + rpId: String, + requestJson: String, + onAssertion: (String) -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var errorRes by remember(requestJson) { mutableStateOf(null) } + var inProgress by remember(requestJson) { mutableStateOf(false) } + + OutlinedCard(modifier = Modifier.fillMaxWidth()) { + Column(modifier = Modifier.padding(16.dp)) { + Text(stringResource(R.string.label_passkey), style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text(rpId, style = MaterialTheme.typography.bodySmall) + errorRes?.let { + Spacer(Modifier.height(8.dp)) + Text( + text = stringResource(it), + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodySmall, + ) + } + Spacer(Modifier.height(12.dp)) + Button( + onClick = { + errorRes = null + inProgress = true + scope.launch { + errorRes = try { + onAssertion(requestPasskeyAssertion(context, requestJson)) + null + } catch (e: GetCredentialCancellationException) { + null + } catch (e: NoCredentialException) { + R.string.error_no_passkey + } catch (e: GetCredentialException) { + R.string.error_passkey_failed + } + inProgress = false + } + }, + enabled = !inProgress, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.action_use_passkey)) + } + } + } +} + +/** + * Shows the platform passkey sheet for [requestJson] and returns the chosen passkey's + * `authenticationResponseJson`, ready for [com.auth0.android.embedded.EmbeddedAuthClient.verifyPasskey]. + */ +private suspend fun requestPasskeyAssertion(context: Context, requestJson: String): String { + val response = CredentialManager.create(context).getCredential( + context, + GetCredentialRequest(listOf(GetPublicKeyCredentialOption(requestJson))), + ) + val credential = response.credential as? PublicKeyCredential + ?: throw GetCredentialUnknownException("The platform returned a credential that isn't a passkey.") + return credential.authenticationResponseJson +} diff --git a/sample-embedded/src/main/res/values/strings.xml b/sample-embedded/src/main/res/values/strings.xml index 05c2738f8..aca5c3501 100644 --- a/sample-embedded/src/main/res/values/strings.xml +++ b/sample-embedded/src/main/res/values/strings.xml @@ -49,5 +49,10 @@ Sign up Your details are verified Create account + Sign in with a passkey + Use passkey + That passkey wasn\'t accepted. Try again. + No passkey for this app is available on this device. + The passkey sign-in couldn\'t complete. Try again. Unsupported action: %1$s