1 package org.cacert.gigi.testUtils;
3 import static org.junit.Assert.*;
5 import java.io.BufferedReader;
6 import java.io.DataOutputStream;
8 import java.io.FileInputStream;
9 import java.io.FileOutputStream;
10 import java.io.IOException;
11 import java.io.InputStreamReader;
12 import java.io.ObjectInputStream;
13 import java.io.ObjectOutputStream;
14 import java.io.OutputStream;
15 import java.io.UnsupportedEncodingException;
16 import java.net.HttpURLConnection;
17 import java.net.InetSocketAddress;
18 import java.net.MalformedURLException;
19 import java.net.Socket;
21 import java.net.URLConnection;
22 import java.net.URLEncoder;
23 import java.nio.file.Files;
24 import java.nio.file.Paths;
25 import java.security.GeneralSecurityException;
26 import java.security.KeyManagementException;
27 import java.security.KeyPair;
28 import java.security.KeyPairGenerator;
29 import java.security.NoSuchAlgorithmException;
30 import java.security.Principal;
31 import java.security.PrivateKey;
32 import java.security.Signature;
33 import java.security.cert.X509Certificate;
34 import java.sql.SQLException;
35 import java.util.Locale;
36 import java.util.Properties;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
40 import javax.net.ssl.HttpsURLConnection;
41 import javax.net.ssl.KeyManager;
42 import javax.net.ssl.SSLContext;
43 import javax.net.ssl.X509KeyManager;
45 import org.cacert.gigi.DevelLauncher;
46 import org.cacert.gigi.GigiApiException;
47 import org.cacert.gigi.database.DatabaseConnection;
48 import org.cacert.gigi.database.GigiPreparedStatement;
49 import org.cacert.gigi.database.GigiResultSet;
50 import org.cacert.gigi.dbObjects.EmailAddress;
51 import org.cacert.gigi.dbObjects.ObjectCache;
52 import org.cacert.gigi.dbObjects.User;
53 import org.cacert.gigi.localisation.Language;
54 import org.cacert.gigi.pages.account.MyDetails;
55 import org.cacert.gigi.pages.main.RegisterPage;
56 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
57 import org.cacert.gigi.util.DatabaseManager;
58 import org.cacert.gigi.util.PEM;
59 import org.cacert.gigi.util.ServerConstants;
60 import org.cacert.gigi.util.SimpleSigner;
61 import org.junit.After;
62 import org.junit.AfterClass;
63 import org.junit.BeforeClass;
65 import sun.security.pkcs10.PKCS10;
66 import sun.security.pkcs10.PKCS10Attributes;
67 import sun.security.x509.X500Name;
69 public class ManagedTest {
72 System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
76 * Some password that fullfills the password criteria.
78 protected static final String TEST_PASSWORD = "xvXV12°§";
80 private static TestEmailReciever ter;
82 private static Process gigi;
84 private static String url = "localhost:4443";
86 private static String acceptLanguage = null;
88 public static void setAcceptLanguage(String acceptLanguage) {
89 ManagedTest.acceptLanguage = acceptLanguage;
92 public static String getServerName() {
96 static Properties testProps = new Properties();
98 public static Properties getTestProps() {
103 InitTruststore.run();
104 HttpURLConnection.setFollowRedirects(false);
108 public static void connectToServer() {
110 testProps.load(new FileInputStream("config/test.properties"));
111 if ( !DatabaseConnection.isInited()) {
112 DatabaseConnection.init(testProps);
115 String type = testProps.getProperty("type");
116 Properties mainProps = generateMainProps();
117 ServerConstants.init(mainProps);
118 if (type.equals("local")) {
119 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
120 String[] parts = testProps.getProperty("mail").split(":", 2);
121 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
124 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
125 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
126 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
127 System.out.println("... starting server");
129 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
130 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
132 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
135 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
137 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
145 while ((line = br.readLine()) != null) {
146 System.err.println(line);
148 } catch (IOException e) {
154 throw new Error("Server startup failed");
156 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
157 SimpleSigner.runSigner();
158 } catch (IOException e) {
160 } catch (SQLException e1) {
161 e1.printStackTrace();
162 } catch (InterruptedException e) {
168 public static void purgeDatabase() throws SQLException, IOException {
169 System.out.print("... resetting Database");
170 long ms = System.currentTimeMillis();
172 DatabaseManager.run(new String[] {
173 testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
175 } catch (ClassNotFoundException e) {
178 System.out.println(" in " + (System.currentTimeMillis() - ms) + " ms");
179 String type = testProps.getProperty("type");
180 ObjectCache.clearAllCaches();
181 if (type.equals("local")) {
182 URL u = new URL("https://" + getServerName() + "/manage");
183 u.openConnection().getHeaderField("Location");
187 private static Properties generateMainProps() {
188 Properties mainProps = new Properties();
189 mainProps.setProperty("host", "127.0.0.1");
190 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
191 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
192 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
194 mainProps.setProperty("https.port", testProps.getProperty("serverPort.https"));
195 mainProps.setProperty("http.port", testProps.getProperty("serverPort.http"));
196 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
197 mainProps.setProperty("emailProvider.port", "8473");
198 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
199 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
200 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
201 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
206 public static void tearDownServer() {
207 String type = testProps.getProperty("type");
209 if (type.equals("local")) {
214 SimpleSigner.stopSigner();
215 } catch (InterruptedException e) {
220 public final String uniq = createUniqueName();
223 public void removeMails() {
228 public void clearAcceptLanguage() {
229 acceptLanguage = null;
232 public TestMail waitForMail() {
234 return ter.recieve();
235 } catch (InterruptedException e) {
240 public static TestEmailReciever getMailReciever() {
244 public static String runRegister(String param) throws IOException {
245 URL regist = new URL("https://" + getServerName() + RegisterPage.PATH);
246 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
247 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
248 if (acceptLanguage != null) {
249 csrfConn.setRequestProperty("Accept-Language", acceptLanguage);
250 uc.setRequestProperty("Accept-Language", acceptLanguage);
253 String headerField = csrfConn.getHeaderField("Set-Cookie");
254 headerField = stripCookie(headerField);
256 String csrf = getCSRF(csrfConn);
257 uc.addRequestProperty("Cookie", headerField);
258 uc.setDoOutput(true);
259 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
260 String d = IOUtils.readURL(uc);
264 public static String fetchStartErrorMessage(String d) throws IOException {
265 String formFail = "<div class='formError'>";
266 int idx = d.indexOf(formFail);
270 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
274 public static void registerUser(String firstName, String lastName, String email, String password) {
276 String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname=" + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1=" + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8") + "&day=1&month=1&year=1910&cca_agree=1";
277 String data = fetchStartErrorMessage(runRegister(query));
279 } catch (UnsupportedEncodingException e) {
281 } catch (IOException e) {
286 public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
287 registerUser(firstName, lastName, email, password);
289 TestMail tm = ter.recieve();
290 String verifyLink = tm.extractLink();
291 String[] parts = verifyLink.split("\\?");
292 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
293 u.openStream().close();
295 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
296 ps.setString(1, email);
297 GigiResultSet rs = ps.executeQuery();
302 } catch (InterruptedException e) {
304 } catch (IOException e) {
310 * Creates a new user with 100 Assurance points given by an (invalid)
321 * @return a new userid.
323 public static int createAssuranceUser(String firstName, String lastName, String email, String password) {
324 int uid = createVerifiedUser(firstName, lastName, email, password);
325 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
329 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
336 static int count = 0;
338 public static String createUniqueName() {
339 return "test" + System.currentTimeMillis() + "a" + (count++) + "u";
342 private static String stripCookie(String headerField) {
343 return headerField.substring(0, headerField.indexOf(';'));
346 public static final String SECURE_REFERENCE = MyDetails.PATH;
348 public static boolean isLoggedin(String cookie) throws IOException {
349 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
350 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
351 huc.addRequestProperty("Cookie", cookie);
352 return huc.getResponseCode() == 200;
355 public static String login(String email, String pw) throws IOException {
356 URL u = new URL("https://" + getServerName() + "/login");
357 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
358 huc.setDoOutput(true);
359 OutputStream os = huc.getOutputStream();
360 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
361 os.write(data.getBytes());
363 String headerField = huc.getHeaderField("Set-Cookie");
364 return stripCookie(headerField);
367 public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
369 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
370 authenticateClientCert(pk, ce, connection);
371 if (connection.getResponseCode() == 302) {
372 assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
373 return stripCookie(connection.getHeaderField("Set-Cookie"));
379 public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
380 KeyManager km = new X509KeyManager() {
383 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
388 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
393 public X509Certificate[] getCertificateChain(String arg0) {
394 return new X509Certificate[] {
400 public String[] getClientAliases(String arg0, Principal[] arg1) {
401 return new String[] {
407 public PrivateKey getPrivateKey(String arg0) {
408 if (arg0.equals("client")) {
415 public String[] getServerAliases(String arg0, Principal[] arg1) {
416 return new String[] {
421 SSLContext sc = SSLContext.getInstance("TLS");
422 sc.init(new KeyManager[] {
425 if (connection instanceof HttpsURLConnection) {
426 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
430 public static String getCSRF(URLConnection u) throws IOException {
431 return getCSRF(u, 0);
434 public static String getCSRF(URLConnection u, int formIndex) throws IOException {
435 String content = IOUtils.readURL(u);
436 return getCSRF(formIndex, content);
439 public static String getCSRF(int formIndex, String content) throws Error {
440 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
441 Matcher m = p.matcher(content);
442 for (int i = 0; i < formIndex + 1; i++) {
444 throw new Error("No CSRF Token");
450 public static KeyPair generateKeypair() throws GeneralSecurityException {
451 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
452 kpg.initialize(4096);
453 KeyPair keyPair = null;
454 File f = new File("testKeypair");
456 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
457 keyPair = (KeyPair) ois.readObject();
458 } catch (ClassNotFoundException e) {
460 } catch (IOException e) {
464 keyPair = kpg.generateKeyPair();
465 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
466 oos.writeObject(keyPair);
468 } catch (IOException e) {
475 public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
476 return generatePEMCSR(kp, dn, new PKCS10Attributes());
479 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
480 return generatePEMCSR(kp, dn, atts, "SHA256WithRSA");
483 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
484 PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
485 Signature s = Signature.getInstance(signature);
486 s.initSign(kp.getPrivate());
487 p10.encodeAndSign(new X500Name(dn), s);
488 return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
491 public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
492 return executeBasicWebInteraction(cookie, path, query, 0);
495 public static String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
496 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
497 uc.addRequestProperty("Cookie", cookie);
498 String csrf = getCSRF(uc, formIndex);
500 uc = new URL("https://" + getServerName() + path).openConnection();
501 uc.addRequestProperty("Cookie", cookie);
502 uc.setDoOutput(true);
503 OutputStream os = uc.getOutputStream();
504 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
508 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
512 public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
513 EmailAddress adrr = new EmailAddress(u, createUniqueName() + "test@test.tld");
514 adrr.insert(Language.getInstance(Locale.ENGLISH));
515 TestMail testMail = getMailReciever().recieve();
516 assertEquals(adrr.getAddress(), testMail.getTo());
517 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
519 getMailReciever().clearMails();
523 public static URLConnection cookie(URLConnection openConnection, String cookie) {
524 openConnection.setRequestProperty("Cookie", cookie);
525 return openConnection;