HackToTech

Hack To Technology

mockito-kotlinでvalue classがサポートされたらしいのでメモ

控えめに言って神 github.com 5.4.0のリリースに含まれている github.com

build.gradle.kts

plugins {
    kotlin("jvm") version "2.0.0"
}

group = "com.github.atr0phy"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
    testImplementation("org.mockito.kotlin:mockito-kotlin:5.4.0")
}

tasks.test {
    useJUnitPlatform()
}
kotlin {
    jvmToolchain(17)
}

コード

import org.mockito.Mockito.mockStatic
import org.mockito.kotlin.any
import kotlin.test.Test
import kotlin.test.assertEquals

@JvmInline
value class SampleValue(val value: String)

object SampleValueRepository {
    @JvmStatic
    fun save(sampleValue: SampleValue): SampleValue {
        return sampleValue
    }
}

private class SampleValueRepositoryTest {
    @Test
    fun test() {
        // setup
        val expected = SampleValue("mocked")
        val mocked = mockStatic(SampleValueRepository::class.java)
        mocked.`when`<SampleValue> { SampleValueRepository.save(any()) }.thenReturn(expected)
        // どっちでもいける
        // mocked.`when`<SampleValue> { SampleValueRepository.save(anyValueClass()) }.thenReturn(expected)

        // exercise
        val actual = SampleValueRepository.save(SampleValue("call"))

        // verify
        assertEquals(expected, actual)
    }
}

結果

5.4.0
> Task :checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :compileKotlin NO-SOURCE
> Task :compileJava NO-SOURCE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :processTestResources NO-SOURCE
> Task :compileTestKotlin
> Task :compileTestJava NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test
BUILD SUCCESSFUL in 3s
2 actionable tasks: 2 executed
23:35:44:  ':test --tests "SampleValueTest"' の実行を完了しました。
5.3.1
> Task :checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :compileKotlin NO-SOURCE
> Task :compileJava NO-SOURCE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :processTestResources NO-SOURCE
> Task :compileTestKotlin
> Task :compileTestJava NO-SOURCE
> Task :testClasses UP-TO-DATE


Misplaced or misused argument matcher detected here:

-> at SampleValueTest.test$lambda$0(SampleValueTest.kt:32)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object 
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced or misused argument matcher detected here:

-> at SampleValueTest.test$lambda$0(SampleValueTest.kt:32)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object 
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

    at SampleValueTest.test(SampleValueTest.kt:22)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)


OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
> Task :test FAILED
SampleValueTest > test() FAILED
    org.mockito.exceptions.misusing.InvalidUseOfMatchersException at SampleValueTest.kt:22
1 test completed, 1 failed

公式でサポートされたの嬉しい

SBOM周りを見てたのでメモ

Spring Boot 3.3でSBOMがサポートされたと聞いたので、どんなもんなのかを試していたのでメモ
(SBOMについて詳しく書いてある記事ではないので、そういった記事が見たい場合はブラウザバック推奨) spring.io

SBOMについては経産省の資料を見るのが良さそうだった www.meti.go.jp

で、この辺り全く詳しくなくて今回から何がどうサポートされたのかが全くわからなかったので、手を動かしながら試していた感じ
対象の gradle plugin を入れれば bootJar のタスク実行時に
JARMETA-INF/sbom/bom.json ( json かは指定によるはず)にSBOMを埋め込んでくれるという話だった github.com

あとは spring-boot-starter-actuator 入れて application.properties 設定しておけばactuator経由で公開できるようになっていたが、
内部的に見たいだけなら特にAPIで取得できなくても良さそうな気もした

普段は trivyJAR の入ったコンテナイメージの脆弱性スキャンをして併せてチェックしているが、
SBOM作ってそっちを trivyosv-scanner に食わせたほうが良かったりするのか気になる

適当にCVEがあるバージョンのライブラリを使ったアプリケーションで、SBOMを作って試して見る

作ったSBOM(直接埋め込むとかなり長いのでgistへのリンク) https://gist.github.com/atr0phy/0d853f5c251e7e20116d50ae78aabf58#file-sbom-json

trivy

$ trivy sbom bom.32.json
2024-05-25T20:44:07+09:00   INFO    Vulnerability scanning is enabled
2024-05-25T20:44:07+09:00   INFO    Detected SBOM format    format="cyclonedx-json"
2024-05-25T20:44:07+09:00   WARN    Third-party SBOM may lead to inaccurate vulnerability detection
2024-05-25T20:44:07+09:00   WARN    Recommend using Trivy to generate SBOMs
....

Java (jar)

Total: 8 (UNKNOWN: 0, LOW: 0, MEDIUM: 2, HIGH: 5, CRITICAL: 1)

┌────────────────────────────────────────────────┬────────────────┬──────────┬────────┬───────────────────┬─────────────────────────────────────────────────┬──────────────────────────────────────────────────────────────┐
│                    Library                     │ Vulnerability  │ Severity │ Status │ Installed Version │                  Fixed Version                  │                            Title                             │
├────────────────────────────────────────────────┼────────────────┼──────────┼────────┼───────────────────┼─────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
│ ch.qos.logback:logback-classic                 │ CVE-2023-6378  │ HIGH     │ fixed  │ 1.4.11            │ 1.3.12, 1.4.12, 1.2.13                          │ logback: serialization vulnerability in logback receiver     │
│                                                │                │          │        │                   │                                                 │ https://avd.aquasec.com/nvd/cve-2023-6378                    │
├────────────────────────────────────────────────┤                │          │        │                   │                                                 │                                                              │
│ ch.qos.logback:logback-core                    │                │          │        │                   │                                                 │                                                              │
│                                                │                │          │        │                   │                                                 │                                                              │
├────────────────────────────────────────────────┼────────────────┼──────────┤        ├───────────────────┼─────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
│ org.apache.tomcat.embed:tomcat-embed-core      │ CVE-2024-24549 │ MEDIUM   │        │ 10.1.16           │ 8.5.99, 9.0.86, 10.1.19, 11.0.0-M17             │ : Apache Tomcat: HTTP/2 header handling DoS                  │
│                                                │                │          │        │                   │                                                 │ https://avd.aquasec.com/nvd/cve-2024-24549                   │
├────────────────────────────────────────────────┼────────────────┤          │        │                   ├─────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
│ org.apache.tomcat.embed:tomcat-embed-websocket │ CVE-2024-23672 │          │        │                   │ 11.0.0-M17, 10.1.19, 9.0.86, 8.5.99             │ Apache Tomcat: WebSocket DoS with incomplete closing         │
│                                                │                │          │        │                   │                                                 │ handshake                                                    │
│                                                │                │          │        │                   │                                                 │ https://avd.aquasec.com/nvd/cve-2024-23672                   │
├────────────────────────────────────────────────┼────────────────┼──────────┤        ├───────────────────┼─────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
│ org.postgresql:postgresql                      │ CVE-2024-1597  │ CRITICAL │        │ 42.7.1            │ 42.2.28, 42.3.9, 42.4.4, 42.5.5, 42.6.1, 42.7.2 │ pgjdbc: PostgreSQL JDBC Driver allows attacker to inject SQL │
│                                                │                │          │        │                   │                                                 │ if using PreferQueryMode=SIMPLE...                           │
│                                                │                │          │        │                   │                                                 │ https://avd.aquasec.com/nvd/cve-2024-1597                    │
├────────────────────────────────────────────────┼────────────────┼──────────┤        ├───────────────────┼─────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
│ org.springframework:spring-web                 │ CVE-2024-22243 │ HIGH     │        │ 6.1.1             │ 6.1.4, 6.0.17, 5.3.32                           │ springframework: URL Parsing with Host Validation            │
│                                                │                │          │        │                   │                                                 │ https://avd.aquasec.com/nvd/cve-2024-22243                   │
│                                                ├────────────────┤          │        │                   ├─────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
│                                                │ CVE-2024-22259 │          │        │                   │ 6.1.5, 6.0.18, 5.3.33                           │ springframework: URL Parsing with Host Validation            │
│                                                │                │          │        │                   │                                                 │ https://avd.aquasec.com/nvd/cve-2024-22259                   │
│                                                ├────────────────┤          │        │                   ├─────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────┤
│                                                │ CVE-2024-22262 │          │        │                   │ 5.3.34, 6.0.19, 6.1.6                           │ springframework: URL Parsing with Host Validation            │
│                                                │                │          │        │                   │                                                 │ https://avd.aquasec.com/nvd/cve-2024-22262                   │
└────────────────────────────────────────────────┴────────────────┴──────────┴────────┴───────────────────┴─────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────┘

trivyの方が修正バージョンも出ていて親切だが、省略した箇所に↓みたいなHASHのWARNが出てくるのだけ見づらいのでどうにかしたほうが良さそうだった

2024-05-25T20:43:52+09:00   WARN    Unsupported hash algorithm  algorithm="SHA3-384"
2024-05-25T20:43:52+09:00   WARN    Unsupported hash algorithm  algorithm="SHA3-256"
2024-05-25T20:43:52+09:00   WARN    Unsupported hash algorithm  algorithm="SHA3-512"

osv-scanner

$ osv-scanner scan --sbom bom.32.json 
Scanned /home/atr0phy/workspace/spring-boot-33/build/reports/bom.32.json as CycloneDX SBOM and found 40 packages
╭─────────────────────────────────────┬──────┬───────────┬────────────────────────────────────────────────┬─────────┬─────────────╮ ≈
│ OSV URL                             │ CVSS │ ECOSYSTEM │ PACKAGE                                        │ VERSION │ SOURCE      │
├─────────────────────────────────────┼──────┼───────────┼────────────────────────────────────────────────┼─────────┼─────────────┤ ≈
│ https://osv.dev/GHSA-24rp-q3w6-vc56 │ 10.0 │ Maven     │ org.postgresql:postgresql                      │ 42.7.1  │ bom.32.json │
│ https://osv.dev/GHSA-vmq6-5m68-f53m │ 7.1  │ Maven     │ ch.qos.logback:logback-core                    │ 1.4.11  │ bom.32.json │
│ https://osv.dev/GHSA-7w75-32cg-r6g2 │      │ Maven     │ org.apache.tomcat.embed:tomcat-embed-core      │ 10.1.16 │ bom.32.json │
│ https://osv.dev/GHSA-2wrp-6fg6-hmc5 │ 8.1  │ Maven     │ org.springframework:spring-web                 │ 6.1.1   │ bom.32.json │
│ https://osv.dev/GHSA-ccgv-vj62-xf9h │ 8.1  │ Maven     │ org.springframework:spring-web                 │ 6.1.1   │ bom.32.json │
│ https://osv.dev/GHSA-hgjh-9rj2-g67j │ 8.1  │ Maven     │ org.springframework:spring-web                 │ 6.1.1   │ bom.32.json │
│ https://osv.dev/GHSA-v682-8vv8-vpwr │      │ Maven     │ org.apache.tomcat.embed:tomcat-embed-websocket │ 10.1.16 │ bom.32.json │
│ https://osv.dev/GHSA-vmq6-5m68-f53m │ 7.1  │ Maven     │ ch.qos.logback:logback-classic                 │ 1.4.11  │ bom.32.json │
╰─────────────────────────────────────┴──────┴───────────┴────────────────────────────────────────────────┴─────────┴─────────────╯ ≈

試していた build.gradle.kts

上記のSBOM生成時は、複数の脆弱性が見たかったので id("org.springframework.boot") version "3.2.0" を使用した

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "3.3.0"
    id("io.spring.dependency-management") version "1.1.5"
    kotlin("jvm") version "1.9.24"
    kotlin("plugin.spring") version "1.9.24"
    id("org.cyclonedx.bom") version "1.8.2"
}

group = "com.github.atr0phy"
version = "0.0.1-SNAPSHOT"

java {
    sourceCompatibility = JavaVersion.VERSION_17
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    // implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    // わざとCVEの含まれるバージョンを入れる
    implementation("org.postgresql:postgresql:42.7.1")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs += "-Xjsr305=strict"
        jvmTarget = "17"
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

tasks.cyclonedxBom {
    // ほぼ公式のサンプル通り
    setIncludeConfigs(listOf("runtimeClasspath"))
    setSkipConfigs(listOf("compileClasspath", "testCompileClasspath"))
    setProjectType("application")
    setSchemaVersion("1.5")
    setOutputName("bom")
    setOutputFormat("json")
    setIncludeBomSerialNumber(true)
    setIncludeLicenseText(true)
    setComponentVersion("2.0.0")
}

Springのmilestoneのバージョンを試してたのでメモ

個人的な備忘録
6.2.0-M1 の新機能の @Fallback 試したかったが、
そもそもどこにライブラリが上がっているのかを知らなかったのでメモ github.com

普通に↓に記載されたリポジトリにあがっているので、 github.com

あとはいつも通り build.gradle.kts に記載すれば良い

repositories {
    mavenCentral()
    maven {
        url = uri("https://repo.spring.io/milestone")
    }
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.springframework:spring-aop:6.2.0-M1")
    implementation("org.springframework:spring-beans:6.2.0-M1")
    implementation("org.springframework:spring-expression:6.2.0-M1")
    implementation("org.springframework:spring-context:6.2.0-M1")
    implementation("org.springframework:spring-core:6.2.0-M1")
    implementation("org.springframework:spring-jcl:6.2.0-M1")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

SpringBootで@Repositoryがついたクラスのメソッドから投げられた例外を変換して投げ直す

個人的な備忘録

レイヤードアーキテクチャでアプリケーションを作っていて、
賛否両論あると思うがドメイン層のバリデーションを作成時とDBからの再構成時にチェックしていて、
作成時は例外をそのまま投げたいが、再構成時はそうしたくないと思っていたので、表題のようなことをしたかった
(変なデータが入ったりしなければこんなことをしなくても良いが、特殊なケースで起こったりする為、モヤモヤしていたので調べていた)

例えば、↓みたいなクラスをドメインとして持っていて、 init でバリデーションを行っているとする
バリデーションに失敗した場合は、 DomainException をスローする

data class UserId(val value: UUID) {
    companion object {
        fun generate(): UserId {
            return UserId(UUID.randomUUID())
        }
    }
}

data class User(
    val id: UserId,
    val name: UserName,
) {
    companion object {
        fun of(
            name: UserName,
        ): User {
            return User(
                id = UserId.generate(),
                name = name,
            )
        }
    }
}

data class UserName(val value: String) {
    companion object {
        private const val MIN_LENGTH = 1
        private const val MAX_LENGTH = 256

        fun of(value: String): UserName {
            return UserName(value)
        }
    }

    init {
        if (MIN_LENGTH > value.length ||
            MAX_LENGTH < value.length) {
            throw DomainException(
                message = "ユーザ名は${MIN_LENGTH}以上${MAX_LENGTH}以下の長さである必要があります",
            )
        }
    }
}

リポジトリのインターフェースはとりあえず保存とID検索だけ用意する

interface UserRepository {
    fun findById(id: UserId): User
    fun save(user: User)
}

実装は以下

@Repository
class UserRepositoryImpl: UserRepository {
    private val user1 = UserEntity(
        id = UUID.fromString("a687b0bc-0887-483c-8851-4604657162c1"),
        name = "", // なんかしらの理由で元々入っていたとする
    )

    private val user2 = UserEntity(
        id = UUID.fromString("bb1304ea-8d78-4b99-b4d1-ce4000c1c9ab"),
        name = "テストユーザ",
    )

    private val map = ConcurrentHashMap(
        mapOf(
            Pair(
                user1.id,
                user1,
            ),
            Pair(
                user2.id,
                user2,
            ),
        )
    )
    override fun findById(id: UserId): User {
        return map.getOrElse(id.value) { throw RuntimeException("ユーザが存在しません") }
            .toUser()
    }

    override fun save(user: User) {
        val entity = UserEntity(
            id = user.id.value,
            name = user.name.toString(),
        )

        if(map.putIfAbsent(user.id.value, entity) != null) {
            throw RuntimeException("ユーザがすでに存在します")
        }
    }
}

今回はDBを使ってないが、DBを使った場合を想定して、DB用のモデルを用意する
ここでDBのモデルからドメインモデルの変換をするが、バリデーションに失敗した場合は DomainException がスローされる

data class UserEntity (
    val id: UUID,
    val name: String,
) {
    fun toUser(): User {
        return User(
            id = UserId(value = id),
            name = UserName(value = name),
        )
    }
}

モデルの変換をするのは @Repository のアノテーションがついたクラスなので、
AOPを使って @Repository 内のメソッドで DomainException が投げられたら DomainMappingException に変換して投げ直すことにした
あとはそれぞれの例外に応じて、例外ハンドラーを設定すればいい感じに作成時と再構成時で振る舞いを変えられる

@Aspect
@Component
class RepositoryExceptionTranslator {
    @AfterThrowing(value = "@within(org.springframework.stereotype.Repository)", throwing = "e")
    fun translate(e: Throwable) {
        throw when(e) {
            is DomainException -> DomainMappingException(e)
            else -> e
        }
    }
}

こういうときはやっぱりAOPが便利だなといった感想
試していたソースのコードは↓

github.com

whiptailでlsしてファイル選択した結果を取得する

スクリプト書いてるとたまーに欲しくなるやつ
検索してもなんかぱっといい感じのやつが出てこないので(長すぎてコピペするのに躊躇うやつとか)、主に自分のローカルで使うように書いた

↓は /sbin で試したやつ

macで使うなら brew install coreutils して、 gls 使わないと動かないので注意

相変わらず bash 使ってるけど、いい加減他のシェルにしたほうが良いか悩ましい