use of com.zimbra.common.soap.SoapFaultException in project zm-mailbox by Zimbra.
the class TestUtil method deleteAccount.
/**
* Deletes the account for the given username. Consider using {@link deleteAccountIfExists} as alternative
* to reduce logging where the account may not exist.
*/
public static void deleteAccount(String username) throws ServiceException {
Provisioning prov = Provisioning.getInstance();
// so that both the account and mailbox are deleted.
if (!(prov instanceof SoapProvisioning)) {
prov = newSoapProvisioning();
}
SoapProvisioning soapProv = (SoapProvisioning) prov;
GetAccountRequest gaReq = new GetAccountRequest(AccountSelector.fromName(username), false, Lists.newArrayList(Provisioning.A_zimbraId));
try {
GetAccountResponse resp = soapProv.invokeJaxb(gaReq);
if (resp != null) {
String id = null;
for (Attr attr : resp.getAccount().getAttrList()) {
if (Provisioning.A_zimbraId.equals(attr.getKey())) {
id = attr.getValue();
break;
}
}
if (null == id) {
ZimbraLog.test.error("GetAccountResponse for '%s' did not contain the zimbraId", username);
return;
}
prov.deleteAccount(id);
}
} catch (SoapFaultException sfe) {
if (!sfe.getMessage().contains("no such account")) {
ZimbraLog.test.error("GetAccountResponse for '%s' hit unexpected problem", username, sfe);
}
}
}
use of com.zimbra.common.soap.SoapFaultException in project zm-mailbox by Zimbra.
the class TestServerEnumeration method testModifyCalres.
@Test
public void testModifyCalres() throws Exception {
List<AdminRight> relatedRights = new ArrayList<AdminRight>();
List<String> notes = new ArrayList<String>();
AdminDocumentHandler handler = new ModifyCalendarResource();
handler.docRights(relatedRights, notes);
createDelegatedAdmin(relatedRights);
grantRightToAdmin(adminSoapProv, com.zimbra.soap.type.TargetType.fromString(com.zimbra.cs.account.accesscontrol.TargetType.calresource.toString()), MY_CALRES, DELEGATED_ADMIN_NAME, Admin.R_modifyCalendarResource.getName());
adminSoapProv.flushCache(CacheEntryType.acl, null);
ModifyCalendarResourceRequest req = new ModifyCalendarResourceRequest(myCalRes.getId());
req.addAttr(new Attr(Provisioning.A_zimbraMailHost, NON_EXISTING_SERVER));
req.addAttr(new Attr(Provisioning.A_description, "test description"));
try {
delegatedSoapProv.invokeJaxb(req);
fail("should have caught an exception");
} catch (SoapFaultException e) {
assertEquals("should be getting 'Permission Denied' response", ServiceException.PERM_DENIED, e.getCode());
}
}
use of com.zimbra.common.soap.SoapFaultException in project zm-mailbox by Zimbra.
the class TestServerEnumeration method testModifyCalresAsGlobalAdmin.
@Test
public void testModifyCalresAsGlobalAdmin() throws Exception {
ModifyCalendarResourceRequest req = new ModifyCalendarResourceRequest(myCalRes.getId());
req.addAttr(new Attr(Provisioning.A_zimbraMailHost, NON_EXISTING_SERVER));
req.addAttr(new Attr(Provisioning.A_description, "test description"));
try {
adminSoapProv.invokeJaxb(req);
fail("should have caught an exception");
} catch (SoapFaultException e) {
assertEquals("should be getting 'no such server' response", AccountServiceException.NO_SUCH_SERVER, e.getCode());
}
}
use of com.zimbra.common.soap.SoapFaultException in project zm-mailbox by Zimbra.
the class SoapEngine method dispatch.
/**
* dispatch to the given serviceName the specified document,
* which should be a soap envelope containing a document to
* execute.
*
* @param path the path (i.e., /service/foo) of the service to dispatch to
* @param envelope the top-level element of the message
* @param context user context parameters
* @return an XmlObject which is a SoapEnvelope containing the response
* @throws CsrfTokenException if CSRF token validation fails
*/
private Element dispatch(String path, Element envelope, Map<String, Object> context) {
SoapProtocol soapProto = SoapProtocol.determineProtocol(envelope);
if (soapProto == null) {
// FIXME: have to pick 1.1 or 1.2 since we can't parse any
soapProto = SoapProtocol.Soap12;
return soapFaultEnv(soapProto, "SOAP exception", ServiceException.INVALID_REQUEST("unable to determine SOAP version", null));
}
Element doc = soapProto.getBodyElement(envelope);
if (doc == null) {
return soapFaultEnv(soapProto, "SOAP exception", ServiceException.INVALID_REQUEST("No SOAP body", null));
}
ServletRequest servReq = (ServletRequest) context.get(SoapServlet.SERVLET_REQUEST);
// Check if this handler requires authentication.
// Do not perform CSRF checks for handlers that do not require authentication
DocumentHandler handler = dispatcher.getHandler(doc);
ZimbraSoapContext zsc = null;
Element ectxt = soapProto.getHeader(envelope, HeaderConstants.CONTEXT);
try {
zsc = new ZimbraSoapContext(ectxt, doc.getQName(), handler, context, soapProto);
} catch (ServiceException e) {
return soapFaultEnv(soapProto, "unable to construct SOAP context", e);
}
boolean doCsrfCheck = false;
if (servReq.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) {
doCsrfCheck = (Boolean) servReq.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK);
} else if (zsc.getAuthToken() != null && zsc.getAuthToken().isCsrfTokenEnabled()) {
doCsrfCheck = true;
}
if (handler == null) {
// handler, all other request should be mapped to a Handler
if (!doc.getName().equals("BatchRequest")) {
doCsrfCheck = false;
} else {
StringBuilder sb = new StringBuilder();
for (Element req : doc.listElements()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(req.getName());
}
LOG.info("BatchRequest [%s] contains %d sub-request(s): %s", path, doc.listElements().size(), sb.toString());
}
} else {
if (doc.getName().equals("AuthRequest")) {
// this is a Auth request, no CSRF validation happens
doCsrfCheck = false;
try {
Element contextElmt = getSoapContextElement(soapProto, envelope);
if (contextElmt != null) {
String jwtSalt = contextElmt.getAttribute(HeaderConstants.E_JWT_SALT);
context.put(JWT_SALT, jwtSalt);
}
} catch (ServiceException e) {
// was trying to get the jwt salt from soap context, if any issue occurred ignore.
}
} else {
doCsrfCheck = doCsrfCheck && handler.needsAuth(context);
}
}
if (doCsrfCheck) {
try {
HttpServletRequest httpReq = (HttpServletRequest) servReq;
// Bug: 96167 SoapEngine should be able to read CSRF token from HTTP headers
String csrfToken = httpReq.getHeader(Constants.CSRF_TOKEN);
if (StringUtil.isNullOrEmpty(csrfToken)) {
Element contextElmt = getSoapContextElement(soapProto, envelope);
if (contextElmt != null) {
csrfToken = contextElmt.getAttribute(HeaderConstants.E_CSRFTOKEN);
}
}
AuthToken authToken = zsc.getAuthToken();
if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) {
LOG.info("CSRF token validation failed for account");
return soapFaultEnv(soapProto, "cannot dispatch request", ServiceException.AUTH_REQUIRED());
}
} catch (ServiceException e) {
// we came here which implies clients supports CSRF authorization
// and CSRF token is generated
LOG.info("Error during CSRF validation.", e);
return soapFaultEnv(soapProto, "cannot dispatch request", ServiceException.AUTH_REQUIRED());
}
}
SoapProtocol responseProto = zsc.getResponseProtocol();
String rid = zsc.getRequestedAccountId();
String proxyAuthToken = null;
if (rid != null) {
Provisioning prov = Provisioning.getInstance();
AccountUtil.addAccountToLogContext(prov, rid, ZimbraLog.C_NAME, ZimbraLog.C_ID, zsc.getAuthToken());
String aid = zsc.getAuthtokenAccountId();
if (aid != null && !rid.equals(aid)) {
AccountUtil.addAccountToLogContext(prov, aid, ZimbraLog.C_ANAME, ZimbraLog.C_AID, zsc.getAuthToken());
} else if (zsc.getAuthToken() != null && zsc.getAuthToken().getAdminAccountId() != null) {
AccountUtil.addAccountToLogContext(prov, zsc.getAuthToken().getAdminAccountId(), ZimbraLog.C_ANAME, ZimbraLog.C_AID, zsc.getAuthToken());
}
try {
Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(rid, false);
if (mbox != null) {
ZimbraLog.addMboxToContext(mbox.getId());
}
} catch (ServiceException ignore) {
}
try {
AuthToken at = zsc.getAuthToken();
if (at != null) {
proxyAuthToken = prov.getProxyAuthToken(rid, context);
at.setProxyAuthToken(proxyAuthToken);
}
} catch (ServiceException e) {
LOG.warn("failed to set proxy auth token: %s", e.getMessage());
}
}
if (zsc.getUserAgent() != null) {
ZimbraLog.addUserAgentToContext(zsc.getUserAgent());
}
if (zsc.getVia() != null) {
ZimbraLog.addViaToContext(zsc.getVia());
}
HttpServletRequest servletRequest = (HttpServletRequest) context.get(SoapServlet.SERVLET_REQUEST);
boolean isResumed = !ContinuationSupport.getContinuation(servletRequest).isInitial();
if (zsc.getSoapRequestId() != null) {
ZimbraLog.addSoapIdToContext(zsc.getSoapRequestId());
} else {
String soapRequestId = (String) servletRequest.getAttribute(ZimbraSoapContext.soapRequestIdAttr);
if (Strings.isNullOrEmpty(soapRequestId)) {
zsc.setNewSoapRequestId();
} else {
zsc.setSoapRequestId(soapRequestId);
}
}
logRequest(context, envelope);
context.put(ZIMBRA_CONTEXT, zsc);
context.put(ZIMBRA_ENGINE, this);
Element responseBody = null;
if (!zsc.isProxyRequest()) {
// if the client's told us that they've seen through notification block 50, we can drop old notifications up to that point
acknowledgeNotifications(zsc);
if (doc.getQName().equals(ZimbraNamespace.E_BATCH_REQUEST)) {
boolean contOnError = doc.getAttribute(ZimbraNamespace.A_ONERROR, ZimbraNamespace.DEF_ONERROR).equals("continue");
responseBody = zsc.createElement(ZimbraNamespace.E_BATCH_RESPONSE);
if (!isResumed) {
ZimbraLog.soap.info(doc.getName());
}
for (Element req : doc.listElements()) {
String id = req.getAttribute(A_REQUEST_CORRELATOR, null);
long start = System.currentTimeMillis();
Element br = dispatchRequest(dispatcher.getHandler(req), req, context, zsc);
if (!isResumed) {
ZimbraLog.soap.info("(batch) %s elapsed=%d", req.getName(), System.currentTimeMillis() - start);
}
if (id != null) {
br.addAttribute(A_REQUEST_CORRELATOR, id);
}
responseBody.addNonUniqueElement(br);
if (!contOnError && responseProto.isFault(br)) {
break;
}
if (proxyAuthToken != null) {
// requests will invalidate it when proxying locally;
// make sure it's set for each sub-request in batch
zsc.getAuthToken().setProxyAuthToken(proxyAuthToken);
}
}
} else {
String id = doc.getAttribute(A_REQUEST_CORRELATOR, null);
long start = System.currentTimeMillis();
responseBody = dispatchRequest(handler, doc, context, zsc);
if (!isResumed) {
ZimbraLog.soap.info("%s elapsed=%d", doc.getName(), System.currentTimeMillis() - start);
}
if (id != null) {
responseBody.addAttribute(A_REQUEST_CORRELATOR, id);
}
}
} else {
// We stick to local server's session when talking to the client.
try {
// Detach doc from its current parent, because it will be added as a child element of a new SOAP
// envelope in the proxy dispatcher. IllegalAddException will be thrown if we don't detach it first.
doc.detach();
ZimbraSoapContext zscTarget = new ZimbraSoapContext(zsc, zsc.getRequestedAccountId()).disableNotifications();
long start = System.currentTimeMillis();
responseBody = zsc.getProxyTarget().dispatch(doc, zscTarget);
ZimbraLog.soap.info("%s proxy=%s,elapsed=%d", doc.getName(), zsc.getProxyTarget(), System.currentTimeMillis() - start);
responseBody.detach();
} catch (SoapFaultException e) {
responseBody = e.getFault() != null ? e.getFault().detach() : responseProto.soapFault(e);
LOG.debug("proxy handler exception", e);
} catch (ServiceException e) {
responseBody = responseProto.soapFault(e);
LOG.info("proxy handler exception", e);
} catch (Throwable e) {
responseBody = responseProto.soapFault(ServiceException.FAILURE(e.toString(), e));
if (e instanceof OutOfMemoryError) {
Zimbra.halt("proxy handler exception", e);
}
LOG.warn("proxy handler exception", e);
}
}
// put notifications (new sessions and incremental change notifications) to header...
Element responseHeader = generateResponseHeader(zsc);
// ... and return the composed response
return responseProto.soapEnvelope(responseBody, responseHeader);
}
use of com.zimbra.common.soap.SoapFaultException in project zm-mailbox by Zimbra.
the class TestDataSource method testRss.
/**
* Creates a folder that syncs to another folder via RSS, and verifies that an
* RSS data source was implicitly created.
*/
@Test
public void testRss() throws Exception {
// Create source folder, make it publicly readable, and add a message to it.
ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
String parentId = Integer.toString(Mailbox.ID_FOLDER_USER_ROOT);
ZFolder sourceFolder = TestUtil.createFolder(mbox, "/" + NAME_PREFIX + " testRss source");
mbox.modifyFolderGrant(sourceFolder.getId(), GranteeType.pub, null, "r", null);
String subject = NAME_PREFIX + " testRss";
TestUtil.addMessage(mbox, subject, sourceFolder.getId());
// Create destination folder that syncs to the source folder via RSS.
String urlString = String.format("https://%s:%s/home/%s%s.rss", TestUtil.getServerAttr(Provisioning.A_zimbraServiceHostname), TestUtil.getServerAttr(Provisioning.A_zimbraMailSSLPort), USER_NAME, sourceFolder.getPath());
urlString = HttpUtil.encodePath(urlString);
ZFolder rssFolder = mbox.createFolder(parentId, NAME_PREFIX + " testRss destination", null, null, null, urlString);
// Get the data source that was implicitly created.
ZRssDataSource ds = (ZRssDataSource) getDataSource(mbox, rssFolder.getId());
assertNotNull(ds);
assertNull(mbox.testDataSource(ds));
// Import data and validate the synced message.
List<ZDataSource> list = new ArrayList<ZDataSource>();
list.add(ds);
mbox.importData(list);
waitForData(mbox, rssFolder);
ZMessage syncedMsg = TestUtil.getMessage(mbox, "in:\"" + rssFolder.getPath() + "\"");
assertEquals(subject, syncedMsg.getSubject());
/*
* Bug 102261 - simulate ZWC deleting an item from the folder
*/
ConvActionSelector sel = ConvActionSelector.createForIdsAndOperation(syncedMsg.getConversationId(), "trash");
sel.setConstraint("-dtjs");
sel.setFolder(syncedMsg.getFolderId());
try {
mbox.invokeJaxb(new ConvActionRequest(sel));
} catch (SoapFaultException sfe) {
fail("SoapFaultException caught when deleting item from RSS datasource folder - " + sfe.getMessage());
}
// Delete folder, import data, and make sure that the data source was deleted.
// Data source import runs asynchronously, so poll until the data source is gone.
mbox.deleteFolder(rssFolder.getId());
// JBF - do not do the import; it will fail if DS is already deleted
// mbox.importData(list);
// XXX bburtin: disabled check to avoid false positives (bug 54816). Some sort
// of race condition is causing this check to fail intermittently. I was unable
// to consistently repro.
/*
for (int i = 1; i <= 10; i++) {
ds = (ZRssDataSource) getDataSource(mbox, rssFolder.getId());
if (ds == null) {
break;
}
Thread.sleep(500);
}
assertNull(ds);
*/
}
Aggregations