feat(subbanner): 응답 계약과 안전한 링크 실행을 추가한다

This commit is contained in:
2026-10-30 12:23:28 +09:00
parent 95e5c2e11f
commit fb914bb6ab
4 changed files with 394 additions and 0 deletions
@@ -0,0 +1,138 @@
package kr.co.vividnext.sodalive.v2.widget.subbanner
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class SubBannerContractTest {
@Test
fun `정수 JSON은 JavaScript 정밀도 범위를 넘어도 Kotlin Long 그대로 보존된다`() {
val items = decode(
"""[
${banner(id = "9007199254740993")},
${banner(id = "9223372036854775807")}
]"""
).toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION)
assertEquals(listOf(9_007_199_254_740_993L, Long.MAX_VALUE), items.map { it.id })
}
@Test
fun `Android 웹 iOS의 여덟 조합에서 Android 또는 웹이 있는 항목만 순서대로 유지한다`() {
val entries = (0..7).map { mask ->
banner(
id = mask.toString(),
android = if (mask and 4 != 0) "\"sodalive://event/$mask\"" else "null",
web = if (mask and 2 != 0) "\"https://example.invalid/$mask\"" else "null",
ios = if (mask and 1 != 0) "\"ios-app://event/$mask\"" else "null"
)
}
val items = decode(entries.joinToString(",", "[", "]")).toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION)
assertEquals(listOf(2L, 3L, 4L, 5L, 6L, 7L), items.map { it.id })
}
@Test
fun `placement는 정확히 일치해야 하며 응답 순서를 재정렬하거나 개수를 제한하지 않는다`() {
val entries = listOf(
banner(id = "9"),
banner(id = "1", placement = "CONTENT_RECOMMENDATION"),
banner(id = "8", placement = "home_recommendation"),
banner(id = "7", placement = "UNKNOWN"),
banner(id = "6"),
banner(id = "5"),
banner(id = "4")
)
val decoded = decode(entries.joinToString(",", "[", "]"))
assertEquals(listOf(9L, 6L, 5L, 4L), decoded.toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION).map { it.id })
assertEquals(listOf(1L), decoded.toSubBannerItems(SubBannerPlacement.CONTENT_RECOMMENDATION).map { it.id })
}
@Test
fun `잘못된 개별 필드와 정수 범위 초과는 정상 이웃 배너를 제거하지 않는다`() {
val invalid = listOf("1.5", "1e3", "\"7\"", "9223372036854775808", "null", "{}", "[]", "true")
.map { banner(id = it) }
val malformed = listOf(
"null",
"false",
"[]",
"{}",
banner().replace("\"id\":7,", ""),
banner().replace("\"imageUrl\":\"https://example.invalid/image\"", "\"imageUrl\":42"),
banner().replace("\"placement\":\"HOME_RECOMMENDATION\"", "\"placement\":{}")
)
val items = decode((invalid + malformed + banner(id = "10")).joinToString(",", "[", "]"))
.toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION)
assertEquals(listOf(10L), items.map { it.id })
}
@Test
fun `이미지는 host가 있는 절대 HTTP 또는 HTTPS만 허용한다`() {
listOf(
"",
"image.png",
"//example.invalid/image",
"file:///image",
"data:image/png;base64,a",
"https:/image",
"https:///image",
"https://",
"https://example.invalid/%zz",
" https://example.invalid/image "
)
.forEach { image ->
val entries = "[${banner().replace("https://example.invalid/image", image)},${banner(id = "8")}]"
val items = decode(entries).toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION)
assertEquals(image, listOf(8L), items.map { it.id })
}
}
@Test
fun `잘못된 Android와 iOS 단독 항목은 제외하고 유효 웹은 원문으로 보존한다`() {
val items = decode(
"""[
${banner(android = "\"JaVaScRiPt:alert(1)\"", web = "\"HTTPS://example.invalid/a%2fb?x=%2F#Raw\"")},
${banner(id = "8", android = "\"https:/no-host\"")},
${banner(id = "9", android = "null", ios = "\"ios-app://event/9\"")}
]"""
).toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION)
assertEquals(1, items.size)
assertEquals("HTTPS://example.invalid/a%2fb?x=%2F#Raw", items.single().webUrl)
assertEquals(null, items.single().androidDeepLink)
}
@Test
fun `Android 링크가 유효하면 잘못된 웹 필드가 표시를 방해하지 않는다`() {
val item = decode("[${banner(web = "\"sodalive://not-a-web-url\"")}]")
.toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION).single()
assertEquals("sodalive://event/7", item.androidDeepLink)
assertEquals(null, item.webUrl)
assertEquals("https://example.invalid/image", item.imageUrl)
}
@Test
fun `빈 목록과 null 목록은 빈 표시 목록이다`() {
assertTrue(decode("[]").toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION).isEmpty())
assertTrue((null as List<SubBannerResponse?>?).toSubBannerItems(SubBannerPlacement.CONTENT_RECOMMENDATION).isEmpty())
}
private fun decode(json: String): List<SubBannerResponse?> =
Gson().fromJson(json, object : TypeToken<List<SubBannerResponse?>>() {}.type)
private fun banner(
id: String = "7",
placement: String = "HOME_RECOMMENDATION",
android: String = "\"sodalive://event/7\"",
web: String = "null",
ios: String = "null"
) = """{"id":$id,"placement":"$placement","imageUrl":"https://example.invalid/image",
"androidDeepLink":$android,"webUrl":$web,"iosDeepLink":$ios}"""
}
@@ -0,0 +1,139 @@
package kr.co.vividnext.sodalive.v2.widget.subbanner
import android.app.Application
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import androidx.test.core.app.ApplicationProvider
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], application = Application::class)
class SubBannerLinkPolicyTest {
@Test
fun `Gson에서 표시 항목을 얻어 실제 Android Context의 ACTION_VIEW 진입까지 연결한다`() {
val responses: List<SubBannerResponse?> = Gson().fromJson(
"""[{
"id":9007199254740993,"placement":"HOME_RECOMMENDATION","imageUrl":"https://example.invalid/image",
"androidDeepLink":"sodalive://event/7?q=%2f","webUrl":"https://example.invalid/fallback","iosDeepLink":null
}]""",
object : TypeToken<List<SubBannerResponse?>>() {}.type
)
val item = responses.toSubBannerItems(SubBannerPlacement.HOME_RECOMMENDATION).single()
val application = ApplicationProvider.getApplicationContext<Application>()
assertTrue(SubBannerLinkPolicy.launch(application, item))
val intent = shadowOf(application).nextStartedActivity
assertEquals(9_007_199_254_740_993L, item.id)
assertEquals(Intent.ACTION_VIEW, intent.action)
assertEquals("sodalive://event/7?q=%2f", intent.dataString)
assertTrue(intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0)
assertNull(shadowOf(application).nextStartedActivity)
}
@Test
fun `Android 성공 시 웹을 실행하지 않고 ACTION_VIEW의 URI 원문을 보존한다`() {
val raw = "SoDaLiVe://event/7?a=%2f&b=%2F#Raw"
val context = LaunchContext()
assertTrue(SubBannerLinkPolicy.launch(context, item(raw, "https://example.invalid/fallback")))
val intent = context.started.single()
assertEquals(Intent.ACTION_VIEW, intent.action)
assertEquals(raw, intent.dataString)
assertNull(intent.extras)
assertNull(intent.component)
assertNull(intent.`package`)
}
@Test
fun `Android가 없거나 잘못되면 유효 웹을 원문 그대로 한 번 실행한다`() {
listOf(null, "", "relative/path", "https:/no-host", " https://example.invalid/path ").forEach { android ->
val context = LaunchContext()
val web = "HTTPS://example.invalid/a%2fb?x=%2F#Raw"
assertTrue(SubBannerLinkPolicy.launch(context, item(android, web)))
assertEquals(listOf(web), context.started.map { it.dataString })
}
}
@Test
fun `금지 scheme은 대소문자와 관계없이 거부하며 웹 필드에는 HTTP 계열만 허용한다`() {
listOf("javascript:alert(1)", "JaVaScRiPt:alert(1)", "DATA:text/plain,a", "FiLe:///tmp/a", "CoNtEnT://items/1")
.forEach { link ->
val context = LaunchContext()
assertFalse(link, SubBannerLinkPolicy.launch(context, item(link, link)))
assertTrue(context.started.isEmpty())
}
listOf("sodalive://event/7", "http:/path", "https:///path", "//example.invalid", "https://example.invalid/%zz")
.forEach { web ->
val context = LaunchContext()
assertFalse(web, SubBannerLinkPolicy.launch(context, item(null, web)))
assertTrue(context.started.isEmpty())
}
}
@Test
fun `Android 실행 불가와 보안 예외에서만 유효 웹으로 한 번 대체 실행한다`() {
listOf(ActivityNotFoundException("private"), SecurityException("private")).forEach { failure ->
val context = LaunchContext(listOf(failure))
assertTrue(SubBannerLinkPolicy.launch(context, item("sodalive://event/7", "https://example.invalid/fallback")))
assertEquals(listOf("sodalive://event/7", "https://example.invalid/fallback"), context.started.map { it.dataString })
}
}
@Test
fun `두 실행 모두 실패해도 예외 없이 false이고 웹 재시도는 없다`() {
val context = LaunchContext(listOf(ActivityNotFoundException("private"), SecurityException("private")))
assertFalse(SubBannerLinkPolicy.launch(context, item("sodalive://event/7", "https://example.invalid/fallback")))
assertEquals(2, context.started.size)
}
@Test
fun `Android만 실패하거나 웹만 실패하면 실행 횟수를 늘리지 않는다`() {
listOf(item("sodalive://event/7", null), item(null, "https://example.invalid/page")).forEach { banner ->
val context = LaunchContext(listOf(SecurityException("private")))
assertFalse(SubBannerLinkPolicy.launch(context, banner))
assertEquals(1, context.started.size)
}
}
@Test
fun `intent URI도 parseUri 없이 원문 ACTION_VIEW만 실행한다`() {
val raw = "intent://event/7#Intent;scheme=sodalive;package=other.app;S.secret=value;end"
val context = LaunchContext()
assertTrue(SubBannerLinkPolicy.launch(context, item(raw, null)))
val intent = context.started.single()
assertEquals(Intent.ACTION_VIEW, intent.action)
assertEquals(raw, intent.dataString)
assertNull(intent.`package`)
assertNull(intent.extras)
}
private fun item(android: String?, web: String?) = SubBannerItem(7L, "https://example.invalid/image", android, web)
private class LaunchContext(private val failures: List<RuntimeException> = emptyList()) :
ContextWrapper(ApplicationProvider.getApplicationContext<Context>()) {
val started = mutableListOf<Intent>()
override fun startActivity(intent: Intent) {
started += intent
failures.getOrNull(started.lastIndex)?.let { throw it }
}
}
}