1 package club.wpia.gigi.testUtils;
3 import static org.junit.Assert.*;
5 import java.io.BufferedReader;
6 import java.io.DataOutputStream;
7 import java.io.IOException;
8 import java.io.InputStreamReader;
9 import java.io.OutputStream;
10 import java.io.UnsupportedEncodingException;
11 import java.net.HttpURLConnection;
12 import java.net.InetSocketAddress;
13 import java.net.MalformedURLException;
14 import java.net.Socket;
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.security.GeneralSecurityException;
21 import java.security.KeyManagementException;
22 import java.security.KeyPair;
23 import java.security.NoSuchAlgorithmException;
24 import java.security.Principal;
25 import java.security.PrivateKey;
26 import java.security.cert.X509Certificate;
27 import java.sql.SQLException;
28 import java.util.Locale;
29 import java.util.Map.Entry;
30 import java.util.Properties;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
34 import javax.net.ssl.HttpsURLConnection;
35 import javax.net.ssl.KeyManager;
36 import javax.net.ssl.SSLContext;
37 import javax.net.ssl.X509KeyManager;
39 import org.hamcrest.CoreMatchers;
40 import org.junit.After;
41 import org.junit.AfterClass;
42 import org.junit.BeforeClass;
44 import club.wpia.gigi.DevelLauncher;
45 import club.wpia.gigi.GigiApiException;
46 import club.wpia.gigi.database.GigiPreparedStatement;
47 import club.wpia.gigi.database.GigiResultSet;
48 import club.wpia.gigi.dbObjects.Certificate;
49 import club.wpia.gigi.dbObjects.Certificate.CSRType;
50 import club.wpia.gigi.dbObjects.Digest;
51 import club.wpia.gigi.dbObjects.EmailAddress;
52 import club.wpia.gigi.dbObjects.Group;
53 import club.wpia.gigi.dbObjects.Job;
54 import club.wpia.gigi.dbObjects.ObjectCache;
55 import club.wpia.gigi.dbObjects.User;
56 import club.wpia.gigi.pages.account.MyDetails;
57 import club.wpia.gigi.pages.main.RegisterPage;
58 import club.wpia.gigi.testUtils.TestEmailReceiver.TestMail;
59 import club.wpia.gigi.util.SimpleSigner;
62 * Base class for test suites who require a launched Gigi instance. The instance
63 * is cleared once per test suite.
65 public class ManagedTest extends ConfiguredTest {
68 System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
71 private static TestEmailReceiver ter;
73 private static Process gigi;
75 private static String url = "localhost:4443";
77 private static String acceptLanguage = null;
79 protected static Certificate loginCertificate;
81 protected static PrivateKey loginPrivateKey;
83 public static void setAcceptLanguage(String acceptLanguage) {
84 ManagedTest.acceptLanguage = acceptLanguage;
87 public static String getServerName() {
88 return url.replaceFirst(":443$", "");
91 public static String getSecureServerName() {
92 return getServerName().replaceAll("^www\\.", "secure.");
97 HttpURLConnection.setFollowRedirects(false);
101 public static void initEnvironmentHook() {
105 private static boolean inited = false;
107 public static Properties initEnvironment() {
108 return initEnvironment(new Properties());
111 public static Properties initEnvironment(Properties additionalConfig) {
113 Properties mainProps = ConfiguredTest.initEnvironment();
114 for (Entry<Object, Object> i : additionalConfig.entrySet()) {
115 if (i.getKey() instanceof String && i.getValue() instanceof String) {
116 mainProps.setProperty((String) i.getKey(), (String) i.getValue());
123 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
125 String type = testProps.getProperty("type");
126 generateMainProps(mainProps);
127 if (type.equals("local")) {
128 String[] parts = testProps.getProperty("mail").split(":", 2);
129 ter = new TestEmailReceiver(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
131 if (testProps.getProperty("withSigner", "false").equals("true")) {
132 SimpleSigner.runSigner();
136 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
137 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
138 System.out.println("... starting server");
140 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
141 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
143 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes("UTF-8"), "changeit".getBytes("UTF-8"), mainProps, cacerts, keystore);
146 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream(), "UTF-8"));
148 while ((line = br.readLine()) != null && !line.contains("System successfully started.")) {
149 System.err.println(line);
157 while ((line = br.readLine()) != null) {
158 System.err.println(line);
160 } catch (IOException e) {
166 throw new Error("Server startup failed");
168 ter = new TestEmailReceiver(new InetSocketAddress("localhost", 8473));
170 SimpleSigner.runSigner();
172 } catch (IOException e) {
174 } catch (SQLException e1) {
176 } catch (InterruptedException e) {
182 protected static void await(Job j) throws InterruptedException {
187 public static void purgeDatabase() throws SQLException, IOException {
194 public static void clearCaches() throws IOException {
195 ObjectCache.clearAllCaches();
196 // String type = testProps.getProperty("type");
197 URL u = new URL("https://" + getServerName() + "/manage");
198 URLConnection connection = u.openConnection();
199 connection.getHeaderField("Location");
200 connection.getInputStream().close();
203 private static void generateMainProps(Properties mainProps) {
204 mainProps.setProperty("testrunner", "true");
205 mainProps.setProperty("host", "127.0.0.1");
207 mainProps.setProperty("emailProvider", "club.wpia.gigi.email.TestEmailProvider");
208 mainProps.setProperty("emailProvider.port", "8473");
209 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
210 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
211 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
212 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
213 mainProps.setProperty("testing", "true");
217 public static void tearDownServer() {
218 String type = testProps.getProperty("type");
220 if (type.equals("local")) {
221 if (testProps.getProperty("withSigner", "false").equals("true")) {
223 SimpleSigner.stopSigner();
224 } catch (InterruptedException e) {
233 SimpleSigner.stopSigner();
234 } catch (InterruptedException e) {
240 public final String uniq = createUniqueName();
243 public void removeMails() {
248 public void clearAcceptLanguage() {
249 ManagedTest.setAcceptLanguage(null);
253 public MailReceiver getMailReceiver() {
257 public static String runRegister(String param) throws IOException {
258 URL regist = new URL("https://" + getServerName() + RegisterPage.PATH);
259 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
260 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
261 if (acceptLanguage != null) {
262 csrfConn.setRequestProperty("Accept-Language", acceptLanguage);
263 uc.setRequestProperty("Accept-Language", acceptLanguage);
266 String headerField = csrfConn.getHeaderField("Set-Cookie");
267 headerField = stripCookie(headerField);
269 String csrf = getCSRF(csrfConn);
270 uc.addRequestProperty("Cookie", headerField);
271 uc.setDoOutput(true);
272 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes("UTF-8"));
273 if (uc.getResponseCode() == 302) {
276 String d = IOUtils.readURL(uc);
280 public static org.hamcrest.Matcher<String> hasError() {
281 return CoreMatchers.containsString("<div class='alert alert-danger error-msgs'>");
284 public static org.hamcrest.Matcher<String> hasNoError() {
285 return CoreMatchers.not(hasError());
288 public static String fetchStartErrorMessage(String d) throws IOException {
289 String formFail = "<div class='alert alert-danger error-msgs'>";
290 int idx = d.indexOf(formFail);
294 String startError = d.substring(idx + formFail.length(), idx + formFail.length() + 150).trim();
298 public static void registerUser(String firstName, String lastName, String email, String password) {
300 String query = "name-type=western&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&tos_agree=1&dp_agree=1";
301 String data = fetchStartErrorMessage(runRegister(query));
303 } catch (UnsupportedEncodingException e) {
305 } catch (IOException e) {
310 public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
311 registerUser(firstName, lastName, email, password);
313 ter.receive(email).verify();
315 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `users` WHERE `email`=?")) {
316 ps.setString(1, email);
318 GigiResultSet rs = ps.executeQuery();
325 } catch (IOException e) {
330 public static void grant(User u, Group g) throws IOException, GigiApiException {
331 u.grantGroup(getSupporter(), g);
336 * Creates a new user with 100 Verification Points given by an (invalid)
347 * @return a new userid.
349 public static int createVerificationUser(String firstName, String lastName, String email, String password) {
350 int uid = createVerifiedUser(firstName, lastName, email, password);
357 protected static String stripCookie(String headerField) {
358 return headerField.substring(0, headerField.indexOf(';'));
361 public static final String SECURE_REFERENCE = MyDetails.PATH;
363 public static boolean isLoggedin(String cookie) throws IOException {
364 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
365 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
366 huc.addRequestProperty("Cookie", cookie);
367 return huc.getResponseCode() == 200;
370 public static String login(String email, String pw) throws IOException {
371 URL u = new URL("https://" + getServerName() + "/login");
372 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
374 String csrf = getCSRF(huc);
375 String headerField = stripCookie(huc.getHeaderField("Set-Cookie"));
377 huc = (HttpURLConnection) u.openConnection();
378 cookie(huc, headerField);
379 huc.setDoOutput(true);
380 OutputStream os = huc.getOutputStream();
381 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8") + "&csrf=" + URLEncoder.encode(csrf, "UTF-8");
382 os.write(data.getBytes("UTF-8"));
384 headerField = huc.getHeaderField("Set-Cookie");
385 if (headerField == null) {
388 if (huc.getResponseCode() != 302) {
389 fail(fetchStartErrorMessage(IOUtils.readURL(huc)));
391 return stripCookie(headerField);
394 public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
396 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getSecureServerName() + "/login").openConnection();
397 authenticateClientCert(pk, ce, connection);
398 if (connection.getResponseCode() == 302) {
399 assertEquals("https://" + getSecureServerName() + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
400 return stripCookie(connection.getHeaderField("Set-Cookie"));
406 public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
407 KeyManager km = new X509KeyManager() {
410 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
415 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
420 public X509Certificate[] getCertificateChain(String arg0) {
421 return new X509Certificate[] {
427 public String[] getClientAliases(String arg0, Principal[] arg1) {
428 return new String[] {
434 public PrivateKey getPrivateKey(String arg0) {
435 if (arg0.equals("client")) {
442 public String[] getServerAliases(String arg0, Principal[] arg1) {
443 return new String[] {
448 SSLContext sc = SSLContext.getInstance("TLS");
449 sc.init(new KeyManager[] {
452 if (connection instanceof HttpsURLConnection) {
453 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
457 public static String getCSRF(URLConnection u) throws IOException {
458 return getCSRF(u, 0);
461 public static String getCSRF(URLConnection u, int formIndex) throws IOException {
462 String content = IOUtils.readURL(u);
463 return getCSRF(formIndex, content);
466 public static String getCSRF(int formIndex, String content) throws Error {
467 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
468 Matcher m = p.matcher(content);
469 for (int i = 0; i < formIndex + 1; i++) {
471 throw new Error("No CSRF Token:\n" + content);
477 public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
478 return executeBasicWebInteraction(cookie, path, query, 0);
481 public static String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
482 HttpURLConnection uc = post(cookie, path, query, formIndex);
483 if (uc.getResponseCode() == 302) {
486 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
490 public static HttpURLConnection post(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
491 String server = getServerName();
492 if (loginCertificate != null) {
493 server = getSecureServerName();
495 URLConnection uc = new URL("https://" + server + path).openConnection();
496 authenticate((HttpURLConnection) uc, cookie);
497 String csrf = getCSRF(uc, formIndex);
499 uc = new URL("https://" + server + path).openConnection();
500 authenticate((HttpURLConnection) uc, cookie);
501 uc.setDoOutput(true);
502 OutputStream os = uc.getOutputStream();
503 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
505 ).getBytes("UTF-8"));
507 return (HttpURLConnection) uc;
510 public static HttpURLConnection get(String cookie, String path) throws IOException {
511 String server = getServerName();
512 if (loginCertificate != null) {
513 server = getSecureServerName();
515 URLConnection uc = new URL("https://" + server + path).openConnection();
516 authenticate((HttpURLConnection) uc, cookie);
517 return (HttpURLConnection) uc;
520 public EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
521 return createVerifiedEmail(u, createUniqueName() + "test@test.tld");
524 public EmailAddress createVerifiedEmail(User u, String email) throws InterruptedException, GigiApiException {
525 EmailAddress addr = new EmailAddress(u, email, Locale.ENGLISH);
526 TestMail testMail = getMailReceiver().receive(addr.getAddress());
527 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
529 getMailReceiver().assertEmpty();
533 public static URLConnection cookie(URLConnection openConnection, String cookie) {
534 openConnection.setRequestProperty("Cookie", cookie);
535 return openConnection;
538 private static User supporter;
540 public static User getSupporter() throws GigiApiException, IOException {
541 if (supporter != null) {
544 int i = createVerifiedUser("fn", "ln", createUniqueName() + "@email.com", TEST_PASSWORD);
545 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
547 ps.setString(2, Group.SUPPORTER.getDBName());
552 supporter = User.getById(i);
556 protected static void authenticate(HttpURLConnection uc, String cookie) throws IOException {
557 uc.addRequestProperty("Cookie", cookie);
558 if (loginCertificate != null) {
560 authenticateClientCert(loginPrivateKey, loginCertificate.cert(), uc);
561 } catch (GeneralSecurityException | GigiApiException e) {
562 throw new IOException(e);
567 protected String cookieWithCertificateLogin(User u) throws IOException, GigiApiException {
571 kp = generateKeypair();
574 csr = generatePEMCSR(kp, "CN=" + u.getPreferredName().toString());
576 Certificate c = new Certificate(u, u, Certificate.buildDN("CN", u.getPreferredName().toString()), Digest.SHA256, csr, CSRType.CSR, getClientProfile());
577 final PrivateKey pk = kp.getPrivate();
578 await(c.issue(null, "2y", u));
579 final X509Certificate ce = c.cert();
580 c.setLoginEnabled(true);
581 loginCertificate = c;
582 loginPrivateKey = pk;
583 return login(pk, ce);
584 } catch (InterruptedException e) {
585 throw new GigiApiException(e.toString());
586 } catch (GeneralSecurityException e) {
587 throw new GigiApiException(e.toString());