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 @@ -2,13 +2,16 @@ package com.afternote.afternote_fe.test

import androidx.lifecycle.SavedStateHandle
import com.afternote.core.common.reporting.ErrorReporter
import com.afternote.core.domain.error.CoreAuthFailure
import com.afternote.core.domain.testing.FakeAuthRepository
import com.afternote.core.domain.testing.FakePasskeyRepository
import com.afternote.core.domain.testing.FakeUserRepository
import com.afternote.core.model.user.Receiver
import com.afternote.core.model.user.User
import com.afternote.core.model.user.UserConnectedAccount
import com.afternote.core.model.user.UserPushSetting
import com.afternote.feature.afternote.domain.AfternoteType
import java.io.IOException

fun afternoteEditorSavedStateHandle(
initialType: AfternoteType,
Expand Down Expand Up @@ -63,6 +66,34 @@ fun appTestUserRepository(
onGetConnectedAccounts = { defaultConnectedAccounts(this.profile.email) }
}

/**
* 계측에서는 패스키 로그인을 시도하지 않는다 (#764).
*
* `LoginEntry` 는 화면 진입만으로 `startPasskeyLogin()` 을 부르므로, 갈아끼우지 않으면 로그인 화면을
* 지나는 모든 계측이 `auth/passkey/authenticate/options` 를 실서버로 호출하고 성공하면 기기의
* Credential Manager 선택기까지 띄운다 — `TestNotificationPermissionStoreModule` 이 막아 둔
* 시스템 다이얼로그와 같은 부류의 위험이다. 옵션 발급을 닫으면 `passkeyRequestJson` 이 서지 않아
* 선택기 호출 자체가 일어나지 않는다.
*
* `FakePasskeyRepository.strict()` 를 쓰지 않는 이유 — 그쪽은 닫힌 경로에서 예외를 던지는데
* `PasskeyLoginUseCase.requestOptions()` 도 `LoginViewModel.startPasskeyLogin()` 도 호출을
* `runCatching` 으로 감싸지 않는다. 던지면 `viewModelScope.launch` 를 뚫고 나가 앱이 죽는다.
* 그래서 `Result.failure` 로 닫는다.
*
* 실패 사유가 [CoreAuthFailure.NetworkUnavailable] 인 것도 우연이 아니다 —
* `startPasskeyLogin()` 이 리포팅을 건너뛰는 유일한 갈래라, 이걸로 닫아야
* `AppAndReceiverCompletionAndroidTest` 의 `fakeErrorReporter.failures.isEmpty()` 가 성립한다.
*/
fun appTestPasskeyRepository(): FakePasskeyRepository =
FakePasskeyRepository(
onAuthenticationOptions = {
Result.failure(CoreAuthFailure.NetworkUnavailable(IOException("androidTest: passkey disabled")))
},
onAuthenticate = {
Result.failure(CoreAuthFailure.NetworkUnavailable(IOException("androidTest: passkey disabled")))
},
)

class FakeErrorReporter : ErrorReporter {
val failures = mutableListOf<Pair<Throwable, Map<String, String>>>()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import com.afternote.afternote_fe.notification.NotificationPermissionRequestStor
import com.afternote.afternote_fe.notification.di.NotificationPermissionStoreModule
import com.afternote.afternote_fe.reporting.ErrorReportingModule
import com.afternote.core.common.reporting.ErrorReporter
import com.afternote.core.data.di.CorePasskeyRepositoryModule
import com.afternote.core.data.di.CoreUserRepositoryModule
import com.afternote.core.domain.repository.UserProfileCacheRepository
import com.afternote.core.domain.repository.UserRepository
import com.afternote.core.domain.repository.auth.AuthRepository
import com.afternote.core.domain.repository.auth.PasskeyRepository
import com.afternote.core.domain.testing.FakeUserProfileCacheRepository
import com.afternote.feature.mindrecord.data.di.MindRecordRepositoryModule
import com.afternote.feature.mindrecord.data.repositoryimpl.MindRecordReceiverRepositoryImpl
Expand Down Expand Up @@ -44,6 +46,29 @@ object TestCoreUserRepositoryModule {
fun provideUserProfileCacheRepository(): UserProfileCacheRepository = FakeUserProfileCacheRepository()
}

@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [CorePasskeyRepositoryModule::class],
)
object TestCorePasskeyRepositoryModule {
/**
* 계측에서는 패스키 로그인을 시도하지 않는다 (#764).
*
* 갈아끼우지 않으면 로그인 화면을 지나는 계측(`AppOnboardingCanaryTest`·
* `AccessibilitySmokeAndroidTest`·`AppAndReceiverCompletionAndroidTest`)이 화면 진입만으로
* 실 Retrofit 을 지나 `auth/passkey/authenticate/options` 를 호출하고, 성공하면 기기의
* Credential Manager 선택기가 테스트 UI 를 덮는다 — [TestNotificationPermissionStoreModule]
* 이 막아 둔 시스템 다이얼로그와 같은 부류의 flake 다.
*
* 닫는 방식과 실패 사유 선택의 근거는 [appTestPasskeyRepository] 에 적었다.
* 패스키 경로 자체의 판정은 단위 테스트(`LoginViewModelPasskeyTest` 등)가 맡는다.
*/
@Provides
@Singleton
fun providePasskeyRepository(): PasskeyRepository = appTestPasskeyRepository()
}

@Module
@TestInstallIn(
components = [SingletonComponent::class],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.afternote.core.data.di

import com.afternote.core.data.repoimpl.auth.PasskeyRepositoryImpl
import com.afternote.core.domain.repository.auth.PasskeyRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton

/**
* 패스키 로그인 저장소 바인딩.
*
* 이 모듈이 `public` 인 이유 — `app` 의 androidTest 가
* `@TestInstallIn(replaces = [CorePasskeyRepositoryModule::class])` 로 이 바인딩을 페이크로 갈아끼운다.
* `replaces` 는 모듈 클래스를 참조하므로 `internal` 로 닫을 수 없다.
*
* 그래서 형제 모듈들과 달리 `interface` 가 아니라 `abstract class` 다. 바인딩 메서드가 `public` 이면
* `'public' function exposes its 'internal' parameter type` 으로 컴파일되지 않는데, interface 멤버에는
* 가시성을 줄 수 없다. abstract class 라야 클래스는 열어 두고 메서드만 `internal` 로 닫는다.
*
* 갈아끼우지 않으면 계측이 실 Retrofit 을 지난다 — 로그인 화면 진입만으로
* `LoginEntry` 의 `LaunchedEffect` 가 `auth/passkey/authenticate/options` 를 실제로 호출하고,
* 성공하면 기기의 Credential Manager 선택기까지 부른다 (#764).
*/
@Module
@InstallIn(SingletonComponent::class)
abstract class CorePasskeyRepositoryModule {
@Binds
@Singleton
internal abstract fun bindPasskeyRepository(impl: PasskeyRepositoryImpl): PasskeyRepository
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.afternote.core.data.mapper.auth

import com.afternote.core.model.PasskeyAuthenticationOptions
import com.afternote.core.network.dto.PasskeyAuthenticateRequestDto
import com.afternote.core.network.dto.PasskeyAuthenticationOptionsDto
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray

/**
* 패스키 wire DTO ↔ Credential Manager 가 먹는 JSON 원문 사이의 변환.
*
* 봉투(`BaseResponse`)를 벗기고 나면 서버 응답은 이미 WebAuthn 표준 옵션의 모양이지만,
* Credential Manager 가 받는 것은 **객체가 아니라 JSON 문자열**이라 한 번 더 직렬화해야 한다.
* 그 조립을 여기 모아 두어 단위 테스트로 못박는다 — 키 이름이 하나만 어긋나도 시스템 선택기가
* 뜨지 않는데, 그 실패는 실기기에서만 드러나기 때문이다.
*/
object PasskeyMapper {
fun toAuthenticationOptions(dto: PasskeyAuthenticationOptionsDto): PasskeyAuthenticationOptions =
PasskeyAuthenticationOptions(
requestJson =
buildJsonObject {
put("challenge", dto.challenge)
put("timeout", dto.timeout)
put("rpId", dto.rpId)
putJsonArray("allowCredentials") {
dto.allowCredentials.forEach { descriptor ->
addJsonObject {
put("type", descriptor.type)
put("id", descriptor.id)
}
}
}
put("userVerification", dto.userVerification)
}.toString(),
)

/**
* assertion 원문을 **트리로만 옮겨** 요청 본문에 싣는다.
*
* 필드를 골라 담지 않는 이유 — 서명 대상(`clientDataJSON`)과 서명값이 이 안에 들어 있어
* 앱이 재조립하면 서버 검증이 깨진다. 파싱은 형식 확인 이상을 하지 않는다.
*
* @throws kotlinx.serialization.SerializationException assertion 이 JSON 이 아닐 때.
* @throws IllegalArgumentException assertion 이 JSON 객체가 아닐 때.
*/
fun toAuthenticateRequest(assertionJson: String): PasskeyAuthenticateRequestDto =
PasskeyAuthenticateRequestDto(credential = assertionJson.toJsonObject())

private fun String.toJsonObject(): JsonObject = Json.parseToJsonElement(this).jsonObject
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.afternote.core.data.repoimpl.auth

import com.afternote.core.common.result.runCatchingCancellable
import com.afternote.core.data.mapper.auth.AuthMapper
import com.afternote.core.data.mapper.auth.PasskeyMapper
import com.afternote.core.domain.error.CoreAuthFailure
import com.afternote.core.domain.repository.auth.PasskeyRepository
import com.afternote.core.model.PasskeyAuthenticationOptions
import com.afternote.core.model.Session
import com.afternote.core.network.model.requireData
import com.afternote.core.network.service.PasskeyApiService
import com.afternote.core.network.token.AccessTokenExpiryTracker
import java.io.IOException
import javax.inject.Inject

internal class PasskeyRepositoryImpl
@Inject
constructor(
private val passkeyApiService: PasskeyApiService,
// 패스키도 발급 응답에 expiresIn 을 실어 오므로 선제 reissue deadline 을 같은 규칙으로 기록한다 (#408/#410).
private val expiryTracker: AccessTokenExpiryTracker,
) : PasskeyRepository {
override suspend fun authenticationOptions(): Result<PasskeyAuthenticationOptions> =
runCatchingCancellable {
PasskeyMapper.toAuthenticationOptions(passkeyApiService.authenticateOptions().requireData())
}.mapTransportFailure()

override suspend fun authenticate(assertionJson: String): Result<Session.DefaultSession> =
runCatchingCancellable {
val data =
passkeyApiService
.authenticate(PasskeyMapper.toAuthenticateRequest(assertionJson))
.requireData()
// AuthRepositoryImpl.recordIssuedExpiresIn 과 같은 규칙 — 서버가 생략하면 이전 토큰 기준
// stale deadline 이 새 세션에 적용되지 않게 비우고, 만료는 401 안전망이 받는다.
data.expiresIn?.let(expiryTracker::record) ?: expiryTracker.clear()
AuthMapper.toDefaultLoginResult(data)
}.mapTransportFailure()
}

/**
* 전송 계층 실패만 도메인 예외로 옮긴다.
*
* `AuthRepositoryImpl.mapLoginFailure` 와 달리 서버 `code` 는 가르지 않는다. 패스키 실패 코드
* 4종(BE `ErrorCode` 2700~2703 — challenge 만료·검증 실패·미등록 자격·중복 등록)은 어느 것도
* 사용자가 화면에서 고칠 수 있는 갈래가 아니라, 지금은 전부 같은 안내 하나로 내려앉는다.
* 코드별로 다른 안내가 필요해지면 그때 가른다 — 미리 갈라 두면 쓰이지 않는 분기만 남는다.
*
* 반면 [IOException] 은 갈라야 한다. 서버가 거절한 것과 요청이 서버에 닿지도 못한 것은
* 소비처의 대응이 다르고, presentation 은 `core:network` 를 보지 않아 이 치환 없이는 구분할 수 없다.
*/
private fun <T> Result<T>.mapTransportFailure(): Result<T> =
when (val exception = exceptionOrNull()) {
is IOException -> Result.failure(CoreAuthFailure.NetworkUnavailable(exception))
else -> this
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package com.afternote.core.data.mapper.auth

import com.afternote.core.network.dto.PasskeyAuthenticationOptionsDto
import com.afternote.core.network.dto.PasskeyCredentialDescriptorDto
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test

/**
* 패스키 요청 JSON 조립 회귀 가드 (#764).
*
* 이 조립이 어긋나면 시스템 선택기가 아예 뜨지 않거나 서버 검증이 challenge 에서 깨진다.
* 어느 쪽이든 **실기기에서만** 드러나므로, 키 이름과 값 보존을 여기서 못박는다.
*
* 기준은 WebAuthn `PublicKeyCredentialRequestOptions` 이고, 값의 출처는 BE
* `PasskeyService.authenticateOptions()` 응답이다.
*/
class PasskeyMapperTest {
private fun optionsDto(allowCredentials: List<PasskeyCredentialDescriptorDto> = emptyList()) =
PasskeyAuthenticationOptionsDto(
challenge = "mptGkG6wQGe9xsxKPuhbiQ",
timeout = 300_000L,
rpId = "afternote.kro.kr",
allowCredentials = allowCredentials,
userVerification = "required",
)

@Test
fun `옵션 조립 - 표준 키 이름으로 전 필드를 싣는다`() {
val requestJson = PasskeyMapper.toAuthenticationOptions(optionsDto()).requestJson

val parsed = Json.parseToJsonElement(requestJson).jsonObject
assertEquals(JsonPrimitive("mptGkG6wQGe9xsxKPuhbiQ"), parsed["challenge"])
assertEquals(JsonPrimitive(300_000L), parsed["timeout"])
assertEquals(JsonPrimitive("afternote.kro.kr"), parsed["rpId"])
assertEquals(JsonPrimitive("required"), parsed["userVerification"])
assertTrue(parsed.getValue("allowCredentials").jsonArray.isEmpty())
}

@Test
fun `옵션 조립 - challenge 는 한 글자도 바꾸지 않는다`() {
// base64url 원문이다. 서버가 clientDataJSON 안의 값과 대조해 소비하므로 패딩 하나만
// 달라져도 검증이 깨진다 — 재인코딩하지 않는지 고정한다.
val challenge = "abc-_123"
val requestJson =
PasskeyMapper.toAuthenticationOptions(optionsDto().copy(challenge = challenge)).requestJson

assertEquals(JsonPrimitive(challenge), Json.parseToJsonElement(requestJson).jsonObject["challenge"])
}

@Test
fun `옵션 조립 - 서버가 후보를 채우면 그대로 실어 보낸다`() {
val requestJson =
PasskeyMapper
.toAuthenticationOptions(
optionsDto(allowCredentials = listOf(PasskeyCredentialDescriptorDto(type = "public-key", id = "abc"))),
).requestJson

val candidates =
Json
.parseToJsonElement(requestJson)
.jsonObject
.getValue("allowCredentials")
.jsonArray
assertEquals(1, candidates.size)
assertEquals(JsonPrimitive("public-key"), candidates.first().jsonObject["type"])
assertEquals(JsonPrimitive("abc"), candidates.first().jsonObject["id"])
}

@Test
fun `검증 요청 - assertion 하위 트리를 손대지 않고 credential 로 감싼다`() {
val assertion =
"""{"id":"cid","rawId":"cid","type":"public-key",""" +
""""response":{"clientDataJSON":"cdj","authenticatorData":"ad","signature":"sig","userHandle":"uh"}}"""

val credential = PasskeyMapper.toAuthenticateRequest(assertion).credential

assertEquals(JsonPrimitive("cid"), credential["id"])
val response = credential.getValue("response").jsonObject
assertEquals(JsonPrimitive("cdj"), response["clientDataJSON"])
assertEquals(JsonPrimitive("sig"), response["signature"])
assertEquals(JsonPrimitive("uh"), response["userHandle"])
}

@Test
fun `검증 요청 - assertion 이 JSON 객체가 아니면 조용히 보내지 않고 드러낸다`() {
assertThrows(IllegalArgumentException::class.java) {
PasskeyMapper.toAuthenticateRequest("\"not-an-object\"")
}
}
}
Loading
Loading