1 package org.cacert.gigi.testUtils;
3 import static org.junit.Assert.assertNotEquals;
4 import static org.junit.Assert.assertTrue;
6 import java.io.BufferedReader;
7 import java.io.DataOutputStream;
8 import java.io.FileInputStream;
9 import java.io.IOException;
10 import java.io.InputStreamReader;
11 import java.io.OutputStream;
12 import java.io.UnsupportedEncodingException;
13 import java.net.HttpURLConnection;
14 import java.net.InetSocketAddress;
16 import java.net.URLConnection;
17 import java.net.URLEncoder;
18 import java.nio.file.Files;
19 import java.nio.file.Paths;
20 import java.sql.PreparedStatement;
21 import java.sql.ResultSet;
22 import java.sql.SQLException;
23 import java.util.Properties;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
27 import org.cacert.gigi.DevelLauncher;
28 import org.cacert.gigi.database.DatabaseConnection;
29 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
30 import org.cacert.gigi.util.DatabaseManager;
31 import org.cacert.gigi.util.SimpleSigner;
32 import org.junit.After;
33 import org.junit.AfterClass;
34 import org.junit.BeforeClass;
36 public class ManagedTest {
37 private final String registerService = "/register";
39 private static TestEmailReciever ter;
40 private static Process gigi;
41 private static String url = "localhost:4443";
43 public static String getServerName() {
47 static Properties testProps = new Properties();
50 HttpURLConnection.setFollowRedirects(false);
54 public static void connectToServer() {
56 testProps.load(new FileInputStream("config/test.properties"));
57 if (!DatabaseConnection.isInited()) {
58 DatabaseConnection.init(testProps);
60 System.out.println("... purging Database");
61 DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"),
62 testProps.getProperty("sql.user"), testProps.getProperty("sql.password") });
64 String type = testProps.getProperty("type");
65 if (type.equals("local")) {
66 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
67 String[] parts = testProps.getProperty("mail").split(":", 2);
68 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
71 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
72 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
73 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
74 System.out.println("... starting server");
75 Properties mainProps = new Properties();
76 mainProps.setProperty("host", "127.0.0.1");
77 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
78 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
79 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
81 mainProps.setProperty("port", testProps.getProperty("serverPort"));
82 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
83 mainProps.setProperty("emailProvider.port", "8473");
84 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
85 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
86 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
87 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
89 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
90 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
92 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
96 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
98 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
105 while ((line = br.readLine()) != null) {
106 System.err.println(line);
108 } catch (IOException e) {
114 throw new Error("Server startup failed");
116 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
117 SimpleSigner.runSigner();
118 } catch (IOException e) {
120 } catch (ClassNotFoundException e1) {
121 e1.printStackTrace();
122 } catch (SQLException e1) {
123 e1.printStackTrace();
124 } catch (InterruptedException e) {
131 public static void tearDownServer() {
132 String type = testProps.getProperty("type");
134 if (type.equals("local")) {
139 SimpleSigner.stopSigner();
140 } catch (InterruptedException e) {
146 public void removeMails() {
150 public TestMail waitForMail() {
152 return ter.recieve();
153 } catch (InterruptedException e) {
158 public static TestEmailReciever getMailReciever() {
162 public String runRegister(String param) throws IOException {
163 URL regist = new URL("https://" + getServerName() + registerService);
164 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
165 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
167 String headerField = csrfConn.getHeaderField("Set-Cookie");
168 headerField = headerField.substring(0, headerField.indexOf(';'));
170 String csrf = getCSRF(csrfConn);
171 uc.addRequestProperty("Cookie", headerField);
172 uc.setDoOutput(true);
173 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
174 String d = IOUtils.readURL(uc);
178 public String fetchStartErrorMessage(String d) throws IOException {
179 String formFail = "<div class='formError'>";
180 int idx = d.indexOf(formFail);
181 assertNotEquals(-1, idx);
182 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
186 public void registerUser(String firstName, String lastName, String email, String password) {
188 String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname="
189 + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1="
190 + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8")
191 + "&day=1&month=1&year=1910&cca_agree=1";
192 String data = fetchStartErrorMessage(runRegister(query));
193 assertTrue(data, data.startsWith("</div>"));
194 } catch (UnsupportedEncodingException e) {
196 } catch (IOException e) {
201 public int createVerifiedUser(String firstName, String lastName, String email, String password) {
202 registerUser(firstName, lastName, email, password);
204 TestMail tm = ter.recieve();
205 String verifyLink = tm.extractLink();
206 String[] parts = verifyLink.split("\\?");
207 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
208 u.openStream().close();
210 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
211 ps.setString(1, email);
212 ResultSet rs = ps.executeQuery();
217 } catch (InterruptedException e) {
219 } catch (IOException e) {
221 } catch (SQLException e) {
227 * Creates a new user with 100 Assurance points given by an (invalid)
238 * @return a new userid.
240 public int createAssuranceUser(String firstName, String lastName, String email, String password) {
241 int uid = createVerifiedUser(firstName, lastName, email, password);
243 PreparedStatement ps = DatabaseConnection.getInstance().prepare(
244 "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
248 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
253 } catch (SQLException e) {
259 static int count = 0;
261 public String createUniqueName() {
262 return "test" + System.currentTimeMillis() + "a" + (count++);
265 public String login(String email, String pw) throws IOException {
266 URL u = new URL("https://" + getServerName() + "/login");
267 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
268 huc.setDoOutput(true);
269 OutputStream os = huc.getOutputStream();
270 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
271 os.write(data.getBytes());
273 String headerField = huc.getHeaderField("Set-Cookie");
274 headerField = headerField.substring(0, headerField.indexOf(';'));
278 public String getCSRF(URLConnection u) throws IOException {
279 String content = IOUtils.readURL(u);
280 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
281 Matcher m = p.matcher(content);
283 throw new Error("No CSRF Token");
288 public static String[] generateCSR(String dn) throws IOException {
289 Process p = Runtime.getRuntime().exec(
290 new String[] { "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config",
291 "keys/selfsign.config" });
292 String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
294 String[] parts = csr.split("(?<=-----)\n(?=-----)");
295 if (parts.length != 2) {
296 System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream())));