|
| 1 | +// Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package software.aws.toolkits.jetbrains.services.amazonq.lsp.encryption |
| 5 | + |
| 6 | +import org.assertj.core.api.Assertions.assertThat |
| 7 | +import org.junit.jupiter.api.Test |
| 8 | +import java.io.ByteArrayOutputStream |
| 9 | +import javax.crypto.spec.SecretKeySpec |
| 10 | +import kotlin.random.Random |
| 11 | + |
| 12 | +class JwtEncryptionManagerTest { |
| 13 | + @Test |
| 14 | + fun `uses a different encryption key for each instance`() { |
| 15 | + val blob = Random.Default.nextBytes(256) |
| 16 | + assertThat(JwtEncryptionManager().encrypt(blob)) |
| 17 | + .isNotEqualTo(JwtEncryptionManager().encrypt(blob)) |
| 18 | + } |
| 19 | + |
| 20 | + @Test |
| 21 | + @OptIn(ExperimentalStdlibApi::class) |
| 22 | + fun `encryption is stable with static key`() { |
| 23 | + val blob = Random.Default.nextBytes(256) |
| 24 | + val bytes = "DEADBEEF".repeat(8).hexToByteArray() // 32 bytes |
| 25 | + val key = SecretKeySpec(bytes, "HmacSHA256") |
| 26 | + assertThat(JwtEncryptionManager(key).encrypt(blob)) |
| 27 | + .isNotEqualTo(JwtEncryptionManager(key).encrypt(blob)) |
| 28 | + } |
| 29 | + |
| 30 | + @Test |
| 31 | + fun `encryption can be round-tripped`() { |
| 32 | + val sut = JwtEncryptionManager() |
| 33 | + val blob = "DEADBEEF".repeat(8) |
| 34 | + assertThat(sut.decrypt(sut.encrypt(blob))).isEqualTo(blob) |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + @OptIn(ExperimentalStdlibApi::class) |
| 39 | + fun writeInitializationPayload() { |
| 40 | + val bytes = "DEADBEEF".repeat(8).hexToByteArray() // 32 bytes |
| 41 | + val key = SecretKeySpec(bytes, "HmacSHA256") |
| 42 | + |
| 43 | + val os = ByteArrayOutputStream() |
| 44 | + JwtEncryptionManager(key).writeInitializationPayload(os) |
| 45 | + assertThat(os.toString()) |
| 46 | + // Flare requires encryption ends with new line |
| 47 | + // https://github.com/aws/language-server-runtimes/blob/4d7f81295dc12b59ed2e1c0ebaedb85ccb86cf76/runtimes/README.md#encryption |
| 48 | + .endsWith("\n") |
| 49 | + // language=JSON |
| 50 | + .isEqualTo(""" |
| 51 | + |{"version":"1.0","mode":"JWT","key":"3q2-796tvu_erb7v3q2-796tvu_erb7v3q2-796tvu8"} |
| 52 | + | |
| 53 | + """.trimMargin() |
| 54 | + ) |
| 55 | + } |
| 56 | +} |
0 commit comments