1 package org.cacert.gigi.testUtils;
3 import static org.junit.Assert.*;
5 import java.io.BufferedReader;
6 import java.io.DataOutputStream;
7 import java.io.FileInputStream;
8 import java.io.IOException;
9 import java.io.InputStreamReader;
10 import java.io.OutputStream;
11 import java.io.UnsupportedEncodingException;
12 import java.net.HttpURLConnection;
13 import java.net.InetSocketAddress;
14 import java.net.MalformedURLException;
15 import java.net.Socket;
17 import java.net.URLConnection;
18 import java.net.URLEncoder;
19 import java.nio.file.Files;
20 import java.nio.file.Paths;
21 import java.security.GeneralSecurityException;
22 import java.security.KeyManagementException;
23 import java.security.KeyPair;
24 import java.security.KeyPairGenerator;
25 import java.security.NoSuchAlgorithmException;
26 import java.security.Principal;
27 import java.security.PrivateKey;
28 import java.security.Signature;
29 import java.security.cert.X509Certificate;
30 import java.sql.PreparedStatement;
31 import java.sql.ResultSet;
32 import java.sql.SQLException;
33 import java.util.Properties;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
37 import javax.net.ssl.HttpsURLConnection;
38 import javax.net.ssl.KeyManager;
39 import javax.net.ssl.SSLContext;
40 import javax.net.ssl.X509KeyManager;
42 import org.cacert.gigi.DevelLauncher;
43 import org.cacert.gigi.EmailAddress;
44 import org.cacert.gigi.GigiApiException;
45 import org.cacert.gigi.Language;
46 import org.cacert.gigi.User;
47 import org.cacert.gigi.database.DatabaseConnection;
48 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
49 import org.cacert.gigi.util.DatabaseManager;
50 import org.cacert.gigi.util.PEM;
51 import org.cacert.gigi.util.ServerConstants;
52 import org.cacert.gigi.util.SimpleSigner;
53 import org.junit.After;
54 import org.junit.AfterClass;
55 import org.junit.BeforeClass;
57 import sun.security.pkcs10.PKCS10;
58 import sun.security.pkcs10.PKCS10Attributes;
59 import sun.security.x509.X500Name;
61 public class ManagedTest {
64 * Some password that fullfills the password criteria.
66 protected static final String TEST_PASSWORD = "xvXV12°§";
68 private final String registerService = "/register";
70 private static TestEmailReciever ter;
72 private static Process gigi;
74 private static String url = "localhost:4443";
76 public static String getServerName() {
80 static Properties testProps = new Properties();
83 HttpURLConnection.setFollowRedirects(false);
87 public static void connectToServer() {
89 testProps.load(new FileInputStream("config/test.properties"));
90 if ( !DatabaseConnection.isInited()) {
91 DatabaseConnection.init(testProps);
93 System.out.println("... purging Database");
94 DatabaseManager.run(new String[] {
95 testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
97 String type = testProps.getProperty("type");
98 Properties mainProps = generateMainProps();
99 ServerConstants.init(mainProps);
100 if (type.equals("local")) {
101 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
102 String[] parts = testProps.getProperty("mail").split(":", 2);
103 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
106 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
107 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
108 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
109 System.out.println("... starting server");
111 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
112 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
114 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
117 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
119 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
127 while ((line = br.readLine()) != null) {
128 System.err.println(line);
130 } catch (IOException e) {
136 throw new Error("Server startup failed");
138 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
139 SimpleSigner.runSigner();
140 } catch (IOException e) {
142 } catch (ClassNotFoundException e1) {
143 e1.printStackTrace();
144 } catch (SQLException e1) {
145 e1.printStackTrace();
146 } catch (InterruptedException e) {
152 private static Properties generateMainProps() {
153 Properties mainProps = new Properties();
154 mainProps.setProperty("host", "127.0.0.1");
155 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
156 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
157 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
159 mainProps.setProperty("port", testProps.getProperty("serverPort"));
160 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
161 mainProps.setProperty("emailProvider.port", "8473");
162 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
163 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
164 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
165 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
170 public static void tearDownServer() {
171 String type = testProps.getProperty("type");
173 if (type.equals("local")) {
178 SimpleSigner.stopSigner();
179 } catch (InterruptedException e) {
185 public void removeMails() {
189 public TestMail waitForMail() {
191 return ter.recieve();
192 } catch (InterruptedException e) {
197 public static TestEmailReciever getMailReciever() {
201 public String runRegister(String param) throws IOException {
202 URL regist = new URL("https://" + getServerName() + registerService);
203 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
204 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
206 String headerField = csrfConn.getHeaderField("Set-Cookie");
207 headerField = stripCookie(headerField);
209 String csrf = getCSRF(csrfConn);
210 uc.addRequestProperty("Cookie", headerField);
211 uc.setDoOutput(true);
212 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
213 String d = IOUtils.readURL(uc);
217 public String fetchStartErrorMessage(String d) throws IOException {
218 String formFail = "<div class='formError'>";
219 int idx = d.indexOf(formFail);
223 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
227 public void registerUser(String firstName, String lastName, String email, String password) {
229 String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname=" + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1=" + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8") + "&day=1&month=1&year=1910&cca_agree=1";
230 String data = fetchStartErrorMessage(runRegister(query));
231 assertTrue(data, data.startsWith("</div>"));
232 } catch (UnsupportedEncodingException e) {
234 } catch (IOException e) {
239 public int createVerifiedUser(String firstName, String lastName, String email, String password) {
240 registerUser(firstName, lastName, email, password);
242 TestMail tm = ter.recieve();
243 String verifyLink = tm.extractLink();
244 String[] parts = verifyLink.split("\\?");
245 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
246 u.openStream().close();
248 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
249 ps.setString(1, email);
250 ResultSet rs = ps.executeQuery();
255 } catch (InterruptedException e) {
257 } catch (IOException e) {
259 } catch (SQLException e) {
265 * Creates a new user with 100 Assurance points given by an (invalid)
276 * @return a new userid.
278 public int createAssuranceUser(String firstName, String lastName, String email, String password) {
279 int uid = createVerifiedUser(firstName, lastName, email, password);
281 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
285 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
290 } catch (SQLException e) {
296 static int count = 0;
298 public static String createUniqueName() {
299 return "test" + System.currentTimeMillis() + "a" + (count++);
302 private String stripCookie(String headerField) {
303 return headerField.substring(0, headerField.indexOf(';'));
306 public static final String SECURE_REFERENCE = "/account/certs/email";
308 public boolean isLoggedin(String cookie) throws IOException {
309 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
310 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
311 huc.addRequestProperty("Cookie", cookie);
312 return huc.getResponseCode() == 200;
315 public String login(String email, String pw) throws IOException {
316 URL u = new URL("https://" + getServerName() + "/login");
317 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
318 huc.setDoOutput(true);
319 OutputStream os = huc.getOutputStream();
320 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
321 os.write(data.getBytes());
323 String headerField = huc.getHeaderField("Set-Cookie");
324 return stripCookie(headerField);
327 public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
329 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
330 authenticateClientCert(pk, ce, connection);
331 if (connection.getResponseCode() == 302) {
332 assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
333 return stripCookie(connection.getHeaderField("Set-Cookie"));
339 public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
340 KeyManager km = new X509KeyManager() {
343 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
348 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
353 public X509Certificate[] getCertificateChain(String arg0) {
354 return new X509Certificate[] {
360 public String[] getClientAliases(String arg0, Principal[] arg1) {
361 return new String[] {
367 public PrivateKey getPrivateKey(String arg0) {
368 if (arg0.equals("client")) {
375 public String[] getServerAliases(String arg0, Principal[] arg1) {
376 return new String[] {
381 SSLContext sc = SSLContext.getInstance("TLS");
382 sc.init(new KeyManager[] {
385 if (connection instanceof HttpsURLConnection) {
386 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
390 public String getCSRF(URLConnection u) throws IOException {
391 return getCSRF(u, 0);
394 public String getCSRF(URLConnection u, int formIndex) throws IOException {
395 String content = IOUtils.readURL(u);
396 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
397 Matcher m = p.matcher(content);
398 for (int i = 0; i < formIndex + 1; i++) {
400 throw new Error("No CSRF Token");
406 public static KeyPair generateKeypair() throws GeneralSecurityException {
407 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
408 kpg.initialize(4096);
409 return kpg.generateKeyPair();
412 public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
413 PKCS10 p10 = new PKCS10(kp.getPublic(), new PKCS10Attributes());
414 Signature s = Signature.getInstance("SHA256WithRSA");
415 s.initSign(kp.getPrivate());
416 p10.encodeAndSign(new X500Name(dn), s);
417 return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
420 public String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
421 return executeBasicWebInteraction(cookie, path, query, 0);
424 public String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
425 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
426 uc.addRequestProperty("Cookie", cookie);
427 String csrf = getCSRF(uc, formIndex);
429 uc = new URL("https://" + getServerName() + path).openConnection();
430 uc.addRequestProperty("Cookie", cookie);
431 uc.setDoOutput(true);
432 OutputStream os = uc.getOutputStream();
433 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
437 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
441 public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
442 EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u);
443 adrr.insert(Language.getInstance("en"));
444 TestMail testMail = getMailReciever().recieve();
445 assertTrue(adrr.getAddress().equals(testMail.getTo()));
446 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
448 getMailReciever().clearMails();