Skip to content

Commit

Permalink
Test Kotlin API (#637)
Browse files Browse the repository at this point in the history
* Configure Kotlin for testing

We are going to write Kotlin in JavaThemis to avoid adding new run-time
dependencies. Kotlin has great interop with Java due to this JVM thingie.
However, it will be nice to test our Java code with Kotlin to ensure that
our API works as intended.

Use the current latest stable version of Kotlin, configuruable via the
"kotlin_version" variable defined in the root project. There we also add
Maven Central repos where Kotlin pluggin and runtime are hosted.

Each subproject has Kotlin configured for it, even BoringSSL that does
not have any Kotlin code, but must have relevant targets as a
dependency. Note that desktop Java and Android use different plugin
because Kotlin compiles a little bit different on Android.

Kotlin runtime is required to run Kotlin code. Since we use Kotlin only
for tests, the runtime is added as test dependency. We build our code
for Java 1.7 so an appropriate runtime flavor is used.

Adding Kotlin also triggers a weird compilation error in Android's DEX
compiler as Kotlin runtime uses a lot of JetBrains annotations. This is
a known issue encountered by some project, and there is a workaround.

* Kotlin API tests

Add test suite written in Kotlin. This code has been automatically
converted by IntelliJ from Java test suite and cleaned up manually
after that.

One painful point is exception testing, the try-catch idiom from Java
looks really awful in Kotlin so I've simply polyfilled assertThrows()
method which is not available with Java 1.7. Kotlin can translate its
lambdas into Runnables so it works pretty well.

* Changelog entries

Note that Java 8 support is now required since Kotlin compiler needs it.
  • Loading branch information
ilammy authored May 13, 2020
1 parent 00a5ec8 commit eac3721
Show file tree
Hide file tree
Showing 10 changed files with 1,223 additions and 0 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ _Code:_

See also: [Java API updates](#0.13.0-java).

- Kotlin is now officially supported language on Android
([#637](https://github.com/cossacklabs/themis/pull/637).

- **Breaking changes**

- Android build now uses Gradle 5.6 and requires Java 8 ([#633](https://github.com/cossacklabs/themis/pull/633)).
Expand Down Expand Up @@ -378,6 +381,8 @@ _Code:_
- It is now possible to build desktop Java with Gradle.
Run `./gradlew :desktop:tasks` to learn more
([#633](https://github.com/cossacklabs/themis/pull/633)).
- Kotlin is now officially supported language for JavaThemis
([#637](https://github.com/cossacklabs/themis/pull/637).

- Secure Cell API updates:

Expand Down Expand Up @@ -663,6 +668,8 @@ _Infrastructure:_
- Automated benchmarking harness is now tracking Themis performance. See [`benches`](https://github.com/cossacklabs/themis/tree/master/benches/) ([#580](https://github.com/cossacklabs/themis/pull/580)).
- Added automated tests for all code samples in documentation, ensuring they are always up-to-date ([#600](https://github.com/cossacklabs/themis/pull/600)).
- All 13 supported platforms are verified on GitHub Actions, along with existing CircleCI and Bitrise tests ([#600](https://github.com/cossacklabs/themis/pull/600)).
- Kotlin API of JavaThemis is now verified by all CI platforms
([#637](https://github.com/cossacklabs/themis/pull/637).
- New Makefile targets:
- `make jsthemis` builds JsThemis from source ([#618](https://github.com/cossacklabs/themis/pull/618)).

Expand Down
5 changes: 5 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@ allprojects {
repositories {
google()
jcenter()
mavenCentral()
}

// Set common Kotlin version that we are going to use.
ext.kotlin_version = '1.3.72'
}

repositories {
google()
jcenter()
mavenCentral()
}
}
15 changes: 15 additions & 0 deletions src/wrappers/themis/android/build.gradle
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'

buildscript {
dependencies {
Expand All @@ -12,6 +13,9 @@ buildscript {
// from: https://android.jlelse.eu/how-to-distribute-android-library-in-a-convenient-way-d43fb68304a7
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'

// Kotlin plugin for Android
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

Expand All @@ -24,6 +28,8 @@ dependencies {
androidTestImplementation 'androidx.test:rules:1.2.0'
// Keep it at 1.2, see tests/themis/wrappers/android/com/cossacklabs/themis/test/Base64.java
androidTestImplementation 'commons-codec:commons-codec:1.2'
// Kotlin for instrumentation tests
androidTestImplementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

android {
Expand Down Expand Up @@ -77,6 +83,15 @@ android {
path "../../../../jni/Android.mk"
}
}

// Due to various renames in annotation modules, Android's DEX compiler is confused.
// Remove them from compiled code to avoid issues.
// https://github.com/vimeo/vimeo-networking-java/issues/285
// https://github.com/vimeo/vimeo-networking-java/pull/321
configurations {
cleanedAnnotations
compile.exclude group: 'org.jetbrains' , module:'annotations'
}
}

// distribution
Expand Down
10 changes: 10 additions & 0 deletions src/wrappers/themis/java/build.gradle
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
apply plugin: 'java-library'
apply plugin: 'kotlin'

buildscript {
dependencies {
// Kotlin plugin for Java
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

sourceSets {
main {
Expand All @@ -17,6 +25,8 @@ dependencies {
testImplementation 'junit:junit:4.13'
// Keep it at 1.2, see tests/themis/wrappers/android/com/cossacklabs/themis/test/Base64.java
testImplementation 'commons-codec:commons-codec:1.2'
// Kotlin for unit tests
testImplementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

test {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2020 Cossack Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.cossacklabs.themis.test;

import org.jetbrains.annotations.NotNull;

// We use Java 7 -- particularly for Android support -- where JUnit does not have "assertThrows()".
// That makes tests very verbose and repetitive. Provide a polyfill a for it.

final class Assert {
static <T extends Throwable> T assertThrows(@NotNull Class<T> expected, Runnable runnable) {
try {
runnable.run();
}
catch (Throwable e) {
if (expected.isInstance(e)) {
return expected.cast(e);
}
throw new AssertionError("expected exception of type "+ expected, e);
}
throw new AssertionError("no expected exception of type " + expected + " was thrown");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
/*
* Copyright (c) 2020 Cossack Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cossacklabs.themis.test

import java.nio.charset.StandardCharsets
import kotlin.experimental.inv

import com.cossacklabs.themis.*
import com.cossacklabs.themis.test.Assert.assertThrows

import org.junit.Assert.*
import org.junit.Test

class SecureCellContextImprintTestKotlin {
@Test
fun initWithGenerated() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
assertNotNull(cell)
}

@Test
fun initWithFixed() {
val keyBase64 = "UkVDMgAAAC13PCVZAKOczZXUpvkhsC+xvwWnv3CLmlG0Wzy8ZBMnT+2yx/dg"
val keyBytes = Base64.getDecoder().decode(keyBase64)
val cell = SecureCell.ContextImprintWithKey(keyBytes)
assertNotNull(cell)
}

@Test
fun initWithEmpty() {
assertThrows(NullArgumentException::class.java) {
SecureCell.ContextImprintWithKey(null as SymmetricKey?)
}
assertThrows(NullArgumentException::class.java) {
SecureCell.ContextImprintWithKey(null as ByteArray?)
}
assertThrows(InvalidArgumentException::class.java) {
SecureCell.ContextImprintWithKey(byteArrayOf())
}
}

@Test
fun roundtrip() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val context = "For great justice".toByteArray(StandardCharsets.UTF_8)

val encrypted = cell.encrypt(message, context)
assertNotNull(encrypted)

val decrypted = cell.decrypt(encrypted, context)
assertNotNull(decrypted)
assertArrayEquals(message, decrypted)
}

@Test
fun dataLengthPreservation() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val context = "For great justice".toByteArray(StandardCharsets.UTF_8)

val encrypted = cell.encrypt(message, context)
assertEquals(message.size.toLong(), encrypted.size.toLong())
}

@Test
fun contextInclusion() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val shortContext = ".".toByteArray(StandardCharsets.UTF_8)
val longContext = "You have no chance to survive make your time. Ha ha ha ha ...".toByteArray(StandardCharsets.UTF_8)

val encryptedShort = cell.encrypt(message, shortContext)
val encryptedLong = cell.encrypt(message, longContext)

// Context is not (directly) included into encrypted message.
assertEquals(encryptedShort.size.toLong(), encryptedLong.size.toLong())
}

@Test
fun contextSignificance() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val correctContext = "We are CATS".toByteArray(StandardCharsets.UTF_8)
val incorrectContext = "Captain !!".toByteArray(StandardCharsets.UTF_8)

val encrypted = cell.encrypt(message, correctContext)

// You can use a different context to decrypt data, but you'll get garbage.
var decrypted = cell.decrypt(encrypted, incorrectContext)
assertNotNull(decrypted)
assertEquals(message.size.toLong(), decrypted.size.toLong())
assertFalse(message.contentEquals(decrypted))

// Only the original context will work.
decrypted = cell.decrypt(encrypted, correctContext)
assertArrayEquals(message, decrypted)
}

@Test
fun noDetectCorruptedData() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val context = "We are CATS".toByteArray(StandardCharsets.UTF_8)

val encrypted = cell.encrypt(message, context)

// Invert every odd byte, this will surely break the message.
val corrupted = encrypted.copyOf(encrypted.size)
for (i in corrupted.indices) {
if (i % 2 == 1) {
corrupted[i] = corrupted[i].inv()
}
}

// Decrypts successfully but the content is garbage.
val decrypted = cell.decrypt(corrupted, context)
assertNotNull(decrypted)
assertEquals(message.size.toLong(), decrypted.size.toLong())
assertFalse(message.contentEquals(decrypted))
}

@Test
fun noDetectTruncatedData() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val context = "We are CATS".toByteArray(StandardCharsets.UTF_8)

val encrypted = cell.encrypt(message, context)
val truncated = encrypted.copyOf(encrypted.size - 1)

// Decrypts successfully but the content is garbage.
val decrypted = cell.decrypt(truncated, context)
assertNotNull(decrypted)
assertEquals(truncated.size.toLong(), decrypted.size.toLong())
assertFalse(message.contentEquals(decrypted))
}

@Test
fun noDetectExtendedData() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val context = "We are CATS".toByteArray(StandardCharsets.UTF_8)

val encrypted = cell.encrypt(message, context)
val extended = encrypted.copyOf(encrypted.size + 1)

// Decrypts successfully but the content is garbage.
val decrypted = cell.decrypt(extended, context)
assertNotNull(decrypted)
assertEquals(extended.size.toLong(), decrypted.size.toLong())
assertFalse(message.contentEquals(decrypted))
}

@Test
fun requiredMessageAndContext() {
val cell = SecureCell.ContextImprintWithKey(SymmetricKey())
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val context = "We are CATS".toByteArray(StandardCharsets.UTF_8)

assertThrows(NullArgumentException::class.java) { cell.encrypt(message, null) }
assertThrows(NullArgumentException::class.java) { cell.decrypt(message, null) }
assertThrows(NullArgumentException::class.java) { cell.encrypt(null, context) }
assertThrows(NullArgumentException::class.java) { cell.decrypt(null, context) }

assertThrows(InvalidArgumentException::class.java) { cell.encrypt(message, byteArrayOf()) }
assertThrows(InvalidArgumentException::class.java) { cell.decrypt(message, byteArrayOf()) }
assertThrows(InvalidArgumentException::class.java) { cell.encrypt(byteArrayOf(), context) }
assertThrows(InvalidArgumentException::class.java) { cell.decrypt(byteArrayOf(), context) }
}

@Test
@Suppress("DEPRECATION")
@Throws(SecureCellException::class)
fun oldAPI() {
val key = SymmetricKey()
val newCell = SecureCell.ContextImprintWithKey(key)
val oldCell = SecureCell(key.toByteArray(), SecureCell.MODE_CONTEXT_IMPRINT)
val message = "All your base are belong to us!".toByteArray(StandardCharsets.UTF_8)
val context = "We are CATS".toByteArray(StandardCharsets.UTF_8)

var encrypted: ByteArray
var decrypted: ByteArray?
val result = oldCell.protect(context, message)
encrypted = result.protectedData
assertNotNull(encrypted)
decrypted = newCell.decrypt(encrypted, context)
assertArrayEquals(message, decrypted)

encrypted = newCell.encrypt(message, context)
assertNotNull(encrypted)
decrypted = oldCell.unprotect(context, SecureCellData(encrypted, null))
assertArrayEquals(message, decrypted)
}
}
Loading

0 comments on commit eac3721

Please sign in to comment.