1 package org.cacert.gigi.testUtils;
3 import static org.junit.Assert.*;
5 import java.io.BufferedReader;
6 import java.io.DataOutputStream;
7 import java.io.FileInputStream;
8 import java.io.IOException;
9 import java.io.InputStreamReader;
10 import java.io.OutputStream;
11 import java.io.UnsupportedEncodingException;
12 import java.net.HttpURLConnection;
13 import java.net.InetSocketAddress;
14 import java.net.MalformedURLException;
15 import java.net.Socket;
17 import java.net.URLConnection;
18 import java.net.URLEncoder;
19 import java.nio.file.Files;
20 import java.nio.file.Paths;
21 import java.security.KeyManagementException;
22 import java.security.NoSuchAlgorithmException;
23 import java.security.Principal;
24 import java.security.PrivateKey;
25 import java.security.cert.X509Certificate;
26 import java.sql.PreparedStatement;
27 import java.sql.ResultSet;
28 import java.sql.SQLException;
29 import java.util.Properties;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
33 import javax.net.ssl.HttpsURLConnection;
34 import javax.net.ssl.KeyManager;
35 import javax.net.ssl.SSLContext;
36 import javax.net.ssl.X509KeyManager;
38 import org.cacert.gigi.DevelLauncher;
39 import org.cacert.gigi.EmailAddress;
40 import org.cacert.gigi.GigiApiException;
41 import org.cacert.gigi.Language;
42 import org.cacert.gigi.User;
43 import org.cacert.gigi.database.DatabaseConnection;
44 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
45 import org.cacert.gigi.util.DatabaseManager;
46 import org.cacert.gigi.util.ServerConstants;
47 import org.cacert.gigi.util.SimpleSigner;
48 import org.junit.After;
49 import org.junit.AfterClass;
50 import org.junit.BeforeClass;
52 public class ManagedTest {
55 * Some password that fullfills the password criteria.
57 protected static final String TEST_PASSWORD = "xvXV12°§";
59 private final String registerService = "/register";
61 private static TestEmailReciever ter;
63 private static Process gigi;
65 private static String url = "localhost:4443";
67 public static String getServerName() {
71 static Properties testProps = new Properties();
74 HttpURLConnection.setFollowRedirects(false);
78 public static void connectToServer() {
80 testProps.load(new FileInputStream("config/test.properties"));
81 if ( !DatabaseConnection.isInited()) {
82 DatabaseConnection.init(testProps);
84 System.out.println("... purging Database");
85 DatabaseManager.run(new String[] {
86 testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
88 String type = testProps.getProperty("type");
89 Properties mainProps = generateMainProps();
90 ServerConstants.init(mainProps);
91 if (type.equals("local")) {
92 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
93 String[] parts = testProps.getProperty("mail").split(":", 2);
94 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
97 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
98 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
99 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
100 System.out.println("... starting server");
102 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
103 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
105 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
108 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
110 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
118 while ((line = br.readLine()) != null) {
119 System.err.println(line);
121 } catch (IOException e) {
127 throw new Error("Server startup failed");
129 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
130 SimpleSigner.runSigner();
131 } catch (IOException e) {
133 } catch (ClassNotFoundException e1) {
134 e1.printStackTrace();
135 } catch (SQLException e1) {
136 e1.printStackTrace();
137 } catch (InterruptedException e) {
143 private static Properties generateMainProps() {
144 Properties mainProps = new Properties();
145 mainProps.setProperty("host", "127.0.0.1");
146 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
147 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
148 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
150 mainProps.setProperty("port", testProps.getProperty("serverPort"));
151 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
152 mainProps.setProperty("emailProvider.port", "8473");
153 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
154 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
155 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
156 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
161 public static void tearDownServer() {
162 String type = testProps.getProperty("type");
164 if (type.equals("local")) {
169 SimpleSigner.stopSigner();
170 } catch (InterruptedException e) {
176 public void removeMails() {
180 public TestMail waitForMail() {
182 return ter.recieve();
183 } catch (InterruptedException e) {
188 public static TestEmailReciever getMailReciever() {
192 public String runRegister(String param) throws IOException {
193 URL regist = new URL("https://" + getServerName() + registerService);
194 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
195 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
197 String headerField = csrfConn.getHeaderField("Set-Cookie");
198 headerField = stripCookie(headerField);
200 String csrf = getCSRF(csrfConn);
201 uc.addRequestProperty("Cookie", headerField);
202 uc.setDoOutput(true);
203 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
204 String d = IOUtils.readURL(uc);
208 public String fetchStartErrorMessage(String d) throws IOException {
209 String formFail = "<div class='formError'>";
210 int idx = d.indexOf(formFail);
214 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
218 public void registerUser(String firstName, String lastName, String email, String password) {
220 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";
221 String data = fetchStartErrorMessage(runRegister(query));
222 assertTrue(data, data.startsWith("</div>"));
223 } catch (UnsupportedEncodingException e) {
225 } catch (IOException e) {
230 public int createVerifiedUser(String firstName, String lastName, String email, String password) {
231 registerUser(firstName, lastName, email, password);
233 TestMail tm = ter.recieve();
234 String verifyLink = tm.extractLink();
235 String[] parts = verifyLink.split("\\?");
236 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
237 u.openStream().close();
239 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
240 ps.setString(1, email);
241 ResultSet rs = ps.executeQuery();
246 } catch (InterruptedException e) {
248 } catch (IOException e) {
250 } catch (SQLException e) {
256 * Creates a new user with 100 Assurance points given by an (invalid)
267 * @return a new userid.
269 public int createAssuranceUser(String firstName, String lastName, String email, String password) {
270 int uid = createVerifiedUser(firstName, lastName, email, password);
272 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
276 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
281 } catch (SQLException e) {
287 static int count = 0;
289 public static String createUniqueName() {
290 return "test" + System.currentTimeMillis() + "a" + (count++);
293 private String stripCookie(String headerField) {
294 return headerField.substring(0, headerField.indexOf(';'));
297 public static final String SECURE_REFERENCE = "/account/certs/email";
299 public boolean isLoggedin(String cookie) throws IOException {
300 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
301 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
302 huc.addRequestProperty("Cookie", cookie);
303 return huc.getResponseCode() == 200;
306 public String login(String email, String pw) throws IOException {
307 URL u = new URL("https://" + getServerName() + "/login");
308 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
309 huc.setDoOutput(true);
310 OutputStream os = huc.getOutputStream();
311 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
312 os.write(data.getBytes());
314 String headerField = huc.getHeaderField("Set-Cookie");
315 return stripCookie(headerField);
318 public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
320 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
321 authenticateClientCert(pk, ce, connection);
322 if (connection.getResponseCode() == 302) {
323 assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
324 return stripCookie(connection.getHeaderField("Set-Cookie"));
330 public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
331 KeyManager km = new X509KeyManager() {
334 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
339 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
344 public X509Certificate[] getCertificateChain(String arg0) {
345 return new X509Certificate[] {
351 public String[] getClientAliases(String arg0, Principal[] arg1) {
352 return new String[] {
358 public PrivateKey getPrivateKey(String arg0) {
359 if (arg0.equals("client")) {
366 public String[] getServerAliases(String arg0, Principal[] arg1) {
367 return new String[] {
372 SSLContext sc = SSLContext.getInstance("TLS");
373 sc.init(new KeyManager[] {
376 if (connection instanceof HttpsURLConnection) {
377 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
381 public String getCSRF(URLConnection u) throws IOException {
382 return getCSRF(u, 0);
385 public String getCSRF(URLConnection u, int formIndex) throws IOException {
386 String content = IOUtils.readURL(u);
387 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
388 Matcher m = p.matcher(content);
389 for (int i = 0; i < formIndex + 1; i++) {
391 throw new Error("No CSRF Token");
397 public static String[] generateCSR(String dn) throws IOException {
398 Process p = Runtime.getRuntime().exec(new String[] {
399 "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config", "keys/selfsign.config"
401 String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
403 String[] parts = csr.split("(?<=-----)\n(?=-----)");
404 if (parts.length != 2) {
405 System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream())));
411 public String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
412 return executeBasicWebInteraction(cookie, path, query, 0);
415 public String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
416 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
417 uc.addRequestProperty("Cookie", cookie);
418 String csrf = getCSRF(uc, formIndex);
420 uc = new URL("https://" + getServerName() + path).openConnection();
421 uc.addRequestProperty("Cookie", cookie);
422 uc.setDoOutput(true);
423 OutputStream os = uc.getOutputStream();
424 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
428 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
432 public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
433 EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u);
434 adrr.insert(Language.getInstance("en"));
435 TestMail testMail = getMailReciever().recieve();
436 assertTrue(adrr.getAddress().equals(testMail.getTo()));
437 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
439 getMailReciever().clearMails();