View Javadoc

1   package com.atlassian.asap.core.keys.publickey;
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.PublicKey;
14  import java.security.interfaces.RSAPublicKey;
15  
16  import static org.junit.Assert.assertSame;
17  import static org.mockito.Matchers.any;
18  import static org.mockito.Mockito.when;
19  
20  @RunWith(MockitoJUnitRunner.class)
21  public class ClasspathPublicKeyProviderTest {
22      public static final String PUBLIC_KEY_BASE_PATH = "/publickeyrepo/";
23      public static final String VALID_KID = "issuer1/rsa-key-for-tests";
24  
25      @Mock
26      private PemReader pemReader;
27      @Mock
28      private RSAPublicKey privateKey;
29  
30      @Test
31      public void shouldBeAbleToReadKeyFromClasspathResource() throws Exception {
32          KeyProvider<PublicKey> keyRetriever = new ClasspathPublicKeyProvider(PUBLIC_KEY_BASE_PATH, pemReader);
33          when(pemReader.readPublicKey(any(InputStreamReader.class))).thenReturn(privateKey);
34  
35          assertSame(privateKey, keyRetriever.getKey(ValidatedKeyId.validate(VALID_KID)));
36      }
37  
38      @Test(expected = CannotRetrieveKeyException.class)
39      public void shouldGetErrorWhenKeyParsingFails() throws Exception {
40          KeyProvider<PublicKey> keyRetriever = new ClasspathPublicKeyProvider(PUBLIC_KEY_BASE_PATH, pemReader);
41          when(pemReader.readPublicKey(any(InputStreamReader.class)))
42                  .thenThrow(new CannotRetrieveKeyException("Random error"));
43  
44          keyRetriever.getKey(ValidatedKeyId.validate(VALID_KID));
45      }
46  
47      @Test(expected = CannotRetrieveKeyException.class)
48      public void shouldGetErrorWhenClasspathResourceDoesNotExist() throws Exception {
49          KeyProvider<PublicKey> keyRetriever = new ClasspathPublicKeyProvider(PUBLIC_KEY_BASE_PATH, pemReader);
50  
51          keyRetriever.getKey(ValidatedKeyId.validate("non-existent"));
52      }
53  
54  }