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.junit.After;
32 import org.junit.AfterClass;
33 import org.junit.BeforeClass;
35 public class ManagedTest {
36 private final String registerService = "/register";
38 private static TestEmailReciever ter;
39 private static Process gigi;
40 private static String url = "localhost:4443";
42 public static String getServerName() {
45 static Properties testProps = new Properties();
48 HttpURLConnection.setFollowRedirects(false);
52 public static void connectToServer() {
54 testProps.load(new FileInputStream("config/test.properties"));
55 if (!DatabaseConnection.isInited()) {
56 DatabaseConnection.init(testProps);
58 System.out.println("... purging Database");
59 DatabaseManager.run(new String[]{
60 testProps.getProperty("sql.driver"),
61 testProps.getProperty("sql.url"),
62 testProps.getProperty("sql.user"),
63 testProps.getProperty("sql.password")});
65 String type = testProps.getProperty("type");
66 if (type.equals("local")) {
67 url = testProps.getProperty("server");
68 String[] parts = testProps.getProperty("mail").split(":", 2);
69 ter = new TestEmailReciever(new InetSocketAddress(parts[0],
70 Integer.parseInt(parts[1])));
73 url = testProps.getProperty("name.www") + ":"
74 + testProps.getProperty("serverPort");
75 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
76 DataOutputStream toGigi = new DataOutputStream(
77 gigi.getOutputStream());
78 System.out.println("... starting server");
79 Properties mainProps = new Properties();
80 mainProps.setProperty("host", "127.0.0.1");
81 mainProps.setProperty("name.secure", "sec");
83 .setProperty("name.www", testProps.getProperty("name.www"));
84 mainProps.setProperty("name.static", "stat");
86 mainProps.setProperty("port", testProps.getProperty("serverPort"));
87 mainProps.setProperty("emailProvider",
88 "org.cacert.gigi.email.TestEmailProvider");
89 mainProps.setProperty("emailProvider.port", "8473");
90 mainProps.setProperty("sql.driver",
91 testProps.getProperty("sql.driver"));
92 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
94 .setProperty("sql.user", testProps.getProperty("sql.user"));
95 mainProps.setProperty("sql.password",
96 testProps.getProperty("sql.password"));
98 byte[] cacerts = Files
99 .readAllBytes(Paths.get("config/cacerts.jks"));
100 byte[] keystore = Files.readAllBytes(Paths
101 .get("config/keystore.pkcs12"));
103 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(),
104 "changeit".getBytes(), mainProps, cacerts, keystore);
107 final BufferedReader br = new BufferedReader(new InputStreamReader(
108 gigi.getErrorStream()));
110 while ((line = br.readLine()) != null
111 && !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(
130 new InetSocketAddress("localhost", 8473));
131 } catch (IOException e) {
133 } catch (ClassNotFoundException e1) {
134 e1.printStackTrace();
135 } catch (SQLException e1) {
136 e1.printStackTrace();
141 public static void tearDownServer() {
142 String type = testProps.getProperty("type");
144 if (type.equals("local")) {
150 public void removeMails() {
154 public TestMail waitForMail() {
156 return ter.recieve();
157 } catch (InterruptedException e) {
161 public static TestEmailReciever getMailReciever() {
164 public String runRegister(String param) throws IOException {
165 HttpURLConnection uc = (HttpURLConnection) new URL("https://"
166 + getServerName() + registerService).openConnection();
167 uc.setDoOutput(true);
168 uc.getOutputStream().write(param.getBytes());
169 String d = IOUtils.readURL(uc);
172 public String fetchStartErrorMessage(String d) throws IOException {
173 String formFail = "<div class='formError'>";
174 int idx = d.indexOf(formFail);
175 assertNotEquals(-1, idx);
176 String startError = d.substring(idx + formFail.length(), idx + 100)
181 public void registerUser(String firstName, String lastName, String email,
184 String query = "fname=" + URLEncoder.encode(firstName, "UTF-8")
185 + "&lname=" + URLEncoder.encode(lastName, "UTF-8")
186 + "&email=" + URLEncoder.encode(email, "UTF-8")
187 + "&pword1=" + URLEncoder.encode(password, "UTF-8")
188 + "&pword2=" + URLEncoder.encode(password, "UTF-8")
189 + "&day=1&month=1&year=1910&cca_agree=1";
190 String data = fetchStartErrorMessage(runRegister(query));
191 assertTrue(data, data.startsWith("</div>"));
192 } catch (UnsupportedEncodingException e) {
194 } catch (IOException e) {
198 public int createVerifiedUser(String firstName, String lastName,
199 String email, String password) {
200 registerUser(firstName, lastName, email, password);
202 TestMail tm = ter.recieve();
203 String verifyLink = tm.extractLink();
204 String[] parts = verifyLink.split("\\?");
205 URL u = new URL("https://" + getServerName() + "/verify?"
207 u.openStream().close();;
208 PreparedStatement ps = DatabaseConnection.getInstance().prepare(
209 "SELECT id FROM users where email=?");
210 ps.setString(1, email);
211 ResultSet rs = ps.executeQuery();
216 } catch (InterruptedException e) {
218 } catch (IOException e) {
220 } catch (SQLException e) {
225 * Creates a new user with 100 Assurance points given by an (invalid)
236 * @return a new userid.
238 public int createAssuranceUser(String firstName, String lastName,
239 String email, String password) {
240 int uid = createVerifiedUser(firstName, lastName, email, password);
242 PreparedStatement ps = DatabaseConnection
245 "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
249 ps = DatabaseConnection.getInstance().prepare(
250 "INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
255 } catch (SQLException e) {
260 static int count = 0;
261 public String createUniqueName() {
262 return "test" + System.currentTimeMillis() + "a" + (count++);
264 public String login(String email, String pw) throws IOException {
265 URL u = new URL("https://" + getServerName() + "/login");
266 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
267 huc.setDoOutput(true);
268 OutputStream os = huc.getOutputStream();
269 String data = "username=" + URLEncoder.encode(email, "UTF-8")
270 + "&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='csrf' value='([^']+)'>");
281 Matcher m = p.matcher(content);
283 throw new Error("New CSRF Token");