diff --git a/.editorconfig b/.editorconfig index 9069e9b7..9fc93349 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,6 +1,7 @@ [*.{kt,kts}] -indent_style=space -indent_size=4 -continuation_indent_size=4 -insert_final_newline=true -disabled_rules=import-ordering +indent_style = space +indent_size = 4 +continuation_indent_size = 4 +insert_final_newline = true +import_ordering = disabled +max_line_length = 100 diff --git a/app/build.gradle b/app/build.gradle index aa0edb42..a02a4f76 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -6,7 +6,7 @@ buildscript { } dependencies { classpath 'com.github.triplet.gradle:play-publisher:3.5.0' - classpath 'com.diffplug.spotless:spotless-plugin-gradle:5.14.1' + classpath 'com.diffplug.spotless:spotless-plugin-gradle:6.23.0' classpath 'de.mannodermaus.gradle.plugins:android-junit5:1.8.2.1' } ext { @@ -174,7 +174,7 @@ dependencies { testImplementation "io.ktor:ktor-test-dispatcher:$ktorVersion" // ORM - def room_version = '2.6.0-rc01' + def room_version = '2.6.0' implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" implementation "androidx.room:room-ktx:$room_version" @@ -221,7 +221,9 @@ dependencies { spotless { kotlin { - ktlint('0.37.2').userData(['disabled_rules': 'import-ordering', 'max_line_length': '100']) + ktlint('1.0.1').editorConfigOverride([ + 'ktlint_standard_property-naming': 'disabled' + ]) target '**/*.kt' } } diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/TestAppModule.kt b/app/src/androidTest/java/tech/relaycorp/gateway/TestAppModule.kt index e20dd3e4..35dd2a6c 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/TestAppModule.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/TestAppModule.kt @@ -12,7 +12,7 @@ import javax.inject.Singleton @Module class TestAppModule( - app: TestApp + app: TestApp, ) : AppModule(app) { @Provides @@ -22,7 +22,7 @@ class TestAppModule( @Provides fun mockedConnectStateObserver( - connectionStateFlow: MutableStateFlow + connectionStateFlow: MutableStateFlow, ): ConnectionStateObserver { val mock = mock() whenever(mock.observe()).thenReturn(connectionStateFlow) diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/EndpointPreRegistrationServiceTest.kt b/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/EndpointPreRegistrationServiceTest.kt index b9b8e960..23b8ef67 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/EndpointPreRegistrationServiceTest.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/EndpointPreRegistrationServiceTest.kt @@ -57,7 +57,7 @@ class EndpointPreRegistrationServiceTest { fun requestPreRegistration() = runBlocking(coroutineContext) { val serviceIntent = Intent( getApplicationContext(), - EndpointPreRegistrationService::class.java + EndpointPreRegistrationService::class.java, ) val binder = serviceRule.bindService(serviceIntent) @@ -79,7 +79,7 @@ class EndpointPreRegistrationServiceTest { } assertEquals( EndpointPreRegistrationService.REGISTRATION_AUTHORIZATION, - resultMessage!!.what + resultMessage!!.what, ) // Check we got a valid authorization @@ -88,11 +88,11 @@ class EndpointPreRegistrationServiceTest { val gatewayCert = localConfig.getIdentityCertificate() val authorization = PrivateNodeRegistrationAuthorization.deserialize( resultData.getByteArray("auth")!!, - gatewayCert.subjectPublicKey + gatewayCert.subjectPublicKey, ) assertEquals( getApplicationContext().packageName, - authorization.gatewayData.toString(Charset.defaultCharset()) + authorization.gatewayData.toString(Charset.defaultCharset()), ) } @@ -100,7 +100,7 @@ class EndpointPreRegistrationServiceTest { fun invalidRequestIsIgnored() { val serviceIntent = Intent( getApplicationContext(), - EndpointPreRegistrationService::class.java + EndpointPreRegistrationService::class.java, ) val binder = serviceRule.bindService(serviceIntent) @@ -116,7 +116,7 @@ class EndpointPreRegistrationServiceTest { val serviceIntent = Intent( getApplicationContext(), - EndpointPreRegistrationService::class.java + EndpointPreRegistrationService::class.java, ) val binder = serviceRule.bindService(serviceIntent) @@ -138,7 +138,7 @@ class EndpointPreRegistrationServiceTest { } assertEquals( EndpointPreRegistrationService.GATEWAY_NOT_REGISTERED, - resultMessage!!.what + resultMessage!!.what, ) } } diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/GatewaySyncServiceParcelCollectionTest.kt b/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/GatewaySyncServiceParcelCollectionTest.kt index 57de35ff..11ef26cc 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/GatewaySyncServiceParcelCollectionTest.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/GatewaySyncServiceParcelCollectionTest.kt @@ -49,8 +49,8 @@ class GatewaySyncServiceParcelCollectionTest { serviceRule.bindService( Intent( getApplicationContext(), - GatewaySyncService::class.java - ) + GatewaySyncService::class.java, + ), ) } @@ -66,15 +66,15 @@ class GatewaySyncServiceParcelCollectionTest { arrayOf( Signer( PDACertPath.PRIVATE_ENDPOINT, - KeyPairSet.PRIVATE_ENDPOINT.private - ) + KeyPairSet.PRIVATE_ENDPOINT.private, + ), ), - StreamingMode.KeepAlive + StreamingMode.KeepAlive, ).take(1).first() assertEquals( Parcel.deserialize(parcel).id, - Parcel.deserialize(parcelCollection.parcelSerialized).id + Parcel.deserialize(parcelCollection.parcelSerialized).id, ) } @@ -89,10 +89,11 @@ class GatewaySyncServiceParcelCollectionTest { arrayOf( Signer( PDACertPath.PRIVATE_ENDPOINT, - KeyPairSet.INTERNET_GW.private // Invalid key to trigger invalid handshake - ) + // Invalid key to trigger invalid handshake + KeyPairSet.INTERNET_GW.private, + ), ), - StreamingMode.CloseUponCompletion + StreamingMode.CloseUponCompletion, ) .collect() } diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/GatewaySyncServiceParcelDeliveryTest.kt b/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/GatewaySyncServiceParcelDeliveryTest.kt index b60cb69b..d9adb103 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/GatewaySyncServiceParcelDeliveryTest.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/background/endpoint/GatewaySyncServiceParcelDeliveryTest.kt @@ -21,8 +21,8 @@ import tech.relaycorp.relaynet.bindings.pdc.RejectedParcelException import tech.relaycorp.relaynet.bindings.pdc.Signer import tech.relaycorp.relaynet.messages.Parcel import tech.relaycorp.relaynet.messages.Recipient -import tech.relaycorp.relaynet.testing.pki.PDACertPath import tech.relaycorp.relaynet.testing.pki.KeyPairSet +import tech.relaycorp.relaynet.testing.pki.PDACertPath import tech.relaycorp.relaynet.wrappers.x509.Certificate import java.time.ZonedDateTime import javax.inject.Inject @@ -47,8 +47,8 @@ class GatewaySyncServiceParcelDeliveryTest { serviceRule.bindService( Intent( getApplicationContext(), - GatewaySyncService::class.java - ) + GatewaySyncService::class.java, + ), ) } @@ -63,14 +63,14 @@ class GatewaySyncServiceParcelDeliveryTest { recipient, ByteArray(0), PDACertPath.PRIVATE_ENDPOINT, - senderCertificateChain = setOf(PDACertPath.PRIVATE_GW) + senderCertificateChain = setOf(PDACertPath.PRIVATE_GW), ).serialize(KeyPairSet.PRIVATE_ENDPOINT.private) PoWebClient.initLocal(PDCServer.PORT).deliverParcel(parcel, endpointSigner) val storedParcels = storedParcelDao.listForRecipients( listOf(MessageAddress.of(recipientId)), - RecipientLocation.ExternalGateway + RecipientLocation.ExternalGateway, ).first() assertEquals(1, storedParcels.size) } @@ -87,7 +87,7 @@ class GatewaySyncServiceParcelDeliveryTest { ByteArray(0), PDACertPath.PRIVATE_ENDPOINT, creationDate = fiveMinutesAgo, - ttl = 1 + ttl = 1, ).serialize(KeyPairSet.PRIVATE_ENDPOINT.private) PoWebClient.initLocal(PDCServer.PORT).deliverParcel(parcel, endpointSigner) diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/data/database/ParcelCollectionDaoTest.kt b/app/src/androidTest/java/tech/relaycorp/gateway/data/database/ParcelCollectionDaoTest.kt index a37a221e..e001fe52 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/data/database/ParcelCollectionDaoTest.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/data/database/ParcelCollectionDaoTest.kt @@ -21,12 +21,12 @@ class ParcelCollectionDaoTest { runBlocking { val element = ParcelCollectionFactory.build() assertFalse( - dao.exists(element.recipientAddress, element.senderAddress, element.messageId) + dao.exists(element.recipientAddress, element.senderAddress, element.messageId), ) dao.insert(element) assertTrue( - dao.exists(element.recipientAddress, element.senderAddress, element.messageId) + dao.exists(element.recipientAddress, element.senderAddress, element.messageId), ) } } diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/data/database/StoredParcelDaoTest.kt b/app/src/androidTest/java/tech/relaycorp/gateway/data/database/StoredParcelDaoTest.kt index f130b21a..c1151c63 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/data/database/StoredParcelDaoTest.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/data/database/StoredParcelDaoTest.kt @@ -42,13 +42,13 @@ class StoredParcelDaoTest { StoredParcelFactory.build() .copy( recipientLocation = RecipientLocation.ExternalGateway, - expirationTimeUtc = nowInUtc().minusMinutes(5) + expirationTimeUtc = nowInUtc().minusMinutes(5), ) .also { dao.insert(it) } val parcelUnexpired = StoredParcelFactory.build() .copy( recipientLocation = RecipientLocation.ExternalGateway, - expirationTimeUtc = nowInUtc().plusMinutes(5) + expirationTimeUtc = nowInUtc().plusMinutes(5), ) .also { dao.insert(it) } diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/data/disk/FileStoreTest.kt b/app/src/androidTest/java/tech/relaycorp/gateway/data/disk/FileStoreTest.kt index 405d867e..2cce77f4 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/data/disk/FileStoreTest.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/data/disk/FileStoreTest.kt @@ -39,7 +39,7 @@ class FileStoreTest { val readData = store.read(fileName) assertEquals( message, - readData!!.toString(Charset.defaultCharset()) + readData!!.toString(Charset.defaultCharset()), ) } } @@ -55,7 +55,7 @@ class FileStoreTest { val readData = store.read(fileName) assertEquals( message2, - readData!!.toString(Charset.defaultCharset()) + readData!!.toString(Charset.defaultCharset()), ) } } diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/domain/endpoint/NotifyEndpointsTest.kt b/app/src/androidTest/java/tech/relaycorp/gateway/domain/endpoint/NotifyEndpointsTest.kt index 6d5c3729..d8b3b685 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/domain/endpoint/NotifyEndpointsTest.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/domain/endpoint/NotifyEndpointsTest.kt @@ -42,17 +42,17 @@ class NotifyEndpointsTest { notifyEndpoints.notify( listOf(endpoint1, endpoint2), - NotificationType.IncomingParcel + NotificationType.IncomingParcel, ) verify(context, times(2)).sendBroadcast( check { assertTrue( listOf(endpoint1.applicationId, endpoint2.applicationId) - .contains(it.component?.packageName) + .contains(it.component?.packageName), ) assertEquals(".Receiver", it.component?.className) - } + }, ) verifyNoMoreInteractions(context) } @@ -69,14 +69,14 @@ class NotifyEndpointsTest { notifyEndpoints.notify( listOf(endpoint, endpoint), - NotificationType.IncomingParcel + NotificationType.IncomingParcel, ) verify(context, times(1)).sendBroadcast( check { assertEquals(appId, it.component?.packageName) assertEquals(".Receiver", it.component?.className) - } + }, ) verifyNoMoreInteractions(context) } @@ -95,7 +95,7 @@ class NotifyEndpointsTest { check { assertEquals(endpoint.applicationId, it.component?.packageName) assertEquals(receiverName, it.component?.className) - } + }, ) } } @@ -114,7 +114,7 @@ class NotifyEndpointsTest { whenever(getEndpointReceiver.get(any(), any())).thenReturn(null) notifyEndpoints.notify( LocalEndpointFactory.build(), - NotificationType.IncomingParcel + NotificationType.IncomingParcel, ) verify(context, never()).sendBroadcast(any(), any()) } diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/test/BaseActivityTestRule.kt b/app/src/androidTest/java/tech/relaycorp/gateway/test/BaseActivityTestRule.kt index 147d2136..ae4a8ebc 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/test/BaseActivityTestRule.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/test/BaseActivityTestRule.kt @@ -13,7 +13,7 @@ import kotlin.reflect.KClass class BaseActivityTestRule( activityClass: KClass, - launchActivity: Boolean = true + launchActivity: Boolean = true, ) : TestRule { private val clearPreferencesRule: ClearPreferencesRule = ClearPreferencesRule() @@ -22,7 +22,7 @@ class BaseActivityTestRule( private val activityTestRule: ActivityTestRule = ActivityTestRule( activityClass.java, true, - launchActivity + launchActivity, ) override fun apply(base: Statement, description: Description): Statement { diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/test/ClearTestDatabaseRule.kt b/app/src/androidTest/java/tech/relaycorp/gateway/test/ClearTestDatabaseRule.kt index 467251e6..5b13112a 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/test/ClearTestDatabaseRule.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/test/ClearTestDatabaseRule.kt @@ -12,13 +12,12 @@ class ClearTestDatabaseRule : TestRule { @Inject lateinit var database: AppDatabase - override fun apply(base: Statement, description: Description?) = - object : Statement() { - override fun evaluate() { - component.inject(this@ClearTestDatabaseRule) - database.clearAllTables() - base.evaluate() - database.clearAllTables() - } + override fun apply(base: Statement, description: Description?) = object : Statement() { + override fun evaluate() { + component.inject(this@ClearTestDatabaseRule) + database.clearAllTables() + base.evaluate() + database.clearAllTables() } + } } diff --git a/app/src/androidTest/java/tech/relaycorp/gateway/test/KeystoreResetTestRule.kt b/app/src/androidTest/java/tech/relaycorp/gateway/test/KeystoreResetTestRule.kt index 85c19e9a..77bea1cc 100644 --- a/app/src/androidTest/java/tech/relaycorp/gateway/test/KeystoreResetTestRule.kt +++ b/app/src/androidTest/java/tech/relaycorp/gateway/test/KeystoreResetTestRule.kt @@ -28,27 +28,26 @@ class KeystoreResetTestRule : TestRule { @Inject lateinit var certificateStore: CertificateStore - override fun apply(base: Statement, description: Description?) = - object : Statement() { - override fun evaluate() { - AppTestProvider.component.inject(this@KeystoreResetTestRule) - - val keystoresFile = File("${context.filesDir}/keystores") - keystoresFile.deleteRecursively() - runBlocking { - privateKeyStore.saveIdentityKey(KeyPairSet.PRIVATE_GW.private) - certificateStore.save( - CertificationPath( - PDACertPath.PRIVATE_GW, - emptyList() - ), - internetGatewayPreferences.getId() - ) - } - - base.evaluate() - - keystoresFile.deleteRecursively() + override fun apply(base: Statement, description: Description?) = object : Statement() { + override fun evaluate() { + AppTestProvider.component.inject(this@KeystoreResetTestRule) + + val keystoresFile = File("${context.filesDir}/keystores") + keystoresFile.deleteRecursively() + runBlocking { + privateKeyStore.saveIdentityKey(KeyPairSet.PRIVATE_GW.private) + certificateStore.save( + CertificationPath( + PDACertPath.PRIVATE_GW, + emptyList(), + ), + internetGatewayPreferences.getId(), + ) } + + base.evaluate() + + keystoresFile.deleteRecursively() } + } } diff --git a/app/src/main/java/tech/relaycorp/gateway/App.kt b/app/src/main/java/tech/relaycorp/gateway/App.kt index b6ccdbe3..9aaf6a1d 100644 --- a/app/src/main/java/tech/relaycorp/gateway/App.kt +++ b/app/src/main/java/tech/relaycorp/gateway/App.kt @@ -108,7 +108,7 @@ open class App : Application() { this@App, Configuration.Builder() .setWorkerFactory(publicSyncWorkerFactory) - .build() + .build(), ) WorkManager.getInstance(this@App) .enqueueUniquePeriodicWork( @@ -118,9 +118,9 @@ open class App : Application() { .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) - .build() + .build(), ) - .build() + .build(), ) } diff --git a/app/src/main/java/tech/relaycorp/gateway/AppModule.kt b/app/src/main/java/tech/relaycorp/gateway/AppModule.kt index 53d8ea90..6504258b 100644 --- a/app/src/main/java/tech/relaycorp/gateway/AppModule.kt +++ b/app/src/main/java/tech/relaycorp/gateway/AppModule.kt @@ -10,7 +10,7 @@ import dagger.Provides @Module open class AppModule( - private val app: App + private val app: App, ) { @Provides @@ -33,6 +33,5 @@ open class AppModule( app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @Provides - fun wifiManager() = - app.getSystemService(Context.WIFI_SERVICE) as WifiManager + fun wifiManager() = app.getSystemService(Context.WIFI_SERVICE) as WifiManager } diff --git a/app/src/main/java/tech/relaycorp/gateway/StrictModeSetup.kt b/app/src/main/java/tech/relaycorp/gateway/StrictModeSetup.kt index c4647ef4..ad658bc6 100644 --- a/app/src/main/java/tech/relaycorp/gateway/StrictModeSetup.kt +++ b/app/src/main/java/tech/relaycorp/gateway/StrictModeSetup.kt @@ -20,13 +20,13 @@ object StrictModeSetup { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { penaltyListener( ContextCompat.getMainExecutor(context), - ThreadPolicyViolationListener() + ThreadPolicyViolationListener(), ) } else { penaltyLog() } } - .build() + .build(), ) StrictMode.setVmPolicy( StrictMode.VmPolicy.Builder() @@ -35,13 +35,13 @@ object StrictModeSetup { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { penaltyListener( ContextCompat.getMainExecutor(context), - VMViolationListener() + VMViolationListener(), ) } else { penaltyLog() } } - .build() + .build(), ) } @@ -65,7 +65,7 @@ object StrictModeSetup { // Huawei startup font loading "Typeface.loadSystemFonts", // Xiaomi startup font loading - "TypefaceUtils.loadFontSettings" + "TypefaceUtils.loadFontSettings", ) @RequiresApi(Build.VERSION_CODES.P) @@ -90,6 +90,6 @@ object StrictModeSetup { "io.ktor.client.engine", "io.ktor.network.sockets", "io.netty.channel.socket", - "io.grpc.okhttp" + "io.grpc.okhttp", ) } diff --git a/app/src/main/java/tech/relaycorp/gateway/background/CheckInternetAccess.kt b/app/src/main/java/tech/relaycorp/gateway/background/CheckInternetAccess.kt index c4e16ece..c1c678ac 100644 --- a/app/src/main/java/tech/relaycorp/gateway/background/CheckInternetAccess.kt +++ b/app/src/main/java/tech/relaycorp/gateway/background/CheckInternetAccess.kt @@ -4,10 +4,9 @@ import javax.inject.Inject class CheckInternetAccess @Inject constructor( - private val pingRemoteServer: PingRemoteServer + private val pingRemoteServer: PingRemoteServer, ) { - suspend fun check() = - pingRemoteServer.pingURL(INTERNET_TEST_WEBSITE) + suspend fun check() = pingRemoteServer.pingURL(INTERNET_TEST_WEBSITE) companion object { private const val INTERNET_TEST_WEBSITE = "https://google.com" diff --git a/app/src/main/java/tech/relaycorp/gateway/background/CheckInternetGatewayAccess.kt b/app/src/main/java/tech/relaycorp/gateway/background/CheckInternetGatewayAccess.kt index 947ca728..23a58aef 100644 --- a/app/src/main/java/tech/relaycorp/gateway/background/CheckInternetGatewayAccess.kt +++ b/app/src/main/java/tech/relaycorp/gateway/background/CheckInternetGatewayAccess.kt @@ -9,7 +9,7 @@ import javax.inject.Inject class CheckInternetGatewayAccess @Inject constructor( private val internetGatewayPreferences: InternetGatewayPreferences, - private val pingRemoteServer: PingRemoteServer + private val pingRemoteServer: PingRemoteServer, ) { suspend fun check(): Boolean { val address = try { diff --git a/app/src/main/java/tech/relaycorp/gateway/background/ConnectionStateObserver.kt b/app/src/main/java/tech/relaycorp/gateway/background/ConnectionStateObserver.kt index c8e0106e..cdf2a927 100644 --- a/app/src/main/java/tech/relaycorp/gateway/background/ConnectionStateObserver.kt +++ b/app/src/main/java/tech/relaycorp/gateway/background/ConnectionStateObserver.kt @@ -26,7 +26,7 @@ open class ConnectionStateObserver private val wifiManager: WifiManager, private val pingRemoteServer: PingRemoteServer, private val checkInternetAccess: CheckInternetAccess, - private val checkInternetGatewayAccess: CheckInternetGatewayAccess + private val checkInternetGatewayAccess: CheckInternetGatewayAccess, ) { private val state = MutableStateFlow(ConnectionState.Disconnected) @@ -82,14 +82,13 @@ open class ConnectionStateObserver connectivityManager.getNetworkCapabilities(this) ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true - private fun Int.toIpAddressString() = - String.format( - "%d.%d.%d.%d", - this and 0xff, - this shr 8 and 0xff, - this shr 16 and 0xff, - this shr 24 and 0xff - ) + private fun Int.toIpAddressString() = String.format( + "%d.%d.%d.%d", + this and 0xff, + this shr 8 and 0xff, + this shr 16 and 0xff, + this shr 24 and 0xff, + ) private fun String.toFullServerAddress() = "https://$this:${CogRPC.PORT}" diff --git a/app/src/main/java/tech/relaycorp/gateway/background/ForegroundAppMonitor.kt b/app/src/main/java/tech/relaycorp/gateway/background/ForegroundAppMonitor.kt index 1130d37d..723c5474 100644 --- a/app/src/main/java/tech/relaycorp/gateway/background/ForegroundAppMonitor.kt +++ b/app/src/main/java/tech/relaycorp/gateway/background/ForegroundAppMonitor.kt @@ -14,7 +14,9 @@ class ForegroundAppMonitor private val activityCountFlow = MutableStateFlow(0) - fun observe() = activityCountFlow.map { if (it == 0) State.Background else State.Foreground } + fun observe() = activityCountFlow.map { + if (it == 0) State.Background else State.Foreground + } override fun onActivityStarted(activity: Activity) { activityCountFlow.value++ @@ -31,6 +33,7 @@ class ForegroundAppMonitor override fun onActivityResumed(activity: Activity) = Unit enum class State { - Foreground, Background + Foreground, + Background, } } diff --git a/app/src/main/java/tech/relaycorp/gateway/background/PingRemoteServer.kt b/app/src/main/java/tech/relaycorp/gateway/background/PingRemoteServer.kt index f81a0c56..a3b4f565 100644 --- a/app/src/main/java/tech/relaycorp/gateway/background/PingRemoteServer.kt +++ b/app/src/main/java/tech/relaycorp/gateway/background/PingRemoteServer.kt @@ -28,38 +28,36 @@ class PingRemoteServer } } - suspend fun pingSocket(address: String, port: Int) = - try { - aSocket(ActorSelectorManager(Dispatchers.IO)) - .tcp() - .connect(address, port) { - socketTimeout = TIMEOUT.inWholeMilliseconds - } - .use { true } - } catch (e: IOException) { - logger.log(Level.INFO, "Could not ping $address:$port") - false - } - - suspend fun pingURL(url: String) = - try { - withTimeout(TIMEOUT) { - ktorClient.head(url) - true + suspend fun pingSocket(address: String, port: Int) = try { + aSocket(ActorSelectorManager(Dispatchers.IO)) + .tcp() + .connect(address, port) { + socketTimeout = TIMEOUT.inWholeMilliseconds } - } catch (e: IOException) { - logger.log(Level.INFO, "Could not ping $url (${e.message})") - false - } catch (e: TimeoutCancellationException) { - logger.log(Level.INFO, "Could not ping $url (${e.message})") - false - } catch (e: ResponseException) { - logger.log( - Level.INFO, - "Successfully pinged $url but got a response exception (${e.message})" - ) + .use { true } + } catch (e: IOException) { + logger.log(Level.INFO, "Could not ping $address:$port") + false + } + + suspend fun pingURL(url: String) = try { + withTimeout(TIMEOUT) { + ktorClient.head(url) true } + } catch (e: IOException) { + logger.log(Level.INFO, "Could not ping $url (${e.message})") + false + } catch (e: TimeoutCancellationException) { + logger.log(Level.INFO, "Could not ping $url (${e.message})") + false + } catch (e: ResponseException) { + logger.log( + Level.INFO, + "Successfully pinged $url but got a response exception (${e.message})", + ) + true + } companion object { private val TIMEOUT = 5.seconds diff --git a/app/src/main/java/tech/relaycorp/gateway/background/endpoint/EndpointPreRegistrationService.kt b/app/src/main/java/tech/relaycorp/gateway/background/endpoint/EndpointPreRegistrationService.kt index bac00ae6..b0202747 100644 --- a/app/src/main/java/tech/relaycorp/gateway/background/endpoint/EndpointPreRegistrationService.kt +++ b/app/src/main/java/tech/relaycorp/gateway/background/endpoint/EndpointPreRegistrationService.kt @@ -36,7 +36,7 @@ class EndpointPreRegistrationService : Service() { override fun handleMessage(msg: Message) { onMessageReceived(msg) } - } + }, ) return messenger.binder } @@ -70,9 +70,9 @@ class EndpointPreRegistrationService : Service() { } else -> { - val authorizationSerialized = endpointRegistration.authorize(endpointApplicationId) + val authSerialized = endpointRegistration.authorize(endpointApplicationId) Message.obtain(null, REGISTRATION_AUTHORIZATION).also { - it.data = Bundle().apply { putByteArray("auth", authorizationSerialized) } + it.data = Bundle().apply { putByteArray("auth", authSerialized) } } } } diff --git a/app/src/main/java/tech/relaycorp/gateway/background/publicsync/PublicSyncWorker.kt b/app/src/main/java/tech/relaycorp/gateway/background/publicsync/PublicSyncWorker.kt index 6e5981c4..ae24812a 100644 --- a/app/src/main/java/tech/relaycorp/gateway/background/publicsync/PublicSyncWorker.kt +++ b/app/src/main/java/tech/relaycorp/gateway/background/publicsync/PublicSyncWorker.kt @@ -14,7 +14,7 @@ import javax.inject.Provider class PublicSyncWorker( appContext: Context, workerParams: WorkerParameters, - private val publicSync: PublicSync + private val publicSync: PublicSync, ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { @@ -33,11 +33,11 @@ class PublicSyncWorker( class PublicSyncWorkerFactory @Inject constructor( - private val PublicSync: Provider + private val PublicSync: Provider, ) : WorkerFactory() { override fun createWorker( appContext: Context, workerClassName: String, - workerParameters: WorkerParameters + workerParameters: WorkerParameters, ) = PublicSyncWorker(appContext, workerParameters, PublicSync.get()) } diff --git a/app/src/main/java/tech/relaycorp/gateway/common/di/AppComponent.kt b/app/src/main/java/tech/relaycorp/gateway/common/di/AppComponent.kt index cea274cc..1fe4c12c 100644 --- a/app/src/main/java/tech/relaycorp/gateway/common/di/AppComponent.kt +++ b/app/src/main/java/tech/relaycorp/gateway/common/di/AppComponent.kt @@ -3,8 +3,8 @@ package tech.relaycorp.gateway.common.di import dagger.Component import tech.relaycorp.gateway.App import tech.relaycorp.gateway.AppModule -import tech.relaycorp.gateway.background.endpoint.GatewaySyncService import tech.relaycorp.gateway.background.endpoint.EndpointPreRegistrationService +import tech.relaycorp.gateway.background.endpoint.GatewaySyncService import tech.relaycorp.gateway.data.DataModule import javax.inject.Singleton @@ -12,8 +12,8 @@ import javax.inject.Singleton @Component( modules = [ AppModule::class, - DataModule::class - ] + DataModule::class, + ], ) interface AppComponent { fun activityComponent(): ActivityComponent diff --git a/app/src/main/java/tech/relaycorp/gateway/common/di/ViewModelFactory.kt b/app/src/main/java/tech/relaycorp/gateway/common/di/ViewModelFactory.kt index da61cf0b..9110f64f 100644 --- a/app/src/main/java/tech/relaycorp/gateway/common/di/ViewModelFactory.kt +++ b/app/src/main/java/tech/relaycorp/gateway/common/di/ViewModelFactory.kt @@ -6,7 +6,7 @@ import javax.inject.Inject import javax.inject.Provider class ViewModelFactory @Inject constructor( - private val viewModelProvider: Provider + private val viewModelProvider: Provider, ) : ViewModelProvider.Factory { diff --git a/app/src/main/java/tech/relaycorp/gateway/data/DataModule.kt b/app/src/main/java/tech/relaycorp/gateway/data/DataModule.kt index 948e77d7..cce40ff3 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/DataModule.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/DataModule.kt @@ -36,45 +36,39 @@ class DataModule { @Provides @Singleton - fun database(context: Context, appMode: App.Mode): AppDatabase = - when (appMode) { - App.Mode.Normal -> - Room.databaseBuilder(context, AppDatabase::class.java, "gateway") - App.Mode.Test -> - Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) - }.build() + fun database(context: Context, appMode: App.Mode): AppDatabase = when (appMode) { + App.Mode.Normal -> + Room.databaseBuilder(context, AppDatabase::class.java, "gateway") + App.Mode.Test -> + Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) + }.build() @Provides @Singleton - fun storedParcelDao(database: AppDatabase) = - database.storedParcelDao() + fun storedParcelDao(database: AppDatabase) = database.storedParcelDao() @Provides @Singleton - fun parcelCollectionDao(database: AppDatabase) = - database.parcelCollectionDao() + fun parcelCollectionDao(database: AppDatabase) = database.parcelCollectionDao() @Provides @Singleton - fun localEndpointDao(database: AppDatabase) = - database.localEndpointDao() + fun localEndpointDao(database: AppDatabase) = database.localEndpointDao() // Preferences @Provides @Named("preferences_name") - fun preferencesName(appMode: App.Mode) = - when (appMode) { - App.Mode.Normal -> "pref_gateway" - App.Mode.Test -> "pref_gateway_test" - } + fun preferencesName(appMode: App.Mode) = when (appMode) { + App.Mode.Normal -> "pref_gateway" + App.Mode.Test -> "pref_gateway_test" + } @Provides fun sharedPreferences( context: Context, - @Named("preferences_name") preferencesName: String - ): SharedPreferences = - context.getSharedPreferences(preferencesName, Context.MODE_PRIVATE) + @Named("preferences_name") preferencesName: String, + ): SharedPreferences = context.getSharedPreferences(preferencesName, Context.MODE_PRIVATE) @Provides fun flowSharedPreferences(sharedPreferences: SharedPreferences) = @@ -111,12 +105,11 @@ class DataModule { @Provides fun poWebClientProvider( internetGatewayPreferences: InternetGatewayPreferences, - poWebClientBuilder: PoWebClientBuilder + poWebClientBuilder: PoWebClientBuilder, ) = object : PoWebClientProvider { - override suspend fun get() = - poWebClientBuilder.build( - internetGatewayPreferences.getPoWebAddress() - ) + override suspend fun get() = poWebClientBuilder.build( + internetGatewayPreferences.getPoWebAddress(), + ) } // Awala keystores @@ -129,9 +122,8 @@ class DataModule { @Singleton fun privateKeyStore( context: Context, - keystoreRoot: Provider - ): PrivateKeyStore = - AndroidPrivateKeyStore(keystoreRoot.get(), context) + keystoreRoot: Provider, + ): PrivateKeyStore = AndroidPrivateKeyStore(keystoreRoot.get(), context) @Provides @Singleton @@ -147,7 +139,6 @@ class DataModule { @Singleton fun gatewayManager( privateKeyStore: Provider, - publicKeyStore: Provider - ) = - GatewayManager(privateKeyStore.get(), publicKeyStore.get()) + publicKeyStore: Provider, + ) = GatewayManager(privateKeyStore.get(), publicKeyStore.get()) } diff --git a/app/src/main/java/tech/relaycorp/gateway/data/database/AppDatabase.kt b/app/src/main/java/tech/relaycorp/gateway/data/database/AppDatabase.kt index 2393f4ab..8a4309c1 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/database/AppDatabase.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/database/AppDatabase.kt @@ -4,16 +4,16 @@ import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import tech.relaycorp.gateway.data.model.LocalEndpoint -import tech.relaycorp.gateway.data.model.StoredParcel import tech.relaycorp.gateway.data.model.ParcelCollection +import tech.relaycorp.gateway.data.model.StoredParcel @Database( entities = [ LocalEndpoint::class, StoredParcel::class, - ParcelCollection::class + ParcelCollection::class, ], - version = 1 + version = 1, ) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { diff --git a/app/src/main/java/tech/relaycorp/gateway/data/database/ParcelCollectionDao.kt b/app/src/main/java/tech/relaycorp/gateway/data/database/ParcelCollectionDao.kt index 8d946594..6ea2811e 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/database/ParcelCollectionDao.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/database/ParcelCollectionDao.kt @@ -34,11 +34,11 @@ interface ParcelCollectionDao { AND messageId = :messageId LIMIT 1 ) - """ + """, ) suspend fun exists( recipientAddress: MessageAddress, senderAddress: PrivateMessageAddress, - messageId: MessageId + messageId: MessageId, ): Boolean } diff --git a/app/src/main/java/tech/relaycorp/gateway/data/database/StoredParcelDao.kt b/app/src/main/java/tech/relaycorp/gateway/data/database/StoredParcelDao.kt index 7971d284..5ddccc28 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/database/StoredParcelDao.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/database/StoredParcelDao.kt @@ -29,7 +29,7 @@ interface StoredParcelDao { suspend fun listForRecipientLocation( recipientLocation: RecipientLocation, - expiresSince: ZonedDateTime = nowInUtc() + expiresSince: ZonedDateTime = nowInUtc(), ) = observeForRecipientLocation(recipientLocation, expiresSince).first() @Query( @@ -37,11 +37,11 @@ interface StoredParcelDao { SELECT * FROM Parcel WHERE recipientLocation = :recipientLocation AND expirationTimeUtc > :expiresSince ORDER BY creationTimeUtc ASC - """ + """, ) fun observeForRecipientLocation( recipientLocation: RecipientLocation, - expiresSince: ZonedDateTime = nowInUtc() + expiresSince: ZonedDateTime = nowInUtc(), ): Flow> @Query( @@ -51,12 +51,12 @@ interface StoredParcelDao { AND recipientLocation = :recipientLocation AND expirationTimeUtc > :expiresSince ORDER BY creationTimeUtc ASC - """ + """, ) fun listForRecipients( recipientAddresses: List, recipientLocation: RecipientLocation, - expiresSince: ZonedDateTime = nowInUtc() + expiresSince: ZonedDateTime = nowInUtc(), ): Flow> @Query("SELECT SUM(Parcel.size) FROM Parcel WHERE recipientLocation = :recipientLocation") @@ -66,11 +66,11 @@ interface StoredParcelDao { """ SELECT SUM(Parcel.size) FROM Parcel WHERE recipientLocation = :recipientLocation AND inTransit = :inTransit - """ + """, ) fun countSizeForRecipientLocationAndInTransit( recipientLocation: RecipientLocation, - inTransit: Boolean + inTransit: Boolean, ): Flow @Query( @@ -80,22 +80,22 @@ interface StoredParcelDao { AND senderAddress = :senderAddress AND messageId = :messageId LIMIT 1 - """ + """, ) suspend fun get( recipientAddress: MessageAddress, senderAddress: MessageAddress, - messageId: MessageId + messageId: MessageId, ): StoredParcel? @Query( """ UPDATE Parcel SET inTransit = :inTransit WHERE recipientLocation = :recipientLocation - """ + """, ) suspend fun setInTransit( recipientLocation: RecipientLocation = RecipientLocation.ExternalGateway, - inTransit: Boolean + inTransit: Boolean, ) } diff --git a/app/src/main/java/tech/relaycorp/gateway/data/disk/AndroidPrivateKeyStore.kt b/app/src/main/java/tech/relaycorp/gateway/data/disk/AndroidPrivateKeyStore.kt index 20b9c0fc..aaebbf25 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/disk/AndroidPrivateKeyStore.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/disk/AndroidPrivateKeyStore.kt @@ -10,7 +10,7 @@ import java.io.OutputStream internal class AndroidPrivateKeyStore( root: FileKeystoreRoot, - private val context: Context + private val context: Context, ) : FilePrivateKeyStore(root) { override fun makeEncryptedInputStream(file: File) = buildEncryptedFile(file).openFileInput() @@ -21,13 +21,12 @@ internal class AndroidPrivateKeyStore( return buildEncryptedFile(file).openFileOutput() } - private fun buildEncryptedFile(file: File) = - EncryptedFile.Builder( - context, - file, - masterKey, - EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB - ).build() + private fun buildEncryptedFile(file: File) = EncryptedFile.Builder( + context, + file, + masterKey, + EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB, + ).build() private val masterKey by lazy { MasterKey.Builder(context, MASTER_KEY_ALIAS) diff --git a/app/src/main/java/tech/relaycorp/gateway/data/disk/CargoStorage.kt b/app/src/main/java/tech/relaycorp/gateway/data/disk/CargoStorage.kt index d60695b9..8c9d221e 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/disk/CargoStorage.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/disk/CargoStorage.kt @@ -12,7 +12,7 @@ import javax.inject.Inject class CargoStorage @Inject constructor( private val diskMessageOperations: DiskMessageOperations, - private val localConfig: LocalConfig + private val localConfig: LocalConfig, ) { @Throws(Exception::class) @@ -41,8 +41,10 @@ class CargoStorage sealed class Exception(message: String?, cause: Throwable? = null) : kotlin.Exception(message, cause) { - class MalformedCargo(cause: Throwable) : Exception(null, cause) - class InvalidCargo(message: String?, cause: Throwable? = null) : Exception(message, cause) + class MalformedCargo(cause: Throwable) : + Exception(null, cause) + class InvalidCargo(message: String?, cause: Throwable? = null) : + Exception(message, cause) } companion object { diff --git a/app/src/main/java/tech/relaycorp/gateway/data/disk/DiskExceptions.kt b/app/src/main/java/tech/relaycorp/gateway/data/disk/DiskExceptions.kt index f713beb2..d6267fd6 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/disk/DiskExceptions.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/disk/DiskExceptions.kt @@ -2,7 +2,7 @@ package tech.relaycorp.gateway.data.disk class MessageDataNotFoundException( message: String? = null, - cause: Throwable? = null + cause: Throwable? = null, ) : Exception(message, cause) class DiskException(cause: Throwable? = null) : Exception(cause) diff --git a/app/src/main/java/tech/relaycorp/gateway/data/disk/DiskMessageOperations.kt b/app/src/main/java/tech/relaycorp/gateway/data/disk/DiskMessageOperations.kt index 45cca47d..7a14cd6a 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/disk/DiskMessageOperations.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/disk/DiskMessageOperations.kt @@ -12,16 +12,15 @@ import javax.inject.Singleton @Singleton class DiskMessageOperations @Inject constructor( - private val context: Context + private val context: Context, ) { @Throws(DiskException::class) - suspend fun writeMessage(folder: String, prefix: String, message: ByteArray): String = - try { - writeMessageUnhandled(folder, prefix, message) - } catch (e: IOException) { - throw DiskException(e) - } + suspend fun writeMessage(folder: String, prefix: String, message: ByteArray): String = try { + writeMessageUnhandled(folder, prefix, message) + } catch (e: IOException) { + throw DiskException(e) + } suspend fun listMessages(folder: String): List<() -> InputStream> = withContext(Dispatchers.IO) { @@ -60,12 +59,11 @@ class DiskMessageOperations file.name } - private suspend fun getOrCreateDir(folder: String) = - withContext(Dispatchers.IO) { - File(context.filesDir, folder).also { - if (!it.exists()) it.mkdir() - } + private suspend fun getOrCreateDir(folder: String) = withContext(Dispatchers.IO) { + File(context.filesDir, folder).also { + if (!it.exists()) it.mkdir() } + } private suspend fun createUniqueFile(folder: String, prefix: String) = withContext(Dispatchers.IO) { diff --git a/app/src/main/java/tech/relaycorp/gateway/data/disk/FileStore.kt b/app/src/main/java/tech/relaycorp/gateway/data/disk/FileStore.kt index 40000d5a..7ce66327 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/disk/FileStore.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/disk/FileStore.kt @@ -11,7 +11,7 @@ import javax.inject.Inject class FileStore @Inject constructor( - private val context: Context + private val context: Context, ) { suspend fun store(location: String, data: ByteArray) { diff --git a/app/src/main/java/tech/relaycorp/gateway/data/disk/ReadRawFile.kt b/app/src/main/java/tech/relaycorp/gateway/data/disk/ReadRawFile.kt index b8dc59d9..a6a4ad4a 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/disk/ReadRawFile.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/disk/ReadRawFile.kt @@ -9,10 +9,9 @@ import javax.inject.Inject class ReadRawFile @Inject constructor( - private val resources: Resources + private val resources: Resources, ) { - suspend fun read(@RawRes fileRes: Int) = - withContext(Dispatchers.IO) { - resources.openRawResource(fileRes).readBytesAndClose() - } + suspend fun read(@RawRes fileRes: Int) = withContext(Dispatchers.IO) { + resources.openRawResource(fileRes).readBytesAndClose() + } } diff --git a/app/src/main/java/tech/relaycorp/gateway/data/doh/ResolveServiceAddress.kt b/app/src/main/java/tech/relaycorp/gateway/data/doh/ResolveServiceAddress.kt index 0922ac32..e6d2b760 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/doh/ResolveServiceAddress.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/doh/ResolveServiceAddress.kt @@ -10,7 +10,7 @@ import kotlin.time.Duration.Companion.seconds class ResolveServiceAddress @Inject constructor( - private val doHClient: DoHClient + private val doHClient: DoHClient, ) { @Throws(InternetAddressResolutionException::class) suspend fun resolvePoWeb(address: String): ServiceAddress { @@ -22,19 +22,19 @@ class ResolveServiceAddress } catch (exc: LookupFailureException) { throw InternetAddressResolutionException( "Failed to resolve DNS for PoWeb address", - exc + exc, ) } catch (exc: TimeoutCancellationException) { throw InternetAddressResolutionException( "Failed to resolve DNS for PoWeb address", - exc + exc, ) } val srvRecordData = answer.data.first() val srvRecordDataFields = srvRecordData.split(" ") if (srvRecordDataFields.size < 4) { throw InternetAddressResolutionException( - "Malformed SRV for $address ($srvRecordData)" + "Malformed SRV for $address ($srvRecordData)", ) } val targetHost = srvRecordDataFields[3] diff --git a/app/src/main/java/tech/relaycorp/gateway/data/model/LocalEndpoint.kt b/app/src/main/java/tech/relaycorp/gateway/data/model/LocalEndpoint.kt index a8db5e0b..b088412e 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/model/LocalEndpoint.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/model/LocalEndpoint.kt @@ -6,10 +6,10 @@ import androidx.room.PrimaryKey @Entity( tableName = "Endpoint", - indices = [Index(value = ["applicationId"], unique = false)] + indices = [Index(value = ["applicationId"], unique = false)], ) data class LocalEndpoint( @PrimaryKey val address: MessageAddress, - val applicationId: String + val applicationId: String, ) diff --git a/app/src/main/java/tech/relaycorp/gateway/data/model/MessageAddress.kt b/app/src/main/java/tech/relaycorp/gateway/data/model/MessageAddress.kt index b8ae9ffb..8c6bd0a9 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/model/MessageAddress.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/model/MessageAddress.kt @@ -14,21 +14,21 @@ sealed class MessageAddress { } companion object { - fun of(value: String) = - if (value.contains(":")) { - PublicMessageAddress(value) - } else { - PrivateMessageAddress(value) - } + fun of(value: String) = if (value.contains(":")) { + PublicMessageAddress(value) + } else { + PrivateMessageAddress(value) + } } enum class Type(val value: String) { - Public("public"), Private("private"); + Public("public"), + Private("private"), + ; companion object { - fun fromValue(value: String) = - values().firstOrNull { it.value == value } - ?: throw IllegalArgumentException("Invalid MessageAddress.Type value = $value") + fun fromValue(value: String) = values().firstOrNull { it.value == value } + ?: throw IllegalArgumentException("Invalid MessageAddress.Type value = $value") } } } diff --git a/app/src/main/java/tech/relaycorp/gateway/data/model/ParcelCollection.kt b/app/src/main/java/tech/relaycorp/gateway/data/model/ParcelCollection.kt index bd2c0cea..845b3f72 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/model/ParcelCollection.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/model/ParcelCollection.kt @@ -6,7 +6,7 @@ import java.time.ZonedDateTime @Entity( tableName = "ParcelCollection", - primaryKeys = ["recipientAddress", "senderAddress", "messageId"] + primaryKeys = ["recipientAddress", "senderAddress", "messageId"], ) data class ParcelCollection( val recipientAddress: MessageAddress, @@ -15,5 +15,5 @@ data class ParcelCollection( @ColumnInfo(index = true) val creationTimeUtc: ZonedDateTime, @ColumnInfo(index = true) - val expirationTimeUtc: ZonedDateTime + val expirationTimeUtc: ZonedDateTime, ) diff --git a/app/src/main/java/tech/relaycorp/gateway/data/model/RecipientLocation.kt b/app/src/main/java/tech/relaycorp/gateway/data/model/RecipientLocation.kt index b0f80ac7..19f39093 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/model/RecipientLocation.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/model/RecipientLocation.kt @@ -2,7 +2,8 @@ package tech.relaycorp.gateway.data.model enum class RecipientLocation(val value: String) { LocalEndpoint("local-endpoint"), - ExternalGateway("external-gateway"); + ExternalGateway("external-gateway"), + ; companion object { fun fromValue(value: String): RecipientLocation { diff --git a/app/src/main/java/tech/relaycorp/gateway/data/model/RegistrationState.kt b/app/src/main/java/tech/relaycorp/gateway/data/model/RegistrationState.kt index 8167363d..89bae421 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/model/RegistrationState.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/model/RegistrationState.kt @@ -1,5 +1,6 @@ package tech.relaycorp.gateway.data.model enum class RegistrationState { - ToDo, Done + ToDo, + Done, } diff --git a/app/src/main/java/tech/relaycorp/gateway/data/model/StorageSize.kt b/app/src/main/java/tech/relaycorp/gateway/data/model/StorageSize.kt index 4507c94d..f45f326e 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/model/StorageSize.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/model/StorageSize.kt @@ -3,7 +3,7 @@ package tech.relaycorp.gateway.data.model import kotlin.math.min data class StorageSize( - val bytes: Long + val bytes: Long, ) : Comparable { val isZero get() = bytes == 0L @@ -20,7 +20,6 @@ data class StorageSize( companion object { val ZERO = StorageSize(0L) - fun min(size1: StorageSize, size2: StorageSize) = - StorageSize(min(size1.bytes, size2.bytes)) + fun min(size1: StorageSize, size2: StorageSize) = StorageSize(min(size1.bytes, size2.bytes)) } } diff --git a/app/src/main/java/tech/relaycorp/gateway/data/model/StoredParcel.kt b/app/src/main/java/tech/relaycorp/gateway/data/model/StoredParcel.kt index 6a9ff51f..0e8609bf 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/model/StoredParcel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/model/StoredParcel.kt @@ -6,7 +6,7 @@ import java.time.ZonedDateTime @Entity( tableName = "Parcel", - primaryKeys = ["recipientAddress", "senderAddress", "messageId"] + primaryKeys = ["recipientAddress", "senderAddress", "messageId"], ) data class StoredParcel( val recipientAddress: MessageAddress, @@ -20,7 +20,7 @@ data class StoredParcel( val expirationTimeUtc: ZonedDateTime, val storagePath: String, val size: StorageSize, - val inTransit: Boolean = false + val inTransit: Boolean = false, ) { companion object { const val STORAGE_FOLDER = "parcels" diff --git a/app/src/main/java/tech/relaycorp/gateway/data/preference/AppPreferences.kt b/app/src/main/java/tech/relaycorp/gateway/data/preference/AppPreferences.kt index 28941c9c..300b4ef8 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/preference/AppPreferences.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/preference/AppPreferences.kt @@ -6,7 +6,7 @@ import javax.inject.Provider class AppPreferences @Inject constructor( - private val preferences: Provider + private val preferences: Provider, ) { // Address diff --git a/app/src/main/java/tech/relaycorp/gateway/data/preference/InternetGatewayPreferences.kt b/app/src/main/java/tech/relaycorp/gateway/data/preference/InternetGatewayPreferences.kt index 584bc8cd..4303bff7 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/preference/InternetGatewayPreferences.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/preference/InternetGatewayPreferences.kt @@ -24,7 +24,7 @@ class InternetGatewayPreferences @Inject constructor( private val preferences: Provider, private val readRawFile: ReadRawFile, - private val resolveServiceAddress: ResolveServiceAddress + private val resolveServiceAddress: ResolveServiceAddress, ) { // Address @@ -70,12 +70,11 @@ class InternetGatewayPreferences preferences.get().getString("public_gateway_id") } - suspend fun getId(): String = - id.get().ifEmpty { - getPublicKey().nodeId.also { - setId(it) - } + suspend fun getId(): String = id.get().ifEmpty { + getPublicKey().nodeId.also { + setId(it) } + } private suspend fun setId(value: String) { id.setAndCommit(value) diff --git a/app/src/main/java/tech/relaycorp/gateway/data/preference/PreferenceUtils.kt b/app/src/main/java/tech/relaycorp/gateway/data/preference/PreferenceUtils.kt index f628a16b..ae154020 100644 --- a/app/src/main/java/tech/relaycorp/gateway/data/preference/PreferenceUtils.kt +++ b/app/src/main/java/tech/relaycorp/gateway/data/preference/PreferenceUtils.kt @@ -4,5 +4,4 @@ import com.fredporciuncula.flow.preferences.Preference import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.flatMapConcat -fun (() -> Preference).toFlow() = - asFlow().flatMapConcat { it.asFlow() } +fun (() -> Preference).toFlow() = asFlow().flatMapConcat { it.asFlow() } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/DeleteParcel.kt b/app/src/main/java/tech/relaycorp/gateway/domain/DeleteParcel.kt index c07382c5..cc03b467 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/DeleteParcel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/DeleteParcel.kt @@ -10,12 +10,12 @@ import javax.inject.Inject class DeleteParcel @Inject constructor( private val storedParcelDao: StoredParcelDao, - private val diskMessageOperations: DiskMessageOperations + private val diskMessageOperations: DiskMessageOperations, ) { suspend fun delete( recipientAddress: MessageAddress, senderAddress: MessageAddress, - messageId: MessageId + messageId: MessageId, ) { storedParcelDao.get(recipientAddress, senderAddress, messageId) ?.let { delete(it) } @@ -23,6 +23,9 @@ class DeleteParcel suspend fun delete(storedParcel: StoredParcel) { storedParcelDao.delete(storedParcel) - diskMessageOperations.deleteMessage(StoredParcel.STORAGE_FOLDER, storedParcel.storagePath) + diskMessageOperations.deleteMessage( + StoredParcel.STORAGE_FOLDER, + storedParcel.storagePath, + ) } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/GetEndpointApplicationsCount.kt b/app/src/main/java/tech/relaycorp/gateway/domain/GetEndpointApplicationsCount.kt index 1a7d4903..836bd7ac 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/GetEndpointApplicationsCount.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/GetEndpointApplicationsCount.kt @@ -5,7 +5,7 @@ import javax.inject.Inject class GetEndpointApplicationsCount @Inject constructor( - private val localEndpointDao: LocalEndpointDao + private val localEndpointDao: LocalEndpointDao, ) { fun get() = localEndpointDao.countApplicationIds() diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/GetOutgoingData.kt b/app/src/main/java/tech/relaycorp/gateway/domain/GetOutgoingData.kt index 209763f3..52104d47 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/GetOutgoingData.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/GetOutgoingData.kt @@ -9,25 +9,23 @@ import javax.inject.Inject class GetOutgoingData @Inject constructor( - private val storedParcelDao: StoredParcelDao + private val storedParcelDao: StoredParcelDao, ) { - fun get() = - combine( - storedParcelDao.countSizeForRecipientLocation(RecipientLocation.ExternalGateway), - storedParcelDao.countSizeForRecipientLocationAndInTransit( - RecipientLocation.ExternalGateway, - true - ) - ) { total, inTransit -> Data(total, inTransit) } + fun get() = combine( + storedParcelDao.countSizeForRecipientLocation(RecipientLocation.ExternalGateway), + storedParcelDao.countSizeForRecipientLocationAndInTransit( + RecipientLocation.ExternalGateway, + true, + ), + ) { total, inTransit -> Data(total, inTransit) } - fun any() = - storedParcelDao.countSizeForRecipientLocation(RecipientLocation.ExternalGateway) - .map { !it.isZero } + fun any() = storedParcelDao.countSizeForRecipientLocation(RecipientLocation.ExternalGateway) + .map { !it.isZero } data class Data( val total: StorageSize = StorageSize.ZERO, - val inTransit: StorageSize = StorageSize.ZERO + val inTransit: StorageSize = StorageSize.ZERO, ) { val percentage get() = if (total.isZero) 0 else (inTransit.bytes / total.bytes).toInt() diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/LocalConfig.kt b/app/src/main/java/tech/relaycorp/gateway/domain/LocalConfig.kt index bc5b0773..f2ab3256 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/LocalConfig.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/LocalConfig.kt @@ -25,7 +25,7 @@ class LocalConfig @Inject constructor( private val privateKeyStore: Provider, private val certificateStore: Provider, - private val internetGatewayPreferences: InternetGatewayPreferences + private val internetGatewayPreferences: InternetGatewayPreferences, ) { private val mutex = Mutex() @@ -61,12 +61,12 @@ class LocalConfig suspend fun setIdentityCertificate( leafCertificate: Certificate, - certificateChain: List = emptyList() + certificateChain: List = emptyList(), ) { certificateStore.get() .save( CertificationPath(leafCertificate, certificateChain), - getInternetGatewayId() + getInternetGatewayId(), ) } @@ -89,39 +89,38 @@ class LocalConfig } } - suspend fun getCargoDeliveryAuth() = - certificateStore.get() - .retrieveLatest( - getIdentityKey().nodeId, - getIdentityCertificate().subjectId - ) - ?.leafCertificate - .let { storedCertificate -> - if (storedCertificate?.isExpiringSoon() == false) { - storedCertificate - } else { - generateCargoDeliveryAuth() - } + suspend fun getCargoDeliveryAuth() = certificateStore.get() + .retrieveLatest( + getIdentityKey().nodeId, + getIdentityCertificate().subjectId, + ) + ?.leafCertificate + .let { storedCertificate -> + if (storedCertificate?.isExpiringSoon() == false) { + storedCertificate + } else { + generateCargoDeliveryAuth() } + } - suspend fun getAllValidCargoDeliveryAuth() = - certificateStore.get() - .retrieveAll( - getIdentityKey().nodeId, - getIdentityCertificate().subjectId - ) - .map { it.leafCertificate } + suspend fun getAllValidCargoDeliveryAuth() = certificateStore.get() + .retrieveAll( + getIdentityKey().nodeId, + getIdentityCertificate().subjectId, + ) + .map { it.leafCertificate } private fun selfIssueCargoDeliveryAuth( privateKey: PrivateKey, - publicKey: PublicKey + publicKey: PublicKey, ): Certificate { return issueGatewayCertificate( subjectPublicKey = publicKey, issuerPrivateKey = privateKey, - validityStartDate = nowInUtc() - .minus(CalculateCRCMessageCreationDate.CLOCK_DRIFT_TOLERANCE.toJavaDuration()), - validityEndDate = nowInUtc().plusMonths(6) + validityStartDate = nowInUtc().minus( + CalculateCRCMessageCreationDate.CLOCK_DRIFT_TOLERANCE.toJavaDuration(), + ), + validityEndDate = nowInUtc().plusMonths(6), ) } @@ -138,11 +137,9 @@ class LocalConfig certificateStore.get().deleteExpired() } - suspend fun getInternetGatewayAddress() = - internetGatewayPreferences.getAddress() + suspend fun getInternetGatewayAddress() = internetGatewayPreferences.getAddress() - private suspend fun getInternetGatewayId() = - internetGatewayPreferences.getId() + private suspend fun getInternetGatewayId() = internetGatewayPreferences.getId() private fun Certificate.isExpiringSoon() = expiryDate < (nowInUtc().plusNanos(CERTIFICATE_EXPIRING_THRESHOLD.inWholeNanoseconds)) diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/StoreParcel.kt b/app/src/main/java/tech/relaycorp/gateway/domain/StoreParcel.kt index 7436de8d..a14f049e 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/StoreParcel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/StoreParcel.kt @@ -21,18 +21,13 @@ class StoreParcel private val storedParcelDao: StoredParcelDao, private val parcelCollectionDao: ParcelCollectionDao, private val diskMessageOperations: DiskMessageOperations, - private val localConfig: LocalConfig + private val localConfig: LocalConfig, ) { - suspend fun store( - parcelStream: InputStream, - recipientLocation: RecipientLocation - ) = store(parcelStream.readBytesAndClose(), recipientLocation) + suspend fun store(parcelStream: InputStream, recipientLocation: RecipientLocation) = + store(parcelStream.readBytesAndClose(), recipientLocation) - suspend fun store( - parcelData: ByteArray, - recipientLocation: RecipientLocation - ): Result { + suspend fun store(parcelData: ByteArray, recipientLocation: RecipientLocation): Result { val parcel = try { Parcel.deserialize(parcelData) } catch (exc: RAMFException) { @@ -58,7 +53,7 @@ class StoreParcel val parcelPath = diskMessageOperations.writeMessage( StoredParcel.STORAGE_FOLDER, StoredParcel.STORAGE_PREFIX, - parcelData + parcelData, ) val parcelSize = StorageSize(parcelData.size.toLong()) @@ -67,28 +62,26 @@ class StoreParcel return Result.Success(parcel) } - private suspend fun isParcelAlreadyCollected(parcel: Parcel) = - parcelCollectionDao.exists( - MessageAddress.of(parcel.recipient.id), - PrivateMessageAddress(parcel.senderCertificate.subjectId), - MessageId(parcel.id) - ) + private suspend fun isParcelAlreadyCollected(parcel: Parcel) = parcelCollectionDao.exists( + MessageAddress.of(parcel.recipient.id), + PrivateMessageAddress(parcel.senderCertificate.subjectId), + MessageId(parcel.id), + ) private fun Parcel.toStoredParcel( storagePath: String, dataSize: StorageSize, - recipientLocation: RecipientLocation - ) = - StoredParcel( - recipientAddress = MessageAddress.of(recipient.id), - senderAddress = MessageAddress.of(senderCertificate.subjectId), - messageId = MessageId(id), - recipientLocation = recipientLocation, - creationTimeUtc = creationDate, - expirationTimeUtc = expiryDate, - size = dataSize, - storagePath = storagePath - ) + recipientLocation: RecipientLocation, + ) = StoredParcel( + recipientAddress = MessageAddress.of(recipient.id), + senderAddress = MessageAddress.of(senderCertificate.subjectId), + messageId = MessageId(id), + recipientLocation = recipientLocation, + creationTimeUtc = creationDate, + expirationTimeUtc = expiryDate, + size = dataSize, + storagePath = storagePath, + ) sealed class Result { data class MalformedParcel(val cause: Throwable) : Result() diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/StoreParcelCollection.kt b/app/src/main/java/tech/relaycorp/gateway/domain/StoreParcelCollection.kt index d2dea847..8d52f4af 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/StoreParcelCollection.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/StoreParcelCollection.kt @@ -10,7 +10,7 @@ import javax.inject.Inject class StoreParcelCollection @Inject constructor( - private val parcelCollectionDao: ParcelCollectionDao + private val parcelCollectionDao: ParcelCollectionDao, ) { suspend fun storeForParcel(parcel: Parcel) { @@ -20,8 +20,8 @@ class StoreParcelCollection PrivateMessageAddress(parcel.senderCertificate.subjectId), MessageId(parcel.id), parcel.creationDate, - parcel.expiryDate - ) + parcel.expiryDate, + ), ) } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/courier/CalculateCRCMessageCreationDate.kt b/app/src/main/java/tech/relaycorp/gateway/domain/courier/CalculateCRCMessageCreationDate.kt index f9167df7..26774102 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/courier/CalculateCRCMessageCreationDate.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/courier/CalculateCRCMessageCreationDate.kt @@ -10,15 +10,15 @@ import kotlin.time.toJavaDuration class CalculateCRCMessageCreationDate @Inject constructor( - private val localConfig: LocalConfig + private val localConfig: LocalConfig, ) { - suspend fun calculate(): ZonedDateTime = - max( - listOf( - nowInUtc().minus(CLOCK_DRIFT_TOLERANCE.toJavaDuration()), - localConfig.getIdentityCertificate().startDate // Never before the GW registration - ) - ) + suspend fun calculate(): ZonedDateTime = max( + listOf( + nowInUtc().minus(CLOCK_DRIFT_TOLERANCE.toJavaDuration()), + // Never before the GW registration + localConfig.getIdentityCertificate().startDate, + ), + ) companion object { val CLOCK_DRIFT_TOLERANCE = 90.minutes diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/courier/CargoCollection.kt b/app/src/main/java/tech/relaycorp/gateway/domain/courier/CargoCollection.kt index b9c4e563..9e81a1ac 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/courier/CargoCollection.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/courier/CargoCollection.kt @@ -21,7 +21,7 @@ class CargoCollection private val notifyEndpoints: IncomingParcelNotifier, private val generateCCA: GenerateCCA, private val cargoStorage: CargoStorage, - private val processCargo: ProcessCargo + private val processCargo: ProcessCargo, ) { @Throws(Disconnected::class) @@ -49,12 +49,11 @@ class CargoCollection generateCCA.generateSerialized().inputStream() } - private suspend fun getCourierAddress() = - connectionStateObserver - .observe() - .map { it as? ConnectionState.WiFiWithCourier } - .first() - ?.courierAddress + private suspend fun getCourierAddress() = connectionStateObserver + .observe() + .map { it as? ConnectionState.WiFiWithCourier } + .first() + ?.courierAddress class Disconnected : Exception() } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/courier/CargoDelivery.kt b/app/src/main/java/tech/relaycorp/gateway/domain/courier/CargoDelivery.kt index 3bc482f8..578ff8ba 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/courier/CargoDelivery.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/courier/CargoDelivery.kt @@ -18,7 +18,7 @@ class CargoDelivery private val clientBuilder: CogRPCClient.Builder, private val connectionStateObserver: ConnectionStateObserver, private val generateCargo: GenerateCargo, - private val storedParcelDao: StoredParcelDao + private val storedParcelDao: StoredParcelDao, ) { suspend fun deliver() { @@ -38,16 +38,14 @@ class CargoDelivery storedParcelDao.setInTransit(inTransit = true) } - private suspend fun generateCargoDeliveries() = - generateCargo.generate() - .map { CargoDeliveryRequest(UUID.randomUUID().toString()) { it } } + private suspend fun generateCargoDeliveries() = generateCargo.generate() + .map { CargoDeliveryRequest(UUID.randomUUID().toString()) { it } } - private suspend fun getCourierAddress() = - connectionStateObserver - .observe() - .map { it as? ConnectionState.WiFiWithCourier } - .first() - ?.courierAddress + private suspend fun getCourierAddress() = connectionStateObserver + .observe() + .map { it as? ConnectionState.WiFiWithCourier } + .first() + ?.courierAddress class Disconnected : Exception() } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/courier/CourierSync.kt b/app/src/main/java/tech/relaycorp/gateway/domain/courier/CourierSync.kt index b1358ad5..45bf7f8a 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/courier/CourierSync.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/courier/CourierSync.kt @@ -11,7 +11,7 @@ import kotlin.time.Duration.Companion.seconds class CourierSync @Inject constructor( private val cargoDelivery: CargoDelivery, - private val cargoCollection: CargoCollection + private val cargoCollection: CargoCollection, ) { private val state = MutableStateFlow(State.Initial) @@ -40,7 +40,12 @@ class CourierSync } enum class State { - DeliveringCargo, Waiting, CollectingCargo, Finished, Error; + DeliveringCargo, + Waiting, + CollectingCargo, + Finished, + Error, + ; companion object { val Initial = DeliveringCargo diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/courier/GenerateCCA.kt b/app/src/main/java/tech/relaycorp/gateway/domain/courier/GenerateCCA.kt index 1d741169..f45894cf 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/courier/GenerateCCA.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/courier/GenerateCCA.kt @@ -18,7 +18,7 @@ class GenerateCCA private val internetGatewayPreferences: InternetGatewayPreferences, private val localConfig: LocalConfig, private val calculateCreationDate: CalculateCRCMessageCreationDate, - private val gatewayManager: Provider + private val gatewayManager: Provider, ) { suspend fun generateSerialized(): ByteArray { @@ -29,23 +29,23 @@ class GenerateCCA internetGatewayPublicKey, identityPrivateKey, ZonedDateTime.now().plusSeconds(TTL.inWholeSeconds), - cdaIssuer + cdaIssuer, ) val ccr = CargoCollectionRequest(cda) val ccrCiphertext = gatewayManager.get().wrapMessagePayload( ccr, internetGatewayPublicKey.nodeId, - cdaIssuer.subjectId + cdaIssuer.subjectId, ) val cca = CargoCollectionAuthorization( recipient = Recipient( internetGatewayPreferences.getId(), - internetGatewayPreferences.getAddress() + internetGatewayPreferences.getAddress(), ), payload = ccrCiphertext, senderCertificate = localConfig.getIdentityCertificate(), creationDate = calculateCreationDate.calculate(), - ttl = TTL.inWholeSeconds.toInt() + ttl = TTL.inWholeSeconds.toInt(), ) return cca.serialize(identityPrivateKey) } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/courier/GenerateCargo.kt b/app/src/main/java/tech/relaycorp/gateway/domain/courier/GenerateCargo.kt index 51d8724e..6d1be9bc 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/courier/GenerateCargo.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/courier/GenerateCargo.kt @@ -36,15 +36,14 @@ class GenerateCargo private val internetGatewayPreferences: InternetGatewayPreferences, private val localConfig: LocalConfig, private val calculateCreationDate: CalculateCRCMessageCreationDate, - private val gatewayManager: Provider + private val gatewayManager: Provider, ) { - suspend fun generate(): Flow = - (getPCAsMessages() + getParcelMessages()) - .asSequence() - .batch() - .asFlow() - .map { it.toCargoSerialized().inputStream() } + suspend fun generate(): Flow = (getPCAsMessages() + getParcelMessages()) + .asSequence() + .batch() + .asFlow() + .map { it.toCargoSerialized().inputStream() } private suspend fun getPCAsMessages() = parcelCollectionDao.getAll().map { it.toCargoMessageWithExpiry() } @@ -53,39 +52,37 @@ class GenerateCargo storedParcelDao.listForRecipientLocation(RecipientLocation.ExternalGateway) .mapNotNull { it.toCargoMessageWithExpiry() } - private fun ParcelCollection.toCargoMessageWithExpiry() = - CargoMessageWithExpiry( - cargoMessageSerialized = ParcelCollectionAck( - senderEndpointId = senderAddress.value, - recipientEndpointId = recipientAddress.value, - parcelId = messageId.value - ).serialize(), - expiryDate = expirationTimeUtc - ) + private fun ParcelCollection.toCargoMessageWithExpiry() = CargoMessageWithExpiry( + cargoMessageSerialized = ParcelCollectionAck( + senderEndpointId = senderAddress.value, + recipientEndpointId = recipientAddress.value, + parcelId = messageId.value, + ).serialize(), + expiryDate = expirationTimeUtc, + ) private suspend fun StoredParcel.toCargoMessageWithExpiry(): CargoMessageWithExpiry? = readParcel()?.let { parcelSerialized -> CargoMessageWithExpiry( cargoMessageSerialized = parcelSerialized, - expiryDate = expirationTimeUtc + expiryDate = expirationTimeUtc, ) } - private suspend fun StoredParcel.readParcel(): ByteArray? = - try { - diskMessageOperations.readMessage( - StoredParcel.STORAGE_FOLDER, - storagePath - )().readBytesAndClose() - } catch (e: MessageDataNotFoundException) { - logger.log(Level.WARNING, "Read parcel", e) - null - } + private suspend fun StoredParcel.readParcel(): ByteArray? = try { + diskMessageOperations.readMessage( + StoredParcel.STORAGE_FOLDER, + storagePath, + )().readBytesAndClose() + } catch (e: MessageDataNotFoundException) { + logger.log(Level.WARNING, "Read parcel", e) + null + } private suspend fun CargoMessageSetWithExpiry.toCargoSerialized(): ByteArray { if (nowInUtc() > latestMessageExpiryDate) { logger.warning( - "The latest expiration date $latestMessageExpiryDate has expired already" + "The latest expiration date $latestMessageExpiryDate has expired already", ) } @@ -100,14 +97,14 @@ class GenerateCargo val cargoMessageSetCiphertext = gatewayManager.get().wrapMessagePayload( cargoMessageSet, internetGatewayPreferences.getId(), - identityCert.subjectId + identityCert.subjectId, ) val cargo = Cargo( recipient = Recipient(recipientId, recipientAddress), payload = cargoMessageSetCiphertext, senderCertificate = identityCert, creationDate = creationDate, - ttl = Duration.between(creationDate, latestMessageExpiryDate).seconds.toInt() + ttl = Duration.between(creationDate, latestMessageExpiryDate).seconds.toInt(), ) return cargo.serialize(identityKey) } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/courier/ProcessCargo.kt b/app/src/main/java/tech/relaycorp/gateway/domain/courier/ProcessCargo.kt index a24ebbce..230fbefb 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/courier/ProcessCargo.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/courier/ProcessCargo.kt @@ -24,7 +24,7 @@ class ProcessCargo private val storeParcelCollection: StoreParcelCollection, private val deleteParcel: DeleteParcel, private val gatewayManager: Provider, - private val rotateCertificate: RotateCertificate + private val rotateCertificate: RotateCertificate, ) { suspend fun process() { @@ -55,7 +55,8 @@ class ProcessCargo val result = storeParcel.store(parcelData, RecipientLocation.LocalEndpoint) ) { is StoreParcel.Result.MalformedParcel, - is StoreParcel.Result.CollectedParcel -> return + is StoreParcel.Result.CollectedParcel, + -> return is StoreParcel.Result.InvalidParcel -> { logger.log(Level.WARNING, "Invalid parcel received", result.cause) result.parcel @@ -70,7 +71,7 @@ class ProcessCargo deleteParcel.delete( recipientAddress = MessageAddress.of(pca.recipientEndpointId), senderAddress = MessageAddress.of(pca.senderEndpointId), - messageId = MessageId(pca.parcelId) + messageId = MessageId(pca.parcelId), ) } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/courier/RotateCertificate.kt b/app/src/main/java/tech/relaycorp/gateway/domain/courier/RotateCertificate.kt index 81796a32..a93c7fb2 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/courier/RotateCertificate.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/courier/RotateCertificate.kt @@ -12,7 +12,7 @@ import javax.inject.Inject class RotateCertificate @Inject constructor( private val localConfig: LocalConfig, private val internetGatewayPreferences: InternetGatewayPreferences, - private val notifyEndpointsChangeNotifier: GatewayCertificateChangeNotifier + private val notifyEndpointsChangeNotifier: GatewayCertificateChangeNotifier, ) { suspend operator fun invoke(certRotationSerialized: ByteArray) { @@ -29,8 +29,8 @@ class RotateCertificate @Inject constructor( if (currentIdCert.expiryDate >= newIdCert.expiryDate) return localConfig.setIdentityCertificate(newIdCert) - certRotation.certificationPath.certificateAuthorities.first().let { internetGatewayCert -> - internetGatewayPreferences.setPublicKey(internetGatewayCert.subjectPublicKey) + certRotation.certificationPath.certificateAuthorities.first().let { internetCert -> + internetGatewayPreferences.setPublicKey(internetCert.subjectPublicKey) } notifyEndpointsChangeNotifier.notifyAll() diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/CollectParcels.kt b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/CollectParcels.kt index 8775a10d..7f46ed16 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/CollectParcels.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/CollectParcels.kt @@ -25,21 +25,21 @@ class CollectParcels @Inject constructor( private val storedParcelDao: StoredParcelDao, private val diskMessageOperations: DiskMessageOperations, - private val deleteParcel: DeleteParcel + private val deleteParcel: DeleteParcel, ) { private val parcelsSent = mutableListOf() private val parcelsWaitingAck = mutableMapOf() - private val _anyParcelsLeft = MutableStateFlow(true) - val anyParcelsLeftToDeliverOrAck: Flow = _anyParcelsLeft + private val anyParcelsLeftMutable = MutableStateFlow(true) + val anyParcelsLeftToDeliverOrAck: Flow = anyParcelsLeftMutable suspend fun getNewParcelsForEndpoints( - endpointsAddresses: List + endpointsAddresses: List, ): Flow>> { return storedParcelDao .listForRecipients(endpointsAddresses, RecipientLocation.LocalEndpoint) - .onEach { _anyParcelsLeft.value = it.any() } + .onEach { anyParcelsLeftMutable.value = it.any() } // Filter only parcels we haven't sent before .map { list -> list.filter { !parcelsSent.contains(it) } } // Associate local ID @@ -66,11 +66,10 @@ class CollectParcels } } - private suspend fun StoredParcel.getInputStream() = - try { - diskMessageOperations.readMessage(StoredParcel.STORAGE_FOLDER, storagePath)() - } catch (e: MessageDataNotFoundException) { - logger.log(Level.WARNING, "Read parcel", e) - null - } + private suspend fun StoredParcel.getInputStream() = try { + diskMessageOperations.readMessage(StoredParcel.STORAGE_FOLDER, storagePath)() + } catch (e: MessageDataNotFoundException) { + logger.log(Level.WARNING, "Read parcel", e) + null + } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/EndpointRegistration.kt b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/EndpointRegistration.kt index c9673738..617e7d51 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/EndpointRegistration.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/EndpointRegistration.kt @@ -24,8 +24,10 @@ class EndpointRegistration */ suspend fun authorize(endpointApplicationId: String): ByteArray { val expiryDate = ZonedDateTime.now().plusSeconds(AUTHORIZATION_VALIDITY_SECONDS) - val authorization = - PrivateNodeRegistrationAuthorization(expiryDate, endpointApplicationId.toByteArray()) + val authorization = PrivateNodeRegistrationAuthorization( + expiryDate, + endpointApplicationId.toByteArray(), + ) return authorization.serialize(localConfig.getIdentityKey()) } @@ -39,15 +41,18 @@ class EndpointRegistration val authorization = try { PrivateNodeRegistrationAuthorization.deserialize( request.pnraSerialized, - identityCert.subjectPublicKey + identityCert.subjectPublicKey, ) } catch (exc: InvalidMessageException) { - throw InvalidPNRAException("Registration request contains invalid authorization", exc) + throw InvalidPNRAException( + "Registration request contains invalid authorization", + exc, + ) } val applicationId = authorization.gatewayData.toString(Charset.defaultCharset()) val endpoint = LocalEndpoint( MessageAddress.of(request.privateNodePublicKey.nodeId), - applicationId + applicationId, ) localEndpointDao.insert(endpoint) @@ -55,12 +60,12 @@ class EndpointRegistration request.privateNodePublicKey, identityKey, identityCert.expiryDate, - identityCert + identityCert, ) val registration = PrivateNodeRegistration( endpointCertificate, identityCert, - localConfig.getInternetGatewayAddress() + localConfig.getInternetGatewayAddress(), ) return registration.serialize() } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/GatewayCertificateChangeNotifier.kt b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/GatewayCertificateChangeNotifier.kt index 71d15290..84d67e4c 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/GatewayCertificateChangeNotifier.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/GatewayCertificateChangeNotifier.kt @@ -6,7 +6,7 @@ import javax.inject.Inject class GatewayCertificateChangeNotifier @Inject constructor( private val notifyEndpoints: NotifyEndpoints, - private val endpointDao: LocalEndpointDao + private val endpointDao: LocalEndpointDao, ) { suspend fun notifyAll() { val registeredEndPoints = endpointDao.list() diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/GetEndpointReceiver.kt b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/GetEndpointReceiver.kt index 897d6e4b..ed957f01 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/GetEndpointReceiver.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/GetEndpointReceiver.kt @@ -6,13 +6,14 @@ import javax.inject.Inject open class GetEndpointReceiver @Inject constructor( - private val packageManager: PackageManager + private val packageManager: PackageManager, ) { open fun get(applicationId: String, action: NotificationType): String? { val intent = Intent(action.action) .setPackage(applicationId) - return packageManager.queryBroadcastReceivers(intent, 0).firstOrNull()?.activityInfo?.name + return packageManager.queryBroadcastReceivers(intent, 0) + .firstOrNull()?.activityInfo?.name } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/IncomingParcelNotifier.kt b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/IncomingParcelNotifier.kt index 812a628f..c8105c03 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/IncomingParcelNotifier.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/IncomingParcelNotifier.kt @@ -10,7 +10,7 @@ import javax.inject.Inject class IncomingParcelNotifier @Inject constructor( private val notifyEndpoints: NotifyEndpoints, private val storedParcelDao: StoredParcelDao, - private val endpointDao: LocalEndpointDao + private val endpointDao: LocalEndpointDao, ) { suspend fun notifyAllPending() { @@ -24,7 +24,8 @@ class IncomingParcelNotifier @Inject constructor( val endpoint = endpointDao.get(endpointAddress) if (endpoint == null) { logger.warning( - "Can't notify endpoint with unknown address $endpointAddress about incoming parcels" + "Can't notify endpoint with unknown address " + + "$endpointAddress about incoming parcels", ) return } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/NotificationType.kt b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/NotificationType.kt index 82d06d2c..7c8e8b58 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/NotificationType.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/NotificationType.kt @@ -2,5 +2,5 @@ package tech.relaycorp.gateway.domain.endpoint enum class NotificationType(val action: String) { IncomingParcel("tech.relaycorp.endpoint.INCOMING_PARCEL"), - GatewayCertificateChange("tech.relaycorp.endpoint.GATEWAY_CERT_CHANGE") + GatewayCertificateChange("tech.relaycorp.endpoint.GATEWAY_CERT_CHANGE"), } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/NotifyEndpoints.kt b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/NotifyEndpoints.kt index 90f7e66a..1157d37f 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/NotifyEndpoints.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/endpoint/NotifyEndpoints.kt @@ -10,7 +10,7 @@ import javax.inject.Inject class NotifyEndpoints @Inject constructor( private val getEndpointReceiver: GetEndpointReceiver, - private val context: Context + private val context: Context, ) { fun notify(localEndpoints: List, notificationType: NotificationType) = @@ -23,7 +23,7 @@ class NotifyEndpoints getEndpointReceiver.get(localEndpoint.applicationId, notificationType) ?: run { logger.warning( "Failed to notify ${localEndpoint.applicationId} " + - "about ${notificationType.name} (receiver not found)" + "about ${notificationType.name} (receiver not found)", ) return@notify } @@ -33,9 +33,9 @@ class NotifyEndpoints .setComponent( ComponentName( localEndpoint.applicationId, - receiverName - ) - ) + receiverName, + ), + ), ) } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/CollectParcelsFromGateway.kt b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/CollectParcelsFromGateway.kt index 73252ecb..5c8f7627 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/CollectParcelsFromGateway.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/CollectParcelsFromGateway.kt @@ -24,7 +24,7 @@ class CollectParcelsFromGateway private val storeParcel: StoreParcel, private val poWebClientProvider: PoWebClientProvider, private val notifyEndpoints: IncomingParcelNotifier, - private val localConfig: LocalConfig + private val localConfig: LocalConfig, ) { suspend fun collect(keepAlive: Boolean) { @@ -36,7 +36,7 @@ class CollectParcelsFromGateway logger.log( Level.WARNING, "Failed to collect parcels due to PoWeb address resolution error", - exc + exc, ) return } @@ -73,8 +73,10 @@ class CollectParcelsFromGateway } private suspend fun collectParcel(parcelCollection: ParcelCollection, keepAlive: Boolean) { - val storeResult = - storeParcel.store(parcelCollection.parcelSerialized, RecipientLocation.LocalEndpoint) + val storeResult = storeParcel.store( + parcelCollection.parcelSerialized, + RecipientLocation.LocalEndpoint, + ) when (storeResult) { is StoreParcel.Result.MalformedParcel -> logger.info("Malformed parcel received") @@ -89,7 +91,7 @@ class CollectParcelsFromGateway logger.info("Collected parcel from Gateway ${storeResult.parcel.id}") if (keepAlive) { notifyEndpoints.notify( - MessageAddress.of(storeResult.parcel.recipient.id) + MessageAddress.of(storeResult.parcel.recipient.id), ) } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/DeliverParcelsToGateway.kt b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/DeliverParcelsToGateway.kt index 1b0c2ce2..8094f228 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/DeliverParcelsToGateway.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/DeliverParcelsToGateway.kt @@ -34,7 +34,7 @@ class DeliverParcelsToGateway private val diskMessageOperations: DiskMessageOperations, private val poWebClientProvider: PoWebClientProvider, private val localConfig: LocalConfig, - private val deleteParcel: DeleteParcel + private val deleteParcel: DeleteParcel, ) { suspend fun deliver(keepAlive: Boolean) { @@ -47,7 +47,7 @@ class DeliverParcelsToGateway logger.log( Level.WARNING, "Failed to deliver parcels due to PoWeb address resolution error", - exc + exc, ) return } @@ -67,14 +67,22 @@ class DeliverParcelsToGateway try { deliverParcel(poWebClient, parcel) } catch (e: ClientBindingException) { - logger.log(Level.SEVERE, "Could not deliver parcel due to client error", e) + logger.log( + Level.SEVERE, + "Could not deliver parcel due to client error", + e, + ) } catch (e: ServerConnectionException) { - logger.log(Level.INFO, "Could not deliver parcel due to server error", e) + logger.log( + Level.INFO, + "Could not deliver parcel due to server error", + e, + ) } catch (e: PDCException) { logger.log( Level.SEVERE, "Could not deliver parcel due to unexpected error", - e + e, ) } } @@ -98,22 +106,20 @@ class DeliverParcelsToGateway deleteParcel.delete(parcel) } - private suspend fun StoredParcel.getInputStream() = - try { - diskMessageOperations.readMessage(StoredParcel.STORAGE_FOLDER, storagePath)() - } catch (e: MessageDataNotFoundException) { - logger.log(Level.WARNING, "Could not read parcel", e) - deleteParcel.delete(this) - null - } + private suspend fun StoredParcel.getInputStream() = try { + diskMessageOperations.readMessage(StoredParcel.STORAGE_FOLDER, storagePath)() + } catch (e: MessageDataNotFoundException) { + logger.log(Level.WARNING, "Could not read parcel", e) + deleteParcel.delete(this) + null + } - private lateinit var _signer: Signer - private suspend fun getSigner() = - if (this::_signer.isInitialized) { - _signer - } else { - Signer(localConfig.getIdentityCertificate(), localConfig.getIdentityKey()).also { - _signer = it - } + private lateinit var signerInternal: Signer + private suspend fun getSigner() = if (this::signerInternal.isInitialized) { + signerInternal + } else { + Signer(localConfig.getIdentityCertificate(), localConfig.getIdentityKey()).also { + signerInternal = it } + } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/MigrateGateway.kt b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/MigrateGateway.kt index 202df970..2945a62f 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/MigrateGateway.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/MigrateGateway.kt @@ -6,25 +6,26 @@ import javax.inject.Inject class MigrateGateway @Inject constructor( private val parcelCollectionDao: ParcelCollectionDao, - private val registerGateway: RegisterGateway + private val registerGateway: RegisterGateway, ) { - suspend fun migrate(address: String) = - when (registerGateway.registerNewAddress(address)) { - RegisterGateway.Result.FailedToRegister -> Result.FailedToRegister - RegisterGateway.Result.FailedToResolve -> Result.FailedToResolve - RegisterGateway.Result.AlreadyRegisteredAndNotExpiring -> Result.Successful - is RegisterGateway.Result.Registered -> { - deleteInvalidatedData() - Result.Successful - } + suspend fun migrate(address: String) = when (registerGateway.registerNewAddress(address)) { + RegisterGateway.Result.FailedToRegister -> Result.FailedToRegister + RegisterGateway.Result.FailedToResolve -> Result.FailedToResolve + RegisterGateway.Result.AlreadyRegisteredAndNotExpiring -> Result.Successful + is RegisterGateway.Result.Registered -> { + deleteInvalidatedData() + Result.Successful } + } private suspend fun deleteInvalidatedData() { parcelCollectionDao.deleteAll() } enum class Result { - Successful, FailedToResolve, FailedToRegister + Successful, + FailedToResolve, + FailedToRegister, } } diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/PublicSync.kt b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/PublicSync.kt index f97a7624..1e721eff 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/PublicSync.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/PublicSync.kt @@ -32,7 +32,7 @@ class PublicSync private val connectionStateObserver: ConnectionStateObserver, private val registerGateway: RegisterGateway, private val deliverParcelsToGateway: DeliverParcelsToGateway, - private val collectParcelsFromGateway: CollectParcelsFromGateway + private val collectParcelsFromGateway: CollectParcelsFromGateway, ) { private var syncJob: Job? = null @@ -47,7 +47,7 @@ class PublicSync pdcServerStateManager.observe(), connectionStateObserver.observe(), // Retry registration and sync every minute in case there's a failure - interval(1.minutes) + interval(1.minutes), ) { foregroundState, pdcState, connectionState, _ -> if ( connectionState is ConnectionState.InternetWithGateway && ( diff --git a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/RegisterGateway.kt b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/RegisterGateway.kt index 71d6157c..5a39b6ad 100644 --- a/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/RegisterGateway.kt +++ b/app/src/main/java/tech/relaycorp/gateway/domain/publicsync/RegisterGateway.kt @@ -29,7 +29,7 @@ class RegisterGateway private val localConfig: LocalConfig, private val poWebClientBuilder: PoWebClientBuilder, private val resolveServiceAddress: ResolveServiceAddress, - private val publicKeyStore: SessionPublicKeyStore + private val publicKeyStore: SessionPublicKeyStore, ) { private val mutex = Mutex() @@ -71,7 +71,8 @@ class RegisterGateway } private suspend fun currentCertificateIsAboutToExpire() = - localConfig.getIdentityCertificate().expiryDate < ZonedDateTime.now().plus(ABOUT_TO_EXPIRE) + localConfig.getIdentityCertificate().expiryDate < + ZonedDateTime.now().plus(ABOUT_TO_EXPIRE) private suspend fun register(address: String): Result { return try { @@ -104,7 +105,7 @@ class RegisterGateway logger.log( Level.WARNING, "Could not register gateway due to failure to resolve PoWeb address", - e + e, ) Result.FailedToResolve } @@ -112,15 +113,17 @@ class RegisterGateway private suspend fun saveSuccessfulResult( internetGatewayAddress: String, - registration: PrivateNodeRegistration + registration: PrivateNodeRegistration, ) { internetGatewayPreferences.setRegistrationState(RegistrationState.ToDo) internetGatewayPreferences.setAddress(internetGatewayAddress) - internetGatewayPreferences.setPublicKey(registration.gatewayCertificate.subjectPublicKey) + internetGatewayPreferences.setPublicKey( + registration.gatewayCertificate.subjectPublicKey, + ) localConfig.setIdentityCertificate(registration.privateNodeCertificate) publicKeyStore.save( registration.gatewaySessionKey!!, - registration.gatewayCertificate.subjectId + registration.gatewayCertificate.subjectId, ) internetGatewayPreferences.setRegistrationState(RegistrationState.Done) } diff --git a/app/src/main/java/tech/relaycorp/gateway/pdc/local/PDCServer.kt b/app/src/main/java/tech/relaycorp/gateway/pdc/local/PDCServer.kt index 1b7d4c3c..6276c0b3 100644 --- a/app/src/main/java/tech/relaycorp/gateway/pdc/local/PDCServer.kt +++ b/app/src/main/java/tech/relaycorp/gateway/pdc/local/PDCServer.kt @@ -20,7 +20,7 @@ class PDCServer private val stateManager: PDCServerStateManager, endpointRegistrationRoute: EndpointRegistrationRoute, parcelCollectionRoute: ParcelCollectionRoute, - parcelDeliveryRoute: ParcelDeliveryRoute + parcelDeliveryRoute: ParcelDeliveryRoute, ) { private val server by lazy { @@ -30,8 +30,8 @@ class PDCServer listOf( endpointRegistrationRoute, parcelCollectionRoute, - parcelDeliveryRoute - ) + parcelDeliveryRoute, + ), ) } } @@ -51,7 +51,8 @@ class PDCServer } enum class State { - Started, Stopped + Started, + Stopped, } companion object { diff --git a/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/EndpointRegistrationRoute.kt b/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/EndpointRegistrationRoute.kt index 91e65dd2..dfeb63a0 100644 --- a/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/EndpointRegistrationRoute.kt +++ b/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/EndpointRegistrationRoute.kt @@ -17,7 +17,7 @@ import javax.inject.Inject class EndpointRegistrationRoute @Inject constructor( - private val endpointRegistration: EndpointRegistration + private val endpointRegistration: EndpointRegistration, ) : PDCServerRoute { override fun register(routing: Routing) { @@ -25,7 +25,7 @@ class EndpointRegistrationRoute if (call.request.contentType() != ContentType.REGISTRATION_REQUEST) { call.respondText( "Content type ${ContentType.REGISTRATION_REQUEST} is required", - status = HttpStatusCode.UnsupportedMediaType + status = HttpStatusCode.UnsupportedMediaType, ) return@post } @@ -35,7 +35,7 @@ class EndpointRegistrationRoute } catch (_: InvalidMessageException) { call.respondText( "Invalid registration request", - status = HttpStatusCode.BadRequest + status = HttpStatusCode.BadRequest, ) return@post } @@ -45,7 +45,7 @@ class EndpointRegistrationRoute } catch (_: InvalidPNRAException) { call.respondText( "Invalid authorization encapsulated in registration request", - status = HttpStatusCode.BadRequest + status = HttpStatusCode.BadRequest, ) return@post } diff --git a/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionRoute.kt b/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionRoute.kt index 1bc3c02b..9aca8ea2 100644 --- a/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionRoute.kt +++ b/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionRoute.kt @@ -30,7 +30,7 @@ import javax.inject.Provider class ParcelCollectionRoute @Inject constructor( private val parcelCollectionHandshake: ParcelCollectionHandshake, - private val collectParcelsProvider: Provider + private val collectParcelsProvider: Provider, ) : PDCServerRoute { @VisibleForTesting @@ -62,8 +62,8 @@ class ParcelCollectionRoute close( CloseReason( CloseReason.Codes.VIOLATED_POLICY, - "Web browser requests are disabled for security reasons" - ) + "Web browser requests are disabled for security reasons", + ), ) return } @@ -78,8 +78,8 @@ class ParcelCollectionRoute val sendJob = sendParcels(collectParcels, certificates.toAddresses()) val receiveJob = receiveAcks(collectParcels) - val keepAlive = - call.request.header(StreamingMode.HEADER_NAME) == StreamingMode.KeepAlive.headerValue + val keepAlive = call.request.header(StreamingMode.HEADER_NAME) == + StreamingMode.KeepAlive.headerValue if (!keepAlive) { collectParcels .anyParcelsLeftToDeliverOrAck @@ -88,8 +88,8 @@ class ParcelCollectionRoute close( CloseReason( CloseReason.Codes.NORMAL, - "All available parcels delivered" - ) + "All available parcels delivered", + ), ) asyncJob.complete() } @@ -107,29 +107,27 @@ class ParcelCollectionRoute if (closeCode != CloseReason.Codes.NORMAL.code) { throw ServerConnectionException( "Server closed the connection unexpectedly " + - "(code: $closeCode, reason: ${reason?.message})" + "(code: $closeCode, reason: ${reason?.message})", ) } } - private fun List.toAddresses() = - map { MessageAddress.of(it.subjectId) } + private fun List.toAddresses() = map { MessageAddress.of(it.subjectId) } private suspend fun DefaultWebSocketServerSession.sendParcels( collectParcels: CollectParcels, - addresses: List - ) = - collectParcels.getNewParcelsForEndpoints(addresses) - .onEach { parcels -> - parcels.iterator().forEach { (localId, parcelStream) -> - val parcelDelivery = - ParcelDelivery(localId, parcelStream.readBytesAndClose()) - outgoing.send( - Frame.Binary(true, parcelDelivery.serialize()) - ) - } + addresses: List, + ) = collectParcels.getNewParcelsForEndpoints(addresses) + .onEach { parcels -> + parcels.iterator().forEach { (localId, parcelStream) -> + val parcelDelivery = + ParcelDelivery(localId, parcelStream.readBytesAndClose()) + outgoing.send( + Frame.Binary(true, parcelDelivery.serialize()), + ) } - .launchIn(asyncScope) + } + .launchIn(asyncScope) private suspend fun DefaultWebSocketServerSession.receiveAcks(collectParcels: CollectParcels) = incoming.receiveAsFlow() diff --git a/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/ParcelDeliveryRoute.kt b/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/ParcelDeliveryRoute.kt index 3facfe8b..645990ad 100644 --- a/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/ParcelDeliveryRoute.kt +++ b/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/ParcelDeliveryRoute.kt @@ -20,7 +20,7 @@ class ParcelDeliveryRoute if (call.request.contentType() != ContentType.PARCEL) { call.respondText( "Content type ${ContentType.PARCEL} is required", - status = HttpStatusCode.UnsupportedMediaType + status = HttpStatusCode.UnsupportedMediaType, ) return@post } @@ -30,11 +30,11 @@ class ParcelDeliveryRoute when (storeResult) { is StoreParcel.Result.MalformedParcel -> call.respondText( "Parcel is malformed", - status = HttpStatusCode.BadRequest + status = HttpStatusCode.BadRequest, ) is StoreParcel.Result.InvalidParcel -> call.respondText( "Parcel is invalid", - status = HttpStatusCode.UnprocessableEntity + status = HttpStatusCode.UnprocessableEntity, ) else -> call.respond(HttpStatusCode.Accepted) } diff --git a/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/PoWebExceptions.kt b/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/PoWebExceptions.kt index e5b85227..91073b4f 100644 --- a/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/PoWebExceptions.kt +++ b/app/src/main/java/tech/relaycorp/gateway/pdc/local/routes/PoWebExceptions.kt @@ -2,7 +2,7 @@ package tech.relaycorp.gateway.pdc.local.routes abstract class PoWebException internal constructor( message: String?, - cause: Throwable? = null + cause: Throwable? = null, ) : Exception(message, cause) /** diff --git a/app/src/main/java/tech/relaycorp/gateway/pdc/local/utils/ParcelCollectionHandshake.kt b/app/src/main/java/tech/relaycorp/gateway/pdc/local/utils/ParcelCollectionHandshake.kt index 3ce05874..e16b541f 100644 --- a/app/src/main/java/tech/relaycorp/gateway/pdc/local/utils/ParcelCollectionHandshake.kt +++ b/app/src/main/java/tech/relaycorp/gateway/pdc/local/utils/ParcelCollectionHandshake.kt @@ -16,7 +16,7 @@ import javax.inject.Inject class ParcelCollectionHandshake @Inject constructor( - private val localConfig: LocalConfig + private val localConfig: LocalConfig, ) { @Throws(HandshakeUnsuccessful::class) @@ -24,7 +24,7 @@ class ParcelCollectionHandshake val nonce = Handshake.generateNonce() val challenge = HandshakeChallenge(nonce) session.outgoing.send( - Frame.Binary(true, challenge.serialize()) + Frame.Binary(true, challenge.serialize()), ) val responseRaw = session.incoming.receive() @@ -48,11 +48,11 @@ class ParcelCollectionHandshake DetachedSignatureType.NONCE.verify( nonceSignature, nonce, - trustedCertificates + trustedCertificates, ) } catch (_: InvalidSignatureException) { session.closeCannotAccept( - "Handshake response included invalid nonce signatures or untrusted signers" + "Handshake response included invalid nonce signatures or untrusted signers", ) throw HandshakeUnsuccessful() } @@ -63,8 +63,8 @@ class ParcelCollectionHandshake close( CloseReason( CloseReason.Codes.CANNOT_ACCEPT, - reason - ) + reason, + ), ) } diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/BaseActivity.kt b/app/src/main/java/tech/relaycorp/gateway/ui/BaseActivity.kt index bd87f755..f584ff97 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/BaseActivity.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/BaseActivity.kt @@ -60,7 +60,7 @@ abstract class BaseActivity : AppCompatActivity() { protected fun setupNavigation( @DrawableRes icon: Int = R.drawable.ic_close, - clickListener: (() -> Unit) = { finish() } + clickListener: (() -> Unit) = { finish() }, ) { toolbar?.setNavigationIcon(icon) toolbar?.setNavigationOnClickListener { clickListener.invoke() } diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/common/ActivityResult.kt b/app/src/main/java/tech/relaycorp/gateway/ui/common/ActivityResult.kt index fa31fe15..5e383f3a 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/common/ActivityResult.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/common/ActivityResult.kt @@ -5,5 +5,5 @@ import android.content.Intent data class ActivityResult( val requestCode: Int, val resultCode: Int, - val data: Intent? + val data: Intent?, ) diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/common/FlowUtils.kt b/app/src/main/java/tech/relaycorp/gateway/ui/common/FlowUtils.kt deleted file mode 100644 index c2b8fe9d..00000000 --- a/app/src/main/java/tech/relaycorp/gateway/ui/common/FlowUtils.kt +++ /dev/null @@ -1 +0,0 @@ -package tech.relaycorp.gateway.ui.common diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/common/Insets.kt b/app/src/main/java/tech/relaycorp/gateway/ui/common/Insets.kt index 70d9c2a9..aa9cf51d 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/common/Insets.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/common/Insets.kt @@ -16,7 +16,7 @@ object Insets { left: Boolean = false, top: Boolean = false, right: Boolean = false, - bottom: Boolean = false + bottom: Boolean = false, ) { val (initialLeft, initialTop, initialRight, initialBottom) = listOf(marginLeft, marginTop, marginRight, marginBottom) @@ -28,7 +28,8 @@ object Insets { left = initialLeft + (if (left) insets.systemWindowInsetLeft else 0), top = initialTop + (if (top) insets.systemWindowInsetTop else 0), right = initialRight + (if (right) insets.systemWindowInsetRight else 0), - bottom = initialBottom + (if (bottom) insets.systemWindowInsetBottom else 0) + bottom = initialBottom + + (if (bottom) insets.systemWindowInsetBottom else 0), ) } } @@ -40,7 +41,7 @@ object Insets { left: Boolean = false, top: Boolean = false, right: Boolean = false, - bottom: Boolean = false + bottom: Boolean = false, ) { val (initialLeft, initialTop, initialRight, initialBottom) = listOf(paddingLeft, paddingTop, paddingRight, paddingBottom) @@ -50,7 +51,7 @@ object Insets { left = initialLeft + (if (left) insets.systemWindowInsetLeft else 0), top = initialTop + (if (top) insets.systemWindowInsetTop else 0), right = initialRight + (if (right) insets.systemWindowInsetRight else 0), - bottom = initialBottom + (if (bottom) insets.systemWindowInsetBottom else 0) + bottom = initialBottom + (if (bottom) insets.systemWindowInsetBottom else 0), ) insets } diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/common/MessageManager.kt b/app/src/main/java/tech/relaycorp/gateway/ui/common/MessageManager.kt index 272dad26..e6d9717f 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/common/MessageManager.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/common/MessageManager.kt @@ -8,23 +8,19 @@ import javax.inject.Inject class MessageManager @Inject constructor( - private val activity: Activity + private val activity: Activity, ) { private val resources get() = activity.resources private val rootView get() = activity.findViewById(android.R.id.content) - fun showMessage(@StringRes messageRes: Int) = - showMessage(resources.getString(messageRes)) + fun showMessage(@StringRes messageRes: Int) = showMessage(resources.getString(messageRes)) - fun showMessage(message: String) = - showSnackbar(message) + fun showMessage(message: String) = showSnackbar(message) - fun showError(@StringRes errorRes: Int) = - showMessage(errorRes) + fun showError(@StringRes errorRes: Int) = showMessage(errorRes) - private fun showSnackbar(text: String) = - Snackbar - .make(rootView, text, Snackbar.LENGTH_LONG) - .show() + private fun showSnackbar(text: String) = Snackbar + .make(rootView, text, Snackbar.LENGTH_LONG) + .show() } diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/common/StorageSizeUI.kt b/app/src/main/java/tech/relaycorp/gateway/ui/common/StorageSizeUI.kt index ca4d7c68..2c98c59f 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/common/StorageSizeUI.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/common/StorageSizeUI.kt @@ -4,5 +4,4 @@ import android.content.Context import android.text.format.Formatter import tech.relaycorp.gateway.data.model.StorageSize -fun StorageSize.format(context: Context): String = - Formatter.formatFileSize(context, bytes) +fun StorageSize.format(context: Context): String = Formatter.formatFileSize(context, bytes) diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/main/MainActivity.kt b/app/src/main/java/tech/relaycorp/gateway/ui/main/MainActivity.kt index 735b5b64..9317525a 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/main/MainActivity.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/main/MainActivity.kt @@ -81,43 +81,40 @@ class MainActivity : BaseActivity() { .launchIn(lifecycleScope) } - private fun ConnectionState.toImageRes() = - when (this) { - ConnectionState.InternetWithGateway -> R.drawable.main_connected_image - is ConnectionState.WiFiWithCourier -> R.drawable.main_courier_image - else -> R.drawable.main_disconnected_image - } + private fun ConnectionState.toImageRes() = when (this) { + ConnectionState.InternetWithGateway -> R.drawable.main_connected_image + is ConnectionState.WiFiWithCourier -> R.drawable.main_courier_image + else -> R.drawable.main_disconnected_image + } - private fun ConnectionState.toTitleRes() = - when (this) { - is ConnectionState.InternetWithoutGateway -> - R.string.main_status_internet_no_gateway - ConnectionState.InternetWithGateway -> - R.string.main_status_internet - is ConnectionState.WiFiWithCourier -> - R.string.main_status_courier - else -> - R.string.main_status_disconnected - } + private fun ConnectionState.toTitleRes() = when (this) { + is ConnectionState.InternetWithoutGateway -> + R.string.main_status_internet_no_gateway + ConnectionState.InternetWithGateway -> + R.string.main_status_internet + is ConnectionState.WiFiWithCourier -> + R.string.main_status_courier + else -> + R.string.main_status_disconnected + } - private fun ConnectionState.toTextRes() = - when (this) { - is ConnectionState.InternetWithoutGateway -> - R.string.main_status_internet_no_gateway_text - ConnectionState.InternetWithGateway -> - R.string.main_status_internet_text - is ConnectionState.WiFiWithCourier -> - R.string.main_status_courier_text - else -> - R.string.main_status_disconnected_text - } + private fun ConnectionState.toTextRes() = when (this) { + is ConnectionState.InternetWithoutGateway -> + R.string.main_status_internet_no_gateway_text + ConnectionState.InternetWithGateway -> + R.string.main_status_internet_text + is ConnectionState.WiFiWithCourier -> + R.string.main_status_courier_text + else -> + R.string.main_status_disconnected_text + } - private fun ConnectionState.toTextGravity() = - when (this) { - ConnectionState.InternetWithGateway, - is ConnectionState.WiFiWithCourier -> Gravity.CENTER_HORIZONTAL - else -> Gravity.START - } + private fun ConnectionState.toTextGravity() = when (this) { + ConnectionState.InternetWithGateway, + is ConnectionState.WiFiWithCourier, + -> Gravity.CENTER_HORIZONTAL + else -> Gravity.START + } companion object { fun getIntent(context: Context) = Intent(context, MainActivity::class.java) diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/main/MainViewModel.kt b/app/src/main/java/tech/relaycorp/gateway/ui/main/MainViewModel.kt index 9510c1e5..0d6ff43f 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/main/MainViewModel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/main/MainViewModel.kt @@ -14,7 +14,7 @@ import javax.inject.Inject class MainViewModel @Inject constructor( appPreferences: AppPreferences, - private val connectionStateObserver: ConnectionStateObserver + private val connectionStateObserver: ConnectionStateObserver, ) : BaseViewModel() { // Outputs diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/main/PublishChannel.kt b/app/src/main/java/tech/relaycorp/gateway/ui/main/PublishFlow.kt similarity index 78% rename from app/src/main/java/tech/relaycorp/gateway/ui/main/PublishChannel.kt rename to app/src/main/java/tech/relaycorp/gateway/ui/main/PublishFlow.kt index b80165b5..62966957 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/main/PublishChannel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/main/PublishFlow.kt @@ -2,4 +2,5 @@ package tech.relaycorp.gateway.ui.main import kotlinx.coroutines.flow.MutableSharedFlow +@Suppress("ktlint:standard:function-naming") fun PublishFlow() = MutableSharedFlow(extraBufferCapacity = 1) diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/onboarding/OnboardingActivity.kt b/app/src/main/java/tech/relaycorp/gateway/ui/onboarding/OnboardingActivity.kt index 0e3ba124..0dba26e2 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/onboarding/OnboardingActivity.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/onboarding/OnboardingActivity.kt @@ -69,7 +69,7 @@ class OnboardingActivity : BaseActivity() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = OnboardingPageViewHolder( LayoutInflater.from(this@OnboardingActivity) - .inflate(R.layout.item_onboarding, parent, false) + .inflate(R.layout.item_onboarding, parent, false), ) override fun onBindViewHolder(holder: OnboardingPageViewHolder, position: Int) { @@ -94,7 +94,7 @@ class OnboardingActivity : BaseActivity() { @StringRes val title: Int, @StringRes val text: Int, @DrawableRes val image: Int, - val getStarted: Boolean = false + val getStarted: Boolean = false, ) companion object { @@ -102,19 +102,19 @@ class OnboardingActivity : BaseActivity() { OnboardingPage( R.string.onboarding_title_1, R.string.onboarding_text_1, - R.drawable.onboarding_image_1 + R.drawable.onboarding_image_1, ), OnboardingPage( R.string.onboarding_title_2, R.string.onboarding_text_2, - R.drawable.onboarding_image_2 + R.drawable.onboarding_image_2, ), OnboardingPage( R.string.onboarding_title_3, R.string.onboarding_text_3, R.drawable.onboarding_image_3, - true - ) + true, + ), ) fun getIntent(context: Context) = Intent(context, OnboardingActivity::class.java) diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayActivity.kt b/app/src/main/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayActivity.kt index be6c2550..c90f913b 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayActivity.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayActivity.kt @@ -43,7 +43,7 @@ class MigrateGatewayActivity : BaseActivity() { binding.address.addTextChangedListener( onTextChanged = { text: CharSequence?, _, _, _ -> viewModel.addressChanged(text?.toString()?.trim() ?: "") - } + }, ) binding.submit.setOnClickListener { showSubmitConfirm() } @@ -77,7 +77,8 @@ class MigrateGatewayActivity : BaseActivity() { ContextCompat.getDrawable(this, R.drawable.ic_check) MigrateGatewayViewModel.State.Error.SameAddress, MigrateGatewayViewModel.State.Error.FailedToResolve, - MigrateGatewayViewModel.State.Error.FailedToRegister -> + MigrateGatewayViewModel.State.Error.FailedToRegister, + -> ContextCompat.getDrawable(this, R.drawable.ic_close) else -> null } @@ -86,7 +87,7 @@ class MigrateGatewayActivity : BaseActivity() { MigrateGatewayViewModel.State.AddressValid -> R.attr.colorSecondary is MigrateGatewayViewModel.State.Error -> R.attr.colorError else -> R.attr.colorOnBackground - } + }, ) binding.addressLayout.setEndIconTintList(ColorStateList.valueOf(infoColor)) @@ -110,12 +111,14 @@ class MigrateGatewayActivity : BaseActivity() { binding.submit.isVisible = when (state) { MigrateGatewayViewModel.State.Insert, MigrateGatewayViewModel.State.Error.SameAddress, - MigrateGatewayViewModel.State.Error.AddressInvalid -> + MigrateGatewayViewModel.State.Error.AddressInvalid, + -> false MigrateGatewayViewModel.State.AddressValid, MigrateGatewayViewModel.State.Submitting, MigrateGatewayViewModel.State.Error.FailedToResolve, - MigrateGatewayViewModel.State.Error.FailedToRegister -> + MigrateGatewayViewModel.State.Error.FailedToRegister, + -> true } diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayViewModel.kt b/app/src/main/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayViewModel.kt index 5972c34a..3a14e954 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayViewModel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayViewModel.kt @@ -20,7 +20,7 @@ class MigrateGatewayViewModel internetGatewayPreferences: InternetGatewayPreferences, migrateGateway: MigrateGateway, @Named("validator_hostname") - hostnameValidator: (@JvmSuppressWildcards String) -> @JvmSuppressWildcards Boolean + hostnameValidator: (@JvmSuppressWildcards String) -> @JvmSuppressWildcards Boolean, ) : BaseViewModel() { val state: Flow get() = _state diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/settings/SettingsActivity.kt b/app/src/main/java/tech/relaycorp/gateway/ui/settings/SettingsActivity.kt index f8ee116f..12910f7d 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/settings/SettingsActivity.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/settings/SettingsActivity.kt @@ -39,7 +39,7 @@ class SettingsActivity : BaseActivity() { binding.version.text = getString( R.string.settings_version, BuildConfig.VERSION_NAME, - BuildConfig.VERSION_CODE.toString() + BuildConfig.VERSION_CODE.toString(), ) binding.internetGateway.setOnClickListener { openMigrateGateway() } binding.learnMore.setOnClickListener { openKnowMore() } diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/settings/SettingsViewModel.kt b/app/src/main/java/tech/relaycorp/gateway/ui/settings/SettingsViewModel.kt index 89438cab..095627bf 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/settings/SettingsViewModel.kt @@ -12,7 +12,7 @@ import javax.inject.Inject class SettingsViewModel @Inject constructor( getOutgoingData: GetOutgoingData, - internetGatewayPreferences: InternetGatewayPreferences + internetGatewayPreferences: InternetGatewayPreferences, ) : BaseViewModel() { val showOutgoingData: Flow get() = _showOutgoingData diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierConnectionViewModel.kt b/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierConnectionViewModel.kt index 76a47e5e..83aa058d 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierConnectionViewModel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierConnectionViewModel.kt @@ -6,7 +6,7 @@ import javax.inject.Inject class CourierConnectionViewModel @Inject constructor( - private val connectionStateObserver: ConnectionStateObserver + private val connectionStateObserver: ConnectionStateObserver, ) : BaseViewModel() { // Outputs diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierSyncActivity.kt b/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierSyncActivity.kt index 44da7bea..902bbfdd 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierSyncActivity.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierSyncActivity.kt @@ -58,7 +58,7 @@ class CourierSyncActivity : BaseActivity() { R.drawable.sync_image } else { R.drawable.sync_done_image - } + }, ) if (isSyncing) { binding.animation.startLoopingAvd(R.drawable.sync_animation) @@ -77,7 +77,7 @@ class CourierSyncActivity : BaseActivity() { CourierSync.State.Finished -> R.drawable.sync_done_image CourierSync.State.Error -> 0 else -> R.drawable.sync_image - } + }, ) } .launchIn(lifecycleScope) @@ -97,14 +97,13 @@ class CourierSyncActivity : BaseActivity() { .show() } - private fun CourierSync.State.toStringRes() = - when (this) { - CourierSync.State.DeliveringCargo -> R.string.sync_delivering_cargo - CourierSync.State.Waiting -> R.string.sync_waiting - CourierSync.State.CollectingCargo -> R.string.sync_collecting_cargo - CourierSync.State.Finished -> R.string.sync_finished - CourierSync.State.Error -> R.string.sync_error - } + private fun CourierSync.State.toStringRes() = when (this) { + CourierSync.State.DeliveringCargo -> R.string.sync_delivering_cargo + CourierSync.State.Waiting -> R.string.sync_waiting + CourierSync.State.CollectingCargo -> R.string.sync_collecting_cargo + CourierSync.State.Finished -> R.string.sync_finished + CourierSync.State.Error -> R.string.sync_error + } companion object { fun getIntent(context: Context) = Intent(context, CourierSyncActivity::class.java) diff --git a/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierSyncViewModel.kt b/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierSyncViewModel.kt index 1c7458ef..b44ae811 100644 --- a/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierSyncViewModel.kt +++ b/app/src/main/java/tech/relaycorp/gateway/ui/sync/CourierSyncViewModel.kt @@ -15,7 +15,7 @@ import javax.inject.Inject class CourierSyncViewModel @Inject constructor( - private val courierSync: CourierSync + private val courierSync: CourierSync, ) : BaseViewModel() { // Inputs diff --git a/app/src/sharedTest/java/tech/relaycorp/gateway/test/CargoDeliveryCertPath.kt b/app/src/sharedTest/java/tech/relaycorp/gateway/test/CargoDeliveryCertPath.kt index 1f6f07df..347edc3f 100644 --- a/app/src/sharedTest/java/tech/relaycorp/gateway/test/CargoDeliveryCertPath.kt +++ b/app/src/sharedTest/java/tech/relaycorp/gateway/test/CargoDeliveryCertPath.kt @@ -16,7 +16,7 @@ object CargoDeliveryCertPath { KeyPairSet.PRIVATE_GW.public, KeyPairSet.PRIVATE_GW.private, endDate, - validityStartDate = startDate + validityStartDate = startDate, ) } @@ -28,7 +28,7 @@ object CargoDeliveryCertPath { KeyPairSet.PRIVATE_GW.private, endDate, PRIVATE_GW, - validityStartDate = startDate + validityStartDate = startDate, ) } } diff --git a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/CargoFactory.kt b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/CargoFactory.kt index e334024e..3d9252c6 100644 --- a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/CargoFactory.kt +++ b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/CargoFactory.kt @@ -13,9 +13,8 @@ object CargoFactory { fun build() = Cargo( Recipient(CargoDeliveryCertPath.PRIVATE_GW.subjectId), "".toByteArray(), - CargoDeliveryCertPath.PUBLIC_GW + CargoDeliveryCertPath.PUBLIC_GW, ) - fun buildSerialized() = - build().serialize(KeyPairSet.INTERNET_GW.private) + fun buildSerialized() = build().serialize(KeyPairSet.INTERNET_GW.private) } diff --git a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/LocalEndpointFactory.kt b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/LocalEndpointFactory.kt index 7c1f1151..6111a139 100644 --- a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/LocalEndpointFactory.kt +++ b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/LocalEndpointFactory.kt @@ -9,6 +9,6 @@ object LocalEndpointFactory { fun build() = LocalEndpoint( address = PrivateMessageAddress(Random.nextInt().toString()), - applicationId = UUID.randomUUID().toString() + applicationId = UUID.randomUUID().toString(), ) } diff --git a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelCollectionAckFactory.kt b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelCollectionAckFactory.kt index 6c04ecff..a073f1f3 100644 --- a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelCollectionAckFactory.kt +++ b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelCollectionAckFactory.kt @@ -8,6 +8,6 @@ object ParcelCollectionAckFactory { fun build() = ParcelCollectionAck( senderEndpointId = Random.nextInt().toString(), recipientEndpointId = Random.nextInt().toString(), - parcelId = Random.nextInt().toString() + parcelId = Random.nextInt().toString(), ) } diff --git a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelCollectionFactory.kt b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelCollectionFactory.kt index 6b48dc33..6e8e0899 100644 --- a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelCollectionFactory.kt +++ b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelCollectionFactory.kt @@ -14,6 +14,6 @@ object ParcelCollectionFactory { recipientAddress = MessageAddress.of(Random.nextInt().toString()), messageId = MessageId(Random.nextInt().toString()), creationTimeUtc = nowInUtc(), - expirationTimeUtc = nowInUtc() + expirationTimeUtc = nowInUtc(), ) } diff --git a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelFactory.kt b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelFactory.kt index 7ffe208a..7e7c270f 100644 --- a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelFactory.kt +++ b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/ParcelFactory.kt @@ -11,7 +11,7 @@ object ParcelFactory { Recipient(PDACertPath.PRIVATE_ENDPOINT.subjectId, internetAddress), "".toByteArray(), PDACertPath.PDA, - senderCertificateChain = setOf(PDACertPath.PRIVATE_ENDPOINT) + senderCertificateChain = setOf(PDACertPath.PRIVATE_ENDPOINT), ) fun buildSerialized(internetAddress: String? = null) = diff --git a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/StoredParcelFactory.kt b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/StoredParcelFactory.kt index fd14373e..dfe0e6ca 100644 --- a/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/StoredParcelFactory.kt +++ b/app/src/sharedTest/java/tech/relaycorp/gateway/test/factory/StoredParcelFactory.kt @@ -19,7 +19,7 @@ object StoredParcelFactory { creationTimeUtc = nowInUtc(), expirationTimeUtc = nowInUtc().plusDays(1), storagePath = "file", - size = StorageSizeFactory.build() + size = StorageSizeFactory.build(), ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/background/CheckInternetGatewayAccessTest.kt b/app/src/test/java/tech/relaycorp/gateway/background/CheckInternetGatewayAccessTest.kt index 5624b220..ca024600 100644 --- a/app/src/test/java/tech/relaycorp/gateway/background/CheckInternetGatewayAccessTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/background/CheckInternetGatewayAccessTest.kt @@ -8,8 +8,8 @@ import com.nhaarman.mockitokotlin2.whenever import kotlinx.coroutines.test.runBlockingTest import org.junit.jupiter.api.Test import tech.relaycorp.gateway.data.doh.InternetAddressResolutionException -import tech.relaycorp.gateway.data.preference.InternetGatewayPreferences import tech.relaycorp.gateway.data.model.ServiceAddress +import tech.relaycorp.gateway.data.preference.InternetGatewayPreferences import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -17,7 +17,8 @@ class CheckInternetGatewayAccessTest { private val mockGatewayPreferences = mock() private val mockPingRemoteServer = mock() private val checkAccess = CheckInternetGatewayAccess( - mockGatewayPreferences, mockPingRemoteServer + mockGatewayPreferences, + mockPingRemoteServer, ) private val powebAddress = ServiceAddress("poweb.example.com", 443) diff --git a/app/src/test/java/tech/relaycorp/gateway/data/disk/CargoStorageTest.kt b/app/src/test/java/tech/relaycorp/gateway/data/disk/CargoStorageTest.kt index 4aaceea9..dd91ca88 100644 --- a/app/src/test/java/tech/relaycorp/gateway/data/disk/CargoStorageTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/data/disk/CargoStorageTest.kt @@ -48,7 +48,7 @@ internal class CargoStorageTest { val cargo = Cargo( Recipient("0deadbeef", "foo.relaycorp.tech"), "".toByteArray(), - CargoDeliveryCertPath.PUBLIC_GW + CargoDeliveryCertPath.PUBLIC_GW, ) assertThrows { @@ -70,12 +70,12 @@ internal class CargoStorageTest { val unauthorizedSenderCert = issueGatewayCertificate( unauthorizedSenderKeyPair.public, unauthorizedSenderKeyPair.private, - ZonedDateTime.now().plusMinutes(1) + ZonedDateTime.now().plusMinutes(1), ) val cargo = Cargo( Recipient(CargoDeliveryCertPath.PRIVATE_GW.subjectId), "".toByteArray(), - unauthorizedSenderCert + unauthorizedSenderCert, ) assertThrows { @@ -99,7 +99,7 @@ internal class CargoStorageTest { verify(diskOperations).writeMessage( eq(CargoStorage.FOLDER), eq(CargoStorage.PREFIX), - capture() + capture(), ) assertEquals(cargoSerialized.asList(), firstValue.asList()) diff --git a/app/src/test/java/tech/relaycorp/gateway/data/doh/ResolveServiceAddressTest.kt b/app/src/test/java/tech/relaycorp/gateway/data/doh/ResolveServiceAddressTest.kt index 55dc5fc3..5d8bbb93 100644 --- a/app/src/test/java/tech/relaycorp/gateway/data/doh/ResolveServiceAddressTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/data/doh/ResolveServiceAddressTest.kt @@ -25,7 +25,7 @@ class ResolveServiceAddressTest { fun `Target host and port should be returned`() = runBlockingTest { whenever(mockDoHClient.lookUp("_awala-gsc._tcp.$internetGatewayAddress", "SRV")) .thenReturn( - Answer(listOf("0 1 $internetGatewayTargetPort $internetGatewayTargetHost.")) + Answer(listOf("0 1 $internetGatewayTargetPort $internetGatewayTargetHost.")), ) val address = subject.resolvePoWeb(internetGatewayAddress) @@ -45,7 +45,7 @@ class ResolveServiceAddressTest { kotlin.test.assertEquals( "Malformed SRV for $internetGatewayAddress ($malformedSRVData)", - exception.message + exception.message, ) kotlin.test.assertNull(exception.cause) } diff --git a/app/src/test/java/tech/relaycorp/gateway/data/preference/InternetGatewayPreferencesTest.kt b/app/src/test/java/tech/relaycorp/gateway/data/preference/InternetGatewayPreferencesTest.kt index 2fe67fd7..d0622f65 100644 --- a/app/src/test/java/tech/relaycorp/gateway/data/preference/InternetGatewayPreferencesTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/data/preference/InternetGatewayPreferencesTest.kt @@ -28,7 +28,7 @@ class InternetGatewayPreferencesTest { private val gwPreferences = InternetGatewayPreferences( Provider { mockSharedPreferences }, mockReadRawFile, - mockResolveServiceAddress + mockResolveServiceAddress, ) private val internetGatewayAddress = "example.com" @@ -46,7 +46,7 @@ class InternetGatewayPreferencesTest { whenever(mockInternetGatewayAddressPreference.get()).thenReturn(internetGatewayAddress) whenever( mockSharedPreferences - .getString("address", InternetGatewayPreferences.DEFAULT_ADDRESS) + .getString("address", InternetGatewayPreferences.DEFAULT_ADDRESS), ).thenReturn(mockInternetGatewayAddressPreference) whenever(mockSharedPreferences.getString(eq("public_gateway_public_key"), anyOrNull())) .thenReturn(emptyStringPreference) @@ -96,8 +96,8 @@ class InternetGatewayPreferencesTest { whenever( mockSharedPreferences.getString( eq("public_gateway_id"), - anyOrNull() - ) + anyOrNull(), + ), ) .thenReturn(emptyStringPreference) whenever(mockReadRawFile.read(any())).thenReturn(PDACertPath.INTERNET_GW.serialize()) @@ -113,7 +113,7 @@ class InternetGatewayPreferencesTest { whenever(it.get()).thenReturn("private_address") } whenever( - mockSharedPreferences.getString(eq("public_gateway_id"), anyOrNull()) + mockSharedPreferences.getString(eq("public_gateway_id"), anyOrNull()), ) .thenReturn(preference) diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/DeleteParcelTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/DeleteParcelTest.kt index 991e59cb..c4dd9a93 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/DeleteParcelTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/DeleteParcelTest.kt @@ -23,7 +23,7 @@ internal class DeleteParcelTest { verify(storedParcelDao).delete(eq(storedParcel)) verify(diskOperations).deleteMessage( eq(StoredParcel.STORAGE_FOLDER), - eq(storedParcel.storagePath) + eq(storedParcel.storagePath), ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/LocalConfigTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/LocalConfigTest.kt index 3ab1a37f..46f49c60 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/LocalConfigTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/LocalConfigTest.kt @@ -23,7 +23,9 @@ class LocalConfigTest : BaseDataTestCase() { private val internetGatewayPreferences = mock() private val localConfig = LocalConfig( - privateKeyStoreProvider, certificateStoreProvider, internetGatewayPreferences + privateKeyStoreProvider, + certificateStoreProvider, + internetGatewayPreferences, ) @BeforeEach @@ -108,7 +110,7 @@ class LocalConfigTest : BaseDataTestCase() { any(), any(), any(), - eq(PDACertPath.INTERNET_GW.subjectId) + eq(PDACertPath.INTERNET_GW.subjectId), ) } diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/StoreParcelTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/StoreParcelTest.kt index 9ff72518..4df5d7ba 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/StoreParcelTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/StoreParcelTest.kt @@ -49,7 +49,8 @@ internal class StoreParcelTest { val parcel = Parcel( Recipient(PDACertPath.PRIVATE_ENDPOINT.subjectId), ByteArray(0), - PDACertPath.INTERNET_GW // Unauthorized sender + // Unauthorized sender + PDACertPath.INTERNET_GW, ).serialize(KeyPairSet.INTERNET_GW.private) val result = storeParcel.store(parcel, RecipientLocation.LocalEndpoint) @@ -63,7 +64,7 @@ internal class StoreParcelTest { ByteArray(0), PDACertPath.PRIVATE_ENDPOINT, "", - ZonedDateTime.now().plusMinutes(2) + ZonedDateTime.now().plusMinutes(2), ).serialize(KeyPairSet.PRIVATE_ENDPOINT.private) val result = storeParcel.store(parcel, RecipientLocation.ExternalGateway) @@ -77,7 +78,7 @@ internal class StoreParcelTest { val parcel = Parcel( Recipient("0deadbeef", publicEndpointAddress), ByteArray(0), - PDACertPath.PDA + PDACertPath.PDA, ).serialize(KeyPairSet.PDA_GRANTEE.private) val result = storeParcel.store(parcel, RecipientLocation.LocalEndpoint) @@ -91,7 +92,7 @@ internal class StoreParcelTest { Recipient(PDACertPath.PRIVATE_ENDPOINT.subjectId), ByteArray(0), PDACertPath.PDA, - senderCertificateChain = setOf(PDACertPath.PRIVATE_ENDPOINT) + senderCertificateChain = setOf(PDACertPath.PRIVATE_ENDPOINT), ).serialize(KeyPairSet.PDA_GRANTEE.private) val result = storeParcel.store(parcel, RecipientLocation.LocalEndpoint) @@ -108,12 +109,12 @@ internal class StoreParcelTest { val untrustedCertificate = issueEndpointCertificate( untrustedKeyPair.public, untrustedKeyPair.private, - ZonedDateTime.now().plusMinutes(2) + ZonedDateTime.now().plusMinutes(2), ) val parcel = Parcel( Recipient("0deadbeef", publicEndpointAddress), ByteArray(0), - untrustedCertificate + untrustedCertificate, ).serialize(untrustedKeyPair.private) val result = storeParcel.store(parcel, RecipientLocation.ExternalGateway) @@ -131,7 +132,7 @@ internal class StoreParcelTest { Recipient(PDACertPath.PRIVATE_ENDPOINT.subjectId), ByteArray(0), PDACertPath.PDA, - senderCertificateChain = setOf(PDACertPath.PRIVATE_ENDPOINT) + senderCertificateChain = setOf(PDACertPath.PRIVATE_ENDPOINT), ).serialize(KeyPairSet.PDA_GRANTEE.private) val result = storeParcel.store(parcel, RecipientLocation.LocalEndpoint) diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/courier/CalculateCRCMessageCreationDateTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/courier/CalculateCRCMessageCreationDateTest.kt index f39bb604..93ea800a 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/courier/CalculateCRCMessageCreationDateTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/courier/CalculateCRCMessageCreationDateTest.kt @@ -22,7 +22,7 @@ class CalculateCRCMessageCreationDateTest { keyPair.public, keyPair.private, nowInUtc().plusMinutes(1), - validityStartDate = nowInUtc().minusDays(1) + validityStartDate = nowInUtc().minusDays(1), ) whenever(localConfig.getIdentityCertificate()).thenReturn(certificate) @@ -30,7 +30,7 @@ class CalculateCRCMessageCreationDateTest { assertTrue( result.isBefore(nowInUtc().minusMinutes(89)) && - result.isAfter(nowInUtc().minusMinutes(91)) + result.isAfter(nowInUtc().minusMinutes(91)), ) } @@ -42,7 +42,7 @@ class CalculateCRCMessageCreationDateTest { keyPair.public, keyPair.private, nowInUtc().plusMinutes(1), - validityStartDate = nowInUtc() + validityStartDate = nowInUtc(), ) whenever(localConfig.getIdentityCertificate()).thenReturn(certificate) diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/courier/GenerateCCATest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/courier/GenerateCCATest.kt index e0db9bc1..b243074e 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/courier/GenerateCCATest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/courier/GenerateCCATest.kt @@ -27,7 +27,9 @@ class GenerateCCATest : BaseDataTestCase() { private val internetGatewayPreferences = mock() private val localConfig = LocalConfig( - privateKeyStoreProvider, certificateStoreProvider, internetGatewayPreferences + privateKeyStoreProvider, + certificateStoreProvider, + internetGatewayPreferences, ) private val calculateCreationDate = mock() @@ -35,7 +37,7 @@ class GenerateCCATest : BaseDataTestCase() { internetGatewayPreferences, localConfig, calculateCreationDate, - gatewayManagerProvider + gatewayManagerProvider, ) companion object { @@ -52,7 +54,7 @@ class GenerateCCATest : BaseDataTestCase() { subjectPublicKey = keyPair.public, issuerPrivateKey = keyPair.private, validityEndDate = nowInUtc().plusMinutes(1), - validityStartDate = nowInUtc().minusDays(1) + validityStartDate = nowInUtc().minusDays(1), ) whenever(certificateStore.retrieveLatest(any(), eq(keyPair.public.nodeId))) .thenReturn(CertificationPath(cda, emptyList())) @@ -84,7 +86,7 @@ class GenerateCCATest : BaseDataTestCase() { val ccr = cca.unwrapPayload(internetGatewaySessionKeyPair.privateKey).payload assertEquals( KeyPairSet.INTERNET_GW.public, - ccr.cargoDeliveryAuthorization.subjectPublicKey + ccr.cargoDeliveryAuthorization.subjectPublicKey, ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/courier/GenerateCargoTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/courier/GenerateCargoTest.kt index 612935a8..785ebfb4 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/courier/GenerateCargoTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/courier/GenerateCargoTest.kt @@ -31,7 +31,9 @@ class GenerateCargoTest : BaseDataTestCase() { private val diskMessageOperations = mock() private val internetGatewayPreferences = mock() private val localConfig = LocalConfig( - privateKeyStoreProvider, certificateStoreProvider, internetGatewayPreferences + privateKeyStoreProvider, + certificateStoreProvider, + internetGatewayPreferences, ) private val calculateCRCMessageCreationDate = mock() private val generateCargo = GenerateCargo( @@ -41,7 +43,7 @@ class GenerateCargoTest : BaseDataTestCase() { internetGatewayPreferences, localConfig, calculateCRCMessageCreationDate, - gatewayManagerProvider + gatewayManagerProvider, ) @BeforeEach @@ -89,7 +91,7 @@ class GenerateCargoTest : BaseDataTestCase() { val cargo = Cargo.deserialize(cargoes.first().readBytes()) assertEquals( internetGatewayPreferences.getAddress(), - cargo.recipient.internetAddress + cargo.recipient.internetAddress, ) assertTrue(Duration.between(parcel.expirationTimeUtc, cargo.expiryDate).abs().seconds <= 2) diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/courier/ProcessCargoTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/courier/ProcessCargoTest.kt index f1db5755..c930e135 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/courier/ProcessCargoTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/courier/ProcessCargoTest.kt @@ -42,7 +42,7 @@ class ProcessCargoTest : BaseDataTestCase() { storeParcelCollection, deleteParcel, gatewayManagerProvider, - rotateCertificate + rotateCertificate, ) @BeforeEach @@ -66,7 +66,7 @@ class ProcessCargoTest : BaseDataTestCase() { verify(deleteParcel).delete( eq(MessageAddress.of(pca.recipientEndpointId)), eq(MessageAddress.of(pca.senderEndpointId)), - eq(MessageId(pca.parcelId)) + eq(MessageId(pca.parcelId)), ) } @@ -74,7 +74,7 @@ class ProcessCargoTest : BaseDataTestCase() { fun `store received parcel with collection`() = runBlockingTest { val parcel = ParcelFactory.build() val cargoSerialized = generateCargoFromMessages( - listOf(parcel.serialize(KeyPairSet.PDA_GRANTEE.private)) + listOf(parcel.serialize(KeyPairSet.PDA_GRANTEE.private)), ) whenever(cargoStorage.list()).thenReturn(listOf(cargoSerialized::inputStream)) whenever(storeParcel.store(any(), any())) @@ -90,7 +90,7 @@ class ProcessCargoTest : BaseDataTestCase() { fun `received malformed parcel that does not get stored`() = runBlockingTest { val parcel = ParcelFactory.build() val cargoSerialized = generateCargoFromMessages( - listOf(parcel.serialize(KeyPairSet.PDA_GRANTEE.private)) + listOf(parcel.serialize(KeyPairSet.PDA_GRANTEE.private)), ) whenever(cargoStorage.list()).thenReturn(listOf(cargoSerialized::inputStream)) whenever(storeParcel.store(any(), any())) @@ -106,7 +106,7 @@ class ProcessCargoTest : BaseDataTestCase() { fun `received duplicated parcel that does not get stored`() = runBlockingTest { val parcel = ParcelFactory.build() val cargoSerialized = generateCargoFromMessages( - listOf(parcel.serialize(KeyPairSet.PDA_GRANTEE.private)) + listOf(parcel.serialize(KeyPairSet.PDA_GRANTEE.private)), ) whenever(cargoStorage.list()).thenReturn(listOf(cargoSerialized::inputStream)) whenever(storeParcel.store(any(), any())) @@ -122,7 +122,7 @@ class ProcessCargoTest : BaseDataTestCase() { fun `received invalid parcel but collection is stored`() = runBlockingTest { val parcel = ParcelFactory.build() val cargoSerialized = generateCargoFromMessages( - listOf(parcel.serialize(KeyPairSet.PDA_GRANTEE.private)) + listOf(parcel.serialize(KeyPairSet.PDA_GRANTEE.private)), ) whenever(cargoStorage.list()).thenReturn(listOf(cargoSerialized::inputStream)) whenever(storeParcel.store(any(), any())) @@ -153,9 +153,9 @@ class ProcessCargoTest : BaseDataTestCase() { Recipient(CDACertPath.PRIVATE_GW.subjectId), cargoMessageSet.encrypt( privateGatewaySessionKeyPair.sessionKey, - internetGatewaySessionKeyPair + internetGatewaySessionKeyPair, ), - CDACertPath.INTERNET_GW + CDACertPath.INTERNET_GW, ) return cargoSerialized.serialize(KeyPairSet.INTERNET_GW.private) } diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/courier/RotateCertificateTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/courier/RotateCertificateTest.kt index d8de47f1..a1739f19 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/courier/RotateCertificateTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/courier/RotateCertificateTest.kt @@ -27,7 +27,9 @@ class RotateCertificateTest { private val notifyEndpoints = mock() private val rotateCertificate = RotateCertificate( - localConfig, internetGatewayPreferences, notifyEndpoints + localConfig, + internetGatewayPreferences, + notifyEndpoints, ) @Test @@ -36,10 +38,10 @@ class RotateCertificateTest { KeyPairSet.PRIVATE_GW.public, KeyPairSet.INTERNET_GW.private, ZonedDateTime.now().plusYears(10), - validityStartDate = ZonedDateTime.now().minusDays(1) + validityStartDate = ZonedDateTime.now().minusDays(1), ) val certificateRotation = CertificateRotation( - CertificationPath(newIdCertificate, listOf(PDACertPath.INTERNET_GW)) + CertificationPath(newIdCertificate, listOf(PDACertPath.INTERNET_GW)), ) whenever(localConfig.getIdentityCertificate()).thenReturn(PDACertPath.PRIVATE_GW) @@ -47,7 +49,7 @@ class RotateCertificateTest { verify(localConfig).setIdentityCertificate( check { assertArrayEquals(newIdCertificate.serialize(), it.serialize()) }, - any() + any(), ) verify(internetGatewayPreferences).setPublicKey(PDACertPath.INTERNET_GW.subjectPublicKey) } @@ -68,10 +70,10 @@ class RotateCertificateTest { KeyPairSet.INTERNET_GW.private, PDACertPath.PRIVATE_GW.expiryDate.minusSeconds(1), PDACertPath.INTERNET_GW, - validityStartDate = ZonedDateTime.now().minusDays(1) + validityStartDate = ZonedDateTime.now().minusDays(1), ) val certificateRotation = CertificateRotation( - CertificationPath(newIdCertificate, listOf(PDACertPath.INTERNET_GW)) + CertificationPath(newIdCertificate, listOf(PDACertPath.INTERNET_GW)), ) whenever(localConfig.getIdentityCertificate()).thenReturn(PDACertPath.PRIVATE_GW) @@ -89,10 +91,10 @@ class RotateCertificateTest { KeyPairSet.INTERNET_GW.private, PDACertPath.PRIVATE_GW.expiryDate.minusSeconds(1), PDACertPath.INTERNET_GW, - validityStartDate = ZonedDateTime.now().minusDays(1) + validityStartDate = ZonedDateTime.now().minusDays(1), ) val certificateRotation = CertificateRotation( - CertificationPath(PDACertPath.PRIVATE_GW, listOf(PDACertPath.INTERNET_GW)) + CertificationPath(PDACertPath.PRIVATE_GW, listOf(PDACertPath.INTERNET_GW)), ) whenever(localConfig.getIdentityCertificate()).thenReturn(oldCertificate) diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/EndpointRegistrationTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/EndpointRegistrationTest.kt index a0cd07a7..0b05db0f 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/EndpointRegistrationTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/EndpointRegistrationTest.kt @@ -31,7 +31,9 @@ class EndpointRegistrationTest : BaseDataTestCase() { private val mockLocalEndpointDao = mock() private val mockInternetGatewayPreferences = mock() private val mockLocalConfig = LocalConfig( - privateKeyStoreProvider, certificateStoreProvider, mockInternetGatewayPreferences + privateKeyStoreProvider, + certificateStoreProvider, + mockInternetGatewayPreferences, ) private val endpointRegistration = EndpointRegistration(mockLocalEndpointDao, mockLocalConfig) @@ -56,12 +58,12 @@ class EndpointRegistrationTest : BaseDataTestCase() { val authorization = PrivateNodeRegistrationAuthorization.deserialize( authorizationSerialized, - KeyPairSet.PRIVATE_GW.public + KeyPairSet.PRIVATE_GW.public, ) assertEquals( dummyApplicationId, - authorization.gatewayData.toString(Charset.defaultCharset()) + authorization.gatewayData.toString(Charset.defaultCharset()), ) } @@ -71,7 +73,7 @@ class EndpointRegistrationTest : BaseDataTestCase() { val authorization = PrivateNodeRegistrationAuthorization.deserialize( authorizationSerialized, - KeyPairSet.PRIVATE_GW.public + KeyPairSet.PRIVATE_GW.public, ) val ttl = ChronoUnit.SECONDS.between(ZonedDateTime.now(), authorization.expiryDate) @@ -83,18 +85,18 @@ class EndpointRegistrationTest : BaseDataTestCase() { inner class Register { private val authorization = PrivateNodeRegistrationAuthorization( ZonedDateTime.now().plusSeconds(10), - dummyApplicationId.toByteArray() + dummyApplicationId.toByteArray(), ) private val crr = PrivateNodeRegistrationRequest( KeyPairSet.PRIVATE_ENDPOINT.public, - authorization.serialize(KeyPairSet.PRIVATE_GW.private) + authorization.serialize(KeyPairSet.PRIVATE_GW.private), ) @Test fun `CRR should be refused if its encapsulated authorization is invalid`() { val invalidCRR = PrivateNodeRegistrationRequest( KeyPairSet.PRIVATE_ENDPOINT.public, - "invalid authorization".toByteArray() + "invalid authorization".toByteArray(), ) val exception = assertThrows { @@ -112,8 +114,8 @@ class EndpointRegistrationTest : BaseDataTestCase() { verify(mockLocalEndpointDao).insert( LocalEndpoint( PrivateMessageAddress(KeyPairSet.PRIVATE_ENDPOINT.public.nodeId), - dummyApplicationId - ) + dummyApplicationId, + ), ) } @@ -132,7 +134,7 @@ class EndpointRegistrationTest : BaseDataTestCase() { val registration = PrivateNodeRegistration.deserialize(registrationSerialized) assertEquals( mockLocalConfig.getInternetGatewayAddress(), - registration.gatewayInternetAddress + registration.gatewayInternetAddress, ) } @@ -147,8 +149,8 @@ class EndpointRegistrationTest : BaseDataTestCase() { listOf(registration.privateNodeCertificate, PDACertPath.PRIVATE_GW), registration.privateNodeCertificate.getCertificationPath( emptyList(), - setOf(PDACertPath.PRIVATE_GW) - ).asList() + setOf(PDACertPath.PRIVATE_GW), + ).asList(), ) } @@ -159,7 +161,7 @@ class EndpointRegistrationTest : BaseDataTestCase() { val registration = PrivateNodeRegistration.deserialize(registrationSerialized) assertEquals( registration.privateNodeCertificate.subjectId, - crr.privateNodePublicKey.nodeId + crr.privateNodePublicKey.nodeId, ) } @@ -170,7 +172,7 @@ class EndpointRegistrationTest : BaseDataTestCase() { val registration = PrivateNodeRegistration.deserialize(registrationSerialized) assertEquals( PDACertPath.PRIVATE_GW.expiryDate, - registration.privateNodeCertificate.expiryDate + registration.privateNodeCertificate.expiryDate, ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/GatewayCertificateChangeNotifierTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/GatewayCertificateChangeNotifierTest.kt index b6d89e7f..ecae6c15 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/GatewayCertificateChangeNotifierTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/GatewayCertificateChangeNotifierTest.kt @@ -26,7 +26,7 @@ class GatewayCertificateChangeNotifierTest { val listOfEndpoints = listOf( LocalEndpointFactory.build(), LocalEndpointFactory.build(), - LocalEndpointFactory.build() + LocalEndpointFactory.build(), ) whenever(endpointDao.list()).thenReturn(listOfEndpoints) @@ -37,7 +37,7 @@ class GatewayCertificateChangeNotifierTest { // Assert verify(notifyEndpoints, times(1)).notify( listOfEndpoints, - NotificationType.GatewayCertificateChange + NotificationType.GatewayCertificateChange, ) } @@ -54,12 +54,12 @@ class GatewayCertificateChangeNotifierTest { // Assert verify(notifyEndpoints, never()).notify( any>(), - eq(NotificationType.GatewayCertificateChange) + eq(NotificationType.GatewayCertificateChange), ) } fun build() = GatewayCertificateChangeNotifier( notifyEndpoints, - endpointDao + endpointDao, ) } diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/IncomingParcelNotifierTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/IncomingParcelNotifierTest.kt index 563735a3..61d2e791 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/IncomingParcelNotifierTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/endpoint/IncomingParcelNotifierTest.kt @@ -1,11 +1,11 @@ package tech.relaycorp.gateway.domain.endpoint import com.nhaarman.mockitokotlin2.any +import com.nhaarman.mockitokotlin2.check import com.nhaarman.mockitokotlin2.mock +import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever -import com.nhaarman.mockitokotlin2.check -import com.nhaarman.mockitokotlin2.never import kotlinx.coroutines.test.runBlockingTest import org.junit.jupiter.api.Test import tech.relaycorp.gateway.data.database.LocalEndpointDao @@ -33,14 +33,14 @@ class IncomingParcelNotifierTest { .copy(recipientLocation = RecipientLocation.LocalEndpoint) val parcel3 = StoredParcelFactory.build().copy( recipientLocation = RecipientLocation.LocalEndpoint, - recipientAddress = parcel2.recipientAddress + recipientAddress = parcel2.recipientAddress, ) val endpoint1 = LocalEndpointFactory.build().copy(address = parcel1.recipientAddress) val endpoint2 = LocalEndpointFactory.build().copy(address = parcel2.recipientAddress) whenever( - storedParcelDao.listForRecipientLocation(any(), any()) + storedParcelDao.listForRecipientLocation(any(), any()), ).thenReturn(listOf(parcel1, parcel2, parcel3)) whenever(localEndpointDao.list(any())).thenReturn(listOf(endpoint1, endpoint2)) @@ -52,11 +52,11 @@ class IncomingParcelNotifierTest { verify(localEndpointDao).list( check { assertEquals(2, it.size) - } + }, ) verify(notifyEndpoints).notify( listOf(endpoint1, endpoint2), - NotificationType.IncomingParcel + NotificationType.IncomingParcel, ) } @@ -74,11 +74,11 @@ class IncomingParcelNotifierTest { verify(localEndpointDao).get( check { assertEquals(endpoint1.address, it) - } + }, ) verify(notifyEndpoints).notify( endpoint1, - NotificationType.IncomingParcel + NotificationType.IncomingParcel, ) } @@ -98,6 +98,6 @@ class IncomingParcelNotifierTest { fun build() = IncomingParcelNotifier( notifyEndpoints, storedParcelDao, - localEndpointDao + localEndpointDao, ) } diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/CollectParcelsFromGatewayTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/CollectParcelsFromGatewayTest.kt index 37f9c184..0c9cad17 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/CollectParcelsFromGatewayTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/CollectParcelsFromGatewayTest.kt @@ -43,11 +43,16 @@ class CollectParcelsFromGatewayTest : BaseDataTestCase() { } private val mockInternetGatewayPreferences = mock() private val mockLocalConfig = LocalConfig( - privateKeyStoreProvider, certificateStoreProvider, mockInternetGatewayPreferences + privateKeyStoreProvider, + certificateStoreProvider, + mockInternetGatewayPreferences, ) private val notifyEndpoints = mock() private val subject = CollectParcelsFromGateway( - storeParcel, poWebClientBuilder, notifyEndpoints, mockLocalConfig + storeParcel, + poWebClientBuilder, + notifyEndpoints, + mockLocalConfig, ) @BeforeEach @@ -65,7 +70,10 @@ class CollectParcelsFromGatewayTest : BaseDataTestCase() { override suspend fun get() = throw InternetAddressResolutionException("Whoops") } val subject = CollectParcelsFromGateway( - storeParcel, failingPoWebClientProvider, notifyEndpoints, mockLocalConfig + storeParcel, + failingPoWebClientProvider, + notifyEndpoints, + mockLocalConfig, ) subject.collect(false) @@ -84,7 +92,7 @@ class CollectParcelsFromGatewayTest : BaseDataTestCase() { verify(poWebClient).collectParcels( check { assertEquals(PDACertPath.PRIVATE_GW, it.first().certificate) }, - check { assertEquals(StreamingMode.CloseUponCompletion, it) } + check { assertEquals(StreamingMode.CloseUponCompletion, it) }, ) verify(storeParcel) .store(eq(parcelCollection.parcelSerialized), eq(RecipientLocation.LocalEndpoint)) @@ -110,31 +118,30 @@ class CollectParcelsFromGatewayTest : BaseDataTestCase() { verify(poWebClient).collectParcels( check { assertEquals(PDACertPath.PRIVATE_GW, it.first().certificate) }, - check { assertEquals(StreamingMode.KeepAlive, it) } + check { assertEquals(StreamingMode.KeepAlive, it) }, ) verify(storeParcel, times(2)) .store(eq(parcelCollection.parcelSerialized), eq(RecipientLocation.LocalEndpoint)) verify(parcelCollection, times(2)).ack verify(notifyEndpoints, times(2)).notify( - eq(MessageAddress.of(mockRecipient.id)) + eq(MessageAddress.of(mockRecipient.id)), ) } @Test - fun `collect invalid parcel, with keepAlive true, acks but does not notify`() = - testSuspend { - val parcelCollection = mock() - whenever(parcelCollection.parcelSerialized).thenReturn(ByteArray(0)) - whenever(parcelCollection.ack).thenReturn {} - whenever(poWebClient.collectParcels(any(), any())).thenReturn(flowOf(parcelCollection)) - whenever(storeParcel.store(any(), any())) - .thenReturn(StoreParcel.Result.InvalidParcel(mock(), Exception())) - - subject.collect(true) - - verify(parcelCollection).ack - verifyNoMoreInteractions(notifyEndpoints) - } + fun `collect invalid parcel, with keepAlive true, acks but does not notify`() = testSuspend { + val parcelCollection = mock() + whenever(parcelCollection.parcelSerialized).thenReturn(ByteArray(0)) + whenever(parcelCollection.ack).thenReturn {} + whenever(poWebClient.collectParcels(any(), any())).thenReturn(flowOf(parcelCollection)) + whenever(storeParcel.store(any(), any())) + .thenReturn(StoreParcel.Result.InvalidParcel(mock(), Exception())) + + subject.collect(true) + + verify(parcelCollection).ack + verifyNoMoreInteractions(notifyEndpoints) + } @Test fun `poWebClient client binding issues are handled`() = testSuspend { diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/DeliverParcelsToGatewayTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/DeliverParcelsToGatewayTest.kt index e8c8dd24..8ed64a7d 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/DeliverParcelsToGatewayTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/DeliverParcelsToGatewayTest.kt @@ -40,11 +40,17 @@ class DeliverParcelsToGatewayTest : BaseDataTestCase() { } private val mockInternetGatewayPreferences = mock() private val localConfig = LocalConfig( - privateKeyStoreProvider, certificateStoreProvider, mockInternetGatewayPreferences + privateKeyStoreProvider, + certificateStoreProvider, + mockInternetGatewayPreferences, ) private val deleteParcel = mock() private val subject = DeliverParcelsToGateway( - storedParcelDao, diskMessageOperations, poWebClientProvider, localConfig, deleteParcel + storedParcelDao, + diskMessageOperations, + poWebClientProvider, + localConfig, + deleteParcel, ) @BeforeEach @@ -66,7 +72,7 @@ class DeliverParcelsToGatewayTest : BaseDataTestCase() { diskMessageOperations, failingPoWebClientProvider, localConfig, - deleteParcel + deleteParcel, ) subject.deliver(false) @@ -87,7 +93,7 @@ class DeliverParcelsToGatewayTest : BaseDataTestCase() { any(), check { assertEquals(PDACertPath.PRIVATE_GW, it.certificate) - } + }, ) verify(deleteParcel).delete(eq(parcel1)) } @@ -102,8 +108,8 @@ class DeliverParcelsToGatewayTest : BaseDataTestCase() { flowOf( listOf(parcel1, parcel2, parcel3), listOf(parcel2, parcel3), - listOf(parcel3) - ) + listOf(parcel3), + ), ) subject.deliver(true) diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/PublicSyncTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/PublicSyncTest.kt index 2f259df9..50798ed9 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/PublicSyncTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/PublicSyncTest.kt @@ -36,7 +36,7 @@ class PublicSyncTest { connectionStateObserver, registerGateway, deliverParcelsToGateway, - collectParcelsFromGateway + collectParcelsFromGateway, ) @Test @@ -45,7 +45,7 @@ class PublicSyncTest { ForegroundAppMonitor.State.Foreground, PDCServer.State.Started, ConnectionState.InternetWithGateway, - RegisterGateway.Result.FailedToRegister + RegisterGateway.Result.FailedToRegister, ) sync() @@ -59,7 +59,7 @@ class PublicSyncTest { ForegroundAppMonitor.State.Foreground, PDCServer.State.Started, ConnectionState.Disconnected, - RegisterGateway.Result.AlreadyRegisteredAndNotExpiring + RegisterGateway.Result.AlreadyRegisteredAndNotExpiring, ) sync() @@ -73,7 +73,7 @@ class PublicSyncTest { ForegroundAppMonitor.State.Background, PDCServer.State.Stopped, ConnectionState.InternetWithGateway, - RegisterGateway.Result.AlreadyRegisteredAndNotExpiring + RegisterGateway.Result.AlreadyRegisteredAndNotExpiring, ) sync() @@ -87,7 +87,7 @@ class PublicSyncTest { ForegroundAppMonitor.State.Foreground, PDCServer.State.Stopped, ConnectionState.InternetWithGateway, - RegisterGateway.Result.AlreadyRegisteredAndNotExpiring + RegisterGateway.Result.AlreadyRegisteredAndNotExpiring, ) sync() @@ -101,7 +101,7 @@ class PublicSyncTest { ForegroundAppMonitor.State.Background, PDCServer.State.Started, ConnectionState.InternetWithGateway, - RegisterGateway.Result.AlreadyRegisteredAndNotExpiring + RegisterGateway.Result.AlreadyRegisteredAndNotExpiring, ) sync() @@ -115,7 +115,7 @@ class PublicSyncTest { ForegroundAppMonitor.State.Background, PDCServer.State.Stopped, ConnectionState.InternetWithGateway, - RegisterGateway.Result.AlreadyRegisteredAndNotExpiring + RegisterGateway.Result.AlreadyRegisteredAndNotExpiring, ) val appStateFlow = MutableStateFlow(ForegroundAppMonitor.State.Background) whenever(foregroundAppMonitor.observe()).thenReturn(appStateFlow.asSharedFlow()) @@ -133,7 +133,7 @@ class PublicSyncTest { appState: ForegroundAppMonitor.State, pdcState: PDCServer.State, connectionState: ConnectionState, - registrationResult: RegisterGateway.Result + registrationResult: RegisterGateway.Result, ) { whenever(foregroundAppMonitor.observe()) .thenReturn(flowOf(appState)) diff --git a/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/RegisterGatewayTest.kt b/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/RegisterGatewayTest.kt index 0798e365..469533b9 100644 --- a/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/RegisterGatewayTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/domain/publicsync/RegisterGatewayTest.kt @@ -36,7 +36,9 @@ class RegisterGatewayTest : BaseDataTestCase() { private val pgwPreferences = mock() private val localConfig = LocalConfig( - privateKeyStoreProvider, certificateStoreProvider, pgwPreferences + privateKeyStoreProvider, + certificateStoreProvider, + pgwPreferences, ) private val poWebClient = mock() private val poWebClientBuilder = object : PoWebClientBuilder { @@ -50,7 +52,7 @@ class RegisterGatewayTest : BaseDataTestCase() { localConfig, poWebClientBuilder, resolveServiceAddress, - publicKeyStore + publicKeyStore, ) @BeforeEach @@ -73,7 +75,7 @@ class RegisterGatewayTest : BaseDataTestCase() { localConfig, failingPoWebClientBuilder, resolveServiceAddress, - publicKeyStore + publicKeyStore, ) registerGateway.registerIfNeeded() @@ -88,9 +90,10 @@ class RegisterGatewayTest : BaseDataTestCase() { issueGatewayCertificate( KeyPairSet.PRIVATE_GW.public, KeyPairSet.INTERNET_GW.private, - ZonedDateTime.now().plusYears(1), // not expiring soon - validityStartDate = ZonedDateTime.now().minusSeconds(1) - ) + // not expiring soon + ZonedDateTime.now().plusYears(1), + validityStartDate = ZonedDateTime.now().minusSeconds(1), + ), ) registerGateway.registerIfNeeded() @@ -105,10 +108,11 @@ class RegisterGatewayTest : BaseDataTestCase() { issueGatewayCertificate( KeyPairSet.PRIVATE_GW.public, KeyPairSet.INTERNET_GW.private, - ZonedDateTime.now().plusDays(1), // expiring soon + // expiring soon + ZonedDateTime.now().plusDays(1), PDACertPath.INTERNET_GW, - validityStartDate = ZonedDateTime.now().minusSeconds(1) - ) + validityStartDate = ZonedDateTime.now().minusSeconds(1), + ), ) whenever(poWebClient.preRegisterNode(any())) .thenReturn(buildPNRR()) @@ -196,11 +200,11 @@ class RegisterGatewayTest : BaseDataTestCase() { private fun buildPNRR(): PrivateNodeRegistrationRequest { val authorization = PrivateNodeRegistrationAuthorization( ZonedDateTime.now().plusSeconds(3), - "1234".toByteArray() + "1234".toByteArray(), ) return PrivateNodeRegistrationRequest( KeyPairSet.PRIVATE_ENDPOINT.public, - authorization.serialize(KeyPairSet.PRIVATE_GW.private) + authorization.serialize(KeyPairSet.PRIVATE_GW.private), ) } @@ -208,6 +212,6 @@ class RegisterGatewayTest : BaseDataTestCase() { PDACertPath.PRIVATE_GW, PDACertPath.INTERNET_GW, "example.org", - internetGatewaySessionKey + internetGatewaySessionKey, ) } diff --git a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/EndpointRegistrationRouteTest.kt b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/EndpointRegistrationRouteTest.kt index 28ac2be2..194cf839 100644 --- a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/EndpointRegistrationRouteTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/EndpointRegistrationRouteTest.kt @@ -16,8 +16,8 @@ import tech.relaycorp.gateway.domain.endpoint.InvalidPNRAException import tech.relaycorp.gateway.pdc.local.utils.ContentType import tech.relaycorp.relaynet.messages.control.PrivateNodeRegistration import tech.relaycorp.relaynet.messages.control.PrivateNodeRegistrationRequest -import tech.relaycorp.relaynet.testing.pki.PDACertPath import tech.relaycorp.relaynet.testing.pki.KeyPairSet +import tech.relaycorp.relaynet.testing.pki.PDACertPath import kotlin.test.assertEquals import io.ktor.http.ContentType as KtorContentType @@ -38,7 +38,7 @@ class EndpointRegistrationRouteTest { assertEquals(plainTextUTF8ContentType, response.contentType()) assertEquals( "Content type ${ContentType.REGISTRATION_REQUEST} is required", - response.content + response.content, ) } } @@ -56,7 +56,7 @@ class EndpointRegistrationRouteTest { assertEquals(plainTextUTF8ContentType, response.contentType()) assertEquals( "Invalid registration request", - response.content + response.content, ) } } @@ -70,7 +70,7 @@ class EndpointRegistrationRouteTest { testPDCServerRoute(route) { val crr = PrivateNodeRegistrationRequest( KeyPairSet.PRIVATE_ENDPOINT.public, - "invalid authorization".toByteArray() + "invalid authorization".toByteArray(), ) val call = handleRequest(HttpMethod.Post, "/v1/nodes") { addHeader("Content-Type", ContentType.REGISTRATION_REQUEST.toString()) @@ -81,7 +81,7 @@ class EndpointRegistrationRouteTest { assertEquals(plainTextUTF8ContentType, response.contentType()) assertEquals( "Invalid authorization encapsulated in registration request", - response.content + response.content, ) } } @@ -92,7 +92,7 @@ class EndpointRegistrationRouteTest { val privateNodeRegistration = PrivateNodeRegistration( PDACertPath.PRIVATE_ENDPOINT, PDACertPath.PRIVATE_GW, - "" + "", ) val privateNodeRegistrationSerialized = privateNodeRegistration.serialize() whenever(endpointRegistration.register(any())).thenReturn(privateNodeRegistrationSerialized) @@ -100,7 +100,7 @@ class EndpointRegistrationRouteTest { testPDCServerRoute(route) { val crr = PrivateNodeRegistrationRequest( KeyPairSet.PRIVATE_ENDPOINT.public, - "invalid authorization".toByteArray() + "invalid authorization".toByteArray(), ) val call = handleRequest(HttpMethod.Post, "/v1/nodes") { addHeader("Content-Type", ContentType.REGISTRATION_REQUEST.toString()) @@ -111,7 +111,7 @@ class EndpointRegistrationRouteTest { assertEquals(ContentType.REGISTRATION, response.contentType()) assertEquals( privateNodeRegistrationSerialized.asList(), - response.byteContent!!.asList() + response.byteContent!!.asList(), ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/PDCTestServer.kt b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/PDCTestServer.kt index daeb3ea2..df16fd45 100644 --- a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/PDCTestServer.kt +++ b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/PDCTestServer.kt @@ -9,5 +9,5 @@ fun testPDCServerRoute(route: PDCServerRoute, test: TestApplicationEngine.() { PDCServerConfiguration.configure(this, listOf(route)) }, - test + test, ) diff --git a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionHandshakeTest.kt b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionHandshakeTest.kt index 68913523..44d06544 100644 --- a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionHandshakeTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionHandshakeTest.kt @@ -23,8 +23,8 @@ import tech.relaycorp.relaynet.bindings.pdc.Signer import tech.relaycorp.relaynet.bindings.pdc.StreamingMode import tech.relaycorp.relaynet.messages.control.HandshakeChallenge import tech.relaycorp.relaynet.messages.control.HandshakeResponse -import tech.relaycorp.relaynet.testing.pki.PDACertPath import tech.relaycorp.relaynet.testing.pki.KeyPairSet +import tech.relaycorp.relaynet.testing.pki.PDACertPath import java.nio.charset.Charset import javax.inject.Provider import kotlin.test.assertEquals @@ -44,10 +44,9 @@ class ParcelCollectionHandshakeTest { @Test fun `Requests with Origin header should be refused`() { testPDCServerRoute(route) { - handleWebSocketConversation( ParcelCollectionRoute.URL_PATH, - { addHeader(ParcelCollectionRoute.HEADER_ORIGIN, "http://example.com") } + { addHeader(ParcelCollectionRoute.HEADER_ORIGIN, "http://example.com") }, ) { incoming, _ -> val closingFrameRaw = incoming.receive() assertEquals(FrameType.CLOSE, closingFrameRaw.frameType) @@ -55,11 +54,11 @@ class ParcelCollectionHandshakeTest { val closingFrame = closingFrameRaw as Frame.Close assertEquals( CloseReason.Codes.VIOLATED_POLICY, - closingFrame.readReason()!!.knownReason + closingFrame.readReason()!!.knownReason, ) assertEquals( "Web browser requests are disabled for security reasons", - closingFrame.readReason()!!.message + closingFrame.readReason()!!.message, ) } } @@ -100,11 +99,11 @@ class ParcelCollectionHandshakeTest { val closingFrame = closingFrameRaw as Frame.Close assertEquals( CloseReason.Codes.CANNOT_ACCEPT, - closingFrame.readReason()!!.knownReason + closingFrame.readReason()!!.knownReason, ) assertEquals( "Invalid handshake response", - closingFrame.readReason()!!.message + closingFrame.readReason()!!.message, ) } } @@ -126,11 +125,11 @@ class ParcelCollectionHandshakeTest { val closingFrame = closingFrameRaw as Frame.Close assertEquals( CloseReason.Codes.CANNOT_ACCEPT, - closingFrame.readReason()!!.knownReason + closingFrame.readReason()!!.knownReason, ) assertEquals( "Handshake response did not include any nonce signatures", - closingFrame.readReason()!!.message + closingFrame.readReason()!!.message, ) } } @@ -144,7 +143,7 @@ class ParcelCollectionHandshakeTest { val validSignature = endpointSigner.sign( challenge.nonce, - DetachedSignatureType.NONCE + DetachedSignatureType.NONCE, ) val invalidSignature = "not really a signature".toByteArray() val response = HandshakeResponse(listOf(validSignature, invalidSignature)) @@ -156,12 +155,12 @@ class ParcelCollectionHandshakeTest { val closingFrame = closingFrameRaw as Frame.Close assertEquals( CloseReason.Codes.CANNOT_ACCEPT, - closingFrame.readReason()!!.knownReason + closingFrame.readReason()!!.knownReason, ) assertEquals( "Handshake response included invalid nonce signatures or untrusted " + "signers", - closingFrame.readReason()!!.message + closingFrame.readReason()!!.message, ) } } @@ -176,9 +175,9 @@ class ParcelCollectionHandshakeTest { setup = { addHeader( StreamingMode.HEADER_NAME, - StreamingMode.CloseUponCompletion.headerValue + StreamingMode.CloseUponCompletion.headerValue, ) - } + }, ) { incoming, outgoing -> val challenge = HandshakeChallenge.deserialize(incoming.receive().readBytes()) @@ -196,12 +195,12 @@ class ParcelCollectionHandshakeTest { val closingFrame = closingFrameRaw as Frame.Close assertEquals( CloseReason.Codes.CANNOT_ACCEPT, - closingFrame.readReason()!!.knownReason + closingFrame.readReason()!!.knownReason, ) assertEquals( "Handshake response included invalid nonce signatures or untrusted " + "signers", - closingFrame.readReason()!!.message + closingFrame.readReason()!!.message, ) } } @@ -221,16 +220,16 @@ class ParcelCollectionHandshakeTest { setup = { addHeader( StreamingMode.HEADER_NAME, - StreamingMode.CloseUponCompletion.headerValue + StreamingMode.CloseUponCompletion.headerValue, ) - } + }, ) { incoming, outgoing -> val challenge = HandshakeChallenge.deserialize(incoming.receive().readBytes()) val validSignature = endpointSigner.sign( challenge.nonce, - DetachedSignatureType.NONCE + DetachedSignatureType.NONCE, ) val response = HandshakeResponse(listOf(validSignature)) outgoing.send(Frame.Binary(true, response.serialize())) @@ -241,7 +240,7 @@ class ParcelCollectionHandshakeTest { val closingFrame = closingFrameRaw as Frame.Close assertEquals( CloseReason.Codes.NORMAL, - closingFrame.readReason()!!.knownReason + closingFrame.readReason()!!.knownReason, ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionRouteTest.kt b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionRouteTest.kt index 4cb3c174..b2b78342 100644 --- a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionRouteTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelCollectionRouteTest.kt @@ -62,9 +62,9 @@ class ParcelCollectionRouteTest { { addHeader( StreamingMode.HEADER_NAME, - StreamingMode.CloseUponCompletion.headerValue + StreamingMode.CloseUponCompletion.headerValue, ) - } + }, ) { incoming, _ -> val closingFrameRaw = incoming.receive() assertEquals(FrameType.CLOSE, closingFrameRaw.frameType) @@ -72,114 +72,108 @@ class ParcelCollectionRouteTest { val closingFrame = closingFrameRaw as Frame.Close assertEquals( CloseReason.Codes.NORMAL, - closingFrame.readReason()!!.knownReason + closingFrame.readReason()!!.knownReason, ) assertEquals( "All available parcels delivered", - closingFrame.readReason()!!.message + closingFrame.readReason()!!.message, ) } } } @Test - fun `Server should keep connection if Keep-Alive is on`() = - runBlockingTest { - whenever(collectParcels.anyParcelsLeftToDeliverOrAck).thenReturn(flowOf(true)) + fun `Server should keep connection if Keep-Alive is on`() = runBlockingTest { + whenever(collectParcels.anyParcelsLeftToDeliverOrAck).thenReturn(flowOf(true)) - testPDCServerRoute(route) { - handleWebSocketConversation( - ParcelCollectionRoute.URL_PATH, - { - addHeader( - StreamingMode.HEADER_NAME, - StreamingMode.KeepAlive.headerValue - ) - } - ) { incoming, _ -> - delay(3_000) // wait to see if the connection is kept alive - assertFalse(incoming.isClosedForReceive) - } + testPDCServerRoute(route) { + handleWebSocketConversation( + ParcelCollectionRoute.URL_PATH, + { + addHeader( + StreamingMode.HEADER_NAME, + StreamingMode.KeepAlive.headerValue, + ) + }, + ) { incoming, _ -> + delay(3_000) // wait to see if the connection is kept alive + assertFalse(incoming.isClosedForReceive) } } + } @Test - fun `Server should keep connection if Keep-Alive is invalid value`() = - runBlockingTest { - whenever(collectParcels.anyParcelsLeftToDeliverOrAck).thenReturn(flowOf(true)) + fun `Server should keep connection if Keep-Alive is invalid value`() = runBlockingTest { + whenever(collectParcels.anyParcelsLeftToDeliverOrAck).thenReturn(flowOf(true)) - testPDCServerRoute(route) { - handleWebSocketConversation( - ParcelCollectionRoute.URL_PATH, - { addHeader(StreamingMode.HEADER_NAME, "whatever") } - ) { incoming, _ -> - delay(3_000) // wait to see if the connection is kept alive - assertFalse(incoming.isClosedForReceive) - } + testPDCServerRoute(route) { + handleWebSocketConversation( + ParcelCollectionRoute.URL_PATH, + { addHeader(StreamingMode.HEADER_NAME, "whatever") }, + ) { incoming, _ -> + delay(3_000) // wait to see if the connection is kept alive + assertFalse(incoming.isClosedForReceive) } } + } @Test - fun `Server should send parcel to deliver`() = - runBlockingTest { - val parcel = Pair("abc", ByteArray(0).inputStream()) - whenever(collectParcels.getNewParcelsForEndpoints(any())) - .thenReturn(flowOf(listOf(parcel))) - - testPDCServerRoute(route) { - handleWebSocketConversation(ParcelCollectionRoute.URL_PATH) { incoming, _ -> - val parcelFrame = incoming.receive() as Frame.Binary - val parcelDelivery = ParcelDelivery.deserialize(parcelFrame.data) - assertEquals(parcel.first, parcelDelivery.deliveryId) - } + fun `Server should send parcel to deliver`() = runBlockingTest { + val parcel = Pair("abc", ByteArray(0).inputStream()) + whenever(collectParcels.getNewParcelsForEndpoints(any())) + .thenReturn(flowOf(listOf(parcel))) + + testPDCServerRoute(route) { + handleWebSocketConversation(ParcelCollectionRoute.URL_PATH) { incoming, _ -> + val parcelFrame = incoming.receive() as Frame.Binary + val parcelDelivery = ParcelDelivery.deserialize(parcelFrame.data) + assertEquals(parcel.first, parcelDelivery.deliveryId) } } + } @Test - fun `Server should process client parcel acks`() = - runBlockingTest { - testPDCServerRoute(route) { - handleWebSocketConversation(ParcelCollectionRoute.URL_PATH) { _, outgoing -> - val localId = "abc" + fun `Server should process client parcel acks`() = runBlockingTest { + testPDCServerRoute(route) { + handleWebSocketConversation(ParcelCollectionRoute.URL_PATH) { _, outgoing -> + val localId = "abc" - outgoing.send(Frame.Text(localId)) + outgoing.send(Frame.Text(localId)) - suspendWaitFor { - verify(collectParcels).processParcelAck(eq(localId)) - } + suspendWaitFor { + verify(collectParcels).processParcelAck(eq(localId)) } } } + } @Test - fun `Server should tell the client that it cannot accept binary acks`() = - runBlockingTest { - testPDCServerRoute(route) { - handleWebSocketConversation(ParcelCollectionRoute.URL_PATH) { incoming, outgoing -> - outgoing.send(Frame.Binary(true, "abc".toByteArray())) + fun `Server should tell the client that it cannot accept binary acks`() = runBlockingTest { + testPDCServerRoute(route) { + handleWebSocketConversation(ParcelCollectionRoute.URL_PATH) { incoming, outgoing -> + outgoing.send(Frame.Binary(true, "abc".toByteArray())) - suspendWaitFor { - assertEquals( - CloseReason.Codes.CANNOT_ACCEPT, - (incoming.receive() as Frame.Close).readReason()?.knownReason - ) - } - verify(collectParcels, never()).processParcelAck(any()) + suspendWaitFor { + assertEquals( + CloseReason.Codes.CANNOT_ACCEPT, + (incoming.receive() as Frame.Close).readReason()?.knownReason, + ) } + verify(collectParcels, never()).processParcelAck(any()) } } + } @Test - fun `Server should handle gracefully client closes with normal`() = - runBlockingTest { - testPDCServerRoute(route) { - handleWebSocketConversation(ParcelCollectionRoute.URL_PATH) { _, outgoing -> - outgoing.send(Frame.Close(CloseReason(CloseReason.Codes.NORMAL, ""))) - delay(1_000) - verify(logger, never()).log(eq(Level.WARNING), any(), anyOrNull()) - } + fun `Server should handle gracefully client closes with normal`() = runBlockingTest { + testPDCServerRoute(route) { + handleWebSocketConversation(ParcelCollectionRoute.URL_PATH) { _, outgoing -> + outgoing.send(Frame.Close(CloseReason(CloseReason.Codes.NORMAL, ""))) + delay(1_000) + verify(logger, never()).log(eq(Level.WARNING), any(), anyOrNull()) } } + } @Test fun `Server should handle gracefully client closes with another reason besides normal`() = @@ -192,7 +186,7 @@ class ParcelCollectionRouteTest { verify(logger).log( eq(Level.WARNING), eq("Connection closed without a normal reason"), - anyOrNull() + anyOrNull(), ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelDeliveryRouteTest.kt b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelDeliveryRouteTest.kt index b91318f7..700289c1 100644 --- a/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelDeliveryRouteTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/pdc/local/routes/ParcelDeliveryRouteTest.kt @@ -16,8 +16,8 @@ import tech.relaycorp.gateway.domain.StoreParcel import tech.relaycorp.gateway.pdc.local.utils.ContentType import tech.relaycorp.relaynet.messages.Parcel import tech.relaycorp.relaynet.messages.Recipient -import tech.relaycorp.relaynet.testing.pki.PDACertPath import tech.relaycorp.relaynet.testing.pki.KeyPairSet +import tech.relaycorp.relaynet.testing.pki.PDACertPath import kotlin.test.assertEquals import io.ktor.http.ContentType as KtorContentType @@ -43,7 +43,7 @@ class ParcelDeliveryRouteTest { assertEquals(plainTextUTF8ContentType, response.contentType()) assertEquals( "Content type ${ContentType.PARCEL} is required", - response.content + response.content, ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/test/BaseDataTestCase.kt b/app/src/test/java/tech/relaycorp/gateway/test/BaseDataTestCase.kt index 7c17b79d..061508ee 100644 --- a/app/src/test/java/tech/relaycorp/gateway/test/BaseDataTestCase.kt +++ b/app/src/test/java/tech/relaycorp/gateway/test/BaseDataTestCase.kt @@ -41,7 +41,7 @@ abstract class BaseDataTestCase { privateKeyStore.saveIdentityKey(KeyPairSet.PRIVATE_GW.private) certificateStore.save( CertificationPath(PDACertPath.PRIVATE_GW, emptyList()), - PDACertPath.INTERNET_GW.subjectId + PDACertPath.INTERNET_GW.subjectId, ) } @@ -50,14 +50,14 @@ abstract class BaseDataTestCase { privateGatewaySessionKeyPair.privateKey, privateGatewaySessionKeyPair.sessionKey.keyId, KeyPairSet.PRIVATE_GW.public.nodeId, - KeyPairSet.INTERNET_GW.public.nodeId + KeyPairSet.INTERNET_GW.public.nodeId, ) } protected suspend fun registerInternetGatewaySessionKey() { publicKeyStore.save( internetGatewaySessionKeyPair.sessionKey, - KeyPairSet.INTERNET_GW.public.nodeId + KeyPairSet.INTERNET_GW.public.nodeId, ) } } diff --git a/app/src/test/java/tech/relaycorp/gateway/ui/main/MainViewModelTest.kt b/app/src/test/java/tech/relaycorp/gateway/ui/main/MainViewModelTest.kt index 00629dca..b3e4a0df 100644 --- a/app/src/test/java/tech/relaycorp/gateway/ui/main/MainViewModelTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/ui/main/MainViewModelTest.kt @@ -35,7 +35,7 @@ class MainViewModelTest { onboardingDoneFlow.emit(false) waitForAssertEquals( ConnectionState.InternetWithGateway, - viewModel.openOnboarding::first + viewModel.openOnboarding::first, ) } } @@ -46,14 +46,13 @@ class MainViewModelTest { connectionStateObserve.emit(ConnectionState.InternetWithGateway) waitForAssertEquals( ConnectionState.InternetWithGateway, - viewModel.connectionState::first + viewModel.connectionState::first, ) } } - private fun buildViewModel() = - MainViewModel( - appPreferences, - connectionStateObserver - ) + private fun buildViewModel() = MainViewModel( + appPreferences, + connectionStateObserver, + ) } diff --git a/app/src/test/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayViewModelTest.kt b/app/src/test/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayViewModelTest.kt index 8bdef18c..5f68d8c1 100644 --- a/app/src/test/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayViewModelTest.kt +++ b/app/src/test/java/tech/relaycorp/gateway/ui/settings/MigrateGatewayViewModelTest.kt @@ -23,7 +23,9 @@ class MigrateGatewayViewModelTest { private val migrateGateway = mock() private val hostnameValidator = mock<(String) -> Boolean>() private val viewModel = MigrateGatewayViewModel( - internetGatewayPreferences, migrateGateway, hostnameValidator + internetGatewayPreferences, + migrateGateway, + hostnameValidator, ) @Before @@ -40,7 +42,7 @@ class MigrateGatewayViewModelTest { viewModel.addressChanged("") assertEquals( MigrateGatewayViewModel.State.Insert, - viewModel.state.first() + viewModel.state.first(), ) } } @@ -54,7 +56,7 @@ class MigrateGatewayViewModelTest { waitForAssertEquals( MigrateGatewayViewModel.State.Error.AddressInvalid, - viewModel.state::first + viewModel.state::first, ) } } @@ -65,7 +67,7 @@ class MigrateGatewayViewModelTest { viewModel.addressChanged("new.url") waitForAssertEquals( MigrateGatewayViewModel.State.AddressValid, - viewModel.state::first + viewModel.state::first, ) } } @@ -76,7 +78,7 @@ class MigrateGatewayViewModelTest { viewModel.addressChanged("old.url") waitForAssertEquals( MigrateGatewayViewModel.State.Error.SameAddress, - viewModel.state::first + viewModel.state::first, ) } } @@ -92,7 +94,7 @@ class MigrateGatewayViewModelTest { waitForAssertEquals( MigrateGatewayViewModel.State.Error.FailedToResolve, - viewModel.state::first + viewModel.state::first, ) } } diff --git a/build.gradle b/build.gradle index 9bc4dab2..cef6cec0 100644 --- a/build.gradle +++ b/build.gradle @@ -2,7 +2,7 @@ buildscript { ext { - kotlinVersion = '1.9.10' + kotlinVersion = '1.9.21' kotlinCoroutinesVersion = '1.7.3' aboutLibrariesVersion = '8.9.3' } @@ -14,7 +14,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.1.4' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" - classpath 'com.diffplug.spotless:spotless-plugin-gradle:6.3.0' + classpath 'com.diffplug.spotless:spotless-plugin-gradle:6.23.0' classpath "com.mikepenz.aboutlibraries.plugin:aboutlibraries-plugin:$aboutLibrariesVersion" classpath 'com.github.triplet.gradle:play-publisher:3.7.0' }