`domainid` int(11) NOT NULL,
`type` enum('email', 'ssl', 'http', 'dns') NOT NULL,
`info` varchar(255) NOT NULL,
- `reping` enum('y','n') NOT NULL DEFAULT 'n',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
import javax.servlet.http.HttpSession;
import org.cacert.gigi.database.DatabaseConnection;
+import org.cacert.gigi.dbObjects.DomainPingConfiguration;
import org.cacert.gigi.dbObjects.User;
import org.cacert.gigi.localisation.Language;
import org.cacert.gigi.output.Menu;
public static final String USER = "user";
+ public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
+
private static final long serialVersionUID = -6386785421902852904L;
private Template baseTemplate;
}
};
+ Language lang = Page.getLanguage(req);
+
vars.put(Menu.USER_VALUE, currentPageUser);
vars.put("menu", rootMenu);
- vars.put("title", Page.getLanguage(req).getTranslation(p.getTitle()));
+ vars.put("title", lang.getTranslation(p.getTitle()));
vars.put("static", getStaticTemplateVar(isSecure));
vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
vars.put("content", content);
if (currentPageUser != null) {
vars.put("loggedInAs", currentPageUser.getName().toString());
+ vars.put("loginMethod", lang.getTranslation((String) req.getSession().getAttribute(LOGIN_METHOD)));
}
resp.setContentType("text/html; charset=utf-8");
- baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars);
+ baseTemplate.output(resp.getWriter(), lang, vars);
} else {
resp.sendError(404, "Page not found.");
}
return instance.reveresePages.get(p).replaceFirst("/?\\*$", "");
}
- public static void notifyPinger() {
+ /**
+ * Requests Pinging of domains.
+ *
+ * @param toReping
+ * if not null, the {@link DomainPingConfiguration} to test, if
+ * null, just re-check if there is something to do.
+ */
+ public static void notifyPinger(DomainPingConfiguration toReping) {
+ if (toReping != null) {
+ instance.pinger.queue(toReping);
+ }
instance.pinger.interrupt();
}
</div>
</div>
<div id="pageNav">
- <? if($loggedInAs) { ?><div><?=_Logged in as?>: <?=$loggedInAs?></div><? } ?>
+ <? if($loggedInAs) { ?><div><?=_Logged in as?>: <?=$loggedInAs?> <?=_with?> <?=$loginMethod?></div><? } ?>
<?=$menu?>
<div>
<h3 class="pointer"><?=_Advertising?></h3>
package org.cacert.gigi;
import java.io.PrintWriter;
+import java.io.StringWriter;
import java.sql.SQLException;
+import java.util.HashMap;
import java.util.LinkedList;
+import java.util.Locale;
import org.cacert.gigi.localisation.Language;
+import org.cacert.gigi.output.template.Outputable;
+import org.cacert.gigi.output.template.TranslateCommand;
public class GigiApiException extends Exception {
private SQLException e;
- private LinkedList<String> messages = new LinkedList<>();
+ private LinkedList<Outputable> messages = new LinkedList<>();
public GigiApiException(SQLException e) {
super(e);
public GigiApiException(String message) {
super(message);
- messages.add(message);
+ messages.add(new TranslateCommand(message));
}
public GigiApiException() {
}
+ public GigiApiException(Outputable out) {
+ messages.add(out);
+ }
+
public void mergeInto(GigiApiException e2) {
messages.addAll(e2.messages);
if (e == null) {
out.println(language.getTranslation("An internal error ouccured."));
out.println("</div>");
}
- for (String message : messages) {
+ HashMap<String, Object> map = new HashMap<>();
+ for (Outputable message : messages) {
+ map.clear();
+
out.print("<div>");
- out.print(language.getTranslation(message));
+ message.output(out, language, map);
out.println("</div>");
}
out.println("</div>");
@Override
public String getMessage() {
if (messages.size() != 0) {
- StringBuffer res = new StringBuffer();
- for (String string : messages) {
- res.append(string + "\n");
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+
+ HashMap<String, Object> map = new HashMap<>();
+ for (Outputable message : messages) {
+ map.clear();
+ message.output(pw, Language.getInstance(Locale.ENGLISH), map);
}
- return res.toString();
+ pw.flush();
+
+ return sw.toString();
}
return "";
}
private void tryConnect() {
try {
c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?zeroDateTimeBehavior=convertToNull", credentials.getProperty("sql.user"), credentials.getProperty("sql.password"));
- PreparedStatement ps = c.prepareStatement("SET SESSION wait_timeout=?;");
+ PreparedStatement ps = c.prepareStatement("SET SESSION wait_timeout=?, time_zone='+0:00';");
ps.setInt(1, CONNECTION_TIMEOUT);
ps.execute();
ps.close();
}
}
- public int executeUpdate() {
+ public void executeUpdate() {
try {
- return target.executeUpdate();
+ int updated = target.executeUpdate();
+ if (updated != 1) {
+ throw new Error("FATAL: multiple or no data updated: " + updated);
+ }
} catch (SQLException e) {
handleSQL(e);
throw new Error(e);
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
-import java.sql.Time;
import java.sql.Timestamp;
public class GigiResultSet {
}
}
- public Time getTime(int columnIndex) {
- try {
- return target.getTime(columnIndex);
- } catch (SQLException e) {
- handleSQL(e);
- throw new Error(e);
- }
- }
-
public String getString(String columnLabel) {
try {
return target.getString(columnLabel);
}
}
- public Time getTime(String columnLabel) {
- try {
- return target.getTime(columnLabel);
- } catch (SQLException e) {
- handleSQL(e);
- throw new Error(e);
- }
- }
-
public boolean next() {
try {
return target.next();
crtName = rs.getString(1);
serial = rs.getString(4);
- if (rs.getTime(2) == null) {
+ if (rs.getTimestamp(2) == null) {
return CertificateStatus.DRAFT;
}
- if (rs.getTime(2) != null && rs.getTime(3) == null) {
+ if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
return CertificateStatus.ISSUED;
}
return CertificateStatus.REVOKED;
package org.cacert.gigi.dbObjects;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.cacert.gigi.Gigi;
+import org.cacert.gigi.GigiApiException;
import org.cacert.gigi.database.DatabaseConnection;
import org.cacert.gigi.database.GigiPreparedStatement;
import org.cacert.gigi.database.GigiResultSet;
+import org.cacert.gigi.output.template.Scope;
+import org.cacert.gigi.output.template.SprintfCommand;
public class DomainPingConfiguration implements IdCachable {
return res;
}
- public void requestReping() {
- GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE pingconfig set reping='y' WHERE id=?");
+ public Date getLastExecution() {
+ GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `when` AS stamp from domainPinglog WHERE configId=? ORDER BY `when` DESC LIMIT 1");
+ ps.setInt(1, id);
+ GigiResultSet rs = ps.executeQuery();
+ if (rs.next()) {
+ return new Date(rs.getTimestamp("stamp").getTime());
+ }
+ return new Date(0);
+ }
+
+ public Date getLastSuccess() {
+ GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `when` AS stamp from domainPinglog WHERE configId=? AND state='success' ORDER BY `when` DESC LIMIT 1");
ps.setInt(1, id);
- ps.execute();
+ GigiResultSet rs = ps.executeQuery();
+ if (rs.next()) {
+ return new Date(rs.getTimestamp("stamp").getTime());
+ }
+ return new Date(0);
}
+ public synchronized void requestReping() throws GigiApiException {
+ Date lastExecution = getLastExecution();
+ if (lastExecution.getTime() + 5 * 60 * 1000 < System.currentTimeMillis()) {
+ Gigi.notifyPinger(this);
+ return;
+ }
+ Map<String, Object> data = new HashMap<String, Object>();
+ data.put("data", new Date(lastExecution.getTime() + 5 * 60 * 1000));
+ throw new GigiApiException(new Scope(new SprintfCommand("Reping is only allowed after 5 minutes, yours end at %s.", Arrays.asList("$data")), data));
+ }
}
ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
ps.setString(1, PasswordHash.hash(newPass));
ps.setInt(2, getId());
- if (ps.executeUpdate() != 1) {
- throw new GigiApiException("Password update failed.");
- }
+ ps.executeUpdate();
}
public void setName(Name name) {
return getAssurancePoints() > 50 && isInGroup(Group.getByString("codesigning"));
case 3:
case 4:
- return false; // has an orga
+ return getOrganisations().size() > 0;
default:
return false;
}
--- /dev/null
+package org.cacert.gigi.output.template;
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.cacert.gigi.localisation.Language;
+
+public class Scope implements Outputable {
+
+ private Map<String, Object> vars;
+
+ private Outputable out;
+
+ public Scope(Outputable out, Map<String, Object> vars) {
+ this.out = out;
+ this.vars = vars;
+ }
+
+ @Override
+ public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+ HashMap<String, Object> map = new HashMap<>();
+ map.putAll(vars);
+ map.putAll(this.vars);
+ this.out.output(out, l, map);
+ }
+
+}
gps.executeUpdate();
}
loginSession(req, User.getById(rs.getInt(2)));
+ req.getSession().setAttribute(LOGIN_METHOD, "Password");
}
}
rs.close();
loginSession(req, User.getById(rs.getInt(1)));
req.getSession().setAttribute(CERT_SERIAL, serial);
req.getSession().setAttribute(CERT_ISSUER, x509Certificate.getIssuerDN());
+ req.getSession().setAttribute(LOGIN_METHOD, "Certificate");
}
rs.close();
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.cacert.gigi.Gigi;
import org.cacert.gigi.GigiApiException;
import org.cacert.gigi.dbObjects.Domain;
import org.cacert.gigi.dbObjects.DomainPingConfiguration;
if (dpc.getTarget() != d) {
return;
}
- dpc.requestReping();
- Gigi.notifyPinger();
+ try {
+ dpc.requestReping();
+ } catch (GigiApiException e) {
+ e.format(resp.getWriter(), getLanguage(req));
+ return;
+ }
resp.sendRedirect(PATH + i);
}
if (req.getParameter("adddomain") != null) {
}
}
- Gigi.notifyPinger();
+ Gigi.notifyPinger(null);
return false;
}
import java.security.KeyStore;
import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Queue;
import org.cacert.gigi.database.DatabaseConnection;
import org.cacert.gigi.database.GigiPreparedStatement;
import org.cacert.gigi.database.GigiResultSet;
import org.cacert.gigi.dbObjects.Domain;
-import org.cacert.gigi.dbObjects.User;
+import org.cacert.gigi.dbObjects.DomainPingConfiguration;
+import org.cacert.gigi.dbObjects.DomainPingConfiguration.PingType;
import org.cacert.gigi.util.RandomToken;
public class PingerDaemon extends Thread {
- HashMap<String, DomainPinger> pingers = new HashMap<>();
+ HashMap<PingType, DomainPinger> pingers = new HashMap<>();
private GigiPreparedStatement searchNeededPings;
private GigiPreparedStatement enterPingResult;
- private GigiPreparedStatement updatePingStatus;
-
private KeyStore truststore;
+ private Queue<DomainPingConfiguration> toExecute = new LinkedList<>();
+
public PingerDaemon(KeyStore truststore) {
this.truststore = truststore;
}
@Override
public void run() {
- searchNeededPings = DatabaseConnection.getInstance().prepare("SELECT pingconfig.*, domains.domain, domains.memid FROM pingconfig LEFT JOIN domainPinglog ON domainPinglog.configId=pingconfig.id INNER JOIN domains ON domains.id=pingconfig.domainid WHERE ( pingconfig.reping='y' OR domainPinglog.configId IS NULL) AND domains.deleted IS NULL GROUP BY pingconfig.id");
+ searchNeededPings = DatabaseConnection.getInstance().prepare("SELECT pingconfig.id FROM pingconfig LEFT JOIN domainPinglog ON domainPinglog.configId=pingconfig.id INNER JOIN domains ON domains.id=pingconfig.domainid WHERE ( domainPinglog.configId IS NULL) AND domains.deleted IS NULL GROUP BY pingconfig.id");
enterPingResult = DatabaseConnection.getInstance().prepare("INSERT INTO domainPinglog SET configId=?, state=?, result=?, challenge=?");
- updatePingStatus = DatabaseConnection.getInstance().prepare("UPDATE pingconfig SET reping='n' WHERE id=?");
- pingers.put("email", new EmailPinger());
- pingers.put("ssl", new SSLPinger(truststore));
- pingers.put("http", new HTTPFetch());
- pingers.put("dns", new DNSPinger());
+ pingers.put(PingType.EMAIL, new EmailPinger());
+ pingers.put(PingType.SSL, new SSLPinger(truststore));
+ pingers.put(PingType.HTTP, new HTTPFetch());
+ pingers.put(PingType.DNS, new DNSPinger());
while (true) {
- execute();
+ synchronized (this) {
+ DomainPingConfiguration conf;
+ while ((conf = toExecute.peek()) != null) {
+ handle(conf);
+ toExecute.remove();
+ }
+ notifyAll();
+ }
+
+ GigiResultSet rs = searchNeededPings.executeQuery();
+ while (rs.next()) {
+ handle(DomainPingConfiguration.getById(rs.getInt("id")));
+ }
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
- private void execute() {
-
- GigiResultSet rs = searchNeededPings.executeQuery();
- while (rs.next()) {
- String type = rs.getString("type");
- String config = rs.getString("info");
- DomainPinger dp = pingers.get(type);
- if (dp != null) {
- String token = null;
- if (dp instanceof EmailPinger) {
- token = RandomToken.generateToken(16);
- config = config + ":" + token;
- }
- updatePingStatus.setInt(1, rs.getInt("id"));
- updatePingStatus.execute();
- enterPingResult.setInt(1, rs.getInt("id"));
- String resp = dp.ping(Domain.getById(rs.getInt("domainid")), config, User.getById(rs.getInt("memid")));
- enterPingResult.setString(2, DomainPinger.PING_STILL_PENDING == resp ? "open" : DomainPinger.PING_SUCCEDED.equals(resp) ? "success" : "failed");
- enterPingResult.setString(3, resp);
- enterPingResult.setString(4, token);
- enterPingResult.execute();
+ private void handle(DomainPingConfiguration conf) {
+ PingType type = conf.getType();
+ String config = conf.getInfo();
+ DomainPinger dp = pingers.get(type);
+ if (dp != null) {
+ String token = null;
+ if (dp instanceof EmailPinger) {
+ token = RandomToken.generateToken(16);
+ config = config + ":" + token;
}
+ enterPingResult.setInt(1, conf.getId());
+ Domain target = conf.getTarget();
+ String resp = dp.ping(target, config, target.getOwner());
+ enterPingResult.setString(2, DomainPinger.PING_STILL_PENDING == resp ? "open" : DomainPinger.PING_SUCCEDED.equals(resp) ? "success" : "failed");
+ enterPingResult.setString(3, resp);
+ enterPingResult.setString(4, token);
+ enterPingResult.execute();
}
}
+ public synchronized void queue(DomainPingConfiguration toReping) {
+ interrupt();
+ toExecute.add(toReping);
+ while (toExecute.size() > 0) {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
}
static {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
- // env.put(Context.AUTHORITATIVE, "true");
- // env.put(Context.PROVIDER_URL, "dns://ns.dyn.dogcraft.de");
try {
context = new InitialDirContext(env);
} catch (NamingException e) {
import org.cacert.gigi.crypto.SPKAC;
import org.cacert.gigi.dbObjects.Digest;
-import org.cacert.gigi.dbObjects.User;
import org.cacert.gigi.pages.account.certs.CertificateAdd;
import org.cacert.gigi.pages.account.certs.CertificateIssueForm;
+import org.cacert.gigi.testUtils.ClientTest;
import org.cacert.gigi.testUtils.IOUtils;
-import org.cacert.gigi.testUtils.ManagedTest;
import org.cacert.gigi.util.PEM;
import org.junit.Test;
import sun.security.x509.SubjectAlternativeNameExtension;
import sun.security.x509.X509Key;
-public class TestCertificateAdd extends ManagedTest {
+public class TestCertificateAdd extends ClientTest {
KeyPair kp = generateKeypair();
- User u = User.getById(createVerifiedUser("testuser", "testname", uniq + "@testdom.com", TEST_PASSWORD));
-
- String session = login(uniq + "@testdom.com", TEST_PASSWORD);
-
String csrf;
public TestCertificateAdd() throws GeneralSecurityException, IOException {
- TestDomain.addDomain(session, uniq + ".tld");
+ TestDomain.addDomain(cookie, uniq + ".tld");
}
public void testSimpleMail() throws IOException, GeneralSecurityException {
PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
CertificateIssueForm.OID_KEY_USAGE_EMAIL_PROTECTION
- }, new DNSName("a." + uniq + ".tld"), new DNSName("b." + uniq + ".tld"), new RFC822Name(uniq + "@testdom.com"));
+ }, new DNSName("a." + uniq + ".tld"), new DNSName("b." + uniq + ".tld"), new RFC822Name(email));
- String pem = generatePEMCSR(kp, "CN=testuser testname", atts, "SHA384WithRSA");
+ String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA384WithRSA");
String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
assertArrayEquals(new String[] {
- "mail", "testuser testname", "dns:a." + uniq + ".tld\ndns:b." + uniq + ".tld\nemail:" + uniq + "@testdom.com\n", Digest.SHA384.toString()
+ "mail", "a b", "dns:a." + uniq + ".tld\ndns:b." + uniq + ".tld\nemail:" + email + "\n", Digest.SHA384.toString()
}, res);
}
public void testSimpleClient() throws IOException, GeneralSecurityException {
PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
CertificateIssueForm.OID_KEY_USAGE_SSL_CLIENT
- }, new RFC822Name(uniq + "@testdom.com"));
+ }, new RFC822Name(email));
- String pem = generatePEMCSR(kp, "CN=testuser testname,email=" + uniq + "@testdom.com", atts, "SHA512WithRSA");
+ String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
assertArrayEquals(new String[] {
- "client", "testuser testname", "email:" + uniq + "@testdom.com\n", Digest.SHA512.toString()
+ "client", "a b", "email:" + email + "\n", Digest.SHA512.toString()
}, res);
}
public void testIssue() throws IOException, GeneralSecurityException {
PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
CertificateIssueForm.OID_KEY_USAGE_SSL_CLIENT
- }, new RFC822Name(uniq + "@testdom.com"));
+ }, new RFC822Name(email));
- String pem = generatePEMCSR(kp, "CN=testuser testname,email=" + uniq + "@testdom.com", atts, "SHA512WithRSA");
+ String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
assertArrayEquals(new String[] {
- "client", "testuser testname", "email:" + uniq + "@testdom.com\n", Digest.SHA512.toString()
+ "client", "a b", "email:" + email + "\n", Digest.SHA512.toString()
}, res);
HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
- huc.setRequestProperty("Cookie", session);
+ huc.setRequestProperty("Cookie", cookie);
huc.setDoOutput(true);
OutputStream out = huc.getOutputStream();
out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes());
- out.write(("&profile=client&CN=testuser+testname&SANs=" + URLEncoder.encode("email:" + uniq + "@testdom.com\n", "UTF-8")).getBytes());
+ out.write(("&profile=client&CN=a+b&SANs=" + URLEncoder.encode("email:" + email + "\n", "UTF-8")).getBytes());
out.write(("&hash_alg=SHA512&CCA=y").getBytes());
URLConnection uc = authenticate(new URL(huc.getHeaderField("Location") + ".crt"));
String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
uc = authenticate(new URL(huc.getHeaderField("Location")));
String gui = IOUtils.readURL(uc);
assertThat(gui, containsString("clientAuth"));
- assertThat(gui, containsString("CN=testuser testname"));
+ assertThat(gui, containsString("CN=a b"));
assertThat(gui, containsString("SHA512withRSA"));
- assertThat(gui, containsString("RFC822Name: " + uniq + "@testdom.com"));
+ assertThat(gui, containsString("RFC822Name: " + email));
}
private X509Certificate createCertWithValidity(String validity) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
CertificateIssueForm.OID_KEY_USAGE_SSL_CLIENT
- }, new RFC822Name(uniq + "@testdom.com"));
+ }, new RFC822Name(email));
- String pem = generatePEMCSR(kp, "CN=testuser testname", atts, "SHA512WithRSA");
+ String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA512WithRSA");
fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
- huc.setRequestProperty("Cookie", session);
+ huc.setRequestProperty("Cookie", cookie);
huc.setDoOutput(true);
OutputStream out = huc.getOutputStream();
out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes());
- out.write(("&profile=client&CN=testuser+testname&SANs=" + URLEncoder.encode("email:" + uniq + "@testdom.com\n", "UTF-8")).getBytes());
+ out.write(("&profile=client&CN=a+b&SANs=" + URLEncoder.encode("email:" + email + "\n", "UTF-8")).getBytes());
out.write(("&hash_alg=SHA512&CCA=y&").getBytes());
out.write(validity.getBytes());
private URLConnection authenticate(URL url) throws IOException {
URLConnection uc = url.openConnection();
- uc.setRequestProperty("Cookie", session);
+ uc.setRequestProperty("Cookie", cookie);
return uc;
}
protected String testSPKAC(boolean correctChallange) throws GeneralSecurityException, IOException {
HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
- uc.setRequestProperty("Cookie", session);
+ uc.setRequestProperty("Cookie", cookie);
String s = IOUtils.readURL(uc);
csrf = extractPattern(s, Pattern.compile("<input [^>]*name='csrf' [^>]*value='([^']*)'>"));
private String[] fillOutForm(String pem) throws IOException {
HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
- uc.setRequestProperty("Cookie", session);
+ uc.setRequestProperty("Cookie", cookie);
csrf = getCSRF(uc);
return fillOutFormDirect(pem);
private String[] fillOutFormDirect(String pem) throws IOException {
HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
- uc.setRequestProperty("Cookie", session);
+ uc.setRequestProperty("Cookie", cookie);
uc.setDoOutput(true);
uc.getOutputStream().write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" + pem).getBytes());
uc.getOutputStream().flush();
import java.net.URLEncoder;
import org.cacert.gigi.GigiApiException;
-import org.cacert.gigi.dbObjects.User;
-import org.cacert.gigi.testUtils.ManagedTest;
+import org.cacert.gigi.testUtils.ClientTest;
import org.junit.Test;
-public class TestChangePassword extends ManagedTest {
-
- User u = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD));
-
- String cookie;
+public class TestChangePassword extends ClientTest {
String path = ChangePasswordPage.PATH;
import java.net.URL;
import java.net.URLConnection;
+import org.cacert.gigi.testUtils.ClientTest;
import org.cacert.gigi.testUtils.IOUtils;
-import org.cacert.gigi.testUtils.ManagedTest;
import org.junit.Test;
-public class TestContactInformation extends ManagedTest {
+public class TestContactInformation extends ClientTest {
@Test
public void testDirectoryListingToggle() throws IOException {
- String email = createUniqueName() + "@e.fg";
- createVerifiedUser("Kurti", createUniqueName(), email, TEST_PASSWORD);
- String cookie = login(email, TEST_PASSWORD);
assertNull(executeBasicWebInteraction(cookie, MyDetails.PATH, "listme=1&contactinfo=&processContact", 1));
URLConnection url = new URL("https://" + getServerName() + MyDetails.PATH).openConnection();
url.setRequestProperty("Cookie", cookie);
@Test
public void testContactinfoSet() throws IOException {
- String email = createUniqueName() + "@e.fg";
- createVerifiedUser("Kurti", createUniqueName(), email, TEST_PASSWORD);
- String cookie = login(email, TEST_PASSWORD);
String text = createUniqueName();
assertNull(executeBasicWebInteraction(cookie, MyDetails.PATH, "listme=1&contactinfo=" + text + "&processContact", 1));
URLConnection url = new URL("https://" + getServerName() + MyDetails.PATH).openConnection();
import java.io.IOException;
import java.net.URLEncoder;
-import org.cacert.gigi.dbObjects.User;
import org.cacert.gigi.pages.account.domain.DomainOverview;
-import org.cacert.gigi.testUtils.ManagedTest;
+import org.cacert.gigi.testUtils.ClientTest;
import org.junit.Test;
-public class TestDomain extends ManagedTest {
-
- User u = User.getById(createVerifiedUser("testuser", "testname", uniq + "@testdom.com", TEST_PASSWORD));
-
- String session = login(uniq + "@testdom.com", TEST_PASSWORD);
+public class TestDomain extends ClientTest {
public TestDomain() throws IOException {}
@Test
public void testAdd() throws IOException {
- assertNull(addDomain(session, uniq + ".de"));
- assertNotNull(addDomain(session, uniq + ".de"));
+ assertNull(addDomain(cookie, uniq + ".de"));
+ assertNotNull(addDomain(cookie, uniq + ".de"));
}
public static String addDomain(String session, String domain) throws IOException {
import org.cacert.gigi.dbObjects.User;
import org.cacert.gigi.localisation.Language;
import org.cacert.gigi.pages.account.mail.MailOverview;
-import org.cacert.gigi.testUtils.ManagedTest;
+import org.cacert.gigi.testUtils.ClientTest;
import org.junit.Test;
-public class TestMailManagement extends ManagedTest {
-
- private User u = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD));
-
- private String cookie;
+public class TestMailManagement extends ClientTest {
private String path = MailOverview.DEFAULT_PATH;
u2 = User.getById(u2.getId());
assertNotEquals(u2.getEmails().length, 0);
}
+
+ @Test
+ public void testMailDeleteWebPrimary() throws MalformedURLException, UnsupportedEncodingException, IOException {
+ assertNotNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + u.getEmails()[0].getId(), 0));
+ assertNotEquals(u.getEmails().length, 0);
+ }
}
import org.cacert.gigi.dbObjects.Organisation;
import org.cacert.gigi.dbObjects.Organisation.Affiliation;
import org.cacert.gigi.dbObjects.User;
+import org.cacert.gigi.testUtils.ClientTest;
import org.cacert.gigi.testUtils.IOUtils;
-import org.cacert.gigi.testUtils.ManagedTest;
import org.junit.Test;
-public class TestOrgaManagement extends ManagedTest {
-
- public User u = User.getById(createVerifiedUser("testuser", "testname", uniq + "@testdom.com", TEST_PASSWORD));
-
- public String session;
+public class TestOrgaManagement extends ClientTest {
public TestOrgaManagement() throws IOException {
u.grantGroup(u, Group.getByString("orgassurer"));
clearCaches();
- session = login(uniq + "@testdom.com", TEST_PASSWORD);
+ cookie = login(email, TEST_PASSWORD);
}
@Test
public void testAdd() throws IOException {
- executeBasicWebInteraction(session, CreateOrgPage.DEFAULT_PATH, "O=name&contact=mail&L=K%C3%B6ln&ST=%C3%9C%C3%96%C3%84%C3%9F&C=DE&comments=jkl%C3%B6loiuzfdfgjlh%C3%B6", 0);
+ executeBasicWebInteraction(cookie, CreateOrgPage.DEFAULT_PATH, "O=name&contact=mail&L=K%C3%B6ln&ST=%C3%9C%C3%96%C3%84%C3%9F&C=DE&comments=jkl%C3%B6loiuzfdfgjlh%C3%B6", 0);
Organisation[] orgs = Organisation.getOrganisations(0, 30);
assertEquals(1, orgs.length);
assertEquals("mail", orgs[0].getContactEmail());
assertEquals("ÜÖÄß", orgs[0].getProvince());
User u2 = User.getById(createVerifiedUser("testworker", "testname", createUniqueName() + "@testdom.com", TEST_PASSWORD));
- executeBasicWebInteraction(session, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "email=" + URLEncoder.encode(u2.getEmail(), "UTF-8") + "&do_affiliate=y&master=y", 1);
+ executeBasicWebInteraction(cookie, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "email=" + URLEncoder.encode(u2.getEmail(), "UTF-8") + "&do_affiliate=y&master=y", 1);
List<Affiliation> allAdmins = orgs[0].getAllAdmins();
assertEquals(1, allAdmins.size());
Affiliation affiliation = allAdmins.get(0);
assertSame(u2, affiliation.getTarget());
assertTrue(affiliation.isMaster());
- executeBasicWebInteraction(session, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "email=" + URLEncoder.encode(u.getEmail(), "UTF-8") + "&do_affiliate=y", 1);
+ executeBasicWebInteraction(cookie, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "email=" + URLEncoder.encode(u.getEmail(), "UTF-8") + "&do_affiliate=y", 1);
allAdmins = orgs[0].getAllAdmins();
assertEquals(2, allAdmins.size());
Affiliation affiliation2 = allAdmins.get(0);
assertSame(u.getId(), affiliation2.getTarget().getId());
assertFalse(affiliation2.isMaster());
- executeBasicWebInteraction(session, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "del=" + URLEncoder.encode(u.getEmail(), "UTF-8") + "&email=&do_affiliate=y", 1);
+ executeBasicWebInteraction(cookie, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "del=" + URLEncoder.encode(u.getEmail(), "UTF-8") + "&email=&do_affiliate=y", 1);
assertEquals(1, orgs[0].getAllAdmins().size());
- executeBasicWebInteraction(session, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "del=" + URLEncoder.encode(u2.getEmail(), "UTF-8") + "&email=&do_affiliate=y", 1);
+ executeBasicWebInteraction(cookie, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "del=" + URLEncoder.encode(u2.getEmail(), "UTF-8") + "&email=&do_affiliate=y", 1);
assertEquals(0, orgs[0].getAllAdmins().size());
- executeBasicWebInteraction(session, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "O=name1&contact=&L=K%C3%B6ln&ST=%C3%9C%C3%96%C3%84%C3%9F&C=DE&comments=jkl%C3%B6loiuzfdfgjlh%C3%B6", 0);
+ executeBasicWebInteraction(cookie, ViewOrgPage.DEFAULT_PATH + "/" + orgs[0].getId(), "O=name1&contact=&L=K%C3%B6ln&ST=%C3%9C%C3%96%C3%84%C3%9F&C=DE&comments=jkl%C3%B6loiuzfdfgjlh%C3%B6", 0);
clearCaches();
orgs = Organisation.getOrganisations(0, 30);
assertEquals("name1", orgs[0].getName());
assertEquals(404, ((HttpURLConnection) uc).getResponseCode());
uc = new URL("https://" + getServerName() + ViewOrgPage.DEFAULT_PATH).openConnection();
- uc.addRequestProperty("Cookie", session);
+ uc.addRequestProperty("Cookie", cookie);
content = IOUtils.readURL(uc);
assertThat(content, containsString("name21"));
assertThat(content, containsString("name12"));
- uc = cookie(new URL("https://" + getServerName() + ViewOrgPage.DEFAULT_PATH + "/" + o1.getId()).openConnection(), session);
+ uc = cookie(new URL("https://" + getServerName() + ViewOrgPage.DEFAULT_PATH + "/" + o1.getId()).openConnection(), cookie);
assertEquals(200, ((HttpURLConnection) uc).getResponseCode());
- uc = cookie(new URL("https://" + getServerName() + ViewOrgPage.DEFAULT_PATH + "/" + o2.getId()).openConnection(), session);
+ uc = cookie(new URL("https://" + getServerName() + ViewOrgPage.DEFAULT_PATH + "/" + o2.getId()).openConnection(), cookie);
assertEquals(200, ((HttpURLConnection) uc).getResponseCode());
o1.delete();
o2.delete();
import org.cacert.gigi.dbObjects.Group;
import org.cacert.gigi.dbObjects.ObjectCache;
import org.cacert.gigi.dbObjects.User;
+import org.cacert.gigi.testUtils.ClientTest;
import org.cacert.gigi.testUtils.IOUtils;
-import org.cacert.gigi.testUtils.ManagedTest;
import org.junit.Test;
-public class TestTTP extends ManagedTest {
-
- User u = User.getById(createVerifiedUser("fn", "ln", "test-" + createUniqueName() + "@example.org", TEST_PASSWORD));
-
- String cookie = login(u.getEmail(), TEST_PASSWORD);
+public class TestTTP extends ClientTest {
URL ttpPage = new URL("https://" + getServerName() + RequestTTPPage.PATH);
import org.cacert.gigi.dbObjects.Group;
import org.cacert.gigi.dbObjects.User;
import org.cacert.gigi.pages.admin.TTPAdminPage;
-import org.cacert.gigi.testUtils.ManagedTest;
+import org.cacert.gigi.testUtils.ClientTest;
import org.junit.Test;
-public class TestTTPAdmin extends ManagedTest {
-
- User us;
-
- String cookie;
+public class TestTTPAdmin extends ClientTest {
User us2;
public TestTTPAdmin() throws IOException {
- String email = uniq + "@example.com";
- us = User.getById(createVerifiedUser("fn", "ln", email, TEST_PASSWORD));
- cookie = login(email, TEST_PASSWORD);
us2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "@example.com", TEST_PASSWORD));
}
public void testTTPAdmin(boolean hasRight) throws IOException {
if (hasRight) {
- grant(us.getEmail(), Group.getByString("ttp-assurer"));
+ grant(email, Group.getByString("ttp-assurer"));
}
- grant(us.getEmail(), TTPAdminPage.TTP_APPLICANT);
- cookie = login(us.getEmail(), TEST_PASSWORD);
+ grant(u.getEmail(), TTPAdminPage.TTP_APPLICANT);
+ cookie = login(u.getEmail(), TEST_PASSWORD);
assertEquals( !hasRight ? 403 : 200, fetchStatusCode("https://" + getServerName() + TTPAdminPage.PATH));
assertEquals( !hasRight ? 403 : 200, fetchStatusCode("https://" + getServerName() + TTPAdminPage.PATH + "/"));
- assertEquals( !hasRight ? 403 : 200, fetchStatusCode("https://" + getServerName() + TTPAdminPage.PATH + "/" + us.getId()));
+ assertEquals( !hasRight ? 403 : 200, fetchStatusCode("https://" + getServerName() + TTPAdminPage.PATH + "/" + u.getId()));
assertEquals( !hasRight ? 403 : 404, fetchStatusCode("https://" + getServerName() + TTPAdminPage.PATH + "/" + us2.getId()));
assertEquals( !hasRight ? 403 : 404, fetchStatusCode("https://" + getServerName() + TTPAdminPage.PATH + "/" + 100));
}
package org.cacert.gigi.ping;
+import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
import javax.naming.NamingException;
+import org.cacert.gigi.GigiApiException;
+import org.cacert.gigi.dbObjects.Domain;
+import org.cacert.gigi.dbObjects.DomainPingConfiguration;
+import org.cacert.gigi.dbObjects.DomainPingConfiguration.PingType;
import org.cacert.gigi.pages.account.domain.DomainOverview;
import org.cacert.gigi.testUtils.IOUtils;
import org.cacert.gigi.testUtils.PingTest;
}
@Test
- public void httpAndMailSuccess() throws IOException, InterruptedException, SQLException {
+ public void httpAndMailSuccess() throws Exception {
testEmailAndHTTP(0, 0, true, true);
}
@Test
- public void httpFailKeyAndMailSuccess() throws IOException, InterruptedException, SQLException {
+ public void httpFailKeyAndMailSuccess() throws Exception {
testEmailAndHTTP(1, 0, false, true);
}
@Test
- public void httpFailValAndMailFail() throws IOException, InterruptedException, SQLException {
+ public void httpFailValAndMailFail() throws Exception {
testEmailAndHTTP(2, 1, false, false);
}
- public void testEmailAndHTTP(int httpVariant, int emailVariant, boolean successHTTP, boolean successMail) throws IOException, InterruptedException, SQLException {
+ public void testEmailAndHTTP(int httpVariant, int emailVariant, boolean successHTTP, boolean successMail) throws IOException, InterruptedException, SQLException, GigiApiException {
String test = getTestProps().getProperty("domain.http");
assumeNotNull(test);
assertTrue(newcontent, !successHTTP ^ pat.matcher(newcontent).find());
pat = Pattern.compile("<td>email</td>\\s*<td>success</td>");
assertTrue(newcontent, !successMail ^ pat.matcher(newcontent).find());
+
+ if (successHTTP) { // give it a second try
+ int id = Integer.parseInt(u2.toString().replaceFirst("^.*/([0-9]+)$", "$1"));
+ Domain d = Domain.getById(id);
+ DomainPingConfiguration dpc = null;
+ for (DomainPingConfiguration conf : d.getConfiguredPings()) {
+ if (conf.getType() == PingType.HTTP) {
+ dpc = conf;
+ break;
+ }
+ }
+ if (dpc == null) {
+ fail("Http config not found");
+ }
+ String res = executeBasicWebInteraction(cookie, u2.getPath(), "configId=" + dpc.getId());
+ assertThat(res, containsString("only allowed after"));
+ }
}
private String readHTTP(String token) throws IOException {
private void createCertificate(String test, CertificateProfile profile) throws GeneralSecurityException, IOException, SQLException, InterruptedException, GigiApiException {
kp = generateKeypair();
String csr = generatePEMCSR(kp, "CN=" + test);
- c = new Certificate(User.getById(userid), Certificate.buildDN("CN", test), "sha256", csr, CSRType.CSR, profile);
+ c = new Certificate(User.getById(id), Certificate.buildDN("CN", test), "sha256", csr, CSRType.CSR, profile);
c.issue(null, "2y").waitFor(60000);
}
import java.io.IOException;
+import org.cacert.gigi.dbObjects.User;
+
+/**
+ * Superclass for testsuites in a scenario where there is an registered member,
+ * who is already logged on.
+ */
public abstract class ClientTest extends ManagedTest {
+ /**
+ * Email of the member.
+ */
protected String email = createUniqueName() + "@example.org";
- protected int userid = createVerifiedUser("a", "b", email, TEST_PASSWORD);
+ /**
+ * Id of the member
+ */
+ protected int id = createVerifiedUser("a", "b", email, TEST_PASSWORD);
- protected String cookie;
+ /**
+ * {@link User} object of the member
+ */
+ protected User u = User.getById(id);
- protected String csrf;
+ /**
+ * Session cookie of the member.
+ */
+ protected String cookie;
public ClientTest() {
try {
import sun.security.pkcs10.PKCS10Attributes;
import sun.security.x509.X500Name;
-public class ConfiguredTest {
+/**
+ * Base class for a Testsuite that makes use of the config variables that define
+ * the environment.
+ */
+public abstract class ConfiguredTest {
static Properties testProps = new Properties();
import org.junit.AfterClass;
import org.junit.BeforeClass;
+/**
+ * Base class for test suites who require a launched Gigi instance. The instance
+ * is cleared once per test suite.
+ */
public class ManagedTest extends ConfiguredTest {
static {
}
/**
- * Some password that fullfills the password criteria.
+ * Some password that fulfills the password criteria.
*/
protected static final String TEST_PASSWORD = "xvXV12°§";
import org.cacert.gigi.pages.account.domain.DomainOverview;
import org.junit.After;
+/**
+ * Base class for test suites that check extensively if the domain-ping
+ * functionality wroks as expected.
+ */
public abstract class PingTest extends ClientTest {
+ protected String csrf;
+
protected static void updateService(String token, String value, String action) throws IOException, MalformedURLException {
String manage = getTestProps().getProperty("domain.manage");
assumeNotNull(manage);