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 @@ -17,6 +17,11 @@ annotation class IoDispatcher
@Retention(AnnotationRetention.RUNTIME)
annotation class BaseHttpClient

/** Apollo client that never sends an access token, for requests made before login. */
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class PublicApolloClient

/** Ktor engine for the auth client, carrying the app's network observability hooks. */
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.apollographql.ktor.ktorClient
import com.hedvig.android.core.buildconstants.HedvigBuildConstants
import com.hedvig.android.core.common.di.AppScope
import com.hedvig.android.core.common.di.BaseHttpClient
import com.hedvig.android.core.common.di.PublicApolloClient
import com.hedvig.android.core.datastore.DeviceIdFetcher
import com.hedvig.android.language.LanguageService
import com.hedvig.android.logger.logcat
Expand Down Expand Up @@ -68,6 +69,25 @@ interface NetworkMetroProviders {
.config {}
.apply { addAuthPlugin(accessTokenFetcher) }

/**
* Built on the token-free [BaseHttpClient], so a request never carries an `Authorization` header and never asks for a
* token. It has its own small cache and no platform interceptors, so a rejected request cannot log the member out.
*/
@Provides
@SingleIn(AppScope::class)
@PublicApolloClient
fun providePublicApolloClient(
@BaseHttpClient httpClient: HttpClient,
hedvigBuildConstants: HedvigBuildConstants,
networkLogPolicy: NetworkLogPolicy,
): ApolloClient = buildHedvigApolloClient(
MemoryCacheFactory(maxSizeBytes = 1024 * 1024),
httpClient,
hedvigBuildConstants,
platformInterceptors = emptyList(),
networkLogPolicy = networkLogPolicy,
)

@Provides
@SingleIn(AppScope::class)
fun provideNormalizedCacheFactory(): NormalizedCacheFactory = MemoryCacheFactory(maxSizeBytes = 10 * 1024 * 1024)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
package com.hedvig.android.network.clients.di

import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.api.Adapter
import com.apollographql.apollo.api.CompiledField
import com.apollographql.apollo.api.CustomScalarAdapters
import com.apollographql.apollo.api.Query
import com.apollographql.apollo.api.json.JsonWriter
import com.apollographql.cache.normalized.FetchPolicy
import com.apollographql.cache.normalized.fetchPolicy
import com.hedvig.android.auth.AccessTokenProvider
import com.hedvig.android.core.buildconstants.AppBuildConfig
import com.hedvig.android.core.buildconstants.Flavor
import com.hedvig.android.core.buildconstants.HedvigBuildConstants
import com.hedvig.android.core.common.ApplicationScope
import com.hedvig.android.core.common.di.AppScope
import com.hedvig.android.core.common.di.AuthHttpClientEngine
import com.hedvig.android.core.common.di.BaseHttpClient
import com.hedvig.android.core.common.di.DesktopDataDirectory
import com.hedvig.android.core.common.di.PublicApolloClient
import com.hedvig.android.logger.TestLogcatLoggingRule
import com.hedvig.android.network.clients.AccessTokenFetcher
import com.hedvig.android.network.clients.ExtraKtorClientConfiguration
import com.hedvig.android.network.clients.NetworkLogPolicy
Expand All @@ -14,24 +27,46 @@ import com.hedvig.android.network.clients.TlsDiagnostics
import dev.zacsweers.metro.DependencyGraph
import dev.zacsweers.metro.Provides
import dev.zacsweers.metro.createGraphFactory
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.okhttp.OkHttpEngine
import io.ktor.client.plugins.HttpSend
import io.ktor.client.plugins.plugin
import io.ktor.client.request.get
import io.ktor.http.Headers
import io.ktor.http.HttpStatusCode
import java.io.File
import javax.net.ssl.SSLHandshakeException
import kotlin.io.path.createTempDirectory
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.job
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Rule

@DependencyGraph(AppScope::class)
internal interface NetworkTestGraph {
val accessTokenFetcher: AccessTokenFetcher
val extraKtorClientConfiguration: ExtraKtorClientConfiguration
val tlsDiagnostics: TlsDiagnostics
val networkLogPolicy: NetworkLogPolicy
val hedvigBuildConstants: HedvigBuildConstants
val applicationScope: ApplicationScope

@PublicApolloClient
val publicApolloClient: ApolloClient

@BaseHttpClient
val baseHttpClient: HttpClient

@AuthHttpClientEngine
val authHttpClientEngine: HttpClientEngine
Expand All @@ -46,11 +81,17 @@ internal interface NetworkTestGraph {
}

class JvmNetworkBindingsTest {
@get:Rule
val testLogcatLogger = TestLogcatLoggingRule()

private val dataDirectory: File = createTempDirectory("network-bindings-test").toFile()
private val graph = createGraphFactory<NetworkTestGraph.Factory>().create(dataDirectory, TestAppBuildConfig)

@AfterTest
fun tearDown() {
// Building the base HTTP client launches the device id's first DataStore write on the application scope. Deleting
// the directory under that write fails it, and the uncaught IOException then fails whichever runTest comes next.
runBlocking { graph.applicationScope.coroutineContext.job.children.toList().joinAll() }
dataDirectory.deleteRecursively()
}

Expand All @@ -71,12 +112,100 @@ class JvmNetworkBindingsTest {
assertIs<OkHttpEngine>(graph.authHttpClientEngine)
}

@Test
fun `the public Apollo client sends through the graph's base HTTP client`() = runTest {
val sent = mutableListOf<Headers>()
graph.baseHttpClient.plugin(HttpSend).intercept { request ->
sent += request.headers.build()
throw RequestRecorded()
}

val response = graph.publicApolloClient.query(TestQuery).fetchPolicy(FetchPolicy.NetworkOnly).execute()

assertEquals(REQUEST_RECORDED_MESSAGE, response.exception?.message)
assertEquals(1, sent.size)
assertNotNull(sent.single()["Accept-Language"])
}

@Test
fun `the public Apollo client never fetches a token while the member client does`() = runTest {
val fetcher = CountingAccessTokenFetcher()
val received = mutableListOf<Headers>()
val engine = MockEngine { request ->
received += request.headers
respond("", HttpStatusCode.InternalServerError)
}
val baseClient = HttpClient(engine) { install(HttpSend) }
val providers = object : NetworkMetroProviders {}
val publicClient = providers.providePublicApolloClient(
baseClient,
graph.hedvigBuildConstants,
graph.networkLogPolicy,
)

publicClient.query(TestQuery).fetchPolicy(FetchPolicy.NetworkOnly).execute()

assertEquals(1, received.size)
assertNull(received.single()["Authorization"])
assertEquals(0, fetcher.calls)

// Control: the member client over the same base client does fetch the token and send it.
providers.provideHttpClient(baseClient, fetcher).get("https://example.com")

assertEquals(2, received.size)
assertEquals("Bearer token", received.last()["Authorization"])
assertTrue(fetcher.calls > 0)

// In the app the member client exists and has been used before the public query runs, so check that order too.
val callsAfterMemberClient = fetcher.calls
publicClient.query(TestQuery).fetchPolicy(FetchPolicy.NetworkOnly).execute()

assertEquals(3, received.size)
assertNull(received.last()["Authorization"])
assertEquals(callsAfterMemberClient, fetcher.calls)
}

@Test
fun `the TLS diagnostics describe nothing, even for a trust failure`() = runTest {
assertNull(graph.tlsDiagnostics.describe(SSLHandshakeException("Trust anchor for certification path not found.")))
}
}

private object TestQuery : Query<TestQuery.Data> {
object Data : Query.Data

override fun document(): String = "query Test { __typename }"

override fun name(): String = "Test"

override fun id(): String = "Test"

override fun adapter(): Adapter<Data> = error("The request is aborted before a response exists")

override fun serializeVariables(
writer: JsonWriter,
customScalarAdapters: CustomScalarAdapters,
withDefaultValues: Boolean,
) {}

override fun rootField(): CompiledField = error("The request is aborted before the cache is read")
}

/** Thrown by the test's last-stop interceptor so the request never leaves the machine. */
private class RequestRecorded : RuntimeException(REQUEST_RECORDED_MESSAGE)

private const val REQUEST_RECORDED_MESSAGE = "Request recorded, not sent"

private class CountingAccessTokenFetcher : AccessTokenFetcher {
var calls = 0
private set

override suspend fun fetch(): String? {
calls++
return "token"
}
}

private object TestAppBuildConfig : AppBuildConfig {
override val debug: Boolean = true
override val applicationId: String = "com.hedvig.dev.app"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import com.hedvig.android.auth.event.AuthEventStorage
import com.hedvig.android.core.buildconstants.AppBuildConfig
import com.hedvig.android.core.common.di.ActivityRetainedScope
import com.hedvig.android.core.common.di.AppScope
import com.hedvig.android.core.common.di.BaseHttpClient
import com.hedvig.android.core.common.di.PublicApolloClient
import com.hedvig.android.core.datastore.DeviceIdFetcher
import com.hedvig.android.core.demomode.IosDemoMode
import com.hedvig.android.initializable.Initializable
Expand All @@ -15,6 +17,7 @@ import com.hedvig.android.network.clients.NetworkLogPolicy
import dev.zacsweers.metro.DependencyGraph
import dev.zacsweers.metro.Provides
import dev.zacsweers.metrox.viewmodel.ViewModelGraph
import io.ktor.client.HttpClient

/**
* The iOS app's single graph. There is no Activity, so [ActivityRetainedScope] shares the graph's lifetime through
Expand All @@ -30,6 +33,13 @@ internal interface IosGraph : ViewModelGraph {

val apolloClient: ApolloClient

@PublicApolloClient
val publicApolloClient: ApolloClient

/** The token-free client behind [publicApolloClient], reached by tests to observe what it sends. */
@BaseHttpClient
val baseHttpClient: HttpClient

@DependencyGraph.Factory
interface Factory {
fun create(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import assertk.assertions.isInstanceOf
import assertk.assertions.isNotNull
import assertk.assertions.isNull
import assertk.assertions.isTrue
import assertk.assertions.single
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.exception.ApolloNetworkException
import com.apollographql.cache.normalized.FetchPolicy
Expand Down Expand Up @@ -48,7 +49,10 @@ import com.hedvig.android.network.clients.NetworkLogPolicy
import io.ktor.client.HttpClient
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.plugins.HttpSend
import io.ktor.client.plugins.plugin
import io.ktor.http.ContentType
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
Expand Down Expand Up @@ -381,6 +385,32 @@ class IosGraphTest {
assertThat(inputs.accessTokenFetcher.calls.value).isEqualTo(2)
}

@Test
fun `a query on the public Apollo client is sent without an Authorization header and without fetching a token`() {
val inputs = FakeInputs()
val holder = inputs.createHolder()
val sent = mutableListOf<Headers>()
// The graph's Darwin engine cannot be replaced, so the request is recorded just before the engine and aborted
// there. The client's default headers are already on it by then.
holder.graph.baseHttpClient.plugin(HttpSend).intercept { request ->
sent += request.headers.build()
throw IllegalStateException("Request recorded, not sent")
}

val response = runBlocking {
holder.graph.publicApolloClient
.query(PayingMemberPhoneNumberQuery())
.fetchPolicy(FetchPolicy.NetworkOnly)
.execute()
}

assertThat(response.exception?.message).isEqualTo("Request recorded, not sent")
assertThat(sent.size).isEqualTo(1)
assertThat(sent.single()["Authorization"]).isNull()
assertThat(sent.single()["Accept-Language"]).isNotNull()
assertThat(inputs.accessTokenFetcher.calls.value).isEqualTo(0)
}

@Test
fun `an UNAUTHENTICATED response does not log out or change demo mode`() {
val inputs = FakeInputs()
Expand Down
Loading