|
| 1 | +package dev.objz.commandbridge.security; |
| 2 | + |
| 3 | +import dev.objz.commandbridge.logging.Log; |
| 4 | +import org.junit.jupiter.api.BeforeAll; |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | +import org.junit.jupiter.api.io.TempDir; |
| 7 | + |
| 8 | +import java.nio.charset.StandardCharsets; |
| 9 | +import java.nio.file.Files; |
| 10 | +import java.nio.file.Path; |
| 11 | +import java.util.logging.Logger; |
| 12 | + |
| 13 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 14 | +import static org.junit.jupiter.api.Assertions.assertNotNull; |
| 15 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 16 | + |
| 17 | +class SecretLoaderTest { |
| 18 | + |
| 19 | + @BeforeAll |
| 20 | + static void installLog() { |
| 21 | + try { |
| 22 | + Log.install(Logger.getLogger("test")); |
| 23 | + } catch (Exception e) { |
| 24 | + // Log already installed or unavailable |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + void loadOrCreateGeneratesNewKeyWhenFileAbsent(@TempDir Path tempDir) { |
| 30 | + SecretLoader loader = new SecretLoader(tempDir); |
| 31 | + String result = loader.loadOrCreate(); |
| 32 | + |
| 33 | + assertNotNull(result); |
| 34 | + assertTrue(!result.isBlank()); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + void loadOrCreateReadsExistingKey(@TempDir Path tempDir) throws Exception { |
| 39 | + Path secretFile = tempDir.resolve("secret.key"); |
| 40 | + Files.createDirectories(tempDir); |
| 41 | + Files.writeString(secretFile, "mysecret", StandardCharsets.UTF_8); |
| 42 | + |
| 43 | + SecretLoader loader = new SecretLoader(tempDir); |
| 44 | + String result = loader.loadOrCreate(); |
| 45 | + |
| 46 | + assertEquals("mysecret", result); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + void generatedKeyIsUrlSafeBase64(@TempDir Path tempDir) { |
| 51 | + SecretLoader loader = new SecretLoader(tempDir); |
| 52 | + String result = loader.loadOrCreate(); |
| 53 | + |
| 54 | + assertTrue(result.matches("[A-Za-z0-9_=-]+")); |
| 55 | + } |
| 56 | + |
| 57 | + @Test |
| 58 | + void loadedKeyIsTrimmed(@TempDir Path tempDir) throws Exception { |
| 59 | + Path secretFile = tempDir.resolve("secret.key"); |
| 60 | + Files.createDirectories(tempDir); |
| 61 | + Files.writeString(secretFile, "mysecret\n\n", StandardCharsets.UTF_8); |
| 62 | + |
| 63 | + SecretLoader loader = new SecretLoader(tempDir); |
| 64 | + String result = loader.loadOrCreate(); |
| 65 | + |
| 66 | + assertEquals("mysecret", result); |
| 67 | + } |
| 68 | +} |
0 commit comments