Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cleartext traffic check #122

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
2 changes: 2 additions & 0 deletions dependencies.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ ext.versions = [
]

ext.libs = [
android: "org.robolectric:android-all:10-robolectric-5803371",

appCompat: "androidx.appcompat:appcompat:$versions.appCompat",
material: "com.google.android.material:material:$versions.material",
multiDex: "androidx.multidex:multidex:$versions.multiDex",
Expand Down
1 change: 1 addition & 0 deletions scarlet-websocket-okhttp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ dependencies {
implementation project(':scarlet-core-internal')
implementation libs.rxJava
implementation libs.kotlin.stdlib
compileOnly libs.android

testImplementation project(':scarlet')
testImplementation project(':scarlet-websocket-mockwebserver')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,34 @@

package com.tinder.scarlet.websocket.okhttp

import android.os.Build
import android.security.NetworkSecurityPolicy
import com.tinder.scarlet.WebSocket
import com.tinder.scarlet.websocket.okhttp.request.RequestFactory
import com.tinder.scarlet.websocket.okhttp.request.StaticUrlRequestFactory
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import java.net.UnknownServiceException

fun OkHttpClient.newWebSocketFactory(requestFactory: RequestFactory): WebSocket.Factory {
return OkHttpWebSocket.Factory(OkHttpClientWebSocketConnectionEstablisher(this, requestFactory))
}

fun OkHttpClient.newWebSocketFactory(url: String): WebSocket.Factory {
if (url.startsWith("ws:", ignoreCase = true)) {
try {
if ((Build.VERSION.SDK_INT > 23 &&
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the Platform#isCleartextTrafficPermitted abstraction. we could tackle it in the next PR

!NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(
HttpUrl.parse("http:${url.substring(3)}")?.host())) ||
(Build.VERSION.SDK_INT == 23 &&
!NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted)) {
throw UnknownServiceException(
"CLEARTEXT communication to $url not permitted by network security policy")
}
} catch (_: ClassNotFoundException) {
// Not running on Android
}
}

return newWebSocketFactory(StaticUrlRequestFactory(url))
}