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