Add missing jar compiles
[aaf/authz.git] / cadi / aaf / src / test / java / org / onap / aaf / cadi / cm / test / JU_Factory.java
1 /*******************************************************************************
2  * ============LICENSE_START====================================================
3  * * org.onap.aaf
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * * 
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * * 
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * *
21  ******************************************************************************/
22 package org.onap.aaf.cadi.cm.test;
23
24 import static org.junit.Assert.*;
25 import static org.hamcrest.CoreMatchers.*;
26 import static org.mockito.Mockito.*;
27 import org.junit.*;
28 import org.mockito.*;
29
30 import java.io.BufferedReader;
31 import java.io.File;
32 import java.io.FileInputStream;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.io.PrintWriter;
36 import java.nio.charset.StandardCharsets;
37 import java.security.cert.Certificate;
38 import java.security.cert.CertificateEncodingException;
39 import java.security.cert.CertificateException;
40 import java.security.cert.X509Certificate;
41 import java.security.KeyPair;
42 import java.security.Principal;
43 import java.security.PrivateKey;
44 import java.security.PublicKey;
45 import java.util.ArrayList;
46 import java.util.Collection;
47 import java.util.List;
48
49 import javax.crypto.Cipher;
50
51 import org.onap.aaf.cadi.cm.CertException;
52 import org.onap.aaf.cadi.cm.Factory;
53 import org.onap.aaf.cadi.cm.Factory.StripperInputStream;
54
55 import org.onap.aaf.misc.env.Env;
56 import org.onap.aaf.misc.env.LogTarget;
57 import org.onap.aaf.misc.env.TimeTaken;
58 import org.onap.aaf.misc.env.Trans;
59
60 public class JU_Factory {
61
62         @Mock
63         Trans transMock;
64
65         @Mock
66         TimeTaken timeTakenMock;
67
68         @Mock
69         LogTarget logTargetMock;
70
71         @Mock
72         X509Certificate x509CertMock;
73
74         @Mock
75         Certificate certMock;
76
77         @Mock
78         Principal subjectDN;
79
80         private final String resourceDirName = "src/test/resources";
81         private File resourceDir;
82         private File publicKeyFile;
83         private File privateKeyFile;
84         private File certFile;
85         
86         private static final String message = "The quick brown fox jumps over the lazy dog.";
87
88         private static final String subjectDNText = "subjectDN";
89         private static final String certText = "Some text that might be included in a certificate";
90
91         @Before
92         public void setup() throws CertificateEncodingException {
93                 MockitoAnnotations.initMocks(this);
94
95                 resourceDir = new File(resourceDirName);
96                 resourceDir.mkdirs();
97                 publicKeyFile = new File(resourceDirName, "/publicKey");
98                 privateKeyFile = new File(resourceDirName, "/privateKey");
99                 publicKeyFile.delete();
100                 privateKeyFile.delete();
101
102                 certFile = new File(resourceDirName + "/exampleCertificate.cer");
103
104                 when(transMock.start(anyString(), anyInt())).thenReturn(timeTakenMock);
105                 when(transMock.debug()).thenReturn(logTargetMock);
106
107                 when(subjectDN.toString()).thenReturn(subjectDNText);
108
109                 when(x509CertMock.getSubjectDN()).thenReturn(subjectDN);
110                 when(x509CertMock.getEncoded()).thenReturn(certText.getBytes());
111
112                 when(certMock.getEncoded()).thenReturn(certText.getBytes());
113         }
114
115         @After
116         public void tearDown() {
117                 publicKeyFile = new File(resourceDirName, "/publicKey");
118                 privateKeyFile = new File(resourceDirName, "/privateKey");
119                 publicKeyFile.delete();
120                 privateKeyFile.delete();
121
122                 if (resourceDir.list().length == 0) {
123                         resourceDir.delete();
124                 }
125         }
126
127         @Test
128         public void generateKeyPairTest() throws Exception {
129                 // This instatiation isn't actually necessary, but it gets coverage
130                 Cipher encryptor = Factory.pkCipher();
131                 Cipher decryptor = Factory.pkCipher();
132
133                 KeyPair kp1 = Factory.generateKeyPair(transMock);
134                 encryptor = Factory.pkCipher(kp1.getPublic(), true);
135                 decryptor = Factory.pkCipher(kp1.getPrivate(), false);
136                 byte[] encrypedMessage1 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
137                 String output1 = new String(decryptor.doFinal(encrypedMessage1));
138                 assertThat(output1, is(message));
139
140                 // coverage
141                 when(transMock.start("Generate KeyPair", Env.SUB)).thenReturn(null);
142                 KeyPair kp2 = Factory.generateKeyPair(transMock);
143                 encryptor = Factory.pkCipher(kp2.getPublic(), true);
144                 decryptor = Factory.pkCipher(kp2.getPrivate(), false);
145                 byte[] encrypedMessage2 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
146                 String output2 = new String(decryptor.doFinal(encrypedMessage2));
147                 assertThat(output2, is(message));
148
149                 KeyPair kp3 = Factory.generateKeyPair(null);
150                 encryptor = Factory.pkCipher(kp3.getPublic(), true);
151                 decryptor = Factory.pkCipher(kp3.getPrivate(), false);
152                 byte[] encrypedMessage3 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
153                 String output3 = new String(decryptor.doFinal(encrypedMessage3));
154                 assertThat(output3, is(message));
155         }
156
157         @Test
158         public void keyStringManipTest() throws Exception {
159                 KeyPair kp = Factory.generateKeyPair(transMock);
160
161                 String publicKeyString = Factory.toString(transMock, kp.getPublic());
162                 String privateKeyString = Factory.toString(transMock, kp.getPrivate());
163
164                 assertThat(publicKeyString.startsWith("-----BEGIN PUBLIC KEY-----"), is(true));
165                 assertThat(publicKeyString.endsWith("-----END PUBLIC KEY-----\n"), is(true));
166
167                 assertThat(privateKeyString.startsWith("-----BEGIN PRIVATE KEY-----"), is(true));
168                 assertThat(privateKeyString.endsWith("-----END PRIVATE KEY-----\n"), is(true));
169
170                 PublicKey publicKey = Factory.toPublicKey(transMock, cleanupString(publicKeyString));
171                 PrivateKey privateKey = Factory.toPrivateKey(transMock, cleanupString(privateKeyString));
172
173                 Cipher encryptor = Factory.pkCipher(publicKey, true);
174                 Cipher decryptor = Factory.pkCipher(privateKey, false);
175                 byte[] encrypedMessage = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
176                 String output = new String(decryptor.doFinal(encrypedMessage));
177                 assertThat(output, is(message));
178         }
179
180         @Test
181         public void keyFileManipTest() throws Exception {
182                 KeyPair kp = Factory.generateKeyPair(transMock);
183
184                 String privateKeyString = Factory.toString(transMock, kp.getPrivate());
185                 writeToFile(privateKeyFile, privateKeyString, "Header:this line has a header");
186
187                 PublicKey publicKey = kp.getPublic();
188                 PrivateKey privateKey = Factory.toPrivateKey(transMock, privateKeyFile);
189
190                 Cipher encryptor = Factory.pkCipher(publicKey, true);
191                 Cipher decryptor = Factory.pkCipher(privateKey, false);
192                 byte[] encrypedMessage = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
193                 String output = new String(decryptor.doFinal(encrypedMessage));
194                 assertThat(output, is(message));
195         }
196
197         @Test
198         public void certToStringTest() throws IOException, CertException, CertificateEncodingException {
199                 String certString;
200                 when(logTargetMock.isLoggable()).thenReturn(true);
201
202                 certString = Factory.toString(transMock, x509CertMock);
203                 assertThat(certString.startsWith("-----BEGIN CERTIFICATE-----"), is(true));
204                 assertThat(certString.endsWith("-----END CERTIFICATE-----\n"), is(true));
205
206                 certString = Factory.toString(transMock, certMock);
207                 assertThat(certString.startsWith("-----BEGIN CERTIFICATE-----"), is(true));
208                 assertThat(certString.endsWith("-----END CERTIFICATE-----\n"), is(true));
209
210                 try {
211                         certString = Factory.toString(transMock, (Certificate)null);
212                         fail("Should have thrown an exception");
213                 } catch (CertException e) {
214                         assertThat(e.getMessage(), is("Certificate not built"));
215                 }
216
217                 when(certMock.getEncoded()).thenThrow(new CertificateEncodingException());
218                 try {
219                         certString = Factory.toString(transMock, certMock);
220                         fail("Should have thrown an exception");
221                 } catch (CertException e) {
222                 }
223
224                 // coverage
225                 when(logTargetMock.isLoggable()).thenReturn(false);
226                 certString = Factory.toString(transMock, x509CertMock);
227         }
228
229         @Test
230         public void toX509Test() throws CertificateException, IOException, CertException {
231                 String output;
232                 Collection<? extends Certificate> certs;
233                 when(logTargetMock.isLoggable()).thenReturn(true);
234
235                 String certString = readFromFile(certFile, false);
236
237                 certs = Factory.toX509Certificate(certString);
238                 // Contrived way of getting a Certificate out of a Collection
239                 output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]);
240                 assertThat(output, is(certString));
241
242                 certs = Factory.toX509Certificate(transMock, certFile);
243                 // Contrived way of getting a Certificate out of a Collection
244                 output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]);
245                 assertThat(output, is(certString));
246
247                 List<String> certStrings = new ArrayList<String>();
248                 certStrings.add(certString);
249                 certStrings.add(certString);
250                 certs = Factory.toX509Certificate(certStrings);
251                 // Contrived way of getting a Certificate out of a Collection
252                 // it doesn't matter which one we get - they're the same
253                 output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]);
254                 assertThat(output, is(certString));
255         }
256
257         @Test
258         public void stripperTest() throws Exception {
259                 KeyPair kp = Factory.generateKeyPair(transMock);
260                 String privateKeyString = Factory.toString(transMock, kp.getPrivate());
261                 writeToFile(privateKeyFile, privateKeyString, "Header:this line has a header");
262
263                 StripperInputStream stripper = new StripperInputStream(privateKeyFile);
264
265                 String expected = cleanupString(privateKeyString);
266                 byte[] buffer = new byte[10000];
267                 stripper.read(buffer);
268                 String output = new String(buffer, 0, expected.length());
269                 assertThat(output, is(expected));
270                 stripper.close();
271
272                 // coverage
273                 stripper = new StripperInputStream(new FileInputStream(privateKeyFile));
274                 stripper.close();
275                 stripper = new StripperInputStream(new BufferedReader(new FileReader(privateKeyFile)));
276                 stripper.close();
277                 stripper.close();  // also coverage...
278         }
279
280         @Test
281         public void binaryTest() throws IOException {
282                 String output = new String(Factory.binary(certFile));
283                 String expected = readFromFile(certFile, true);
284                 assertThat(output, is(expected));
285         }
286
287         @Test
288         public void signatureTest() throws Exception {
289                 KeyPair kp = Factory.generateKeyPair(transMock);
290                 String signedString = "Something that needs signing";
291                 byte[] signedBytes = Factory.sign(transMock, signedString.getBytes(), kp.getPrivate());
292                 String output = Factory.toSignatureString(signedBytes);
293                 assertThat(output.startsWith("-----BEGIN SIGNATURE-----"), is(true));
294                 assertThat(output.endsWith("-----END SIGNATURE-----\n"), is(true));
295                 assertThat(Factory.verify(transMock, signedString.getBytes(), signedBytes, kp.getPublic()), is(true));
296         }
297
298         // TODO: Ian - finish these tests
299         // @Test
300         // public void base64ISTest() throws Exception {
301         //      KeyPair kp = Factory.generateKeyPair(transMock);
302
303         //      String privateKeyString = Factory.toString(transMock, kp.getPrivate());
304         //      String cleaned = cleanupString(privateKeyString);
305         //      System.out.println(cleaned);
306         //      writeToFile(privateKeyFile, cleaned);
307         //      Base64InputStream b64is = new Base64InputStream(privateKeyFile);
308         //      byte[] buffer = new byte[10000];
309         //      b64is.read(buffer);
310         //      System.out.println(new String(buffer));
311         //      b64is.close();
312         // }
313
314         // @Test
315         // public void getSecurityProviderTest() {
316         // }
317
318         private String cleanupString(String str) {
319                 String[] lines = str.split("\n", 0);
320                 List<String> rawLines = new ArrayList<String>();
321                 for (int i = 0; i < lines.length - 2; i++) {
322                         rawLines.add(lines[i + 1]);
323                 }
324                 return join("", rawLines);
325         }
326
327         /** 
328          * Note: String.join is not part of JDK 7, which is what we compile to for CADI
329          */
330         private String join(String delim, List<String> rawLines) {
331                 StringBuilder sb = new StringBuilder();
332                 boolean first = true;
333                 for(String s : rawLines) {
334                         if(first) {
335                                 first = false;
336                         } else {
337                                 sb.append(delim);
338                         }
339                         sb.append(s);
340                 }
341                 return sb.toString();
342         }
343         
344         /* Not used locally
345         private void writeToFile(File file, String contents) throws Exception {
346                 writeToFile(file, contents, null);
347         }
348         */
349
350         private void writeToFile(File file, String contents, String header) throws Exception {
351                 PrintWriter writer = new PrintWriter(file, "UTF-8");
352                 if (header != null) {
353                         writer.println(header);
354                 }
355                 writer.println(contents);
356                 writer.close();
357         }
358
359         private String readFromFile(File file, boolean addCR) throws IOException {
360                 BufferedReader br = new BufferedReader(new FileReader(file));
361                 StringBuilder sb = new StringBuilder();
362                 String line;
363                 while ((line = br.readLine()) != null) {
364                         String lineEnd = (addCR) ? "\r\n" : "\n";
365                         sb.append(line + lineEnd);
366                 }
367                 br.close();
368                 return sb.toString();
369         }
370
371 }