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.Properties;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
33 import javax.net.ssl.HttpsURLConnection;
34 import javax.net.ssl.KeyManager;
35 import javax.net.ssl.SSLContext;
36 import javax.net.ssl.X509KeyManager;
38 import org.hamcrest.CoreMatchers;
39 import org.junit.After;
40 import org.junit.AfterClass;
41 import org.junit.BeforeClass;
43 import club.wpia.gigi.DevelLauncher;
44 import club.wpia.gigi.GigiApiException;
45 import club.wpia.gigi.database.GigiPreparedStatement;
46 import club.wpia.gigi.database.GigiResultSet;
47 import club.wpia.gigi.dbObjects.Certificate;
48 import club.wpia.gigi.dbObjects.Certificate.CSRType;
49 import club.wpia.gigi.dbObjects.Digest;
50 import club.wpia.gigi.dbObjects.EmailAddress;
51 import club.wpia.gigi.dbObjects.Group;
52 import club.wpia.gigi.dbObjects.Job;
53 import club.wpia.gigi.dbObjects.ObjectCache;
54 import club.wpia.gigi.dbObjects.User;
55 import club.wpia.gigi.pages.account.MyDetails;
56 import club.wpia.gigi.pages.main.RegisterPage;
57 import club.wpia.gigi.testUtils.TestEmailReceiver.TestMail;
58 import club.wpia.gigi.util.SimpleSigner;
61 * Base class for test suites who require a launched Gigi instance. The instance
62 * is cleared once per test suite.
64 public class ManagedTest extends ConfiguredTest {
67 System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
70 private static TestEmailReceiver ter;
72 private static Process gigi;
74 private static String url = "localhost:4443";
76 private static String acceptLanguage = null;
78 protected static Certificate loginCertificate;
80 protected static PrivateKey loginPrivateKey;
82 public static void setAcceptLanguage(String acceptLanguage) {
83 ManagedTest.acceptLanguage = acceptLanguage;
86 public static String getServerName() {
87 return url.replaceFirst(":443$", "");
90 public static String getSecureServerName() {
91 return getServerName().replaceAll("^www\\.", "secure.");
96 HttpURLConnection.setFollowRedirects(false);
100 public static void initEnvironmentHook() {
104 private static boolean inited = false;
106 public static Properties initEnvironment() {
108 Properties mainProps = ConfiguredTest.initEnvironment();
113 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
115 String type = testProps.getProperty("type");
116 generateMainProps(mainProps);
117 if (type.equals("local")) {
118 String[] parts = testProps.getProperty("mail").split(":", 2);
119 ter = new TestEmailReceiver(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
121 if (testProps.getProperty("withSigner", "false").equals("true")) {
122 SimpleSigner.runSigner();
126 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
127 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
128 System.out.println("... starting server");
130 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
131 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
133 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes("UTF-8"), "changeit".getBytes("UTF-8"), mainProps, cacerts, keystore);
136 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream(), "UTF-8"));
138 while ((line = br.readLine()) != null && !line.contains("System successfully started.")) {
139 System.err.println(line);
147 while ((line = br.readLine()) != null) {
148 System.err.println(line);
150 } catch (IOException e) {
156 throw new Error("Server startup failed");
158 ter = new TestEmailReceiver(new InetSocketAddress("localhost", 8473));
160 SimpleSigner.runSigner();
162 } catch (IOException e) {
164 } catch (SQLException e1) {
166 } catch (InterruptedException e) {
172 protected static void await(Job j) throws InterruptedException {
177 public static void purgeDatabase() throws SQLException, IOException {
184 public static void clearCaches() throws IOException {
185 ObjectCache.clearAllCaches();
186 // String type = testProps.getProperty("type");
187 URL u = new URL("https://" + getServerName() + "/manage");
188 URLConnection connection = u.openConnection();
189 connection.getHeaderField("Location");
190 connection.getInputStream().close();
193 private static void generateMainProps(Properties mainProps) {
194 mainProps.setProperty("testrunner", "true");
195 mainProps.setProperty("host", "127.0.0.1");
197 mainProps.setProperty("emailProvider", "club.wpia.gigi.email.TestEmailProvider");
198 mainProps.setProperty("emailProvider.port", "8473");
199 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
200 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
201 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
202 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
203 mainProps.setProperty("testing", "true");
207 public static void tearDownServer() {
208 String type = testProps.getProperty("type");
210 if (type.equals("local")) {
211 if (testProps.getProperty("withSigner", "false").equals("true")) {
213 SimpleSigner.stopSigner();
214 } catch (InterruptedException e) {
223 SimpleSigner.stopSigner();
224 } catch (InterruptedException e) {
230 public final String uniq = createUniqueName();
233 public void removeMails() {
238 public void clearAcceptLanguage() {
239 ManagedTest.setAcceptLanguage(null);
243 public MailReceiver getMailReceiver() {
247 public static String runRegister(String param) throws IOException {
248 URL regist = new URL("https://" + getServerName() + RegisterPage.PATH);
249 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
250 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
251 if (acceptLanguage != null) {
252 csrfConn.setRequestProperty("Accept-Language", acceptLanguage);
253 uc.setRequestProperty("Accept-Language", acceptLanguage);
256 String headerField = csrfConn.getHeaderField("Set-Cookie");
257 headerField = stripCookie(headerField);
259 String csrf = getCSRF(csrfConn);
260 uc.addRequestProperty("Cookie", headerField);
261 uc.setDoOutput(true);
262 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes("UTF-8"));
263 if (uc.getResponseCode() == 302) {
266 String d = IOUtils.readURL(uc);
270 public static org.hamcrest.Matcher<String> hasError() {
271 return CoreMatchers.containsString("<div class='alert alert-danger error-msgs'>");
274 public static org.hamcrest.Matcher<String> hasNoError() {
275 return CoreMatchers.not(hasError());
278 public static String fetchStartErrorMessage(String d) throws IOException {
279 String formFail = "<div class='alert alert-danger error-msgs'>";
280 int idx = d.indexOf(formFail);
284 String startError = d.substring(idx + formFail.length(), idx + formFail.length() + 150).trim();
288 public static void registerUser(String firstName, String lastName, String email, String password) {
290 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";
291 String data = fetchStartErrorMessage(runRegister(query));
293 } catch (UnsupportedEncodingException e) {
295 } catch (IOException e) {
300 public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
301 registerUser(firstName, lastName, email, password);
303 ter.receive(email).verify();
305 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `users` WHERE `email`=?")) {
306 ps.setString(1, email);
308 GigiResultSet rs = ps.executeQuery();
315 } catch (IOException e) {
320 public static void grant(User u, Group g) throws IOException, GigiApiException {
321 u.grantGroup(getSupporter(), g);
326 * Creates a new user with 100 Verification Points given by an (invalid)
337 * @return a new userid.
339 public static int createVerificationUser(String firstName, String lastName, String email, String password) {
340 int uid = createVerifiedUser(firstName, lastName, email, password);
347 protected static String stripCookie(String headerField) {
348 return headerField.substring(0, headerField.indexOf(';'));
351 public static final String SECURE_REFERENCE = MyDetails.PATH;
353 public static boolean isLoggedin(String cookie) throws IOException {
354 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
355 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
356 huc.addRequestProperty("Cookie", cookie);
357 return huc.getResponseCode() == 200;
360 public static String login(String email, String pw) throws IOException {
361 URL u = new URL("https://" + getServerName() + "/login");
362 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
364 String csrf = getCSRF(huc);
365 String headerField = stripCookie(huc.getHeaderField("Set-Cookie"));
367 huc = (HttpURLConnection) u.openConnection();
368 cookie(huc, headerField);
369 huc.setDoOutput(true);
370 OutputStream os = huc.getOutputStream();
371 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8") + "&csrf=" + URLEncoder.encode(csrf, "UTF-8");
372 os.write(data.getBytes("UTF-8"));
374 headerField = huc.getHeaderField("Set-Cookie");
375 if (headerField == null) {
378 if (huc.getResponseCode() != 302) {
379 fail(fetchStartErrorMessage(IOUtils.readURL(huc)));
381 return stripCookie(headerField);
384 public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
386 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getSecureServerName() + "/login").openConnection();
387 authenticateClientCert(pk, ce, connection);
388 if (connection.getResponseCode() == 302) {
389 assertEquals("https://" + getSecureServerName() + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
390 return stripCookie(connection.getHeaderField("Set-Cookie"));
396 public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
397 KeyManager km = new X509KeyManager() {
400 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
405 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
410 public X509Certificate[] getCertificateChain(String arg0) {
411 return new X509Certificate[] {
417 public String[] getClientAliases(String arg0, Principal[] arg1) {
418 return new String[] {
424 public PrivateKey getPrivateKey(String arg0) {
425 if (arg0.equals("client")) {
432 public String[] getServerAliases(String arg0, Principal[] arg1) {
433 return new String[] {
438 SSLContext sc = SSLContext.getInstance("TLS");
439 sc.init(new KeyManager[] {
442 if (connection instanceof HttpsURLConnection) {
443 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
447 public static String getCSRF(URLConnection u) throws IOException {
448 return getCSRF(u, 0);
451 public static String getCSRF(URLConnection u, int formIndex) throws IOException {
452 String content = IOUtils.readURL(u);
453 return getCSRF(formIndex, content);
456 public static String getCSRF(int formIndex, String content) throws Error {
457 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
458 Matcher m = p.matcher(content);
459 for (int i = 0; i < formIndex + 1; i++) {
461 throw new Error("No CSRF Token:\n" + content);
467 public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
468 return executeBasicWebInteraction(cookie, path, query, 0);
471 public static String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
472 HttpURLConnection uc = post(cookie, path, query, formIndex);
473 if (uc.getResponseCode() == 302) {
476 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
480 public static HttpURLConnection post(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
481 String server = getServerName();
482 if (loginCertificate != null) {
483 server = getSecureServerName();
485 URLConnection uc = new URL("https://" + server + path).openConnection();
486 authenticate((HttpURLConnection) uc, cookie);
487 String csrf = getCSRF(uc, formIndex);
489 uc = new URL("https://" + server + path).openConnection();
490 authenticate((HttpURLConnection) uc, cookie);
491 uc.setDoOutput(true);
492 OutputStream os = uc.getOutputStream();
493 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
495 ).getBytes("UTF-8"));
497 return (HttpURLConnection) uc;
500 public static HttpURLConnection get(String cookie, String path) throws IOException {
501 String server = getServerName();
502 if (loginCertificate != null) {
503 server = getSecureServerName();
505 URLConnection uc = new URL("https://" + server + path).openConnection();
506 authenticate((HttpURLConnection) uc, cookie);
507 return (HttpURLConnection) uc;
510 public EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
511 return createVerifiedEmail(u, createUniqueName() + "test@test.tld");
514 public EmailAddress createVerifiedEmail(User u, String email) throws InterruptedException, GigiApiException {
515 EmailAddress addr = new EmailAddress(u, email, Locale.ENGLISH);
516 TestMail testMail = getMailReceiver().receive(addr.getAddress());
517 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
519 getMailReceiver().assertEmpty();
523 public static URLConnection cookie(URLConnection openConnection, String cookie) {
524 openConnection.setRequestProperty("Cookie", cookie);
525 return openConnection;
528 private static User supporter;
530 public static User getSupporter() throws GigiApiException, IOException {
531 if (supporter != null) {
534 int i = createVerifiedUser("fn", "ln", createUniqueName() + "@email.com", TEST_PASSWORD);
535 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
537 ps.setString(2, Group.SUPPORTER.getDBName());
542 supporter = User.getById(i);
546 protected static void authenticate(HttpURLConnection uc, String cookie) throws IOException {
547 uc.addRequestProperty("Cookie", cookie);
548 if (loginCertificate != null) {
550 authenticateClientCert(loginPrivateKey, loginCertificate.cert(), uc);
551 } catch (GeneralSecurityException | GigiApiException e) {
552 throw new IOException(e);
557 protected String cookieWithCertificateLogin(User u) throws IOException, GigiApiException {
561 kp = generateKeypair();
564 csr = generatePEMCSR(kp, "CN=" + u.getPreferredName().toString());
566 Certificate c = new Certificate(u, u, Certificate.buildDN("CN", u.getPreferredName().toString()), Digest.SHA256, csr, CSRType.CSR, getClientProfile());
567 final PrivateKey pk = kp.getPrivate();
568 await(c.issue(null, "2y", u));
569 final X509Certificate ce = c.cert();
570 c.setLoginEnabled(true);
571 loginCertificate = c;
572 loginPrivateKey = pk;
573 return login(pk, ce);
574 } catch (InterruptedException e) {
575 throw new GigiApiException(e.toString());
576 } catch (GeneralSecurityException e) {
577 throw new GigiApiException(e.toString());