]> WPIA git - gigi.git/blob - tests/club/wpia/gigi/testUtils/ConfiguredTest.java
chg: Make synchronization on the Database layer explicit
[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             return generateProps();
82         }
83         envInited = true;
84         try (FileInputStream inStream = new FileInputStream("config/test.properties")) {
85             testProps.load(inStream);
86         }
87         Properties props = generateProps();
88         ServerConstants.init(props);
89         TimeConditions.init(props);
90         DomainAssessment.init(props);
91         PasswordHash.init(props);
92
93         if ( !DatabaseConnection.isInited()) {
94             DatabaseConnection.init(testProps);
95             try {
96                 synchronized (ConfiguredTest.class) {
97                     l = DatabaseConnection.newLink(false);
98                 }
99             } catch (InterruptedException e) {
100                 throw new Error(e);
101             }
102         }
103
104         return props;
105     }
106
107     @AfterClass
108     public static void closeDBLink() {
109         synchronized (ConfiguredTest.class) {
110             if (l != null) {
111                 l.close();
112                 l = null;
113             }
114         }
115     }
116
117     private static Properties generateProps() throws Error {
118         Properties mainProps = new Properties();
119         mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
120         mainProps.setProperty("name.www", testProps.getProperty("name.www"));
121         mainProps.setProperty("name.static", testProps.getProperty("name.static"));
122         mainProps.setProperty("name.api", testProps.getProperty("name.api"));
123
124         mainProps.setProperty("appName", "SomeCA");
125         mainProps.setProperty("appIdentifier", "someca");
126
127         mainProps.setProperty("https.port", testProps.getProperty("serverPort.https"));
128         mainProps.setProperty("http.port", testProps.getProperty("serverPort.http"));
129
130         File out = new File("financial.dat");
131         if ( !out.exists()) {
132             try (FileOutputStream fos = new FileOutputStream(out)) {
133                 fos.write("google.com\ntwitter.com\n".getBytes("UTF-8"));
134             } catch (IOException e) {
135                 throw new Error(e);
136             }
137         }
138         mainProps.setProperty("highFinancialValue", out.getAbsolutePath());
139         mainProps.setProperty("scrypt.params", "1;1;1");
140         return mainProps;
141     }
142
143     public static KeyPair generateKeypair() throws GeneralSecurityException {
144         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
145         kpg.initialize(4096);
146         KeyPair keyPair = null;
147         File f = new File("testKeypair");
148         if (f.exists()) {
149             try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
150                 keyPair = (KeyPair) ois.readObject();
151             } catch (ClassNotFoundException e) {
152                 e.printStackTrace();
153             } catch (IOException e) {
154                 e.printStackTrace();
155             }
156         } else {
157             keyPair = kpg.generateKeyPair();
158             try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
159                 oos.writeObject(keyPair);
160                 oos.close();
161             } catch (IOException e) {
162                 e.printStackTrace();
163             }
164         }
165         return keyPair;
166     }
167
168     public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
169         return generatePEMCSR(kp, dn, new PKCS10Attributes());
170     }
171
172     public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
173         return generatePEMCSR(kp, dn, atts, "SHA512WithRSA");
174     }
175
176     public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
177         PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
178         Signature s = Signature.getInstance(signature);
179         s.initSign(kp.getPrivate());
180         p10.encodeAndSign(new X500Name(dn), s);
181         return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
182     }
183
184     static int count = 0;
185
186     public static String createRandomIDString() {
187         final char[] chars = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
188         final int idStringLength = 16;
189
190         Random sr;
191         sr = new Random();
192
193         StringBuilder sb = new StringBuilder(idStringLength);
194         for (int i = 0; i < idStringLength; i++) {
195             sb.append(chars[sr.nextInt(chars.length)]);
196         }
197
198         return sb.toString();
199     }
200
201     public static synchronized String createUniqueName() {
202         return "test" + createRandomIDString() + "a" + (count++) + "u";
203     }
204
205     public static CertificateProfile getClientProfile() {
206         return CertificateProfile.getByName("client");
207     }
208
209     public static int countRegex(String text, String pattern) {
210         Pattern p = Pattern.compile(pattern);
211         Matcher m = p.matcher(text);
212         int i = 0;
213         while (m.find()) {
214             i++;
215         }
216         return i;
217     }
218
219     public static void makeAgent(int uid) {
220         try (GigiPreparedStatement ps1 = new GigiPreparedStatement("INSERT INTO cats_passed SET user_id=?, variant_id=?, language='en_EN', version='1'")) {
221             ps1.setInt(1, uid);
222             ps1.setInt(2, CATSType.AGENT_CHALLENGE.getId());
223             ps1.execute();
224         }
225
226         try (GigiPreparedStatement ps2 = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'")) {
227             ps2.setInt(1, uid);
228             ps2.setInt(2, User.getById(uid).getPreferredName().getId());
229             ps2.execute();
230         }
231     }
232
233     public MailReceiver getMailReceiver() {
234         throw new Error("Feature requires Business or ManagedTest.");
235     }
236
237     public void verify(Domain d) {
238         try {
239             d.addPing(DomainPingType.EMAIL, "admin");
240             TestMail testMail = getMailReceiver().receive();
241             testMail.verify();
242             assertTrue(d.isVerified());
243         } catch (GigiApiException e) {
244             throw new Error(e);
245         } catch (IOException e) {
246             throw new Error(e);
247         }
248     }
249
250     public static void purgeOnlyDB() throws SQLException, IOException {
251         System.out.println("... resetting Database");
252         long ms = System.currentTimeMillis();
253         try {
254             DatabaseManager.run(new String[] {
255                     testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
256             }, ImportType.TRUNCATE);
257         } catch (ClassNotFoundException e) {
258             e.printStackTrace();
259         }
260         System.out.println("Database reset complete in " + (System.currentTimeMillis() - ms) + " ms.");
261     }
262
263     public static String validVerificationDateString() {
264         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
265         Calendar c = Calendar.getInstance();
266         c.setTimeInMillis(System.currentTimeMillis());
267         c.add(Calendar.MONTH, -Notary.LIMIT_MAX_MONTHS_VERIFICATION + 1);
268         return sdf.format(new Date(c.getTimeInMillis()));
269     }
270 }