diff --git a/CHANGES.md b/CHANGES.md index a6c9df4dd2..a750467c8d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,6 +4,17 @@ ### Behaviour changes worth reading before upgrading +- **Only global admins manage Admin on the aggregated front-page weblog.** + With `site.frontpage.weblog.aggregated=true`, that weblog's templates can + read the whole site, so granting, removing or inviting an Admin there now + needs a global admin. Before turning aggregation on, review who is Admin + on the front-page weblog. + +- **OAuth 1.0a needs AtomPub with OAuth authentication.** The OAuth endpoints + and the OAuth keys page answer only when AtomPub is enabled and its + authentication is set to OAuth. A request token is issued only for a + correctly signed request, and each request gets new credentials. + - **Check "Absolute URL to site" (`site.absoluteurl`) after upgrading.** Roller no longer takes the site's URL from the first request after a start. New installs save it during setup, and on an upgraded site where it's empty, @@ -103,6 +114,9 @@ ### Bug fixes +- **The comment filter works after editing a comment.** Saving a comment + on the Comments page left the filter form with a used-up form token, so + filtering then failed with an error. - **Media filenames keep their punctuation** when inserted into an entry. - **Changing a password ends the account's other sessions.** Saving a new password in the profile, an administrator's reset, or disabling an account diff --git a/app/src/main/java/org/apache/roller/weblogger/business/OAuthManager.java b/app/src/main/java/org/apache/roller/weblogger/business/OAuthManager.java index 80657bbe99..05111cae83 100644 --- a/app/src/main/java/org/apache/roller/weblogger/business/OAuthManager.java +++ b/app/src/main/java/org/apache/roller/weblogger/business/OAuthManager.java @@ -124,7 +124,8 @@ boolean authorizeRequestToken(String consumerKey, String requestToken, String us throws OAuthException; /** - * Generate a fresh request token and secret for a consumer. + * Generate fresh temporary credentials for a consumer. A consumer with + * active access credentials keeps its current grant. * * @throws OAuthException */ @@ -133,7 +134,7 @@ void generateRequestToken( throws OAuthException; /** - * Generate a fresh request token and secret for a consumer. + * Exchange the approved temporary credentials for an access token. * * @throws OAuthException */ diff --git a/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerImpl.java b/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerImpl.java index 373711c94a..14c544ba14 100644 --- a/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerImpl.java +++ b/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerImpl.java @@ -22,6 +22,8 @@ import java.sql.Timestamp; import java.util.Date; import java.util.UUID; +import jakarta.persistence.EntityManager; +import jakarta.persistence.LockModeType; import jakarta.persistence.Query; import jakarta.persistence.TypedQuery; import net.oauth.OAuthAccessor; @@ -31,7 +33,6 @@ import net.oauth.OAuthProblemException; import net.oauth.OAuthServiceProvider; import net.oauth.OAuthValidator; -import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -159,58 +160,47 @@ public boolean authorizeRequestToken(String consumerKey, String requestToken, St } } - /** - * Generate a fresh request token and secret for a consumer. - * @throws OAuthException - */ @Override - public void generateRequestToken( - OAuthAccessor accessor) - throws OAuthException { - - // generate oauth_token and oauth_secret - String consumer_key = accessor.consumer.consumerKey; - // generate token and secret based on consumer_key - - // for now use md5 of name + current time as token - String token_data = consumer_key + System.nanoTime(); - String token = DigestUtils.md5Hex(token_data); - // for now use md5 of name + current time + token as secret - String secret_data = consumer_key + System.nanoTime() + token; - String secret = DigestUtils.md5Hex(secret_data); - - accessor.requestToken = token; - accessor.tokenSecret = secret; - accessor.accessToken = null; + public void generateRequestToken(OAuthAccessor accessor) throws OAuthException { + String consumerKey = accessor.consumer.consumerKey; + EntityManager em = strategy.getEntityManager(true); + // Serializes issuance even while the consumer has no accessor row. + if (em.find(OAuthConsumerRecord.class, consumerKey, LockModeType.PESSIMISTIC_WRITE) == null) { + throw new OAuthProblemException("consumer_key_unknown"); + } + OAuthAccessorRecord record = em.find(OAuthAccessorRecord.class, consumerKey, + LockModeType.PESSIMISTIC_WRITE); + if (record != null && record.getAccessToken() != null) { + throw new OAuthProblemException("permission_denied"); + } - // add to the local cache - addAccessor(accessor); + accessor.requestToken = UUID.randomUUID().toString(); + accessor.tokenSecret = UUID.randomUUID().toString(); + if (record == null) { + addAccessor(accessor); + } else { + record.setRequestToken(accessor.requestToken); + record.setTokenSecret(accessor.tokenSecret); + record.setAuthorized(Boolean.FALSE); + record.setUserName(null); + record.setUpdated(new Timestamp(System.currentTimeMillis())); + } } - - /** - * Generate a fresh request token and secret for a consumer. - * @throws OAuthException - */ - @Override - public void generateAccessToken(OAuthAccessor accessor) - throws OAuthException { + @Override + public void generateAccessToken(OAuthAccessor accessor) throws OAuthException { + String token = UUID.randomUUID().toString(); try { - // generate oauth_token and oauth_secret - // generate token and secret based on consumer_key - String consumer_key = accessor.consumer.consumerKey; - - OAuthAccessorRecord record = (OAuthAccessorRecord) strategy.load( - OAuthAccessorRecord.class, accessor.consumer.consumerKey); - - // for now use md5 of name + current time as token - String token_data = consumer_key + System.nanoTime(); - String token = DigestUtils.md5Hex(token_data); - - record.setRequestToken(null); - record.setAccessToken(token); - strategy.store(record); - + Query query = strategy.getNamedUpdate("OAuthAccessorRecord.exchangeRequestToken"); + query.setParameter(1, token); + query.setParameter(2, new Timestamp(System.currentTimeMillis())); + query.setParameter(3, accessor.consumer.consumerKey); + query.setParameter(4, accessor.requestToken); + if (query.executeUpdate() != 1) { + throw new OAuthProblemException("permission_denied"); + } + accessor.accessToken = token; + accessor.requestToken = null; } catch (WebloggerException ex) { throw new OAuthException("ERROR: generating access token", ex); } diff --git a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java index 7ecbbe9d18..e2fd43bfe6 100644 --- a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java +++ b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java @@ -54,6 +54,11 @@ * We also provide some methods for converting to different data types. */ public final class WebloggerRuntimeConfig { + + public static boolean isAtomPubOAuthEnabled() { + return getBooleanProperty("webservices.enableAtomPub") + && "oauth".equals(getProperty("webservices.atomPubAuth")); + } private static Log log = LogFactory.getLog(WebloggerRuntimeConfig.class); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java index 6bf9cc9dd4..a3d5a71ad9 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -17,6 +17,7 @@ package org.apache.roller.weblogger.ui.core.security; +import java.nio.charset.StandardCharsets; import java.util.LinkedHashSet; import java.util.Set; @@ -116,16 +117,26 @@ public boolean matches(CharSequence rawPassword, String encodedPassword) { return false; } // BCrypt, for one, treats some other passwords as equal to a marker, - // so refuse any password whose stored value a marker matches too - for (String marker : markers) { - if (delegate.matches(marker, encodedPassword)) { - logRefusal(); - return false; + // so refuse any password whose stored value a marker matches too. + // BCrypt repeats its key with a NUL after each copy and reads at most + // 72 bytes, so only a password with a NUL, or of 72 bytes or more, + // can collide; the rest skip the extra hashes. + if (mayCollideWithAMarker(rawPassword.toString())) { + for (String marker : markers) { + if (delegate.matches(marker, encodedPassword)) { + logRefusal(); + return false; + } } } return true; } + private static boolean mayCollideWithAMarker(String rawPassword) { + return rawPassword.indexOf('\0') >= 0 + || rawPassword.getBytes(StandardCharsets.UTF_8).length >= 72; + } + private static void logRefusal() { // the password itself is never logged log.info("Refused a password that Roller treats as an external-login marker" diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/OAuthSettingsInterceptor.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/OAuthSettingsInterceptor.java new file mode 100644 index 0000000000..3a80367051 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/OAuthSettingsInterceptor.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + */ + +package org.apache.roller.weblogger.ui.struts2.core; + +import com.opensymphony.xwork2.ActionInvocation; +import com.opensymphony.xwork2.interceptor.AbstractInterceptor; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; + +/** Applies the AtomPub OAuth settings before running an OAuth UI action. */ +public class OAuthSettingsInterceptor extends AbstractInterceptor { + + @Override + public String intercept(ActionInvocation invocation) throws Exception { + if (!WebloggerRuntimeConfig.isAtomPubOAuthEnabled()) { + return "oauth-disabled"; + } + return invocation.invoke(); + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Members.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Members.java index 358b99e8c5..c0879128ed 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Members.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Members.java @@ -114,6 +114,18 @@ public String save() { addError("memberPermissions.oneAdminRequired"); error = true; } + if (!error && isAdminMembershipLocked()) { + for (WeblogPermission perms : permsList) { + String sval = getParameter("perm-" + perms.getId()); + if (sval != null && !perms.hasAction(sval) + && (perms.hasAction(WeblogPermission.ADMIN) + || Utilities.stringToStringList(sval, ",").contains(WeblogPermission.ADMIN))) { + addError("memberPermissions.frontPageAdminsGlobalOnly"); + error = true; + break; + } + } + } // one iteration for each line (user) in the members table Map> changes = new LinkedHashMap<>(); for (WeblogPermission perms : permsList) { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MembersInvite.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MembersInvite.java index 6d589f9694..3f3efea216 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MembersInvite.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MembersInvite.java @@ -98,6 +98,10 @@ public String save() { addError("Error looking up invitee"); } + if (WeblogPermission.ADMIN.equals(getPermissionString()) && isAdminMembershipLocked()) { + addError("memberPermissions.frontPageAdminsGlobalOnly"); + } + // if we already have an error then bail now if(hasActionErrors()) { return INPUT; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Pings.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Pings.java index d6ea886782..3756739c21 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Pings.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Pings.java @@ -171,8 +171,7 @@ public String pingNow() { if (pingResult.isError()) { log.debug("Ping Result: " + pingResult); if (pingResult.getMessage() != null && !pingResult.getMessage().isBlank()) { - addError("ping.transmittedButError"); - addError(pingResult.getMessage()); + addPingServerError(pingResult.getMessage()); } else { addError("ping.transmissionFailed"); } @@ -272,4 +271,13 @@ public Map getPingStatus() { public void setPingStatus(Map pingStatus) { this.pingStatus = pingStatus; } + + /** + * Shows the ping server's error message. It is passed as an argument, so + * it is escaped and never looked up as a message key. + */ + void addPingServerError(String message) { + addError("ping.transmittedButError"); + addError("ping.serverMessage", message); + } } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/UIAction.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/UIAction.java index 0eca476fe7..05db5efd7e 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/UIAction.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/UIAction.java @@ -19,6 +19,7 @@ package org.apache.roller.weblogger.ui.struts2.util; import com.opensymphony.xwork2.ActionSupport; +import com.opensymphony.xwork2.interceptor.ParameterNameAware; import com.opensymphony.xwork2.util.ValueStack; import org.apache.commons.text.StringEscapeUtils; import org.apache.roller.weblogger.business.UserManager; @@ -54,7 +55,7 @@ * getText(key) on the param passed into setError() and setSuccess(). */ public abstract class UIAction extends ActionSupport - implements UIActionPreparable, UISecurityEnforced, RequestAware { + implements UIActionPreparable, UISecurityEnforced, RequestAware, ParameterNameAware { // a result that sends the user to an access denied warning public static final String DENIED = "access-denied"; @@ -147,6 +148,18 @@ public boolean isUserIsAdmin() { return false; } + /** + * Whether Admin membership of the action weblog is closed to this user. + * On the aggregated front-page weblog, whose templates read the whole + * site, only global admins may grant, change or remove Admin. + */ + protected boolean isAdminMembershipLocked() { + Weblog weblog = getActionWeblog(); + return weblog != null + && WebloggerRuntimeConfig.isSiteWideWeblog(weblog.getHandle()) + && !isUserIsAdmin(); + } + /** * Cancel. * @@ -325,7 +338,30 @@ public void setWeblog(String weblog) { } public String getPageTitle() { - return getText(pageTitle); + return isPageTitleKey(pageTitle) ? getText(pageTitle) : ""; + } + + /** + * A page title is a message key from struts.xml or the action, made of + * letters, digits, dots, dashes and underscores. Struts evaluates part of + * an unknown key, so nothing else is looked up. + */ + static boolean isPageTitleKey(String key) { + return key != null && PAGE_TITLE_KEY.matcher(key).matches(); + } + + private static final java.util.regex.Pattern PAGE_TITLE_KEY = + java.util.regex.Pattern.compile("[A-Za-z0-9_.-]+"); + + /** + * Request parameters never set the page title. Some actions take it from + * struts.xml through their setter, which the params interceptor would + * otherwise also call with request values. + */ + @Override + public boolean acceptableParameterName(String parameterName) { + return parameterName == null + || !parameterName.toLowerCase(Locale.ROOT).contains("pagetitle"); } public void setPageTitle(String pageTitle) { diff --git a/app/src/main/java/org/apache/roller/weblogger/webservices/oauth/OAuthSettingsFilter.java b/app/src/main/java/org/apache/roller/weblogger/webservices/oauth/OAuthSettingsFilter.java new file mode 100644 index 0000000000..cec2748227 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/webservices/oauth/OAuthSettingsFilter.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + */ + +package org.apache.roller.weblogger.webservices.oauth; + +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; + +/** Applies the AtomPub OAuth settings to the OAuth service and UI routes. */ +public class OAuthSettingsFilter implements Filter { + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + if (!WebloggerRuntimeConfig.isAtomPubOAuthEnabled()) { + ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_NOT_FOUND); + return; + } + chain.doFilter(request, response); + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/webservices/oauth/RequestTokenServlet.java b/app/src/main/java/org/apache/roller/weblogger/webservices/oauth/RequestTokenServlet.java index 797252f8bb..f70cf8e9f2 100644 --- a/app/src/main/java/org/apache/roller/weblogger/webservices/oauth/RequestTokenServlet.java +++ b/app/src/main/java/org/apache/roller/weblogger/webservices/oauth/RequestTokenServlet.java @@ -63,36 +63,19 @@ public void processRequest(HttpServletRequest request, HttpServletResponse respo try { OAuthMessage requestMessage = OAuthServlet.getMessage(request, null); OAuthManager omgr = WebloggerFactory.getWeblogger().getOAuthManager(); - OAuthAccessor accessor = omgr.getAccessor(requestMessage); + OAuthConsumer consumer = omgr.getConsumer(requestMessage); + OAuthAccessor accessor = new OAuthAccessor(consumer); + omgr.getValidator().validateMessage(requestMessage, accessor); - if (accessor == null) { + omgr.generateRequestToken(accessor); + WebloggerFactory.getWeblogger().flush(); - OAuthConsumer consumer = omgr.getConsumer(requestMessage); - accessor = new OAuthAccessor(consumer); - omgr.getValidator().validateMessage(requestMessage, accessor); - - { - // Support the 'Variable Accessor Secret' extension - // described in http://oauth.pbwiki.com/AccessorSecret - String secret = requestMessage.getParameter("oauth_accessor_secret"); - if (secret != null) { - accessor.setProperty(OAuthConsumer.ACCESSOR_SECRET, secret); - } - } - - // generate request_token and secret - omgr.generateRequestToken(accessor); - WebloggerFactory.getWeblogger().flush(); - } - - response.setContentType("text/plain"); + response.setContentType("application/x-www-form-urlencoded"); try (OutputStream out = response.getOutputStream()) { - String token = accessor.requestToken != null ? accessor.requestToken: accessor.accessToken; OAuth.formEncode(OAuth.newList( - "oauth_token", token, + "oauth_token", accessor.requestToken, "oauth_token_secret", accessor.tokenSecret), out); } - } catch (Exception e){ handleException(e, request, response, true); } diff --git a/app/src/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index 24686a12ab..59a12e1578 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -924,6 +924,7 @@ memberPermissions.remove=Remove memberPermissions.noSelfModifications=Only another admin may alter your role. memberPermissions.oneAdminRequired=Blog must have at least one admin. +memberPermissions.frontPageAdminsGlobalOnly=Only a global admin can grant, change or remove Admin on the aggregated front-page weblog. memberPermissions.membersRemoved=Removed {0} user(s) memberPermissions.membersChanged=Changed permission for {0} user(s) @@ -1081,6 +1082,7 @@ You can send pings to any of these well-known sites. ping.successful=The ping was successful. ping.transmittedButError=The ping was transmitted but the server \ responded with the following error message. +ping.serverMessage={0} ping.transmissionFailed=The ping transmission failed. Check to make sure the \ ping target URL is correct. ping.unknownHost=The hostname in the ping target URL is unknown. diff --git a/app/src/main/resources/org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml b/app/src/main/resources/org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml index 59ba4a1cc6..61f947e73a 100644 --- a/app/src/main/resources/org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml +++ b/app/src/main/resources/org/apache/roller/weblogger/pojos/OAuthAccessorRecord.orm.xml @@ -19,6 +19,9 @@ UPDATE OAuthAccessorRecord p SET p.userName = ?1, p.authorized = true, p.updated = ?2 WHERE p.consumerKey = ?3 AND p.requestToken = ?4 AND p.accessToken IS NULL AND ((p.authorized IS NULL OR p.authorized = false) OR (p.authorized = true AND p.userName = ?1)) + + UPDATE OAuthAccessorRecord p SET p.accessToken = ?1, p.updated = ?2, p.requestToken = NULL WHERE p.consumerKey = ?3 AND p.requestToken = ?4 AND p.authorized = true AND p.accessToken IS NULL + diff --git a/app/src/main/resources/struts.xml b/app/src/main/resources/struts.xml index b074bcfd69..b5af0308c2 100644 --- a/app/src/main/resources/struts.xml +++ b/app/src/main/resources/struts.xml @@ -31,6 +31,8 @@ + + + + + @@ -160,12 +166,20 @@ .OAuthKeys + + 404 + + execute .OAuthAuthorize + + 404 + + execute diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/Comments.jsp b/app/src/main/webapp/WEB-INF/jsps/editor/Comments.jsp index 04d8fbe611..d3cbf788cf 100644 --- a/app/src/main/webapp/WEB-INF/jsps/editor/Comments.jsp +++ b/app/src/main/webapp/WEB-INF/jsps/editor/Comments.jsp @@ -462,7 +462,8 @@ try { var cdata = JSON.parse(rdata); if (cdata.salt) { - $("#comments_salt").val(cdata.salt); + // the save used up the page's salt; every form on the page shares it + $("input[name='salt']").val(cdata.salt); } return cdata; } catch (error) { diff --git a/app/src/main/webapp/WEB-INF/web.xml b/app/src/main/webapp/WEB-INF/web.xml index 7b273b1500..00db4228e5 100644 --- a/app/src/main/webapp/WEB-INF/web.xml +++ b/app/src/main/webapp/WEB-INF/web.xml @@ -94,6 +94,11 @@ org.apache.roller.weblogger.ui.core.filters.ValidateSaltFilter + + OAuthSettingsFilter + org.apache.roller.weblogger.webservices.oauth.OAuthSettingsFilter + + DebugFilter @@ -171,6 +176,16 @@ REQUEST + + OAuthSettingsFilter + /roller-services/oauth/* + /roller-ui/oauthKeys.rol + /roller-ui/oauthAuthorize.rol + REQUEST + FORWARD + INCLUDE + + ValidateSaltFilter /roller-ui/* diff --git a/app/src/test/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerTest.java b/app/src/test/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerTest.java index 1791d46e03..5c302d7fd6 100644 --- a/app/src/test/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/business/jpa/JPAOAuthManagerTest.java @@ -18,8 +18,11 @@ package org.apache.roller.weblogger.business.jpa; +import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; +import net.oauth.OAuthMessage; +import net.oauth.OAuthProblemException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.TestUtils; @@ -121,4 +124,55 @@ public void testAuthorizeRequestTokenTransition() throws Exception { omgr.removeConsumer(consumer); TestUtils.endSession(true); } + + @Test + void temporaryCredentialsCanBeReissuedAndExchanged() throws Exception { + JPAOAuthManagerImpl manager = (JPAOAuthManagerImpl) + WebloggerFactory.getWeblogger().getOAuthManager(); + String owner = "oauth-client-user"; + String key = "oauth-client-key"; + OAuthConsumer consumer = manager.addConsumer(owner, key); + TestUtils.endSession(true); + + OAuthAccessor first = new OAuthAccessor(consumer); + manager.generateRequestToken(first); + TestUtils.endSession(true); + + assertNotNull(manager.getAccessorByToken(first.requestToken)); + TestUtils.endSession(false); + + OAuthAccessor second = new OAuthAccessor(consumer); + manager.generateRequestToken(second); + TestUtils.endSession(true); + + String pendingToken = second.requestToken; + assertNotEquals(first.requestToken, pendingToken); + assertNotEquals(first.tokenSecret, second.tokenSecret); + assertNull(manager.getAccessorByToken(first.requestToken)); + assertNotNull(manager.getAccessorByToken(pendingToken)); + assertTrue(manager.authorizeRequestToken(key, pendingToken, owner)); + TestUtils.endSession(true); + + OAuthAccessor approved = manager.getAccessorByToken(pendingToken); + manager.generateAccessToken(approved); + TestUtils.endSession(true); + assertNotNull(approved.accessToken); + assertNull(manager.getAccessorByToken(pendingToken)); + + OAuthAccessor active = manager.getAccessorByToken(approved.accessToken); + OAuthMessage atomRequest = approved.newRequestMessage("GET", + "https://roller.example/roller-services/app", OAuth.newList("oauth_signature_method", "HMAC-SHA1")); + manager.getValidator().validateMessage(atomRequest, manager.getAccessor(atomRequest)); + assertEquals(owner, active.consumer.getProperty("userId")); + TestUtils.endSession(false); + + assertThrows(OAuthProblemException.class, + () -> manager.generateRequestToken(new OAuthAccessor(consumer))); + TestUtils.endSession(false); + + assertEquals(approved.accessToken, manager.getAccessorByKey(key).accessToken); + manager.removeAccessor(active); + manager.removeConsumer(consumer); + TestUtils.endSession(true); + } } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java index e93592900c..e154c5e995 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java @@ -194,6 +194,26 @@ void emptyEntriesInThePreviousPlaceholdersAreIgnored() throws Exception { assertFalse(ExternalLoginAwarePasswordEncoder.isExternalLoginMarker(" ")); } + @Test + void aPasswordThatBcryptTreatsAsEqualToAPlaceholderIsNotAPassword() throws Exception { + String longMarker = ""; + setProperty("users.passwords.externalAuthValue", longMarker); + PasswordEncoder encoder = new ExternalLoginAwarePasswordEncoder(new BCryptPasswordEncoder()); + // BCrypt repeats its key with a NUL after each copy, so this has the + // default placeholder's hash + String repeated = "" + '\0' + ""; + // BCrypt reads only the first 72 bytes, so this has the long one's + String sameStart = longMarker + "suffix"; + for (String[] pair : new String[][] {{"", repeated}, {longMarker, sameStart}}) { + String stored = encoder.encode(pair[0]); + assertTrue(new BCryptPasswordEncoder().matches(pair[1], stored)); + assertFalse(encoder.matches(pair[1], stored)); + } + // a long password that isn't a placeholder still works + String longPassword = "y".repeat(80); + assertTrue(encoder.matches(longPassword, encoder.encode(longPassword))); + } + @Test void anEmptyConfiguredPlaceholderIsNotAPassword() throws Exception { setProperty("authentication.method", "db"); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/FrontPageAdminMembershipTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/FrontPageAdminMembershipTest.java new file mode 100644 index 0000000000..59ccc264c3 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/FrontPageAdminMembershipTest.java @@ -0,0 +1,224 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.roller.weblogger.ui.struts2.editor; + +import java.util.List; +import java.util.Map; +import org.apache.roller.weblogger.TestUtils; +import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.business.UserManager; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; +import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.pojos.Weblog; +import org.apache.roller.weblogger.pojos.WeblogPermission; +import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +/** + * The aggregated front-page weblog's templates read the whole site, so only + * global admins decide who is Admin there. + */ +class FrontPageAdminMembershipTest { + + private static final String LOCKED = "memberPermissions.frontPageAdminsGlobalOnly"; + + private String ownerName; + private String memberName; + private String weblogId; + private String handle; + private String savedHandle; + private String savedAggregated; + + @BeforeEach + void setUp() throws Exception { + TestUtils.setupWeblogger(); + User owner = TestUtils.setupUser("frontpageowner"); + User member = TestUtils.setupUser("frontpagemember"); + ownerName = owner.getUserName(); + memberName = member.getUserName(); + Weblog weblog = TestUtils.setupWeblog("frontpageadmins", owner); + weblogId = weblog.getId(); + handle = weblog.getHandle(); + users().grantWeblogPermission(weblog, member, List.of(WeblogPermission.POST)); + // the weblog's Admin is not a global admin + if (users().hasRole("admin", owner)) { + users().revokeRole("admin", owner); + } + TestUtils.endSession(true); + savedHandle = setProperty("site.frontpage.weblog.handle", handle); + savedAggregated = setProperty("site.frontpage.weblog.aggregated", "true"); + } + + @AfterEach + void tearDown() throws Exception { + setProperty("site.frontpage.weblog.handle", savedHandle); + setProperty("site.frontpage.weblog.aggregated", savedAggregated); + TestUtils.teardownWeblog(weblogId); + TestUtils.teardownUser(ownerName); + TestUtils.teardownUser(memberName); + TestUtils.endSession(true); + } + + @Test + void weblogAdminCannotPromoteAMember() throws Exception { + Members action = membersSaving(Map.of( + ownerName, WeblogPermission.ADMIN, + memberName, WeblogPermission.ADMIN)); + assertEquals(List.of(LOCKED), List.copyOf(action.getActionErrors())); + assertEquals(List.of(WeblogPermission.POST), permission(memberName).getActionsAsList()); + } + + @Test + void weblogAdminCannotRemoveAnotherAdmin() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.ADMIN)); + TestUtils.endSession(true); + Members action = membersSaving(Map.of( + ownerName, WeblogPermission.ADMIN, + memberName, "-1")); + assertEquals(List.of(LOCKED), List.copyOf(action.getActionErrors())); + assertTrue(permission(memberName).hasAction(WeblogPermission.ADMIN)); + } + + @Test + void weblogAdminCanStillChangeOtherRoles() throws Exception { + Members action = membersSaving(Map.of( + ownerName, WeblogPermission.ADMIN, + memberName, WeblogPermission.EDIT_DRAFT)); + assertFalse(action.hasActionErrors(), () -> action.getActionErrors().toString()); + assertEquals(List.of(WeblogPermission.EDIT_DRAFT), permission(memberName).getActionsAsList()); + } + + @Test + void globalAdminCanPromoteAMember() throws Exception { + users().grantRole("admin", user(ownerName)); + TestUtils.endSession(true); + Members action = membersSaving(Map.of( + ownerName, WeblogPermission.ADMIN, + memberName, WeblogPermission.ADMIN)); + assertFalse(action.hasActionErrors(), () -> action.getActionErrors().toString()); + assertTrue(permission(memberName).hasAction(WeblogPermission.ADMIN)); + } + + @Test + void withoutAggregationTheWeblogAdminCanPromote() throws Exception { + setProperty("site.frontpage.weblog.aggregated", "false"); + Members action = membersSaving(Map.of( + ownerName, WeblogPermission.ADMIN, + memberName, WeblogPermission.ADMIN)); + assertFalse(action.hasActionErrors(), () -> action.getActionErrors().toString()); + assertTrue(permission(memberName).hasAction(WeblogPermission.ADMIN)); + } + + @Test + void weblogAdminCannotInviteAnAdmin() throws Exception { + User invitee = TestUtils.setupUser("frontpageinvitee"); + TestUtils.endSession(true); + try { + MembersInvite action = inviting(invitee.getUserName(), WeblogPermission.ADMIN); + assertEquals(List.of(LOCKED), List.copyOf(action.getActionErrors())); + assertNull(permission(invitee.getUserName())); + + MembersInvite author = inviting(invitee.getUserName(), WeblogPermission.POST); + assertFalse(author.hasActionErrors(), () -> author.getActionErrors().toString()); + } finally { + // remove the invitation first, so no permission is left without its user + if (permission(invitee.getUserName()) != null) { + users().revokeWeblogPermission(weblog(), user(invitee.getUserName()), + WeblogPermission.ALL_ACTIONS); + TestUtils.endSession(true); + } + TestUtils.teardownUser(invitee.getUserName()); + TestUtils.endSession(true); + } + } + + private MembersInvite inviting(String name, String permission) throws Exception { + MembersInvite action = spy(new MembersInvite()); + stubText(action); + action.setAuthenticatedUser(user(ownerName)); + action.setActionWeblog(weblog()); + action.setUserName(name); + action.setPermissionString(permission); + action.save(); + TestUtils.endSession(true); + return action; + } + + private Members membersSaving(Map choices) throws Exception { + Members action = spy(new Members()); + stubText(action); + action.setAuthenticatedUser(user(ownerName)); + action.setActionWeblog(weblog()); + doAnswer(call -> null).when(action).getParameter(anyString()); + for (Map.Entry choice : choices.entrySet()) { + doAnswer(call -> choice.getValue()).when(action) + .getParameter("perm-" + permission(choice.getKey()).getId()); + } + action.save(); + TestUtils.endSession(true); + return action; + } + + private static String setProperty(String name, String value) throws Exception { + PropertiesManager mgr = WebloggerFactory.getWeblogger().getPropertiesManager(); + RuntimeConfigProperty prop = mgr.getProperty(name); + String old = prop.getValue(); + prop.setValue(value); + mgr.saveProperty(prop); + TestUtils.endSession(true); + return old; + } + + private static void stubText(UIAction action) { + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString()); + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString(), anyString()); + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString(), anyList()); + doAnswer(call -> call.getArgument(0)).when(action) + .getText(anyString(), anyString(), anyString()); + } + + private WeblogPermission permission(String name) throws Exception { + return users().getWeblogPermissionIncludingPending(weblog(), user(name)); + } + + private static UserManager users() { + return WebloggerFactory.getWeblogger().getUserManager(); + } + + private Weblog weblog() throws Exception { + return WebloggerFactory.getWeblogger().getWeblogManager().getWeblog(weblogId); + } + + private static User user(String name) throws Exception { + return users().getUserByUserName(name, null); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/PingsTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/PingsTest.java new file mode 100644 index 0000000000..444a27daa1 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/PingsTest.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.roller.weblogger.ui.struts2.editor; + +import com.opensymphony.xwork2.ActionContext; +import com.opensymphony.xwork2.LocalizedTextProvider; +import com.opensymphony.xwork2.config.ConfigurationManager; +import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider; +import com.opensymphony.xwork2.inject.Container; +import com.opensymphony.xwork2.util.ValueStack; +import com.opensymphony.xwork2.util.ValueStackFactory; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PingsTest { + + // the ping server's reply is shown as text, never looked up as a message key + @Test + public void pingServerErrorIsShownAsText() { + ConfigurationManager configurationManager = new ConfigurationManager("xwork"); + configurationManager.addContainerProvider(new XWorkConfigurationProvider()); + Container container = configurationManager.getConfiguration().getContainer(); + ValueStack stack = container.getInstance(ValueStackFactory.class).createValueStack(); + ActionContext.setContext(new ActionContext(stack.getContext())); + try { + container.getInstance(LocalizedTextProvider.class) + .addDefaultResourceBundle("ApplicationResources"); + Pings action = new Pings(); + container.inject(action); + stack.push(action); + + action.addPingServerError("addActionMessage('marker'+7*191).x "); + + assertTrue(action.getActionMessages().isEmpty(), "the reply was evaluated"); + List errors = List.copyOf(action.getActionErrors()); + assertEquals(2, errors.size()); + assertTrue(errors.get(0).startsWith("The ping was transmitted")); + assertEquals("addActionMessage('marker'+7*191).x <b>", errors.get(1)); + } finally { + ActionContext.setContext(null); + } + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/util/UIActionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/util/UIActionTest.java index 19e4027ec8..a7029b3df8 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/util/UIActionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/util/UIActionTest.java @@ -30,6 +30,8 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class UIActionTest { @@ -97,4 +99,27 @@ public void testGetTextWithValueStackEscapesStringArgs() { } } + // the page title comes from struts.xml or the action itself, never from + // the request, because it is looked up as a message key + @Test + public void testPageTitleIsNotARequestParameter() { + UIAction action = new org.apache.roller.weblogger.ui.struts2.core.Install(); + for (String name : new String[] {"pageTitle", "PageTitle", "top.pageTitle", + "[0].pageTitle", "pageTitle[0]"}) { + assertFalse(action.acceptableParameterName(name), name); + } + assertTrue(action.acceptableParameterName("bean.title")); + assertTrue(action.acceptableParameterName("weblog")); + } + + @Test + public void testPageTitleOnlyLooksUpPlainKeys() { + assertTrue(UIAction.isPageTitleKey("weblogEdit.title.newEntry")); + assertTrue(UIAction.isPageTitleKey("installer.error.connection.pageTitle")); + assertFalse(UIAction.isPageTitleKey(null)); + assertFalse(UIAction.isPageTitleKey("addActionMessage('x').x")); + assertFalse(UIAction.isPageTitleKey("a b.c")); + assertFalse(UIAction.isPageTitleKey("#a.b")); + } + } diff --git a/app/src/test/java/org/apache/roller/weblogger/webservices/oauth/OAuthSettingsTest.java b/app/src/test/java/org/apache/roller/weblogger/webservices/oauth/OAuthSettingsTest.java new file mode 100644 index 0000000000..692d0e3647 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/webservices/oauth/OAuthSettingsTest.java @@ -0,0 +1,103 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one or more +* contributor license agreements. The ASF licenses this file to You +* under the Apache License, Version 2.0 (the "License"); you may not +* use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. For additional information regarding +* copyright in this work, please see the NOTICE file in the top level +* directory of this distribution. +*/ + +package org.apache.roller.weblogger.webservices.oauth; + +import com.opensymphony.xwork2.ActionInvocation; +import java.nio.file.Path; +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathFactory; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; +import org.apache.roller.weblogger.ui.struts2.core.OAuthSettingsInterceptor; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.w3c.dom.Document; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +class OAuthSettingsTest { + @Test + void servicesAndActionsUseAtomPubSettings() throws Exception { + assertRouteSettings(false, "basic", false); + assertRouteSettings(false, "oauth", false); + assertRouteSettings(true, "basic", false); + assertRouteSettings(true, "oauth", true); + } + + private void assertRouteSettings(boolean atomPub, String scheme, boolean enabled) throws Exception { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + FilterChain chain = mock(FilterChain.class); + ActionInvocation invocation = mock(ActionInvocation.class); + when(invocation.invoke()).thenReturn("success"); + try (MockedStatic config = mockStatic(WebloggerRuntimeConfig.class)) { + config.when(() -> WebloggerRuntimeConfig.getBooleanProperty("webservices.enableAtomPub")) + .thenReturn(atomPub); + config.when(() -> WebloggerRuntimeConfig.getProperty("webservices.atomPubAuth")).thenReturn(scheme); + config.when(WebloggerRuntimeConfig::isAtomPubOAuthEnabled).thenCallRealMethod(); + + new OAuthSettingsFilter().doFilter(request, response, chain); + String result = new OAuthSettingsInterceptor().intercept(invocation); + + if (enabled) { + verify(chain).doFilter(request, response); + assertEquals("success", result); + } else { + verify(response).setStatus(HttpServletResponse.SC_NOT_FOUND); + verifyNoInteractions(chain); + verify(invocation, never()).invoke(); + assertEquals("oauth-disabled", result); + } + } + } + + @Test + void descriptorsConnectTheOAuthRoutes() throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + Document web = factory.newDocumentBuilder().parse( + Path.of("src/main/webapp/WEB-INF/web.xml").toFile()); + Document struts = factory.newDocumentBuilder().parse( + Path.of("src/main/resources/struts.xml").toFile()); + XPath xpath = XPathFactory.newInstance().newXPath(); + + String mapping = "/web-app/filter-mapping[filter-name='OAuthSettingsFilter']"; + assertEquals("/roller-services/oauth/*", xpath.evaluate(mapping + "/url-pattern[1]", web)); + assertEquals("/roller-ui/oauthKeys.rol", xpath.evaluate(mapping + "/url-pattern[2]", web)); + assertEquals("/roller-ui/oauthAuthorize.rol", xpath.evaluate(mapping + "/url-pattern[3]", web)); + assertTrue(Boolean.parseBoolean(xpath.evaluate( + "boolean(" + mapping + "/following-sibling::filter-mapping[filter-name='ValidateSaltFilter'])", + web))); + String ui = "/struts/package[@namespace='/roller-ui']"; + assertEquals("OAuthSettingsInterceptor", xpath.evaluate( + ui + "/interceptors/interceptor-stack[@name='oauthStack']/interceptor-ref[1]/@name", struts)); + for (String name : new String[]{"oauthKeys", "oauthAuthorize"}) { + String action = ui + "/action[@name='" + name + "']"; + assertEquals("oauthStack", xpath.evaluate(action + "/interceptor-ref/@name", struts)); + assertEquals("404", xpath.evaluate( + action + "/result[@name='oauth-disabled' and @type='httpheader']/param[@name='status']", + struts)); + } + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/webservices/oauth/RequestTokenServletTest.java b/app/src/test/java/org/apache/roller/weblogger/webservices/oauth/RequestTokenServletTest.java new file mode 100644 index 0000000000..35ca9ae9af --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/webservices/oauth/RequestTokenServletTest.java @@ -0,0 +1,156 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one or more +* contributor license agreements. The ASF licenses this file to You +* under the Apache License, Version 2.0 (the "License"); you may not +* use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. For additional information regarding +* copyright in this work, please see the NOTICE file in the top level +* directory of this distribution. +*/ + +package org.apache.roller.weblogger.webservices.oauth; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import net.oauth.OAuth; +import net.oauth.OAuthAccessor; +import net.oauth.OAuthConsumer; +import net.oauth.OAuthMessage; +import net.oauth.SimpleOAuthValidator; +import org.apache.roller.weblogger.business.OAuthManager; +import org.apache.roller.weblogger.business.Weblogger; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +class RequestTokenServletTest { + private static final String URL = "https://roller.example/roller-services/oauth/requestToken"; + private static final String CALLBACK = "https://client.example/return?state=ready"; + + private final RequestTokenServlet servlet = new RequestTokenServlet(); + private final Weblogger weblogger = mock(Weblogger.class); + private final OAuthManager manager = mock(OAuthManager.class); + private final HttpServletResponse response = mock(HttpServletResponse.class); + private final OAuthConsumer consumer = new OAuthConsumer(null, "reader", "client-key", null); + private final ByteArrayOutputStream body = new ByteArrayOutputStream(); + + @BeforeEach + void setUp() throws Exception { + when(weblogger.getOAuthManager()).thenReturn(manager); + when(manager.getConsumer(any())).thenReturn(consumer); + when(manager.getValidator()).thenReturn(new SimpleOAuthValidator()); + when(response.getOutputStream()).thenReturn(new ServletOutputStream() { + @Override + public void write(int value) { + body.write(value); + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setWriteListener(WriteListener listener) { + } + }); + doAnswer(call -> { + OAuthAccessor accessor = call.getArgument(0); + accessor.requestToken = "issued-token"; + accessor.tokenSecret = "issued-secret"; + return null; + }).when(manager).generateRequestToken(any()); + } + + @Test + void signedPostReceivesTemporaryCredentials() throws Exception { + assertTemporaryCredentials("POST"); + } + + @Test + void signedGetReceivesTemporaryCredentials() throws Exception { + assertTemporaryCredentials("GET"); + } + + private void assertTemporaryCredentials(String method) throws Exception { + try (MockedStatic factory = mockStatic(WebloggerFactory.class)) { + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + + issue(method, request(method, CALLBACK, consumer)); + + ArgumentCaptor generated = ArgumentCaptor.forClass(OAuthAccessor.class); + verify(manager).generateRequestToken(generated.capture()); + assertNull(generated.getValue().accessToken); + assertEquals(OAuth.formEncode(OAuth.newList("oauth_token", "issued-token", + "oauth_token_secret", "issued-secret")), + body.toString(StandardCharsets.UTF_8)); + verify(manager, never()).getAccessor(any()); + verify(weblogger).flush(); + } + } + + @Test + void postRequiresMatchingClientCredentials() throws Exception { + assertMatchingClientCredentials("POST"); + } + + @Test + void getRequiresMatchingClientCredentials() throws Exception { + assertMatchingClientCredentials("GET"); + } + + private void assertMatchingClientCredentials(String method) throws Exception { + OAuthConsumer other = new OAuthConsumer(null, consumer.consumerKey, "other-client-key", null); + try (MockedStatic factory = mockStatic(WebloggerFactory.class)) { + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + + issue(method, request(method, CALLBACK, other)); + + verify(manager, never()).generateRequestToken(any()); + verify(weblogger, never()).flush(); + assertTrue(body.toString(StandardCharsets.UTF_8).contains("oauth_problem=signature_invalid")); + } + } + + private void issue(String method, HttpServletRequest request) throws Exception { + if ("GET".equals(method)) { + servlet.doGet(request, response); + } else { + servlet.doPost(request, response); + } + } + + private HttpServletRequest request(String method, String callback, OAuthConsumer signer) throws Exception { + OAuthMessage message = new OAuthAccessor(signer).newRequestMessage(method, URL, + OAuth.newList("oauth_signature_method", "HMAC-SHA1", "oauth_callback", callback)); + Map parameters = new HashMap<>(); + message.getParameters().forEach(parameter -> + parameters.put(parameter.getKey(), new String[]{parameter.getValue()})); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getMethod()).thenReturn(method); + when(request.getRequestURL()).thenReturn(new StringBuffer(URL)); + when(request.getParameterMap()).thenReturn(parameters); + return request; + } +}