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