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