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