]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/ManagedTest.java
Factor out dummy password.
[gigi.git] / tests / org / cacert / gigi / testUtils / ManagedTest.java
1 package org.cacert.gigi.testUtils;
2
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertNotEquals;
5 import static org.junit.Assert.assertTrue;
6
7 import java.io.BufferedReader;
8 import java.io.DataOutputStream;
9 import java.io.FileInputStream;
10 import java.io.IOException;
11 import java.io.InputStreamReader;
12 import java.io.OutputStream;
13 import java.io.UnsupportedEncodingException;
14 import java.net.HttpURLConnection;
15 import java.net.InetSocketAddress;
16 import java.net.MalformedURLException;
17 import java.net.Socket;
18 import java.net.URL;
19 import java.net.URLConnection;
20 import java.net.URLEncoder;
21 import java.nio.file.Files;
22 import java.nio.file.Paths;
23 import java.security.KeyManagementException;
24 import java.security.NoSuchAlgorithmException;
25 import java.security.Principal;
26 import java.security.PrivateKey;
27 import java.security.cert.X509Certificate;
28 import java.sql.PreparedStatement;
29 import java.sql.ResultSet;
30 import java.sql.SQLException;
31 import java.util.Properties;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
35 import javax.net.ssl.HttpsURLConnection;
36 import javax.net.ssl.KeyManager;
37 import javax.net.ssl.SSLContext;
38 import javax.net.ssl.X509KeyManager;
39
40 import org.cacert.gigi.DevelLauncher;
41 import org.cacert.gigi.database.DatabaseConnection;
42 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
43 import org.cacert.gigi.util.DatabaseManager;
44 import org.cacert.gigi.util.SimpleSigner;
45 import org.junit.After;
46 import org.junit.AfterClass;
47 import org.junit.BeforeClass;
48
49 public class ManagedTest {
50         /**
51          * Some password that fullfills the password criteria.
52          */
53         protected static final String TEST_PASSWORD = "xvXV12°§";
54
55         private final String registerService = "/register";
56
57         private static TestEmailReciever ter;
58         private static Process gigi;
59         private static String url = "localhost:4443";
60
61         public static String getServerName() {
62                 return url;
63         }
64
65         static Properties testProps = new Properties();
66         static {
67                 InitTruststore.run();
68                 HttpURLConnection.setFollowRedirects(false);
69         }
70
71         @BeforeClass
72         public static void connectToServer() {
73                 try {
74                         testProps.load(new FileInputStream("config/test.properties"));
75                         if (!DatabaseConnection.isInited()) {
76                                 DatabaseConnection.init(testProps);
77                         }
78                         System.out.println("... purging Database");
79                         DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"),
80                                         testProps.getProperty("sql.user"), testProps.getProperty("sql.password") });
81
82                         String type = testProps.getProperty("type");
83                         if (type.equals("local")) {
84                                 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
85                                 String[] parts = testProps.getProperty("mail").split(":", 2);
86                                 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
87                                 return;
88                         }
89                         url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
90                         gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
91                         DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
92                         System.out.println("... starting server");
93                         Properties mainProps = new Properties();
94                         mainProps.setProperty("host", "127.0.0.1");
95                         mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
96                         mainProps.setProperty("name.www", testProps.getProperty("name.www"));
97                         mainProps.setProperty("name.static", testProps.getProperty("name.static"));
98
99                         mainProps.setProperty("port", testProps.getProperty("serverPort"));
100                         mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
101                         mainProps.setProperty("emailProvider.port", "8473");
102                         mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
103                         mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
104                         mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
105                         mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
106
107                         byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
108                         byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
109
110                         DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
111                                 keystore);
112                         toGigi.flush();
113
114                         final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
115                         String line;
116                         while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
117                         }
118                         new Thread() {
119                                 @Override
120                                 public void run() {
121                                         String line;
122                                         try {
123                                                 while ((line = br.readLine()) != null) {
124                                                         System.err.println(line);
125                                                 }
126                                         } catch (IOException e) {
127                                                 e.printStackTrace();
128                                         }
129                                 }
130                         }.start();
131                         if (line == null) {
132                                 throw new Error("Server startup failed");
133                         }
134                         ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
135                         SimpleSigner.runSigner();
136                 } catch (IOException e) {
137                         throw new Error(e);
138                 } catch (ClassNotFoundException e1) {
139                         e1.printStackTrace();
140                 } catch (SQLException e1) {
141                         e1.printStackTrace();
142                 } catch (InterruptedException e) {
143                         e.printStackTrace();
144                 }
145
146         }
147
148         @AfterClass
149         public static void tearDownServer() {
150                 String type = testProps.getProperty("type");
151                 ter.destroy();
152                 if (type.equals("local")) {
153                         return;
154                 }
155                 gigi.destroy();
156                 try {
157                         SimpleSigner.stopSigner();
158                 } catch (InterruptedException e) {
159                         e.printStackTrace();
160                 }
161         }
162
163         @After
164         public void removeMails() {
165                 ter.reset();
166         }
167
168         public TestMail waitForMail() {
169                 try {
170                         return ter.recieve();
171                 } catch (InterruptedException e) {
172                         throw new Error(e);
173                 }
174         }
175
176         public static TestEmailReciever getMailReciever() {
177                 return ter;
178         }
179
180         public String runRegister(String param) throws IOException {
181                 URL regist = new URL("https://" + getServerName() + registerService);
182                 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
183                 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
184
185                 String headerField = csrfConn.getHeaderField("Set-Cookie");
186                 headerField = stripCookie(headerField);
187
188                 String csrf = getCSRF(csrfConn);
189                 uc.addRequestProperty("Cookie", headerField);
190                 uc.setDoOutput(true);
191                 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
192                 String d = IOUtils.readURL(uc);
193                 return d;
194         }
195
196         public String fetchStartErrorMessage(String d) throws IOException {
197                 String formFail = "<div class='formError'>";
198                 int idx = d.indexOf(formFail);
199                 assertNotEquals(-1, idx);
200                 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
201                 return startError;
202         }
203
204         public void registerUser(String firstName, String lastName, String email, String password) {
205                 try {
206                         String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname="
207                                 + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1="
208                                 + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8")
209                                 + "&day=1&month=1&year=1910&cca_agree=1";
210                         String data = fetchStartErrorMessage(runRegister(query));
211                         assertTrue(data, data.startsWith("</div>"));
212                 } catch (UnsupportedEncodingException e) {
213                         throw new Error(e);
214                 } catch (IOException e) {
215                         throw new Error(e);
216                 }
217         }
218
219         public int createVerifiedUser(String firstName, String lastName, String email, String password) {
220                 registerUser(firstName, lastName, email, password);
221                 try {
222                         TestMail tm = ter.recieve();
223                         String verifyLink = tm.extractLink();
224                         String[] parts = verifyLink.split("\\?");
225                         URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
226                         u.openStream().close();
227                         ;
228                         PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
229                         ps.setString(1, email);
230                         ResultSet rs = ps.executeQuery();
231                         if (rs.next()) {
232                                 return rs.getInt(1);
233                         }
234                         throw new Error();
235                 } catch (InterruptedException e) {
236                         throw new Error(e);
237                 } catch (IOException e) {
238                         throw new Error(e);
239                 } catch (SQLException e) {
240                         throw new Error(e);
241                 }
242         }
243
244         /**
245          * Creates a new user with 100 Assurance points given by an (invalid)
246          * assurance.
247          * 
248          * @param firstName
249          *            the first name
250          * @param lastName
251          *            the last name
252          * @param email
253          *            the email
254          * @param password
255          *            the password
256          * @return a new userid.
257          */
258         public int createAssuranceUser(String firstName, String lastName, String email, String password) {
259                 int uid = createVerifiedUser(firstName, lastName, email, password);
260                 try {
261                         PreparedStatement ps = DatabaseConnection.getInstance().prepare(
262                                 "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
263                         ps.setInt(1, uid);
264                         ps.setInt(2, 0);
265                         ps.execute();
266                         ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
267                         ps.setInt(1, uid);
268                         ps.setInt(2, uid);
269                         ps.execute();
270
271                 } catch (SQLException e) {
272                         throw new Error(e);
273                 }
274                 return uid;
275         }
276
277         static int count = 0;
278
279         public String createUniqueName() {
280                 return "test" + System.currentTimeMillis() + "a" + (count++);
281         }
282
283         private String stripCookie(String headerField) {
284                 return headerField.substring(0, headerField.indexOf(';'));
285         }
286
287         public static final String SECURE_REFERENCE = "/account/certs/email";
288
289         public boolean isLoggedin(String cookie) throws IOException {
290                 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
291                 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
292                 huc.addRequestProperty("Cookie", cookie);
293                 return huc.getResponseCode() == 200;
294         }
295
296         public String login(String email, String pw) throws IOException {
297                 URL u = new URL("https://" + getServerName() + "/login");
298                 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
299                 huc.setDoOutput(true);
300                 OutputStream os = huc.getOutputStream();
301                 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
302                 os.write(data.getBytes());
303                 os.flush();
304                 String headerField = huc.getHeaderField("Set-Cookie");
305                 return stripCookie(headerField);
306         }
307
308         public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException,
309                 KeyManagementException, IOException, MalformedURLException {
310
311                 HttpURLConnection connection = (HttpURLConnection) new URL("https://"
312                         + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
313                 authenticateClientCert(pk, ce, connection);
314                 if (connection.getResponseCode() == 302) {
315                         assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/",
316                                 connection.getHeaderField("Location").replaceFirst(":443$", ""));
317                         return stripCookie(connection.getHeaderField("Set-Cookie"));
318                 } else {
319                         return null;
320                 }
321         }
322
323         public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection)
324                 throws NoSuchAlgorithmException, KeyManagementException {
325                 KeyManager km = new X509KeyManager() {
326
327                         @Override
328                         public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
329                                 return "client";
330                         }
331
332                         @Override
333                         public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
334                                 return null;
335                         }
336
337                         @Override
338                         public X509Certificate[] getCertificateChain(String arg0) {
339                                 return new X509Certificate[] { ce };
340                         }
341
342                         @Override
343                         public String[] getClientAliases(String arg0, Principal[] arg1) {
344                                 return new String[] { "client" };
345                         }
346
347                         @Override
348                         public PrivateKey getPrivateKey(String arg0) {
349                                 if (arg0.equals("client")) {
350                                         return pk;
351                                 }
352                                 return null;
353                         }
354
355                         @Override
356                         public String[] getServerAliases(String arg0, Principal[] arg1) {
357                                 return new String[] { "client" };
358                         }
359                 };
360                 SSLContext sc = SSLContext.getInstance("TLS");
361                 sc.init(new KeyManager[] { km }, null, null);
362                 if (connection instanceof HttpsURLConnection) {
363                         ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
364                 }
365         }
366
367         public String getCSRF(URLConnection u) throws IOException {
368                 String content = IOUtils.readURL(u);
369                 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
370                 Matcher m = p.matcher(content);
371                 if (!m.find()) {
372                         throw new Error("No CSRF Token");
373                 }
374                 return m.group(1);
375         }
376
377         public static String[] generateCSR(String dn) throws IOException {
378                 Process p = Runtime.getRuntime().exec(
379                         new String[] { "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config",
380                                         "keys/selfsign.config" });
381                 String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
382
383                 String[] parts = csr.split("(?<=-----)\n(?=-----)");
384                 if (parts.length != 2) {
385                         System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream())));
386                         throw new Error();
387                 }
388                 return parts;
389         }
390
391 }