Skip to content
Closed
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 @@ -49,5 +49,7 @@ sealed class AuthException(override val message: String) : RuntimeException(mess
internal const val UNKNOWN = "Unknown error occurred"

internal const val INVALID_STATE = "State parameter mismatch possible CSRF attack"

internal const val INVALID_NONCE = "Nonce claim in id_token does not match the sent nonce"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import com.uber.sdk2.auth.internal.service.AuthService
import com.uber.sdk2.auth.internal.sso.SsoLinkFactory
import com.uber.sdk2.auth.internal.sso.UniversalSsoLink.Companion.RESPONSE_TYPE
import com.uber.sdk2.auth.internal.utils.Base64Util
import com.uber.sdk2.auth.internal.utils.NonceUtil
import com.uber.sdk2.auth.request.AuthContext
import com.uber.sdk2.auth.request.AuthType
import com.uber.sdk2.auth.request.SsoConfig
Expand Down Expand Up @@ -86,8 +87,16 @@ class AuthProvider(
)

return if (tokenResponse.isSuccessful) {
tokenResponse.body()?.let { AuthResult.Success(it) }
?: AuthResult.Error(AuthException.ClientError("Token request failed with empty response"))
tokenResponse.body()?.let { token ->
val sentNonce = authContext.nonce
if (sentNonce != null) {
val claimNonce = token.idToken?.let { NonceUtil.extractNonceFromIdToken(it) }
if (claimNonce != sentNonce) {
return AuthResult.Error(AuthException.ClientError(AuthException.INVALID_NONCE))
}
}
AuthResult.Success(token)
} ?: AuthResult.Error(AuthException.ClientError("Token request failed with empty response"))
} else {
AuthResult.Error(
AuthException.ClientError("Token request failed with code: ${tokenResponse.code()}")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Copyright (c) 2024 Uber Technologies, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.uber.sdk2.auth.internal.utils

import android.util.Base64
import org.json.JSONObject

object NonceUtil {

/**
* Extracts the `nonce` claim from a JWT id_token by decoding the payload segment (without
* verifying the signature). Returns null if the token is malformed or contains no nonce claim.
*/
fun extractNonceFromIdToken(idToken: String): String? {
val parts = idToken.split(".")
if (parts.size != 3) return null
return try {
val payload = Base64.decode(parts[1], Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)
val json = JSONObject(String(payload, Charsets.UTF_8))
json.optString("nonce", null)
} catch (_: Exception) {
null
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,5 @@ data class UberToken(
@Json(name = "refresh_token") val refreshToken: String? = null,
@Json(name = "expires_in") val expiresIn: Long? = null,
@Json(name = "scope") val scope: String? = null,
@Json(name = "id_token") val idToken: String? = null,
) : Parcelable
Original file line number Diff line number Diff line change
Expand Up @@ -445,4 +445,98 @@ class AuthProviderTest : RobolectricTestBase() {
assertEquals(AuthOptionalConfig(), authContext.options)
assertEquals(UriConfig.UberEnvironment.PRODUCTION, authContext.environment)
}

// ---- Nonce validation tests ----

@Test
fun `test PKCE with nonce validates id_token nonce claim`() = runTest {
val idToken = buildJwt("""{"sub":"user","nonce":"my-nonce"}""")
whenever(ssoLink.execute(any())).thenReturn("code")
whenever(codeVerifierGenerator.generateCodeVerifier()).thenReturn("verifier")
whenever(codeVerifierGenerator.generateCodeChallenge("verifier")).thenReturn("challenge")
whenever(authService.token(any(), any(), any(), any(), any()))
.thenReturn(Response.success(UberToken(accessToken = "accessToken", idToken = idToken)))
val authContext =
AuthContext(
AuthDestination.CrossAppSso(listOf(CrossApp.Rider)),
AuthType.PKCE(),
nonce = "my-nonce",
)
val authProvider = AuthProvider(activity, authContext, authService, codeVerifierGenerator)
val result = authProvider.authenticate()
assert(result is AuthResult.Success)
assert((result as AuthResult.Success).uberToken.accessToken == "accessToken")
}

@Test
fun `test PKCE with nonce mismatch returns error`() = runTest {
val idToken = buildJwt("""{"sub":"user","nonce":"wrong-nonce"}""")
whenever(ssoLink.execute(any())).thenReturn("code")
whenever(codeVerifierGenerator.generateCodeVerifier()).thenReturn("verifier")
whenever(codeVerifierGenerator.generateCodeChallenge("verifier")).thenReturn("challenge")
whenever(authService.token(any(), any(), any(), any(), any()))
.thenReturn(Response.success(UberToken(accessToken = "accessToken", idToken = idToken)))
val authContext =
AuthContext(
AuthDestination.CrossAppSso(listOf(CrossApp.Rider)),
AuthType.PKCE(),
nonce = "expected-nonce",
)
val authProvider = AuthProvider(activity, authContext, authService, codeVerifierGenerator)
val result = authProvider.authenticate()
assert(result is AuthResult.Error)
assertEquals(AuthException.INVALID_NONCE, (result as AuthResult.Error).authException.message)
}

@Test
fun `test PKCE with nonce but missing id_token returns error`() = runTest {
whenever(ssoLink.execute(any())).thenReturn("code")
whenever(codeVerifierGenerator.generateCodeVerifier()).thenReturn("verifier")
whenever(codeVerifierGenerator.generateCodeChallenge("verifier")).thenReturn("challenge")
whenever(authService.token(any(), any(), any(), any(), any()))
.thenReturn(Response.success(UberToken(accessToken = "accessToken")))
val authContext =
AuthContext(
AuthDestination.CrossAppSso(listOf(CrossApp.Rider)),
AuthType.PKCE(),
nonce = "my-nonce",
)
val authProvider = AuthProvider(activity, authContext, authService, codeVerifierGenerator)
val result = authProvider.authenticate()
assert(result is AuthResult.Error)
assertEquals(AuthException.INVALID_NONCE, (result as AuthResult.Error).authException.message)
}

@Test
fun `test PKCE without nonce skips id_token validation`() = runTest {
whenever(ssoLink.execute(any())).thenReturn("code")
whenever(codeVerifierGenerator.generateCodeVerifier()).thenReturn("verifier")
whenever(codeVerifierGenerator.generateCodeChallenge("verifier")).thenReturn("challenge")
whenever(authService.token(any(), any(), any(), any(), any()))
.thenReturn(Response.success(UberToken(accessToken = "accessToken")))
val authContext =
AuthContext(AuthDestination.CrossAppSso(listOf(CrossApp.Rider)), AuthType.PKCE(), null)
val authProvider = AuthProvider(activity, authContext, authService, codeVerifierGenerator)
val result = authProvider.authenticate()
assert(result is AuthResult.Success)
assert((result as AuthResult.Success).uberToken.accessToken == "accessToken")
}

private fun buildJwt(payloadJson: String): String {
val header =
android.util.Base64.encodeToString(
"""{"alg":"RS256","typ":"JWT"}""".toByteArray(),
android.util.Base64.URL_SAFE or
android.util.Base64.NO_WRAP or
android.util.Base64.NO_PADDING,
)
val payload =
android.util.Base64.encodeToString(
payloadJson.toByteArray(),
android.util.Base64.URL_SAFE or
android.util.Base64.NO_WRAP or
android.util.Base64.NO_PADDING,
)
return "$header.$payload.fake-signature"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Copyright (c) 2024 Uber Technologies, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.uber.sdk2.auth.internal.utils

import com.uber.sdk2.auth.RobolectricTestBase
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test

class NonceUtilTest : RobolectricTestBase() {

private fun buildJwt(payloadJson: String): String {
val header =
android.util.Base64.encodeToString(
"""{"alg":"RS256","typ":"JWT"}""".toByteArray(),
android.util.Base64.URL_SAFE or
android.util.Base64.NO_WRAP or
android.util.Base64.NO_PADDING,
)
val payload =
android.util.Base64.encodeToString(
payloadJson.toByteArray(),
android.util.Base64.URL_SAFE or
android.util.Base64.NO_WRAP or
android.util.Base64.NO_PADDING,
)
return "$header.$payload.fake-signature"
}

@Test
fun `extractNonceFromIdToken returns nonce when present`() {
val jwt = buildJwt("""{"sub":"user123","nonce":"my-nonce-value"}""")
assertEquals("my-nonce-value", NonceUtil.extractNonceFromIdToken(jwt))
}

@Test
fun `extractNonceFromIdToken returns null when nonce is absent`() {
val jwt = buildJwt("""{"sub":"user123"}""")
assertNull(NonceUtil.extractNonceFromIdToken(jwt))
}

@Test
fun `extractNonceFromIdToken returns null for malformed JWT`() {
assertNull(NonceUtil.extractNonceFromIdToken("not-a-jwt"))
}

@Test
fun `extractNonceFromIdToken returns null for two-segment token`() {
assertNull(NonceUtil.extractNonceFromIdToken("header.payload"))
}

@Test
fun `extractNonceFromIdToken returns null for invalid base64 payload`() {
assertNull(NonceUtil.extractNonceFromIdToken("header.!!!invalid!!!.sig"))
}
}
Loading