Skip to content

Commit 1a5c3af

Browse files
committed
Addressed review comments
1 parent 51444de commit 1a5c3af

5 files changed

Lines changed: 143 additions & 15 deletions

File tree

‎auth0/src/main/java/com/auth0/android/embedded/EmbeddedAuthClient.kt‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ import okhttp3.HttpUrl.Companion.toHttpUrl
3434
* **Note**
3535
* Embedded Authorization is currently in [Beta](https://auth0.com/docs/troubleshoot/product-lifecycle/product-release-stages#beta). Please reach out to Auth0 support to get it enabled for your tenant.
3636
*/
37-
public class EmbeddedAuthClient internal constructor(
37+
public class EmbeddedAuthClient private constructor(
3838
private val auth0: Auth0,
3939
private val algorithmHelper: AlgorithmHelper
4040
) {
@@ -91,7 +91,6 @@ public class EmbeddedAuthClient internal constructor(
9191
)
9292
)
9393
}
94-
transactionState = EmbeddedAuthState(codeVerifier = verifier)
9594
val request = factory.post(authorizeUrl)
9695
.addParameters(buildMap {
9796
put(CLIENT_ID_KEY, clientId)
@@ -102,7 +101,7 @@ public class EmbeddedAuthClient internal constructor(
102101
put(CODE_CHALLENGE_METHOD_KEY, CODE_CHALLENGE_METHOD_S256)
103102
})
104103
.addParameter(CAPABILITIES_KEY, capabilities.map { it.value })
105-
return stepping(request)
104+
return stepping(request) { error -> updateSessionFromFailure(error, verifier) }
106105
}
107106

108107
/**
@@ -330,8 +329,9 @@ public class EmbeddedAuthClient internal constructor(
330329
)
331330

332331
private fun stepping(
333-
request: Request<Void?, EmbeddedAuthException>
334-
): Request<Void?, EmbeddedAuthException> = StepRequest(request, ::updateSessionFromFailure)
332+
request: Request<Void?, EmbeddedAuthException>,
333+
onStepFailure: (EmbeddedAuthException) -> Unit = { error -> updateSessionFromFailure(error) }
334+
): Request<Void?, EmbeddedAuthException> = StepRequest(request, onStepFailure)
335335

336336
/**
337337
* Wraps a final step. The verifier is captured here because the session state is cleared as soon as
@@ -343,7 +343,7 @@ public class EmbeddedAuthClient internal constructor(
343343
): Request<Credentials, EmbeddedAuthException> = AdvancingRequest(
344344
authorize = request,
345345
exchange = { code -> exchange(code, codeVerifier) },
346-
onStepFailure = ::updateSessionFromFailure,
346+
onStepFailure = { error -> updateSessionFromFailure(error) },
347347
onFlowComplete = { transactionState = null }
348348
)
349349

@@ -372,19 +372,26 @@ public class EmbeddedAuthClient internal constructor(
372372
.toString()
373373
}
374374

375-
private fun updateSessionFromFailure(error: EmbeddedAuthException) {
375+
private fun updateSessionFromFailure(error: EmbeddedAuthException, authorizeVerifier: String? = null) {
376376
if (error.statusCode in 500..599) return
377377

378378
when (error.error) {
379379
is EmbeddedAuthError.InsufficientAuthorization ->
380-
error.authSession?.let { session -> transactionState = transactionState?.copy(authSession = session) }
380+
error.authSession?.let { session ->
381+
transactionState = authorizeVerifier?.let { EmbeddedAuthState(it, session) }
382+
?: transactionState?.copy(authSession = session)
383+
}
381384

382385
is EmbeddedAuthError.Network -> Unit
383386
else -> transactionState = null
384387
}
385388
}
386389

387-
private companion object {
390+
internal companion object {
391+
@JvmSynthetic
392+
fun create(auth0: Auth0, algorithmHelper: AlgorithmHelper): EmbeddedAuthClient =
393+
EmbeddedAuthClient(auth0, algorithmHelper)
394+
388395
private const val EMBEDDED_PATH = "e"
389396
private const val AUTHORIZE_PATH = "authorize"
390397
private const val OAUTH_PATH = "oauth"
Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
package com.auth0.android.embedded.authorize
22

33
/**
4-
* The state of the flow in progress, created by `authorize()` with the PKCE [codeVerifier] that is sent with
5-
* the token exchange. [authSession] is the latest session from the server, and is `null` until the first
6-
* response arrives. Neither is ever logged.
4+
* The state of the flow in progress, created when the first response to `authorize()` arrives. It holds the PKCE
5+
* [codeVerifier] that is sent with the token exchange, and the latest [authSession] from the server.
76
*/
87
internal data class EmbeddedAuthState(
98
val codeVerifier: String,
10-
val authSession: String? = null
9+
val authSession: String
1110
) {
1211
override fun toString(): String = "EmbeddedAuthState(codeVerifier='xxxxx', authSession='xxxxx')"
1312
}

‎auth0/src/main/java/com/auth0/android/util/AlgorithmHelper.kt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import java.security.SecureRandom
1313
*/
1414
internal open class AlgorithmHelper {
1515

16+
private val secureRandom = SecureRandom()
17+
1618
open fun getASCIIBytes(value: String): ByteArray = value.toByteArray(StandardCharsets.US_ASCII)
1719

1820
/**
@@ -32,7 +34,7 @@ internal open class AlgorithmHelper {
3234
/** A random, base64url-encoded code verifier made of 32 random bytes. */
3335
open fun generateCodeVerifier(): String {
3436
val code = ByteArray(32)
35-
SecureRandom().nextBytes(code)
37+
secureRandom.nextBytes(code)
3638
return encode(code)
3739
}
3840

‎auth0/src/test/java/com/auth0/android/embedded/EmbeddedAuthClientTest.kt‎

Lines changed: 104 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ public class EmbeddedAuthClientTest {
219219
on { generateCodeVerifier() } doReturn "verifier"
220220
on { generateCodeChallenge(any()) } doThrow IllegalStateException("no SHA-256")
221221
}
222-
val failing = EmbeddedAuthClient(auth0, helper)
222+
val failing = EmbeddedAuthClient.create(auth0, helper)
223223

224224
val error = assertEmbeddedErrorSuspending { failing.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION).await() }
225225

@@ -228,6 +228,109 @@ public class EmbeddedAuthClientTest {
228228
assertThat(mockAPI.server.requestCount, `is`(0))
229229
}
230230

231+
@Test
232+
public fun `authorize sends exactly the initial request fields`(): Unit = runTest {
233+
mockAPI.willReturnInsufficientAuthorization()
234+
235+
assertEmbeddedErrorSuspending { client.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION).await() }
236+
237+
val body = bodyOf(mockAPI.takeRequest())
238+
assertThat(
239+
body.keys().asSequence().toSet(),
240+
`is`(setOf("client_id", "connection", "scope", "capabilities", "code_challenge", "code_challenge_method"))
241+
)
242+
}
243+
244+
@Test
245+
public fun `the token exchange sends exactly the authorization code grant fields`(): Unit = runTest {
246+
mockAPI.willReturnInsufficientAuthorization()
247+
assertEmbeddedErrorSuspending { client.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION).await() }
248+
mockAPI.takeRequest()
249+
mockAPI.willReturnAuthorizeCode()
250+
mockAPI.willReturnTokens()
251+
252+
client.verifyOtp("123456", OtpType.OOB).await()
253+
mockAPI.takeRequest()
254+
255+
assertThat(
256+
bodyOf(mockAPI.takeRequest()).keys().asSequence().toSet(),
257+
`is`(setOf("client_id", "grant_type", "code", "code_verifier"))
258+
)
259+
}
260+
261+
@Test
262+
public fun `only authorize carries PKCE parameters, not the later steps`(): Unit = runTest {
263+
mockAPI.willReturnInsufficientAuthorization()
264+
assertEmbeddedErrorSuspending { client.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION).await() }
265+
mockAPI.takeRequest()
266+
mockAPI.willReturnInsufficientAuthorization(EmbeddedAuthMockServer.ROTATED_AUTH_SESSION)
267+
assertEmbeddedErrorSuspending { client.identify("jane@example.com", IdentifierType.EMAIL).await() }
268+
val identify = bodyOf(mockAPI.takeRequest())
269+
mockAPI.willReturnInsufficientAuthorization(EmbeddedAuthMockServer.ROTATED_AUTH_SESSION)
270+
assertEmbeddedErrorSuspending { client.challengeEmail().await() }
271+
val challenge = bodyOf(mockAPI.takeRequest())
272+
mockAPI.willReturnAuthorizeCode()
273+
mockAPI.willReturnTokens()
274+
client.verifyOtp("123456", OtpType.OOB).await()
275+
val verify = bodyOf(mockAPI.takeRequest())
276+
277+
for (body in listOf(identify, challenge, verify)) {
278+
assertThat(body.has("code_challenge"), `is`(false))
279+
assertThat(body.has("code_challenge_method"), `is`(false))
280+
assertThat(body.has("code_verifier"), `is`(false))
281+
}
282+
}
283+
284+
@Test
285+
public fun `a rejected token exchange surfaces SessionExpired on invalid_grant`(): Unit = runTest {
286+
mockAPI.willReturnInsufficientAuthorization()
287+
assertEmbeddedErrorSuspending { client.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION).await() }
288+
mockAPI.takeRequest()
289+
mockAPI.willReturnAuthorizeCode()
290+
mockAPI.willReturnInvalidGrant()
291+
292+
val error = assertEmbeddedErrorSuspending { client.verifyOtp("123456", OtpType.OOB).await() }
293+
294+
assertThat(error.error, `is`(EmbeddedAuthError.SessionExpired))
295+
}
296+
297+
@Test
298+
public fun `overlapping authorize calls keep the verifier and the session of the same response`(): Unit = runTest {
299+
val first = client.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION)
300+
val second = client.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION)
301+
mockAPI.willReturnInsufficientAuthorization(EmbeddedAuthMockServer.ROTATED_AUTH_SESSION)
302+
assertEmbeddedErrorSuspending { second.await() }
303+
mockAPI.takeRequest()
304+
mockAPI.willReturnInsufficientAuthorization(EmbeddedAuthMockServer.AUTH_SESSION)
305+
assertEmbeddedErrorSuspending { first.await() }
306+
val firstChallenge = bodyOf(mockAPI.takeRequest()).getString("code_challenge")
307+
mockAPI.willReturnAuthorizeCode()
308+
mockAPI.willReturnTokens()
309+
310+
client.verifyOtp("123456", OtpType.OOB).await()
311+
val verify = bodyOf(mockAPI.takeRequest())
312+
val exchange = bodyOf(mockAPI.takeRequest())
313+
314+
assertThat(verify.getString("auth_session"), `is`(EmbeddedAuthMockServer.AUTH_SESSION))
315+
assertThat(s256(exchange.getString("code_verifier")), `is`(firstChallenge))
316+
}
317+
318+
@Test
319+
public fun `a failed challenge creation abandons the flow in progress`(): Unit = runTest {
320+
val helper = mock<AlgorithmHelper> {
321+
on { generateCodeVerifier() } doReturn "verifier"
322+
on { generateCodeChallenge(any()) } doReturn "challenge" doThrow IllegalStateException("no SHA-256")
323+
}
324+
val flaky = EmbeddedAuthClient.create(auth0, helper)
325+
mockAPI.willReturnInsufficientAuthorization()
326+
assertEmbeddedErrorSuspending { flaky.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION).await() }
327+
assertEmbeddedErrorSuspending { flaky.authorize(EmbeddedAuthMockServer.AUTHORIZE_CONNECTION).await() }
328+
329+
val error = assertEmbeddedErrorSuspending { flaky.identify("jane@example.com", IdentifierType.EMAIL).await() }
330+
331+
assertThat(error.error, `is`(EmbeddedAuthError.NoActiveSession))
332+
}
333+
231334
// ── verifyOtp — token exchange ──────────────────────────────────────────────
232335

233336
@Test
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.auth0.android.embedded.authorize
2+
3+
import org.hamcrest.MatcherAssert.assertThat
4+
import org.hamcrest.Matchers.containsString
5+
import org.hamcrest.Matchers.not
6+
import org.junit.Test
7+
8+
public class EmbeddedAuthStateTest {
9+
10+
@Test
11+
public fun `toString hides the verifier and the session`() {
12+
val text = EmbeddedAuthState("the-verifier", "the-session").toString()
13+
14+
assertThat(text, not(containsString("the-verifier")))
15+
assertThat(text, not(containsString("the-session")))
16+
}
17+
}

0 commit comments

Comments
 (0)