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() {
46 static Properties testProps = new Properties();
49 HttpURLConnection.setFollowRedirects(false);
53 public static void connectToServer() {
55 testProps.load(new FileInputStream("config/test.properties"));
56 if (!DatabaseConnection.isInited()) {
57 DatabaseConnection.init(testProps);
59 System.out.println("... purging Database");
60 DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"),
61 testProps.getProperty("sql.user"), testProps.getProperty("sql.password") });
63 String type = testProps.getProperty("type");
64 if (type.equals("local")) {
65 url = testProps.getProperty("server");
66 String[] parts = testProps.getProperty("mail").split(":", 2);
67 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
70 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
71 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
72 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
73 System.out.println("... starting server");
74 Properties mainProps = new Properties();
75 mainProps.setProperty("host", "127.0.0.1");
76 mainProps.setProperty("name.secure", "sec");
77 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
78 mainProps.setProperty("name.static", "stat");
80 mainProps.setProperty("port", testProps.getProperty("serverPort"));
81 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
82 mainProps.setProperty("emailProvider.port", "8473");
83 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
84 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
85 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
86 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
88 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
89 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
91 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
95 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
97 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
104 while ((line = br.readLine()) != null) {
105 System.err.println(line);
107 } catch (IOException e) {
113 throw new Error("Server startup failed");
115 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
116 } catch (IOException e) {
118 } catch (ClassNotFoundException e1) {
119 e1.printStackTrace();
120 } catch (SQLException e1) {
121 e1.printStackTrace();
127 public static void tearDownServer() {
128 String type = testProps.getProperty("type");
130 if (type.equals("local")) {
137 public void removeMails() {
141 public TestMail waitForMail() {
143 return ter.recieve();
144 } catch (InterruptedException e) {
149 public static TestEmailReciever getMailReciever() {
153 public String runRegister(String param) throws IOException {
154 HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName() + registerService)
156 uc.setDoOutput(true);
157 uc.getOutputStream().write(param.getBytes());
158 String d = IOUtils.readURL(uc);
162 public String fetchStartErrorMessage(String d) throws IOException {
163 String formFail = "<div class='formError'>";
164 int idx = d.indexOf(formFail);
165 assertNotEquals(-1, idx);
166 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
170 public void registerUser(String firstName, String lastName, String email, String password) {
172 String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname="
173 + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1="
174 + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8")
175 + "&day=1&month=1&year=1910&cca_agree=1";
176 String data = fetchStartErrorMessage(runRegister(query));
177 assertTrue(data, data.startsWith("</div>"));
178 } catch (UnsupportedEncodingException e) {
180 } catch (IOException e) {
185 public int createVerifiedUser(String firstName, String lastName, String email, String password) {
186 registerUser(firstName, lastName, email, password);
188 TestMail tm = ter.recieve();
189 String verifyLink = tm.extractLink();
190 String[] parts = verifyLink.split("\\?");
191 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
192 u.openStream().close();
194 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
195 ps.setString(1, email);
196 ResultSet rs = ps.executeQuery();
201 } catch (InterruptedException e) {
203 } catch (IOException e) {
205 } catch (SQLException e) {
211 * Creates a new user with 100 Assurance points given by an (invalid)
222 * @return a new userid.
224 public int createAssuranceUser(String firstName, String lastName, String email, String password) {
225 int uid = createVerifiedUser(firstName, lastName, email, password);
227 PreparedStatement ps = DatabaseConnection.getInstance().prepare(
228 "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
232 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
237 } catch (SQLException e) {
243 static int count = 0;
245 public String createUniqueName() {
246 return "test" + System.currentTimeMillis() + "a" + (count++);
249 public String login(String email, String pw) throws IOException {
250 URL u = new URL("https://" + getServerName() + "/login");
251 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
252 huc.setDoOutput(true);
253 OutputStream os = huc.getOutputStream();
254 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
255 os.write(data.getBytes());
257 String headerField = huc.getHeaderField("Set-Cookie");
258 headerField = headerField.substring(0, headerField.indexOf(';'));
262 public String getCSRF(URLConnection u) throws IOException {
263 String content = IOUtils.readURL(u);
264 Pattern p = Pattern.compile("<input type='csrf' value='([^']+)'>");
265 Matcher m = p.matcher(content);
267 throw new Error("New CSRF Token");