1 package com.atlassian.asap.core.keys.privatekey;
2
3 import com.atlassian.asap.api.exception.CannotRetrieveKeyException;
4 import com.atlassian.asap.core.keys.KeyProvider;
5 import com.atlassian.asap.core.keys.PemReader;
6 import com.atlassian.asap.core.validator.ValidatedKeyId;
7 import org.junit.Test;
8 import org.junit.runner.RunWith;
9 import org.mockito.Mock;
10 import org.mockito.runners.MockitoJUnitRunner;
11
12 import java.io.InputStreamReader;
13 import java.security.PrivateKey;
14 import java.security.interfaces.RSAPrivateKey;
15
16 import static com.atlassian.asap.core.keys.ClassPathUri.classPathUri;
17 import static org.junit.Assert.assertSame;
18 import static org.mockito.Matchers.any;
19 import static org.mockito.Mockito.when;
20
21 @RunWith(MockitoJUnitRunner.class)
22 public class ClasspathPrivateKeyProviderTest {
23 public static final String PRIVATE_KEY_BASE_PATH = "/privatekeys/";
24 public static final String VALID_KID = "issuer1/rsa-key-for-tests";
25
26 @Mock
27 private PemReader pemReader;
28 @Mock
29 private RSAPrivateKey privateKey;
30
31 @Test
32 public void shouldBeAbleToReadKeyFromClasspathResource() throws Exception {
33 KeyProvider<PrivateKey> keyRetriever = new ClasspathPrivateKeyProvider(PRIVATE_KEY_BASE_PATH, pemReader);
34 when(pemReader.readPrivateKey(any(InputStreamReader.class))).thenReturn(privateKey);
35
36 assertSame(privateKey, keyRetriever.getKey(ValidatedKeyId.validate(VALID_KID)));
37 }
38
39 @Test
40 public void shouldBeAbleToReadKeyFromSpecificClasspathResource() throws Exception {
41 String customClasspathBase = "/custom/keylocation/";
42 String customKeyId = "issuer3/rsa-key-for-tests";
43
44 KeyProvider<PrivateKey> keyRetriever = new ClasspathPrivateKeyProvider(customClasspathBase, pemReader);
45 when(pemReader.readPrivateKey(any(InputStreamReader.class))).thenReturn(privateKey);
46
47 assertSame(privateKey, keyRetriever.getKey(ValidatedKeyId.validate(customKeyId)));
48 }
49
50 @Test(expected = CannotRetrieveKeyException.class)
51 public void shouldGetErrorWhenKeyParsingFails() throws Exception {
52 KeyProvider<PrivateKey> keyRetriever = new ClasspathPrivateKeyProvider(PRIVATE_KEY_BASE_PATH, pemReader);
53 when(pemReader.readPrivateKey(any(InputStreamReader.class)))
54 .thenThrow(new CannotRetrieveKeyException("Random error", classPathUri(PRIVATE_KEY_BASE_PATH + VALID_KID)));
55
56 keyRetriever.getKey(ValidatedKeyId.validate(VALID_KID));
57 }
58
59 @Test(expected = CannotRetrieveKeyException.class)
60 public void shouldGetErrorWhenClasspathResourceDoesNotExist() throws Exception {
61 KeyProvider<PrivateKey> keyRetriever = new ClasspathPrivateKeyProvider(PRIVATE_KEY_BASE_PATH, pemReader);
62
63 keyRetriever.getKey(ValidatedKeyId.validate("non-existent"));
64 }
65 }