Skip to content

Commit

Permalink
Added AuthProvider implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
lalwani committed Mar 20, 2024
1 parent a8f9739 commit 715a232
Show file tree
Hide file tree
Showing 6 changed files with 364 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@ package com.uber.sdk2.auth.api
import com.uber.sdk2.auth.api.response.AuthResult

/** Provides a way to authenticate the user using SSO flow. */
fun interface AuthProviding {
interface AuthProviding {
/**
* Executes the SSO flow.
*
* @param ssoLink The SSO link to execute.
* @return The result from the authentication flow encapsulated in [AuthResult]
*/
suspend fun authenticate(): AuthResult

/** Handles the authentication code received from the SSO flow via deeplink. */
fun handleAuthCode(authCode: String)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2024. Uber Technologies
*
* 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
*
* https://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 com.uber.sdk2.auth.internal

import androidx.appcompat.app.AppCompatActivity
import com.uber.sdk2.auth.api.AuthProviding
import com.uber.sdk2.auth.api.PKCEGenerator
import com.uber.sdk2.auth.api.exception.AuthException
import com.uber.sdk2.auth.api.request.AuthContext
import com.uber.sdk2.auth.api.request.AuthType
import com.uber.sdk2.auth.api.request.SsoConfigProvider
import com.uber.sdk2.auth.api.response.AuthResult
import com.uber.sdk2.auth.api.response.PARResponse
import com.uber.sdk2.auth.api.response.UberToken
import com.uber.sdk2.auth.internal.service.AuthService
import com.uber.sdk2.auth.internal.sso.SsoLinkFactory

class AuthProvider(
private val activity: AppCompatActivity,
private val authContext: AuthContext,
private val authService: AuthService = AuthService.create(),
private val codeVerifierGenerator: PKCEGenerator = PKCEGeneratorImpl,
) : AuthProviding {

private val verifier: String = codeVerifierGenerator.generateCodeVerifier()
private val ssoLink = SsoLinkFactory.generateSsoLink(activity, authContext)

override suspend fun authenticate(): AuthResult {
val ssoConfig = SsoConfigProvider.getSsoConfig(activity)
val parResponse =
authContext.prefillInfo?.let {
val response =
authService.loginParRequest(ssoConfig.clientId, "code", it, ssoConfig.scope ?: "profile")
if (response.isSuccessful && response.body() != null) {
response.body()
} else {
throw AuthException.ServerError("bad response ${response.code()}")
}
} ?: PARResponse("", "")

val queryParams: Map<String, String> =
mapOf(
"request_uri" to parResponse.requestUri,
"code_challenge" to codeVerifierGenerator.generateCodeChallenge(verifier),
)
try {
val authCode = ssoLink.execute(queryParams)
return when (authContext.authType) {
AuthType.AuthCode -> AuthResult.Success(UberToken(authCode = authCode))
is AuthType.PKCE -> {
val tokenResponse =
authService.token(
ssoConfig.clientId,
verifier,
authContext.authType.grantType,
ssoConfig.redirectUri,
authCode,
)

if (tokenResponse.isSuccessful) {
tokenResponse.body()?.let { AuthResult.Success(it) }
?: AuthResult.Error(
AuthException.ClientError("Token request failed with empty response")
)
} else {
AuthResult.Error(
AuthException.ClientError("Token request failed with code: ${tokenResponse.code()}")
)
}
}
}
} catch (e: AuthException) {
return AuthResult.Error(e)
}
}

override fun handleAuthCode(authCode: String) {
ssoLink.handleAuthCode(authCode)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2024. Uber Technologies
*
* 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
*
* https://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 com.uber.sdk2.auth.internal

import android.util.Base64
import androidx.annotation.VisibleForTesting
import com.uber.sdk2.auth.api.PKCEGenerator
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom

object PKCEGeneratorImpl : PKCEGenerator {
override fun generateCodeVerifier(): String {
val sr = SecureRandom()
val code = ByteArray(BYTE_ARRAY_SIZE)
sr.nextBytes(code)
return Base64.encodeToString(code, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)
}

override fun generateCodeChallenge(codeVerifier: String): String {
val bytes = codeVerifier.toByteArray(StandardCharsets.US_ASCII)
return try { // StandardLoginAvailabilityHelper#supportsSha256 already checks for this
val md = MessageDigest.getInstance(SHA_256)
md.update(bytes, 0, bytes.size)
val digest = md.digest()
Base64.encodeToString(digest, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)
} catch (e: NoSuchAlgorithmException) {
throw IllegalStateException("SHA-256 is not supported", e)
}
}

@VisibleForTesting private const val BYTE_ARRAY_SIZE: Int = 32
private const val SHA_256 = "SHA-256"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright (C) 2024. Uber Technologies
*
* 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
*
* https://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 com.uber.sdk2.auth.internal.service

// import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.squareup.moshi.Moshi
import com.uber.sdk2.auth.api.request.PrefillInfo
import com.uber.sdk2.auth.api.response.PARResponse
import com.uber.sdk2.auth.api.response.UberToken
import com.uber.sdk2.core.config.UriConfig
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST

/** Service for making network requests to the auth server. */
interface AuthService {

// @FormUrlEncoded
// @POST("/oauth/v2/par")
// suspend fun loginParRequest(
// @Field("client_id") clientId: String,
// @Field("response_type") responseType: String,
// @Field("login_hint") loginHint: String,
// @Field("scope") scope: String,
// ): Response<PARResponse>

@FormUrlEncoded
@POST("/oauth/v2/par")
suspend fun loginParRequest(
@Field("client_id") clientId: String,
@Field("response_type") responseType: String,
@Field("login_hint") prefillInfo: PrefillInfo,
@Field("scope") scope: String,
): Response<PARResponse>

@FormUrlEncoded
@POST("/oauth/v2/token")
suspend fun token(
@Field("client_id") clientId: String?,
@Field("code_verifier") codeVerifier: String?,
@Field("grant_type") grantType: String?,
@Field("redirect_uri") redirectUri: String?,
@Field("code") authCode: String?,
): Response<UberToken>

companion object {
/** Creates an instance of [AuthService]. */
fun create(): AuthService {
val moshi =
Moshi.Builder()
.add(Base64PrefillInfoAdapter())
// .add(KotlinJsonAdapterFactory()) // Needed for Kotlin data classes
.build()
return Retrofit.Builder()
.baseUrl(UriConfig.getAuthHost())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
.create(AuthService::class.java)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright (C) 2024. Uber Technologies
*
* 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
*
* https://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 com.uber.sdk2.auth.internal

import androidx.appcompat.app.AppCompatActivity
import com.uber.sdk2.auth.RobolectricTestBase
import com.uber.sdk2.auth.api.PKCEGenerator
import com.uber.sdk2.auth.api.exception.AuthException
import com.uber.sdk2.auth.api.request.AuthContext
import com.uber.sdk2.auth.api.request.AuthDestination
import com.uber.sdk2.auth.api.request.AuthType
import com.uber.sdk2.auth.api.request.CrossApp
import com.uber.sdk2.auth.api.request.PrefillInfo
import com.uber.sdk2.auth.api.response.AuthResult
import com.uber.sdk2.auth.api.response.PARResponse
import com.uber.sdk2.auth.api.response.UberToken
import com.uber.sdk2.auth.api.sso.SsoLink
import com.uber.sdk2.auth.internal.service.AuthService
import com.uber.sdk2.auth.internal.shadow.ShadowSsoConfigProvider
import com.uber.sdk2.auth.internal.shadow.ShadowSsoLinkFactory
import com.uber.sdk2.auth.internal.sso.SsoLinkFactory
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.robolectric.annotation.Config
import org.robolectric.shadow.api.Shadow
import retrofit2.Response

@Config(shadows = [ShadowSsoLinkFactory::class, ShadowSsoConfigProvider::class])
class AuthProviderTest : RobolectricTestBase() {
private val activity: AppCompatActivity = mock()
private val authService: AuthService = mock()
private val codeVerifierGenerator: PKCEGenerator = mock()

private lateinit var ssoLink: SsoLink

@Before
fun setUp() {
ssoLink = Shadow.extract<ShadowSsoLinkFactory>(SsoLinkFactory).ssoLink
}

@Test
fun `test authenticate when PKCE flow should return tokens`() = runTest {
whenever(ssoLink.execute(any())).thenReturn("code")
whenever(authService.loginParRequest(any(), any(), any(), any()))
.thenReturn(Response.success(PARResponse("requestUri", "codeVerifier")))
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()
verify(authService, never()).loginParRequest(any(), any(), any(), any())
verify(authService).token("clientId", "verifier", "code", "redirectUri", "code")
assert(result is AuthResult.Success)
assert((result as AuthResult.Success).uberToken.accessToken == "accessToken")
}

@Test
fun `test authenticate with prefill when PKCE flow should return tokens`() = runTest {
whenever(ssoLink.execute(any())).thenReturn("authCode")
whenever(authService.loginParRequest(any(), any(), any(), any()))
.thenReturn(Response.success(PARResponse("requestUri", "codeVerifier")))
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 prefillInfo = PrefillInfo("email", "firstName", "lastName", "phoneNumber")
val authContext =
AuthContext(AuthDestination.CrossAppSso(listOf(CrossApp.Rider)), AuthType.PKCE, prefillInfo)
val authProvider = AuthProvider(activity, authContext, authService, codeVerifierGenerator)
val result = authProvider.authenticate()
verify(authService).loginParRequest("clientId", "code", prefillInfo, "profile")
verify(authService).token("clientId", "verifier", "code", "redirectUri", "authCode")
assert(result is AuthResult.Success)
assert((result as AuthResult.Success).uberToken.accessToken == "accessToken")
}

@Test
fun `test authenticate when AuthCode flow should return only AuthCode`() = runTest {
whenever(ssoLink.execute(any())).thenReturn("authCode")
whenever(authService.loginParRequest(any(), any(), any(), any()))
.thenReturn(Response.success(PARResponse("requestUri", "codeVerifier")))
val authContext =
AuthContext(AuthDestination.CrossAppSso(listOf(CrossApp.Rider)), AuthType.AuthCode, null)
val authProvider = AuthProvider(activity, authContext, authService, codeVerifierGenerator)
val result = authProvider.authenticate()
verify(authService, never()).token(any(), any(), any(), any(), any())
assert(result is AuthResult.Success)
assert((result as AuthResult.Success).uberToken.authCode == "authCode")
}

@Test
fun `test authenticate when authException should return error result`() = runTest {
whenever(ssoLink.execute(any())).thenThrow(AuthException.ClientError("error"))
val authContext =
AuthContext(AuthDestination.CrossAppSso(listOf(CrossApp.Rider)), AuthType.AuthCode, null)
val authProvider = AuthProvider(activity, authContext, authService, codeVerifierGenerator)
val result = authProvider.authenticate()
assert(result is AuthResult.Error && result.authException.message == "error")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.uber.sdk2.auth.internal

import com.uber.sdk2.auth.RobolectricTestBase
import org.junit.Assert.assertNotNull
import org.junit.Test

class PKCEGeneratorImplTest: RobolectricTestBase() {
@Test
fun testGenerateCodeVerifier() {
val codeVerifier = PKCEGeneratorImpl.generateCodeVerifier()
assert(codeVerifier.isNullOrBlank().not())
}

@Test
fun testGenerateCodeChallenge() {
val codeVerifier = PKCEGeneratorImpl.generateCodeVerifier()
val codeChallenge = PKCEGeneratorImpl.generateCodeChallenge(codeVerifier)
assert(codeChallenge.isNullOrBlank().not())
}
}

0 comments on commit 715a232

Please sign in to comment.