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.KeyManagementException;
21 import java.security.NoSuchAlgorithmException;
22 import java.security.Principal;
23 import java.security.PrivateKey;
24 import java.security.cert.X509Certificate;
25 import java.sql.SQLException;
26 import java.util.Locale;
27 import java.util.Properties;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
31 import javax.net.ssl.HttpsURLConnection;
32 import javax.net.ssl.KeyManager;
33 import javax.net.ssl.SSLContext;
34 import javax.net.ssl.X509KeyManager;
36 import org.hamcrest.CoreMatchers;
37 import org.junit.After;
38 import org.junit.AfterClass;
39 import org.junit.BeforeClass;
41 import club.wpia.gigi.DevelLauncher;
42 import club.wpia.gigi.GigiApiException;
43 import club.wpia.gigi.database.GigiPreparedStatement;
44 import club.wpia.gigi.database.GigiResultSet;
45 import club.wpia.gigi.dbObjects.EmailAddress;
46 import club.wpia.gigi.dbObjects.Group;
47 import club.wpia.gigi.dbObjects.Job;
48 import club.wpia.gigi.dbObjects.ObjectCache;
49 import club.wpia.gigi.dbObjects.User;
50 import club.wpia.gigi.pages.account.MyDetails;
51 import club.wpia.gigi.pages.main.RegisterPage;
52 import club.wpia.gigi.testUtils.TestEmailReceiver.TestMail;
53 import club.wpia.gigi.util.SimpleSigner;
56 * Base class for test suites who require a launched Gigi instance. The instance
57 * is cleared once per test suite.
59 public class ManagedTest extends ConfiguredTest {
62 System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
65 private static TestEmailReceiver ter;
67 private static Process gigi;
69 private static String url = "localhost:4443";
71 private static String acceptLanguage = null;
73 public static void setAcceptLanguage(String acceptLanguage) {
74 ManagedTest.acceptLanguage = acceptLanguage;
77 public static String getServerName() {
78 return url.replaceFirst(":443$", "");
81 public static String getSecureServerName() {
82 return getServerName().replaceAll("^www\\.", "secure.");
87 HttpURLConnection.setFollowRedirects(false);
91 public static void initEnvironmentHook() {
95 private static boolean inited = false;
97 public static Properties initEnvironment() {
99 Properties mainProps = ConfiguredTest.initEnvironment();
105 String type = testProps.getProperty("type");
106 generateMainProps(mainProps);
107 if (type.equals("local")) {
108 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
109 String[] parts = testProps.getProperty("mail").split(":", 2);
110 ter = new TestEmailReceiver(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
112 if (testProps.getProperty("withSigner", "false").equals("true")) {
113 SimpleSigner.runSigner();
117 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
118 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
119 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
120 System.out.println("... starting server");
122 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
123 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
125 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes("UTF-8"), "changeit".getBytes("UTF-8"), mainProps, cacerts, keystore);
128 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream(), "UTF-8"));
130 while ((line = br.readLine()) != null && !line.contains("System successfully started.")) {
131 System.err.println(line);
139 while ((line = br.readLine()) != null) {
140 System.err.println(line);
142 } catch (IOException e) {
148 throw new Error("Server startup failed");
150 ter = new TestEmailReceiver(new InetSocketAddress("localhost", 8473));
152 SimpleSigner.runSigner();
154 } catch (IOException e) {
156 } catch (SQLException e1) {
158 } catch (InterruptedException e) {
164 protected static void await(Job j) throws InterruptedException {
169 public static void purgeDatabase() throws SQLException, IOException {
174 public static void clearCaches() throws IOException {
175 ObjectCache.clearAllCaches();
176 // String type = testProps.getProperty("type");
177 URL u = new URL("https://" + getServerName() + "/manage");
178 u.openConnection().getHeaderField("Location");
181 private static void generateMainProps(Properties mainProps) {
182 mainProps.setProperty("testrunner", "true");
183 mainProps.setProperty("host", "127.0.0.1");
185 mainProps.setProperty("emailProvider", "club.wpia.gigi.email.TestEmailProvider");
186 mainProps.setProperty("emailProvider.port", "8473");
187 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
188 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
189 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
190 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
191 mainProps.setProperty("testing", "true");
195 public static void tearDownServer() {
196 String type = testProps.getProperty("type");
198 if (type.equals("local")) {
203 SimpleSigner.stopSigner();
204 } catch (InterruptedException e) {
209 public final String uniq = createUniqueName();
212 public void removeMails() {
217 public void clearAcceptLanguage() {
218 ManagedTest.setAcceptLanguage(null);
222 public MailReceiver getMailReceiver() {
226 public static String runRegister(String param) throws IOException {
227 URL regist = new URL("https://" + getServerName() + RegisterPage.PATH);
228 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
229 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
230 if (acceptLanguage != null) {
231 csrfConn.setRequestProperty("Accept-Language", acceptLanguage);
232 uc.setRequestProperty("Accept-Language", acceptLanguage);
235 String headerField = csrfConn.getHeaderField("Set-Cookie");
236 headerField = stripCookie(headerField);
238 String csrf = getCSRF(csrfConn);
239 uc.addRequestProperty("Cookie", headerField);
240 uc.setDoOutput(true);
241 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes("UTF-8"));
242 if (uc.getResponseCode() == 302) {
245 String d = IOUtils.readURL(uc);
249 public static org.hamcrest.Matcher<String> hasError() {
250 return CoreMatchers.containsString("<div class='alert alert-danger error-msgs'>");
253 public static org.hamcrest.Matcher<String> hasNoError() {
254 return CoreMatchers.not(hasError());
257 public static String fetchStartErrorMessage(String d) throws IOException {
258 String formFail = "<div class='alert alert-danger error-msgs'>";
259 int idx = d.indexOf(formFail);
263 String startError = d.substring(idx + formFail.length(), idx + formFail.length() + 150).trim();
267 public static void registerUser(String firstName, String lastName, String email, String password) {
269 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";
270 String data = fetchStartErrorMessage(runRegister(query));
272 } catch (UnsupportedEncodingException e) {
274 } catch (IOException e) {
279 public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
280 registerUser(firstName, lastName, email, password);
282 ter.receive().verify();
284 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `users` WHERE `email`=?")) {
285 ps.setString(1, email);
287 GigiResultSet rs = ps.executeQuery();
294 } catch (IOException e) {
299 public static void grant(User u, Group g) throws IOException, GigiApiException {
300 u.grantGroup(getSupporter(), g);
305 * Creates a new user with 100 Verification Points given by an (invalid)
316 * @return a new userid.
318 public static int createVerificationUser(String firstName, String lastName, String email, String password) {
319 int uid = createVerifiedUser(firstName, lastName, email, password);
326 protected static String stripCookie(String headerField) {
327 return headerField.substring(0, headerField.indexOf(';'));
330 public static final String SECURE_REFERENCE = MyDetails.PATH;
332 public static boolean isLoggedin(String cookie) throws IOException {
333 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
334 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
335 huc.addRequestProperty("Cookie", cookie);
336 return huc.getResponseCode() == 200;
339 public static String login(String email, String pw) throws IOException {
340 URL u = new URL("https://" + getServerName() + "/login");
341 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
343 String csrf = getCSRF(huc);
344 String headerField = stripCookie(huc.getHeaderField("Set-Cookie"));
346 huc = (HttpURLConnection) u.openConnection();
347 cookie(huc, headerField);
348 huc.setDoOutput(true);
349 OutputStream os = huc.getOutputStream();
350 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8") + "&csrf=" + URLEncoder.encode(csrf, "UTF-8");
351 os.write(data.getBytes("UTF-8"));
353 headerField = huc.getHeaderField("Set-Cookie");
354 if (headerField == null) {
357 if (huc.getResponseCode() != 302) {
358 fail(fetchStartErrorMessage(IOUtils.readURL(huc)));
360 return stripCookie(headerField);
363 public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
365 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getSecureServerName() + "/login").openConnection();
366 authenticateClientCert(pk, ce, connection);
367 if (connection.getResponseCode() == 302) {
368 assertEquals("https://" + getSecureServerName() + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
369 return stripCookie(connection.getHeaderField("Set-Cookie"));
375 public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
376 KeyManager km = new X509KeyManager() {
379 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
384 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
389 public X509Certificate[] getCertificateChain(String arg0) {
390 return new X509Certificate[] {
396 public String[] getClientAliases(String arg0, Principal[] arg1) {
397 return new String[] {
403 public PrivateKey getPrivateKey(String arg0) {
404 if (arg0.equals("client")) {
411 public String[] getServerAliases(String arg0, Principal[] arg1) {
412 return new String[] {
417 SSLContext sc = SSLContext.getInstance("TLS");
418 sc.init(new KeyManager[] {
421 if (connection instanceof HttpsURLConnection) {
422 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
426 public static String getCSRF(URLConnection u) throws IOException {
427 return getCSRF(u, 0);
430 public static String getCSRF(URLConnection u, int formIndex) throws IOException {
431 String content = IOUtils.readURL(u);
432 return getCSRF(formIndex, content);
435 public static String getCSRF(int formIndex, String content) throws Error {
436 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
437 Matcher m = p.matcher(content);
438 for (int i = 0; i < formIndex + 1; i++) {
440 throw new Error("No CSRF Token:\n" + content);
446 public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
447 return executeBasicWebInteraction(cookie, path, query, 0);
450 public static String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
451 HttpURLConnection uc = post(cookie, path, query, formIndex);
452 if (uc.getResponseCode() == 302) {
455 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
459 public static HttpURLConnection post(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
460 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
461 uc.addRequestProperty("Cookie", cookie);
462 String csrf = getCSRF(uc, formIndex);
464 uc = new URL("https://" + getServerName() + path).openConnection();
465 uc.addRequestProperty("Cookie", cookie);
466 uc.setDoOutput(true);
467 OutputStream os = uc.getOutputStream();
468 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
470 ).getBytes("UTF-8"));
472 return (HttpURLConnection) uc;
475 public static HttpURLConnection get(String cookie, String path) throws IOException {
476 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
477 uc.addRequestProperty("Cookie", cookie);
478 return (HttpURLConnection) uc;
481 public EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
482 return createVerifiedEmail(u, createUniqueName() + "test@test.tld");
485 public EmailAddress createVerifiedEmail(User u, String email) throws InterruptedException, GigiApiException {
486 EmailAddress addr = new EmailAddress(u, email, Locale.ENGLISH);
487 TestMail testMail = getMailReceiver().receive();
488 assertEquals(addr.getAddress(), testMail.getTo());
489 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
491 getMailReceiver().clearMails();
495 public static URLConnection cookie(URLConnection openConnection, String cookie) {
496 openConnection.setRequestProperty("Cookie", cookie);
497 return openConnection;
500 private static User supporter;
502 public static User getSupporter() throws GigiApiException, IOException {
503 if (supporter != null) {
506 int i = createVerifiedUser("fn", "ln", createUniqueName() + "@email.com", TEST_PASSWORD);
507 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
509 ps.setString(2, Group.SUPPORTER.getDBName());
514 supporter = User.getById(i);