]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/ManagedTest.java
869d417a47b7b932795e3bb6d32e20f075345cb0
[gigi.git] / tests / org / cacert / gigi / testUtils / ManagedTest.java
1 package org.cacert.gigi.testUtils;
2
3 import static org.junit.Assert.assertNotEquals;
4 import static org.junit.Assert.assertTrue;
5
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;
15 import java.net.URL;
16 import java.net.URLEncoder;
17 import java.nio.file.Files;
18 import java.nio.file.Paths;
19 import java.sql.PreparedStatement;
20 import java.sql.ResultSet;
21 import java.sql.SQLException;
22 import java.util.Properties;
23
24 import org.cacert.gigi.DevelLauncher;
25 import org.cacert.gigi.database.DatabaseConnection;
26 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
27 import org.cacert.gigi.util.DatabaseManager;
28 import org.junit.After;
29 import org.junit.AfterClass;
30 import org.junit.BeforeClass;
31
32 public class ManagedTest {
33         private final String registerService = "/register";
34
35         private static TestEmailReciever ter;
36         private static Process gigi;
37         private static String url = "localhost:4443";
38
39         public static String getServerName() {
40                 return url;
41         }
42         static Properties testProps = new Properties();
43         static {
44                 InitTruststore.run();
45                 HttpURLConnection.setFollowRedirects(false);
46         }
47
48         @BeforeClass
49         public static void connectToServer() {
50                 try {
51                         testProps.load(new FileInputStream("config/test.properties"));
52                         if (!DatabaseConnection.isInited()) {
53                                 DatabaseConnection.init(testProps);
54                         }
55                         System.out.println("... purging Database");
56                         DatabaseManager.run(new String[]{
57                                         testProps.getProperty("sql.driver"),
58                                         testProps.getProperty("sql.url"),
59                                         testProps.getProperty("sql.user"),
60                                         testProps.getProperty("sql.password")});
61
62                         String type = testProps.getProperty("type");
63                         if (type.equals("local")) {
64                                 url = testProps.getProperty("server");
65                                 String[] parts = testProps.getProperty("mail").split(":", 2);
66                                 ter = new TestEmailReciever(new InetSocketAddress(parts[0],
67                                                 Integer.parseInt(parts[1])));
68                                 return;
69                         }
70                         url = testProps.getProperty("name.www") + ":"
71                                         + testProps.getProperty("serverPort");
72                         gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
73                         DataOutputStream toGigi = new DataOutputStream(
74                                         gigi.getOutputStream());
75                         System.out.println("... starting server");
76                         Properties mainProps = new Properties();
77                         mainProps.setProperty("host", "127.0.0.1");
78                         mainProps.setProperty("name.secure", "sec");
79                         mainProps
80                                         .setProperty("name.www", testProps.getProperty("name.www"));
81                         mainProps.setProperty("name.static", "stat");
82
83                         mainProps.setProperty("port", testProps.getProperty("serverPort"));
84                         mainProps.setProperty("emailProvider",
85                                         "org.cacert.gigi.email.TestEmailProvider");
86                         mainProps.setProperty("emailProvider.port", "8473");
87                         mainProps.setProperty("sql.driver",
88                                         testProps.getProperty("sql.driver"));
89                         mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
90                         mainProps
91                                         .setProperty("sql.user", testProps.getProperty("sql.user"));
92                         mainProps.setProperty("sql.password",
93                                         testProps.getProperty("sql.password"));
94
95                         byte[] cacerts = Files
96                                         .readAllBytes(Paths.get("config/cacerts.jks"));
97                         byte[] keystore = Files.readAllBytes(Paths
98                                         .get("config/keystore.pkcs12"));
99
100                         DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(),
101                                         "changeit".getBytes(), mainProps, cacerts, keystore);
102                         toGigi.flush();
103
104                         final BufferedReader br = new BufferedReader(new InputStreamReader(
105                                         gigi.getErrorStream()));
106                         String line;
107                         while ((line = br.readLine()) != null
108                                         && !line.contains("Server:main: Started")) {
109                                 System.err.println(line);
110                         }
111                         new Thread() {
112                                 @Override
113                                 public void run() {
114                                         String line;
115                                         try {
116                                                 while ((line = br.readLine()) != null) {
117                                                         System.err.println(line);
118                                                 }
119                                         } catch (IOException e) {
120                                                 e.printStackTrace();
121                                         }
122                                 }
123                         }.start();
124                         System.err.println(line);
125                         if (line == null) {
126                                 throw new Error("Server startup failed");
127                         }
128                         ter = new TestEmailReciever(
129                                         new InetSocketAddress("localhost", 8473));
130                 } catch (IOException e) {
131                         throw new Error(e);
132                 } catch (ClassNotFoundException e1) {
133                         e1.printStackTrace();
134                 } catch (SQLException e1) {
135                         e1.printStackTrace();
136                 }
137
138         }
139         @AfterClass
140         public static void tearDownServer() {
141                 String type = testProps.getProperty("type");
142                 if (type.equals("local")) {
143                         return;
144                 }
145                 gigi.destroy();
146         }
147
148         @After
149         public void removeMails() {
150                 ter.reset();
151         }
152
153         public TestMail waitForMail() {
154                 try {
155                         return ter.recieve();
156                 } catch (InterruptedException e) {
157                         throw new Error(e);
158                 }
159         }
160         public static TestEmailReciever getMailReciever() {
161                 return ter;
162         }
163         public String runRegister(String param) throws IOException {
164                 HttpURLConnection uc = (HttpURLConnection) new URL("https://"
165                                 + getServerName() + registerService).openConnection();
166                 uc.setDoOutput(true);
167                 uc.getOutputStream().write(param.getBytes());
168                 String d = IOUtils.readURL(uc);
169                 return d;
170         }
171         public String fetchStartErrorMessage(String d) throws IOException {
172                 String formFail = "<div class='formError'>";
173                 int idx = d.indexOf(formFail);
174                 assertNotEquals(-1, idx);
175                 String startError = d.substring(idx + formFail.length(), idx + 100)
176                                 .trim();
177                 return startError;
178         }
179
180         public void registerUser(String firstName, String lastName, String email,
181                         String password) {
182                 try {
183                         String query = "fname=" + URLEncoder.encode(firstName, "UTF-8")
184                                         + "&lname=" + URLEncoder.encode(lastName, "UTF-8")
185                                         + "&email=" + URLEncoder.encode(email, "UTF-8")
186                                         + "&pword1=" + URLEncoder.encode(password, "UTF-8")
187                                         + "&pword2=" + URLEncoder.encode(password, "UTF-8")
188                                         + "&day=1&month=1&year=1910&cca_agree=1";
189                         String data = fetchStartErrorMessage(runRegister(query));
190                         assertTrue(data, data.startsWith("</div>"));
191                 } catch (UnsupportedEncodingException e) {
192                         throw new Error(e);
193                 } catch (IOException e) {
194                         throw new Error(e);
195                 }
196         }
197         public int createVerifiedUser(String firstName, String lastName,
198                         String email, String password) {
199                 registerUser(firstName, lastName, email, password);
200                 try {
201                         TestMail tm = ter.recieve();
202                         String verifyLink = tm.extractLink();
203                         String[] parts = verifyLink.split("\\?");
204                         URL u = new URL("https://" + getServerName() + "/verify?"
205                                         + parts[1]);
206                         u.openStream().close();;
207                         PreparedStatement ps = DatabaseConnection.getInstance().prepare(
208                                         "SELECT id FROM users where email=?");
209                         ps.setString(1, email);
210                         ResultSet rs = ps.executeQuery();
211                         if (rs.next()) {
212                                 return rs.getInt(1);
213                         }
214                         throw new Error();
215                 } catch (InterruptedException e) {
216                         throw new Error(e);
217                 } catch (IOException e) {
218                         throw new Error(e);
219                 } catch (SQLException e) {
220                         throw new Error(e);
221                 }
222         }
223         public int createAssuranceUser(String firstName, String lastName,
224                         String email, String password) {
225                 int uid = createVerifiedUser(firstName, lastName, email, password);
226                 try {
227                         PreparedStatement ps = DatabaseConnection
228                                         .getInstance()
229                                         .prepare(
230                                                         "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
231                         ps.setInt(1, uid);
232                         ps.setInt(2, 0);
233                         ps.execute();
234                         ps = DatabaseConnection.getInstance().prepare(
235                                         "INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
236                         ps.setInt(1, uid);
237                         ps.setInt(2, uid);
238                         ps.execute();
239
240                 } catch (SQLException e) {
241                         throw new Error(e);
242                 }
243                 return uid;
244         }
245         static int count = 0;
246         public String createUniqueName() {
247                 return "test" + System.currentTimeMillis() + "a" + (count++);
248         }
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")
255                                 + "&password=" + URLEncoder.encode(pw, "UTF-8");
256                 os.write(data.getBytes());
257                 os.flush();
258                 String headerField = huc.getHeaderField("Set-Cookie");
259                 headerField = headerField.substring(0, headerField.indexOf(';'));
260                 return headerField;
261         }
262 }