]> WPIA git - gigi.git/blob - tests/club/wpia/gigi/testUtils/ConfiguredTest.java
upd: allow clean testcase setup and teardown
[gigi.git] / tests / club / wpia / gigi / testUtils / ConfiguredTest.java
1 package club.wpia.gigi.testUtils;
2
3 import static org.junit.Assert.*;
4
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.ObjectInputStream;
10 import java.io.ObjectOutputStream;
11 import java.security.GeneralSecurityException;
12 import java.security.KeyPair;
13 import java.security.KeyPairGenerator;
14 import java.security.Signature;
15 import java.sql.SQLException;
16 import java.text.SimpleDateFormat;
17 import java.util.Calendar;
18 import java.util.Date;
19 import java.util.Properties;
20 import java.util.Random;
21 import java.util.TimeZone;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24
25 import org.junit.AfterClass;
26 import org.junit.BeforeClass;
27
28 import club.wpia.gigi.GigiApiException;
29 import club.wpia.gigi.database.DatabaseConnection;
30 import club.wpia.gigi.database.DatabaseConnection.Link;
31 import club.wpia.gigi.database.GigiPreparedStatement;
32 import club.wpia.gigi.database.SQLFileManager.ImportType;
33 import club.wpia.gigi.dbObjects.CATS.CATSType;
34 import club.wpia.gigi.dbObjects.CertificateProfile;
35 import club.wpia.gigi.dbObjects.Domain;
36 import club.wpia.gigi.dbObjects.DomainPingType;
37 import club.wpia.gigi.dbObjects.User;
38 import club.wpia.gigi.testUtils.TestEmailReceiver.TestMail;
39 import club.wpia.gigi.util.DatabaseManager;
40 import club.wpia.gigi.util.DomainAssessment;
41 import club.wpia.gigi.util.Notary;
42 import club.wpia.gigi.util.PEM;
43 import club.wpia.gigi.util.PasswordHash;
44 import club.wpia.gigi.util.ServerConstants;
45 import club.wpia.gigi.util.TimeConditions;
46 import sun.security.pkcs10.PKCS10;
47 import sun.security.pkcs10.PKCS10Attributes;
48 import sun.security.x509.X500Name;
49
50 /**
51  * Base class for a Testsuite that makes use of the config variables that define
52  * the environment.
53  */
54 public abstract class ConfiguredTest {
55
56     static Properties testProps = new Properties();
57
58     public static Properties getTestProps() {
59         return testProps;
60     }
61
62     private static boolean envInited = false;
63
64     /**
65      * Some password that fulfills the password criteria.
66      */
67     public static final String TEST_PASSWORD = "xvXV12°§";
68
69     public static final String DIFFICULT_CHARS = "ÜÖÄß𐀀";
70
71     @BeforeClass
72     public static void initEnvironmentHook() throws IOException {
73         initEnvironment();
74     }
75
76     private static Link l;
77
78     public static Properties initEnvironment() throws IOException {
79         TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
80         if (envInited) {
81             try {
82                 synchronized (ConfiguredTest.class) {
83                     if (l == null) {
84                         l = DatabaseConnection.newLink(false);
85                     }
86                 }
87             } catch (InterruptedException e) {
88                 throw new Error(e);
89             }
90             return generateProps();
91         }
92         envInited = true;
93         try (FileInputStream inStream = new FileInputStream("config/test.properties")) {
94             testProps.load(inStream);
95         }
96         Properties props = generateProps();
97         ServerConstants.init(props);
98         TimeConditions.init(props);
99         DomainAssessment.init(props);
100         PasswordHash.init(props);
101
102         if ( !DatabaseConnection.isInited()) {
103             DatabaseConnection.init(testProps);
104             try {
105                 synchronized (ConfiguredTest.class) {
106                     if (l == null) {
107                         l = DatabaseConnection.newLink(false);
108                     }
109                 }
110             } catch (InterruptedException e) {
111                 throw new Error(e);
112             }
113         }
114
115         return props;
116     }
117
118     @AfterClass
119     public static void closeDBLink() {
120         synchronized (ConfiguredTest.class) {
121             if (l != null) {
122                 l.close();
123                 l = null;
124             }
125         }
126     }
127
128     private static Properties generateProps() throws Error {
129         Properties mainProps = new Properties();
130         mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
131         mainProps.setProperty("name.www", testProps.getProperty("name.www"));
132         mainProps.setProperty("name.static", testProps.getProperty("name.static"));
133         mainProps.setProperty("name.api", testProps.getProperty("name.api"));
134
135         mainProps.setProperty("appName", "SomeCA");
136         mainProps.setProperty("appIdentifier", "someca");
137
138         mainProps.setProperty("https.port", testProps.getProperty("serverPort.https"));
139         mainProps.setProperty("http.port", testProps.getProperty("serverPort.http"));
140
141         File out = new File("financial.dat");
142         if ( !out.exists()) {
143             try (FileOutputStream fos = new FileOutputStream(out)) {
144                 fos.write("google.com\ntwitter.com\n".getBytes("UTF-8"));
145             } catch (IOException e) {
146                 throw new Error(e);
147             }
148         }
149         mainProps.setProperty("highFinancialValue", out.getAbsolutePath());
150         mainProps.setProperty("scrypt.params", "1;1;1");
151         return mainProps;
152     }
153
154     public static KeyPair generateKeypair() throws GeneralSecurityException {
155         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
156         kpg.initialize(4096);
157         KeyPair keyPair = null;
158         File f = new File("testKeypair");
159         if (f.exists()) {
160             try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
161                 keyPair = (KeyPair) ois.readObject();
162             } catch (ClassNotFoundException e) {
163                 e.printStackTrace();
164             } catch (IOException e) {
165                 e.printStackTrace();
166             }
167         } else {
168             keyPair = kpg.generateKeyPair();
169             try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
170                 oos.writeObject(keyPair);
171                 oos.close();
172             } catch (IOException e) {
173                 e.printStackTrace();
174             }
175         }
176         return keyPair;
177     }
178
179     public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
180         return generatePEMCSR(kp, dn, new PKCS10Attributes());
181     }
182
183     public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
184         return generatePEMCSR(kp, dn, atts, "SHA512WithRSA");
185     }
186
187     public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
188         PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
189         Signature s = Signature.getInstance(signature);
190         s.initSign(kp.getPrivate());
191         p10.encodeAndSign(new X500Name(dn), s);
192         return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
193     }
194
195     static int count = 0;
196
197     public static String createRandomIDString() {
198         final char[] chars = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
199         final int idStringLength = 16;
200
201         Random sr;
202         sr = new Random();
203
204         StringBuilder sb = new StringBuilder(idStringLength);
205         for (int i = 0; i < idStringLength; i++) {
206             sb.append(chars[sr.nextInt(chars.length)]);
207         }
208
209         return sb.toString();
210     }
211
212     public static synchronized String createUniqueName() {
213         return "test" + createRandomIDString() + "a" + (count++) + "u";
214     }
215
216     public static CertificateProfile getClientProfile() {
217         return CertificateProfile.getByName("client");
218     }
219
220     public static int countRegex(String text, String pattern) {
221         Pattern p = Pattern.compile(pattern);
222         Matcher m = p.matcher(text);
223         int i = 0;
224         while (m.find()) {
225             i++;
226         }
227         return i;
228     }
229
230     public static void makeAgent(int uid) {
231         try (GigiPreparedStatement ps1 = new GigiPreparedStatement("INSERT INTO cats_passed SET user_id=?, variant_id=?, language='en_EN', version='1'")) {
232             ps1.setInt(1, uid);
233             ps1.setInt(2, CATSType.AGENT_CHALLENGE.getId());
234             ps1.execute();
235         }
236
237         try (GigiPreparedStatement ps2 = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'")) {
238             ps2.setInt(1, uid);
239             ps2.setInt(2, User.getById(uid).getPreferredName().getId());
240             ps2.execute();
241         }
242     }
243
244     public MailReceiver getMailReceiver() {
245         throw new Error("Feature requires Business or ManagedTest.");
246     }
247
248     public void verify(Domain d) {
249         try {
250             d.addPing(DomainPingType.EMAIL, "admin");
251             TestMail testMail = getMailReceiver().receive();
252             testMail.verify();
253             assertTrue(d.isVerified());
254         } catch (GigiApiException e) {
255             throw new Error(e);
256         } catch (IOException e) {
257             throw new Error(e);
258         }
259     }
260
261     public static void purgeOnlyDB() throws SQLException, IOException {
262         System.out.println("... resetting Database");
263         long ms = System.currentTimeMillis();
264         try {
265             DatabaseManager.run(new String[] {
266                     testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
267             }, ImportType.TRUNCATE);
268         } catch (ClassNotFoundException e) {
269             e.printStackTrace();
270         }
271         System.out.println("Database reset complete in " + (System.currentTimeMillis() - ms) + " ms.");
272     }
273
274     public static String validVerificationDateString() {
275         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
276         Calendar c = Calendar.getInstance();
277         c.setTimeInMillis(System.currentTimeMillis());
278         c.add(Calendar.MONTH, -Notary.LIMIT_MAX_MONTHS_VERIFICATION + 1);
279         return sdf.format(new Date(c.getTimeInMillis()));
280     }
281 }