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.PreparedStatement;
35 import java.sql.ResultSet;
36 import java.sql.SQLException;
37 import java.util.Locale;
38 import java.util.Properties;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
42 import javax.net.ssl.HttpsURLConnection;
43 import javax.net.ssl.KeyManager;
44 import javax.net.ssl.SSLContext;
45 import javax.net.ssl.X509KeyManager;
47 import org.cacert.gigi.DevelLauncher;
48 import org.cacert.gigi.GigiApiException;
49 import org.cacert.gigi.database.DatabaseConnection;
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 * Some password that fullfills the password criteria.
74 protected static final String TEST_PASSWORD = "xvXV12°§";
76 private static TestEmailReciever ter;
78 private static Process gigi;
80 private static String url = "localhost:4443";
82 private static String acceptLanguage = null;
84 public static void setAcceptLanguage(String acceptLanguage) {
85 ManagedTest.acceptLanguage = acceptLanguage;
88 public static String getServerName() {
92 static Properties testProps = new Properties();
94 public static Properties getTestProps() {
100 HttpURLConnection.setFollowRedirects(false);
104 public static void connectToServer() {
106 testProps.load(new FileInputStream("config/test.properties"));
107 if ( !DatabaseConnection.isInited()) {
108 DatabaseConnection.init(testProps);
111 String type = testProps.getProperty("type");
112 Properties mainProps = generateMainProps();
113 ServerConstants.init(mainProps);
114 if (type.equals("local")) {
115 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
116 String[] parts = testProps.getProperty("mail").split(":", 2);
117 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
120 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
121 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
122 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
123 System.out.println("... starting server");
125 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
126 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
128 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
131 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
133 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
141 while ((line = br.readLine()) != null) {
142 System.err.println(line);
144 } catch (IOException e) {
150 throw new Error("Server startup failed");
152 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
153 SimpleSigner.runSigner();
154 } catch (IOException e) {
156 } catch (SQLException e1) {
157 e1.printStackTrace();
158 } catch (InterruptedException e) {
164 public static void purgeDatabase() throws SQLException, IOException {
165 System.out.print("... resetting Database");
166 long ms = System.currentTimeMillis();
168 DatabaseManager.run(new String[] {
169 testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
171 } catch (ClassNotFoundException e) {
174 System.out.println(" in " + (System.currentTimeMillis() - ms) + " ms");
175 String type = testProps.getProperty("type");
176 ObjectCache.clearAllCaches();
177 if (type.equals("local")) {
178 URL u = new URL("https://" + getServerName() + "/manage");
179 u.openConnection().getHeaderField("Location");
183 private static Properties generateMainProps() {
184 Properties mainProps = new Properties();
185 mainProps.setProperty("host", "127.0.0.1");
186 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
187 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
188 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
190 mainProps.setProperty("https.port", testProps.getProperty("serverPort.https"));
191 mainProps.setProperty("http.port", testProps.getProperty("serverPort.http"));
192 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
193 mainProps.setProperty("emailProvider.port", "8473");
194 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
195 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
196 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
197 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
202 public static void tearDownServer() {
203 String type = testProps.getProperty("type");
205 if (type.equals("local")) {
210 SimpleSigner.stopSigner();
211 } catch (InterruptedException e) {
216 public final String uniq = createUniqueName();
219 public void removeMails() {
224 public void clearAcceptLanguage() {
225 acceptLanguage = null;
228 public TestMail waitForMail() {
230 return ter.recieve();
231 } catch (InterruptedException e) {
236 public static TestEmailReciever getMailReciever() {
240 public static String runRegister(String param) throws IOException {
241 URL regist = new URL("https://" + getServerName() + RegisterPage.PATH);
242 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
243 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
244 if (acceptLanguage != null) {
245 csrfConn.setRequestProperty("Accept-Language", acceptLanguage);
246 uc.setRequestProperty("Accept-Language", acceptLanguage);
249 String headerField = csrfConn.getHeaderField("Set-Cookie");
250 headerField = stripCookie(headerField);
252 String csrf = getCSRF(csrfConn);
253 uc.addRequestProperty("Cookie", headerField);
254 uc.setDoOutput(true);
255 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
256 String d = IOUtils.readURL(uc);
260 public static String fetchStartErrorMessage(String d) throws IOException {
261 String formFail = "<div class='formError'>";
262 int idx = d.indexOf(formFail);
266 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
270 public static void registerUser(String firstName, String lastName, String email, String password) {
272 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";
273 String data = fetchStartErrorMessage(runRegister(query));
275 } catch (UnsupportedEncodingException e) {
277 } catch (IOException e) {
282 public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
283 registerUser(firstName, lastName, email, password);
285 TestMail tm = ter.recieve();
286 String verifyLink = tm.extractLink();
287 String[] parts = verifyLink.split("\\?");
288 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
289 u.openStream().close();
291 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
292 ps.setString(1, email);
293 ResultSet rs = ps.executeQuery();
298 } catch (InterruptedException e) {
300 } catch (IOException e) {
302 } catch (SQLException e) {
308 * Creates a new user with 100 Assurance points given by an (invalid)
319 * @return a new userid.
321 public static int createAssuranceUser(String firstName, String lastName, String email, String password) {
322 int uid = createVerifiedUser(firstName, lastName, email, password);
324 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
328 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
333 } catch (SQLException e) {
339 static int count = 0;
341 public static String createUniqueName() {
342 return "test" + System.currentTimeMillis() + "a" + (count++) + "u";
345 private static String stripCookie(String headerField) {
346 return headerField.substring(0, headerField.indexOf(';'));
349 public static final String SECURE_REFERENCE = MyDetails.PATH;
351 public static boolean isLoggedin(String cookie) throws IOException {
352 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
353 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
354 huc.addRequestProperty("Cookie", cookie);
355 return huc.getResponseCode() == 200;
358 public static String login(String email, String pw) throws IOException {
359 URL u = new URL("https://" + getServerName() + "/login");
360 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
361 huc.setDoOutput(true);
362 OutputStream os = huc.getOutputStream();
363 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
364 os.write(data.getBytes());
366 String headerField = huc.getHeaderField("Set-Cookie");
367 return stripCookie(headerField);
370 public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
372 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
373 authenticateClientCert(pk, ce, connection);
374 if (connection.getResponseCode() == 302) {
375 assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
376 return stripCookie(connection.getHeaderField("Set-Cookie"));
382 public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
383 KeyManager km = new X509KeyManager() {
386 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
391 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
396 public X509Certificate[] getCertificateChain(String arg0) {
397 return new X509Certificate[] {
403 public String[] getClientAliases(String arg0, Principal[] arg1) {
404 return new String[] {
410 public PrivateKey getPrivateKey(String arg0) {
411 if (arg0.equals("client")) {
418 public String[] getServerAliases(String arg0, Principal[] arg1) {
419 return new String[] {
424 SSLContext sc = SSLContext.getInstance("TLS");
425 sc.init(new KeyManager[] {
428 if (connection instanceof HttpsURLConnection) {
429 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
433 public static String getCSRF(URLConnection u) throws IOException {
434 return getCSRF(u, 0);
437 public static String getCSRF(URLConnection u, int formIndex) throws IOException {
438 String content = IOUtils.readURL(u);
439 return getCSRF(formIndex, content);
442 public static String getCSRF(int formIndex, String content) throws Error {
443 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
444 Matcher m = p.matcher(content);
445 for (int i = 0; i < formIndex + 1; i++) {
447 throw new Error("No CSRF Token");
453 public static KeyPair generateKeypair() throws GeneralSecurityException {
454 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
455 kpg.initialize(4096);
456 KeyPair keyPair = null;
457 File f = new File("testKeypair");
459 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
460 keyPair = (KeyPair) ois.readObject();
461 } catch (ClassNotFoundException e) {
463 } catch (IOException e) {
467 keyPair = kpg.generateKeyPair();
468 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
469 oos.writeObject(keyPair);
471 } catch (IOException e) {
478 public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
479 return generatePEMCSR(kp, dn, new PKCS10Attributes());
482 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
483 return generatePEMCSR(kp, dn, atts, "SHA256WithRSA");
486 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
487 PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
488 Signature s = Signature.getInstance(signature);
489 s.initSign(kp.getPrivate());
490 p10.encodeAndSign(new X500Name(dn), s);
491 return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
494 public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
495 return executeBasicWebInteraction(cookie, path, query, 0);
498 public static String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
499 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
500 uc.addRequestProperty("Cookie", cookie);
501 String csrf = getCSRF(uc, formIndex);
503 uc = new URL("https://" + getServerName() + path).openConnection();
504 uc.addRequestProperty("Cookie", cookie);
505 uc.setDoOutput(true);
506 OutputStream os = uc.getOutputStream();
507 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
511 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
515 public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
516 EmailAddress adrr = new EmailAddress(u, createUniqueName() + "test@test.tld");
517 adrr.insert(Language.getInstance(Locale.ENGLISH));
518 TestMail testMail = getMailReciever().recieve();
519 assertEquals(adrr.getAddress(), testMail.getTo());
520 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
522 getMailReciever().clearMails();
526 public static URLConnection cookie(URLConnection openConnection, String cookie) {
527 openConnection.setRequestProperty("Cookie", cookie);
528 return openConnection;