This repository was archived by the owner on Jan 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathMASMultiServerTest.java
More file actions
770 lines (657 loc) · 32.8 KB
/
MASMultiServerTest.java
File metadata and controls
770 lines (657 loc) · 32.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
/*
* Copyright (c) 2016 CA. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/
package com.ca.mas.foundation;
import android.net.Uri;
import com.ca.mas.MASCallbackFuture;
import com.ca.mas.MASLoginTestBase;
import com.ca.mas.core.cert.CertUtils;
import com.ca.mas.core.cert.PublicKeyHash;
import com.ca.mas.core.http.ContentType;
import com.ca.mas.core.io.Charsets;
import junit.framework.Assert;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URL;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.x500.X500Principal;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import static com.ca.mas.TestUtils.getJSONObject;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
public class MASMultiServerTest extends MASLoginTestBase {
private static MockWebServer mockServer;
private static int PORT = 41980;
private X509Certificate certificate;
private JSONObject expectResponse;
private String HOST = "localhost:41980";
@Before
public void multiServerSetup() throws Exception {
expectResponse = new JSONObject();
expectResponse.put("test", "value");
mockServer = new MockWebServer();
mockServer.useHttps(getSSLSocketFactory(), false);
mockServer.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
return new MockResponse().setResponseCode(200)
.setBody(expectResponse.toString())
.addHeader("Content-type", ContentType.APPLICATION_JSON.toString());
}
});
mockServer.start(PORT);
}
@Test
public void testMultiServerCertificatePinning() throws Exception {
Assert.assertNotNull(certificate);
Assert.assertNotNull(certificate.getPublicKey());
Assert.assertNotNull(PublicKeyHash.fromPublicKey(certificate.getPublicKey()));
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(certificate)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
}
@Test
public void testHttpOverrideContentType() throws InterruptedException {
final ContentType customCharset = new ContentType("application/x-www-form-urlencoded", Charsets.UTF8);
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(certificate)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.header("Content-Type", customCharset.toString())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
RecordedRequest req = mockServer.takeRequest();
String head = req.getHeader("Content-type");
assertEquals(head, customCharset.toString());
}
@Test
public void testMultiServerCertificatePinningWithCertChain() throws Exception {
URL url = new URL("https://swapi.co:443");
MASSecurityConfiguration.Builder configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(url.getHost() + ":" + url.getPort()).build());
Certificate[] certificates = getCert(url);
for (Certificate certificate : certificates) {
configuration.add(certificate);
}
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration.build());
Uri uri = new Uri.Builder().encodedAuthority(url.getAuthority())
.scheme(url.getProtocol())
.appendPath("api")
.appendPath("people")
.appendPath("1")
.build();
MASRequest request = new MASRequest.MASRequestBuilder(uri)
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
JSONObject result = callback.get().getBody().getContent();
Assert.assertNotNull(result);
Assert.assertEquals("Luke Skywalker", result.getString("name"));
}
@Test
public void testMultiServerCertificatePinningFailed() throws Exception {
URL url = new URL("https://swapi.co:443");
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(getCert(url)[0])
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
try {
callback.get();
Assert.fail();
} catch (ExecutionException e) {
//Should throw InvalidServerException or IOException or SSL....Exception
assertTrue(e.getCause().getCause() instanceof SSLHandshakeException);
}
}
@Test
public void testMultiServerPublicKeyPinningFailed() throws Exception {
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add("ZHVtbXk=") //Dummy
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
try {
callback.get();
Assert.fail();
} catch (ExecutionException e) {
//Should throw InvalidServerException or IOException or SSL....Exception
assertTrue(e.getCause().getCause() instanceof SSLHandshakeException);
}
}
@Test
public void testMultiServerPublicKeyPinning() throws Exception {
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(PublicKeyHash.fromCertificate(certificate).getHashString())
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
}
@Test
public void testMultiServerMultiplePublicKeyPinning() throws Exception {
URL url = new URL("https://swapi.co:443");
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(PublicKeyHash.fromCertificate(certificate).getHashString())
.add(PublicKeyHash.fromCertificate(getCert(url)[0]).getHashString())
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
}
@Test
public void testMultiServerNoPinning() throws Exception {
URL url = new URL("https://swapi.co:443");
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(url.getHost() + ":" + url.getPort()).build())
.trustPublicPKI(true)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
Uri uri = new Uri.Builder().encodedAuthority(url.getAuthority())
.scheme(url.getProtocol())
.appendPath("api")
.appendPath("people")
.appendPath("1")
.build();
MASRequest request = new MASRequest.MASRequestBuilder(uri)
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
JSONObject result = callback.get().getBody().getContent();
Assert.assertNotNull(result);
}
@Test
public void testMultiServerIsPublicFlagOverride() throws Exception {
//Set isPublic on MASRequest
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(certificate)
.isPublic(false)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.setPublic()
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
RecordedRequest recordedRequest = mockServer.takeRequest();
Assert.assertNull(recordedRequest.getHeader("mag-identifier"));
Assert.assertNull(recordedRequest.getHeader("Authorization"));
}
@Test
public void testMultiServerMssoConfigOverride() throws Exception {
//Update msso-config setting
//using a wrong hash for the msso-config
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add("ZHVtbXk=") //Dummy
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
// MASRequest request = new MASRequest.MASRequestBuilder(new URI(GatewayDefaultDispatcher.PROTECTED_RESOURCE_PRODUCTS))
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
try {
callback.get().getBody();
Assert.fail();
} catch (ExecutionException e) {
//Should throw InvalidServerException or IOException or SSL....Exception
assertTrue(e.getCause().getCause() instanceof SSLHandshakeException);
}
}
@Test
public void testMultiServerConfigurationRuntimeUpdated() throws Exception {
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(certificate)
.add(PublicKeyHash.fromCertificate(certificate).getHashString())
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
//Update new configuration during runtime
MASSecurityConfiguration configuration2 = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(certificate)
.add("ZHVtbXk=") //Dummy
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration2);
MASCallbackFuture<MASResponse<JSONObject>> callback2 = new MASCallbackFuture<>();
MAS.invoke(request, callback2);
try {
callback2.get();
Assert.fail();
} catch (ExecutionException e) {
//Should throw InvalidServerException or IOException or SSL....Exception
assertTrue(e.getCause().getCause() instanceof SSLHandshakeException);
}
}
@Test
public void testMultiServerDynamicSDK() throws Exception {
Uri orig = new Uri.Builder().encodedAuthority(getHost() + ":" + getPort()).build();
Assert.assertNotNull(MASConfiguration.getCurrentConfiguration().getSecurityConfiguration(orig));
MAS.start(getContext(), getJSONObject("/msso_config_multi_server.json"));
Assert.assertNull(MASConfiguration.getCurrentConfiguration().getSecurityConfiguration(orig));
Uri newUri = new Uri.Builder().encodedAuthority("dummy:12345").build();
Assert.assertNotNull(MASConfiguration.getCurrentConfiguration().getSecurityConfiguration(newUri));
}
@Test
public void testMultiServerIsPublic() throws Exception {
//No access token header
//No mag-identifier header
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(certificate)
.add(PublicKeyHash.fromCertificate(certificate).getHashString())
.isPublic(true)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
RecordedRequest recordedRequest = mockServer.takeRequest();
Assert.assertNull(recordedRequest.getHeader("mag-identifier"));
Assert.assertNull(recordedRequest.getHeader("Authorization"));
}
@Test
public void testMultiServerWithUnknownHost() throws Exception {
}
@Test
public void testMultiServerValidCertInvalidPin() throws Exception {
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(certificate)
.add("ZHVtbXk=") //Dummy
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
try {
callback.get();
Assert.fail();
} catch (ExecutionException e) {
//Should throw InvalidServerException or IOException or SSL....Exception
assertTrue(e.getCause().getCause() instanceof SSLHandshakeException);
}
}
@Test
public void testMultiServerIsNotPublic() throws Exception {
//Contain access token header
//Contains mag-identifier header
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add(certificate)
.add(PublicKeyHash.fromCertificate(certificate).getHashString())
.isPublic(false)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
RecordedRequest recordedRequest = mockServer.takeRequest();
Assert.assertNotNull(recordedRequest.getHeader("mag-identifier"));
Assert.assertNotNull(recordedRequest.getHeader("Authorization"));
}
@Test
public void testPublicCA() throws Exception {
//https://swapi.co/api/people/1/
//https://en.wikipedia.org/w/api.php?action=query&titles=CA_Technologies&prop=revisions&rvprop=content&format=json
//https://itunes.apple.com/search?term=red+hot+chili+peppers&entity=musicVideo
//https://www.googleapis.com/books/v1/volumes?q=patrick+rothfuss
//https://api.ipify.org?format=json
//Star Wars API
URL url = new URL("https://swapi.co:443");
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(url.getHost() + ":" + url.getPort()).build())
.trustPublicPKI(true)
.isPublic(true)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
Uri uri = new Uri.Builder().encodedAuthority(url.getAuthority())
.scheme(url.getProtocol())
.appendPath("api").appendPath("people").appendPath("1")
.build();
MASRequest request = new MASRequest.MASRequestBuilder(uri).build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
JSONObject result = callback.get().getBody().getContent();
Assert.assertNotNull(result);
Assert.assertEquals("Luke Skywalker", result.getString("name"));
//Google API
URL url2 = new URL("https://www.googleapis.com:443");
MASSecurityConfiguration configuration2 = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(url2.getHost() + ":" + url2.getPort()).build())
.trustPublicPKI(true)
.isPublic(true)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration2);
Uri uri2 = new Uri.Builder().encodedAuthority(url2.getAuthority())
.scheme(url2.getProtocol())
.appendPath("books").appendPath("v1")
.appendPath("volumes")
.appendQueryParameter("q", "patrick+rothfuss")
.build();
MASRequest request2 = new MASRequest.MASRequestBuilder(uri2).build();
MASCallbackFuture<MASResponse<JSONObject>> callback2 = new MASCallbackFuture<>();
MAS.invoke(request2, callback2);
JSONObject result2 = callback2.get().getBody().getContent();
Assert.assertNotNull(result2);
String expectedAuthor = result2.getJSONArray("items").getJSONObject(0).getJSONObject("volumeInfo").getJSONArray("authors").getString(0);
Assert.assertEquals(expectedAuthor, "Patrick Rothfuss");
}
@Test
public void testNoPinningAndNonTrustPublicPKI() throws Exception {
URL url = new URL("https://swapi.co:443");
try {
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(url.getHost() + ":" + url.getPort()).build())
.trustPublicPKI(false)
.build();
} catch (Exception e) {
//Should throw InvalidServerException or IOException or SSL....Exception
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testMultiServerGeneratedSecurityConfiguration() throws Exception {
List<MASSecurityConfiguration> securityConfigs = getSecurityConfiguration("multiservercerts.json");
MASConfiguration config = MASConfiguration.getCurrentConfiguration();
for (MASSecurityConfiguration securityConfig : securityConfigs) {
config.addSecurityConfiguration(securityConfig);
}
URL url = new URL("https://en.wikipedia.org:443");
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(url.getHost() + ":" + url.getPort()).build())
.trustPublicPKI(true)
.isPublic(true)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
Uri uri = new Uri.Builder().encodedAuthority(url.getAuthority())
.scheme(url.getProtocol())
.appendPath("w").appendPath("api.php")
.appendQueryParameter("action", "query")
.appendQueryParameter("titles", "CA_Technologies")
.appendQueryParameter("prop", "revisions")
.appendQueryParameter("rvprop", "content")
.appendQueryParameter("format", "json")
.build();
MASRequest request = new MASRequest.MASRequestBuilder(uri).build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
JSONObject result = callback.get().getBody().getContent();
Assert.assertNotNull(result);
String expectedResult = result.getJSONObject("query").getJSONArray("normalized").getJSONObject(0).getString("to");
Assert.assertEquals(expectedResult, "CA Technologies");
}
@Test
public void testMultiServerEnableSSLPinning() throws Exception {
MAS.setSSLPinningEnabled(false);
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add("ZHVtbXk=") //Dummy
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
// Should pass as enableSSLPinning is false.
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
}
@Test
public void testMultiServerAllowSSLPinning() throws Exception {
MAS.setSSLPinningEnabled(true);
MASSecurityConfiguration configuration = new MASSecurityConfiguration.Builder()
.host(new Uri.Builder().encodedAuthority(HOST).build())
.add("ZHVtbXk=") //Dummy
.allowSSLPinning(false)
.build();
MASConfiguration.getCurrentConfiguration().addSecurityConfiguration(configuration);
MASRequest request = new MASRequest.MASRequestBuilder(
new Uri.Builder().encodedAuthority(HOST)
.scheme("https")
.path("test")
.build())
.build();
MASCallbackFuture<MASResponse<JSONObject>> callback = new MASCallbackFuture<>();
MAS.invoke(request, callback);
// Should pass as allowSSLPinning is set to False
Assert.assertEquals(expectResponse.toString(), callback.get().getBody().getContent().toString());
}
private Certificate[] getCert(URL url) throws Exception {
//URL url = new URL("https://mobile-staging-androidautomation.l7tech.com:8443");
//URL url = new URL("https://swapi.co");
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(null, new TrustManager[]{new X509TrustManager() {
private X509Certificate[] accepted;
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
throw new CertificateException("This trust manager is only for clients");
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
accepted = xcs;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return accepted;
}
}}, null);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(sslCtx.getSocketFactory());
connection.getResponseCode();
Certificate[] certificates = connection.getServerCertificates();
connection.disconnect();
return certificates;
}
@Override
@After
public void deregister() throws InterruptedException, ExecutionException {
super.deregister();
try {
if (mockServer != null) {
mockServer.shutdown();
}
} catch (IOException e) {
//Couldn't shut down the mock server
}
Map securityConfigurations = getValue(MASConfiguration.getCurrentConfiguration(), "securityConfigurations", Map.class);
securityConfigurations.clear();
}
private SSLSocketFactory getSSLSocketFactory() throws Exception {
char[] password = "password".toCharArray();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Calendar notAfter = Calendar.getInstance();
notAfter.add(Calendar.DAY_OF_YEAR, 1);
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
new X500Principal("CN=localhost"),
new BigInteger("1"),
new Date(),
notAfter.getTime(),
new X500Principal("CN=localhost"),
keyPair.getPublic());
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
.build(keyPair.getPrivate());
builder.build(contentSigner);
certificate = new JcaX509CertificateConverter().getCertificate(builder.build(contentSigner));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = null;
keyStore.load(in, password);
Certificate[] certificateChain = {certificate};
keyStore.setKeyEntry("private", keyPair.getPrivate(), password, certificateChain);
keyStore.setCertificateEntry("cert", certificate);
// Wrap it up in an SSL context.
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
new SecureRandom());
return sslContext.getSocketFactory();
}
private List<MASSecurityConfiguration> getSecurityConfiguration(String filename) throws IOException, JSONException {
List<MASSecurityConfiguration> securityConfigurations = new ArrayList<>();
JSONObject sc = getJSONObject("/" + filename);
for (int i = 0; i < sc.names().length(); i++) {
MASSecurityConfiguration.Builder builder = new MASSecurityConfiguration.Builder();
URL url = new URL(sc.names().getString(i));
Uri uri = new Uri.Builder().encodedAuthority(url.getHost() + ":" + url.getPort()).build();
builder.host(uri);
JSONObject config = sc.getJSONObject(sc.names().getString(i));
//Certificate
JSONArray certificates = config.optJSONArray("certificates");
if (certificates != null) {
for (int j = 0; j < certificates.length(); j++) {
JSONArray certificate = certificates.getJSONArray(j);
String c = certificate.join("\n").replace("\"", "");
Certificate cert = CertUtils.decodeCertFromPem(c);
builder.add(cert);
}
}
//PublicKeyHash
JSONArray hashes = config.optJSONArray("publicKeyHashes");
if (hashes != null) {
for (int j = 0; j < hashes.length(); j++) {
builder.add(hashes.getString(j));
}
}
builder.isPublic(config.optBoolean("isPublic", false));
builder.trustPublicPKI(config.optBoolean("trustPublicPKI", false));
securityConfigurations.add(builder.build());
}
return securityConfigurations;
}
}