Author: angela
Date: Thu May 16 07:01:13 2019
New Revision: 1859352
URL: http://svn.apache.org/viewvc?rev=1859352&view=rev
Log:
OAK-8320 : Improve tests for o.a.j.oak.security.authentication.token package
Added:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplExceptionTest.java
(with props)
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/AbstractSecurityTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/AbstractTokenTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestCredentialsSupport.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestLoginModule.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenAuthenticationTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenCleanupTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenConfigurationImplOSGiTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenDefaultLoginModuleTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenInfoTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleCredentialsSupportTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenNoRefreshTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplReadOnlyTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplTest.java
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenValidatorTest.java
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/AbstractSecurityTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/AbstractSecurityTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/AbstractSecurityTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/AbstractSecurityTest.java
Thu May 16 07:01:13 2019
@@ -241,7 +241,7 @@ public abstract class AbstractSecurityTe
return new PartialValueFactory(getNamePathMapper());
}
- protected long waitForSystemTimeIncrement(long old) {
+ protected static long waitForSystemTimeIncrement(long old) {
while (old == System.currentTimeMillis()) {
// wait for system timer to move
}
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/AbstractTokenTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/AbstractTokenTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/AbstractTokenTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/AbstractTokenTest.java
Thu May 16 07:01:13 2019
@@ -23,17 +23,21 @@ import org.apache.jackrabbit.oak.Abstrac
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.plugins.identifier.IdentifierManager;
+import org.apache.jackrabbit.oak.plugins.tree.TreeUtil;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import
org.apache.jackrabbit.oak.spi.security.authentication.credentials.CredentialsSupport;
import
org.apache.jackrabbit.oak.spi.security.authentication.credentials.SimpleCredentialsSupport;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConstants;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenInfo;
+import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenProvider;
import org.apache.jackrabbit.oak.spi.security.user.UserConfiguration;
-import org.apache.jackrabbit.oak.util.NodeUtil;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
import org.junit.Before;
+import java.util.Collections;
+
+import static org.junit.Assert.assertNotNull;
+
/**
* AbstractTokenTest...
*/
@@ -68,30 +72,41 @@ public abstract class AbstractTokenTest
return new TokenProviderImpl(root, options, userConfiguration,
credentialsSupport);
}
+ @NotNull
ConfigurationParameters getTokenConfig() {
return ConfigurationParameters.EMPTY;
}
- @Nullable
+ @NotNull
Tree getTokenTree(@NotNull TokenInfo info) {
String token = info.getToken();
int pos = token.indexOf('_');
String nodeId = (pos == -1) ? token : token.substring(0, pos);
- return new IdentifierManager(root).getTree(nodeId);
+ Tree t = new IdentifierManager(root).getTree(nodeId);
+ assertNotNull(t);
+ return t;
}
@NotNull
- Tree createTokenTree(@NotNull TokenInfo base, @NotNull NodeUtil parent,
- @NotNull String ntName) throws AccessDeniedException {
+ Tree replaceTokenTree(@NotNull TokenInfo base, @NotNull Tree parent,
+ @NotNull String ntName) throws AccessDeniedException
{
Tree tokenTree = getTokenTree(base);
- Tree tree = parent.addChild("token", ntName).getTree();
+ Tree tree = TreeUtil.addChild(parent, "token", ntName);
tree.setProperty(tokenTree.getProperty(JcrConstants.JCR_UUID));
tree.setProperty(tokenTree.getProperty(TOKEN_ATTRIBUTE_KEY));
tree.setProperty(tokenTree.getProperty(TOKEN_ATTRIBUTE_EXPIRY));
+ tokenTree.remove();
return tree;
}
- void waitUntilExpired(@NotNull TokenInfo info) {
+ @NotNull
+ static TokenInfo createTokenInfo(@NotNull TokenProvider tp, @NotNull
String userId) {
+ TokenInfo info = tp.createToken(userId, Collections.emptyMap());
+ assertNotNull(info);
+ return info;
+ }
+
+ static void waitUntilExpired(@NotNull TokenInfo info) {
long now = System.currentTimeMillis();
while (!info.isExpired(now)) {
now = waitForSystemTimeIncrement(now);
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestCredentialsSupport.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestCredentialsSupport.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestCredentialsSupport.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestCredentialsSupport.java
Thu May 16 07:01:13 2019
@@ -16,7 +16,6 @@
*/
package org.apache.jackrabbit.oak.security.authentication.token;
-import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.jcr.Credentials;
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestLoginModule.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestLoginModule.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestLoginModule.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TestLoginModule.java
Thu May 16 07:01:13 2019
@@ -21,7 +21,6 @@ import java.util.Set;
import javax.jcr.Credentials;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
import
org.apache.jackrabbit.oak.spi.security.authentication.AbstractLoginModule;
import org.apache.jackrabbit.oak.spi.security.authentication.AuthInfoImpl;
@@ -49,7 +48,7 @@ public class TestLoginModule extends Abs
}
@Override
- public boolean login() throws LoginException {
+ public boolean login() {
credentials = getCredentials();
if (credentials != null) {
userId = credentialsSupport.getUserId(credentials);
@@ -62,7 +61,7 @@ public class TestLoginModule extends Abs
}
@Override
- public boolean commit() throws LoginException {
+ public boolean commit() {
if (userId != null) {
subject.getPrincipals().add(EveryonePrincipal.getInstance());
setAuthInfo(new AuthInfoImpl(userId,
credentialsSupport.getAttributes(credentials), subject.getPrincipals()),
subject);
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenAuthenticationTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenAuthenticationTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenAuthenticationTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenAuthenticationTest.java
Thu May 16 07:01:13 2019
@@ -17,7 +17,6 @@
package org.apache.jackrabbit.oak.security.authentication.token;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.UUID;
import javax.jcr.Credentials;
@@ -27,12 +26,10 @@ import javax.security.auth.login.LoginEx
import com.google.common.collect.ImmutableMap;
import
org.apache.jackrabbit.api.security.authentication.token.TokenCredentials;
-import org.apache.jackrabbit.oak.AbstractSecurityTest;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConstants;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenInfo;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenProvider;
-import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -77,7 +74,7 @@ public class TokenAuthenticationTest ext
}
@Test
- public void testAuthenticateWithInvalidTokenCredentials() throws Exception
{
+ public void testAuthenticateWithInvalidTokenCredentials() {
try {
authentication.authenticate(new
TokenCredentials(UUID.randomUUID().toString()));
fail("LoginException expected");
@@ -88,7 +85,7 @@ public class TokenAuthenticationTest ext
@Test
public void testAuthenticate() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertTrue(authentication.authenticate(new
TokenCredentials(info.getToken())));
}
@@ -104,7 +101,7 @@ public class TokenAuthenticationTest ext
@Test
public void testGetTokenInfoAfterAuthenticate() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
authentication.authenticate(new TokenCredentials(info.getToken()));
TokenInfo info2 = authentication.getTokenInfo();
@@ -115,6 +112,7 @@ public class TokenAuthenticationTest ext
@Test
public void testAuthenticateNotMatchingToken() {
TokenInfo info = tokenProvider.createToken(userId,
ImmutableMap.of(TokenConstants.TOKEN_ATTRIBUTE + "_mandatory", "val"));
+ assertNotNull(info);
try {
authentication.authenticate(new TokenCredentials(info.getToken()));
fail("LoginException expected");
@@ -129,7 +127,7 @@ public class TokenAuthenticationTest ext
ConfigurationParameters.of(TokenProvider.PARAM_TOKEN_EXPIRATION, 1),
getUserConfiguration());
- TokenInfo info = tp.createToken(userId, Collections.<String,
Object>emptyMap());
+ TokenInfo info = createTokenInfo(tp, userId);
waitUntilExpired(info);
try {
@@ -150,7 +148,7 @@ public class TokenAuthenticationTest ext
@Test
public void testGetUserId() throws LoginException {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertTrue(authentication.authenticate(new
TokenCredentials(info.getToken())));
assertEquals(userId, authentication.getUserId());
}
@@ -162,7 +160,7 @@ public class TokenAuthenticationTest ext
@Test
public void testGetUserPrincipal() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertTrue(authentication.authenticate(new
TokenCredentials(info.getToken())));
assertEquals(getTestUser().getPrincipal(),
authentication.getUserPrincipal());
}
@@ -181,7 +179,7 @@ public class TokenAuthenticationTest ext
}
@Test
- public void testAuthenticateRefreshToken() throws Exception {
+ public void testAuthenticateRefreshToken() {
TokenCredentials tc = new TokenCredentials("token");
TokenProvider tp = mock(TokenProvider.class);
TokenInfo ti = mock(TokenInfo.class);
@@ -200,7 +198,7 @@ public class TokenAuthenticationTest ext
}
@Test
- public void testAuthenticateSkipRefreshToken() throws Exception {
+ public void testAuthenticateSkipRefreshToken() {
TokenCredentials tc = new TokenCredentials("token");
tc.setAttribute(TokenConstants.TOKEN_SKIP_REFRESH, "");
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenCleanupTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenCleanupTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenCleanupTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenCleanupTest.java
Thu May 16 07:01:13 2019
@@ -37,6 +37,7 @@ public class TokenCleanupTest extends Ab
userId = getTestUser().getID();
}
+ @NotNull
@Override
ConfigurationParameters getTokenConfig() {
return
ConfigurationParameters.of(TokenProviderImpl.PARAM_TOKEN_CLEANUP_THRESHOLD, 5);
@@ -61,7 +62,7 @@ public class TokenCleanupTest extends Ab
int tkn = 0;
boolean clean = false;
while (!clean && tkn < 50) {
- TokenInfo tokenInfo = tokenProvider.createToken(userId,
ImmutableMap.of());
+ TokenInfo tokenInfo = createTokenInfo(tokenProvider, userId);
clean = TokenProviderImpl.shouldRunCleanup(tokenInfo.getToken());
tkn++;
}
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenConfigurationImplOSGiTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenConfigurationImplOSGiTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenConfigurationImplOSGiTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenConfigurationImplOSGiTest.java
Thu May 16 07:01:13 2019
@@ -49,7 +49,7 @@ public class TokenConfigurationImplOSGiT
tokenConfiguration.setSecurityProvider(getSecurityProvider());
- context.registerInjectActivateService(tokenConfiguration,
ImmutableMap.<String, Object>of(
+ context.registerInjectActivateService(tokenConfiguration,
ImmutableMap.of(
TokenProvider.PARAM_TOKEN_EXPIRATION, 25,
TokenProvider.PARAM_TOKEN_LENGTH, 4));
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenDefaultLoginModuleTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenDefaultLoginModuleTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenDefaultLoginModuleTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenDefaultLoginModuleTest.java
Thu May 16 07:01:13 2019
@@ -61,16 +61,10 @@ public class TokenDefaultLoginModuleTest
@Test
public void testNullLogin() throws Exception {
- ContentSession cs = null;
- try {
- cs = login(null);
+ try (ContentSession cs = login(null)) {
fail("Null login should fail");
} catch (LoginException e) {
// success
- } finally {
- if (cs != null) {
- cs.close();
- }
}
}
}
\ No newline at end of file
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenInfoTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenInfoTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenInfoTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenInfoTest.java
Thu May 16 07:01:13 2019
@@ -48,7 +48,7 @@ public class TokenInfoTest extends Abstr
@Test
public void testGetUserId() {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertEquals(userId, info.getUserId());
info = tokenProvider.getTokenInfo(info.getToken());
@@ -57,7 +57,7 @@ public class TokenInfoTest extends Abstr
@Test
public void testGetToken() {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertNotNull(info.getToken());
info = tokenProvider.getTokenInfo(info.getToken());
@@ -68,7 +68,7 @@ public class TokenInfoTest extends Abstr
public void testIsExpired() {
long loginTime = new Date().getTime();
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertFalse(info.isExpired(loginTime));
loginTime = new Date().getTime() + 3600000;
@@ -80,7 +80,7 @@ public class TokenInfoTest extends Abstr
@Test
public void testMatches() {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertTrue(info.matches(new TokenCredentials(info.getToken())));
Map<String,String> attributes = new HashMap<String, String>();
@@ -101,6 +101,12 @@ public class TokenInfoTest extends Abstr
}
@Test
+ public void testMatchesCredentialsWithUnsupportedToken() {
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
+ assertFalse(info.matches(new TokenCredentials("invaldToken")));
+ }
+
+ @Test
public void testGetAttributes() {
Map<String, String> reserved = new HashMap<String, String>();
reserved.put(TOKEN_ATTRIBUTE, "value");
@@ -144,20 +150,20 @@ public class TokenInfoTest extends Abstr
}
@Test
- public void testRemoveToken() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ public void testRemoveToken() {
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertTrue(info.remove());
}
@Test
- public void testRemoveToken2() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ public void testRemoveToken2() {
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertTrue(info.remove());
}
@Test
public void testRemoveTokenRemovesNode() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
Tree userTree =
root.getTree(getUserManager(root).getAuthorizable(userId).getPath());
Tree tokens = userTree.getChild(TOKENS_NODE_NAME);
@@ -168,8 +174,21 @@ public class TokenInfoTest extends Abstr
}
@Test
- public void testResetTokenExpirationExpiredToken() throws Exception {
+ public void testRemoveTokenTreeRemoved() {
TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ assertNotNull(info);
+
+ Tree tokenTree = getTokenTree(info);
+ assertNotNull(tokenTree);
+ tokenTree.remove();
+
+ // resetting expiration on a token tree that no longer exists should
not success
+ assertFalse(info.remove());
+ }
+
+ @Test
+ public void testResetTokenExpirationExpiredToken() {
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
long expiredTime = new Date().getTime() + 7200001;
assertTrue(info.isExpired(expiredTime));
@@ -177,13 +196,23 @@ public class TokenInfoTest extends Abstr
}
@Test
- public void testResetTokenExpiration() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
-
+ public void testResetTokenExpiration() {
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertFalse(info.resetExpiration(new Date().getTime()));
long loginTime = new Date().getTime() + 3600000;
assertFalse(info.isExpired(loginTime));
assertTrue(info.resetExpiration(loginTime));
}
+
+ @Test
+ public void testResetTokenTreeRemoved() {
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
+ Tree tokenTree = getTokenTree(info);
+ assertNotNull(tokenTree);
+ tokenTree.remove();
+
+ // resetting expiration on a token tree that no longer exists should
not success
+ assertFalse(info.resetExpiration(new Date().getTime() + 3600000));
+ }
}
\ No newline at end of file
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleCredentialsSupportTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleCredentialsSupportTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleCredentialsSupportTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleCredentialsSupportTest.java
Thu May 16 07:01:13 2019
@@ -118,18 +118,10 @@ public class TokenLoginModuleCredentials
SimpleCredentials credentials = (SimpleCredentials)
getAdminCredentials();
credentials.setAttribute(TokenConstants.TOKEN_ATTRIBUTE, "");
- ContentSession cs = null;
- try {
- cs = login(credentials);
+ try (ContentSession cs = login(credentials)) {
assertEquals(credentials.getUserID(),
cs.getAuthInfo().getUserID());
String token =
credentials.getAttribute(TokenConstants.TOKEN_ATTRIBUTE).toString();
assertFalse(token.isEmpty());
- cs.close();
- } finally {
-
- if (cs != null) {
- cs.close();
- }
}
}
}
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenLoginModuleTest.java
Thu May 16 07:01:13 2019
@@ -31,23 +31,41 @@ import javax.security.auth.login.Configu
import javax.security.auth.login.LoginException;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
import
org.apache.jackrabbit.api.security.authentication.token.TokenCredentials;
+import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.oak.AbstractSecurityTest;
import org.apache.jackrabbit.oak.api.ContentSession;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import
org.apache.jackrabbit.oak.spi.security.authentication.AbstractLoginModule;
+import
org.apache.jackrabbit.oak.spi.security.authentication.callback.PrincipalProviderCallback;
+import
org.apache.jackrabbit.oak.spi.security.authentication.callback.RepositoryCallback;
import
org.apache.jackrabbit.oak.spi.security.authentication.callback.TokenProviderCallback;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConfiguration;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenInfo;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenProvider;
+import org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal;
+import org.apache.jackrabbit.oak.spi.security.principal.PrincipalConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class TokenLoginModuleTest extends AbstractSecurityTest {
@@ -68,31 +86,19 @@ public class TokenLoginModuleTest extend
@Test
public void testNullLogin() throws Exception {
- ContentSession cs = null;
- try {
- cs = login(null);
+ try (ContentSession cs = login(null)) {
fail("Null login should fail");
} catch (LoginException e) {
// success
- } finally {
- if (cs != null) {
- cs.close();
- }
}
}
@Test
public void testGuestLogin() throws Exception {
- ContentSession cs = null;
- try {
- cs = login(new GuestCredentials());
+ try (ContentSession cs = login(new GuestCredentials())) {
fail("GuestCredentials login should fail");
} catch (LoginException e) {
// success
- } finally {
- if (cs != null) {
- cs.close();
- }
}
}
@@ -132,21 +138,15 @@ public class TokenLoginModuleTest extend
@Test
public void testInvalidTokenCredentials() throws Exception {
- ContentSession cs = null;
- try {
- cs = login(new TokenCredentials("invalid"));
+ try (ContentSession cs = login(new TokenCredentials("invalid"))) {
fail("Invalid token credentials login should fail");
} catch (LoginException e) {
// success
- } finally {
- if (cs != null) {
- cs.close();
- }
}
}
@Test
- public void testValidTokenCredentials() throws Exception {
+ public void testTokenCredentials() throws Exception {
Root root = adminSession.getLatestRoot();
TokenConfiguration tokenConfig =
getSecurityProvider().getConfiguration(TokenConfiguration.class);
TokenProvider tp = tokenConfig.getTokenProvider(root);
@@ -154,11 +154,24 @@ public class TokenLoginModuleTest extend
SimpleCredentials sc = (SimpleCredentials) getAdminCredentials();
TokenInfo info = tp.createToken(sc.getUserID(), Collections.<String,
Object>emptyMap());
- ContentSession cs = login(new TokenCredentials(info.getToken()));
- try {
+ try (ContentSession cs = login(new TokenCredentials(info.getToken())))
{
assertEquals(sc.getUserID(), cs.getAuthInfo().getUserID());
- } finally {
- cs.close();
+ }
+ }
+
+ @Test
+ public void testTokenCredentialsWithPublicAttributes() throws Exception {
+ Root root = adminSession.getLatestRoot();
+ TokenConfiguration tokenConfig =
getSecurityProvider().getConfiguration(TokenConfiguration.class);
+ TokenProvider tp = tokenConfig.getTokenProvider(root);
+
+ SimpleCredentials sc = (SimpleCredentials) getAdminCredentials();
+ TokenInfo info = tp.createToken(sc.getUserID(),
ImmutableMap.of("public", "value"));
+
+ TokenCredentials tc = new TokenCredentials(info.getToken());
+ try (ContentSession cs = login(tc)) {
+ assertEquals(sc.getUserID(), cs.getAuthInfo().getUserID());
+ assertEquals("value", cs.getAuthInfo().getAttribute("public"));
}
}
@@ -178,6 +191,18 @@ public class TokenLoginModuleTest extend
assertFalse(lm.login());
}
+
+ @Test
+ public void testMissingTokenProvider3() throws Exception {
+ TokenLoginModule lm = new TokenLoginModule();
+ lm.initialize(new Subject(), new TestCallbackHandler(null),
+ ImmutableMap.of(AbstractLoginModule.SHARED_KEY_CREDENTIALS,
mock(Credentials.class)),
+ ImmutableMap.of());
+
+ assertFalse(lm.login());
+ assertFalse(lm.commit());
+ }
+
@Test
public void testTokenProviderCallback() throws Exception {
TokenProvider tp = new TokenProviderImpl(root,
ConfigurationParameters.EMPTY, getUserConfiguration());
@@ -204,55 +229,175 @@ public class TokenLoginModuleTest extend
assertFalse(lm.login());
}
+ @Test(expected = LoginException.class)
+ public void testCreateTokenFailure() throws Exception {
+ TokenProvider tp = mock(TokenProvider.class);
+ when(tp.doCreateToken(any(Credentials.class))).thenReturn(true);
+ when(tp.createToken(any(Credentials.class))).thenReturn(null);
+ when(tp.createToken(anyString(), any(Map.class))).thenReturn(null);
+
+ TokenLoginModule lm = new TokenLoginModule();
+ lm.initialize(new Subject(), new TestCallbackHandler(tp),
+ ImmutableMap.<String,
Object>of(AbstractLoginModule.SHARED_KEY_CREDENTIALS, new Credentials() {}),
+ ImmutableMap.<String, Object>of());
+
+ assertFalse(lm.login());
+ try {
+ lm.commit();
+ } finally {
+ verify(tp, times(1)).doCreateToken(any(Credentials.class));
+ }
+ }
+
@Test
- public void testCreateTokenFailed() throws Exception {
- TokenProvider tp = new TokenProvider() {
+ public void testMissingUserPrincipal() throws Exception {
+ TokenInfo info = mock(TokenInfo.class);
+ when(info.isExpired(anyLong())).thenReturn(false);
+ when(info.matches(any(TokenCredentials.class))).thenReturn(true);
+ when(info.getUserId()).thenReturn(getTestUser().getID());
- @Override
- public boolean doCreateToken(@NotNull Credentials credentials) {
- return true;
- }
+ TokenProvider tp =
when(mock(TokenProvider.class).getTokenInfo(anyString())).thenReturn(info).getMock();
+ TokenCredentials tc = new TokenCredentials("token");
- @Nullable
- @Override
- public TokenInfo createToken(@NotNull Credentials credentials) {
- return null;
+ TokenLoginModule lm = new TokenLoginModule();
+ Map sharedState =
Maps.newHashMap(ImmutableMap.of(AbstractLoginModule.SHARED_KEY_CREDENTIALS,
tc));
+
+ Subject subject = new Subject();
+ CallbackHandler cbh = callbacks -> {
+ for (Callback callback : callbacks) {
+ if (callback instanceof PrincipalProviderCallback) {
+ ((PrincipalProviderCallback)
callback).setPrincipalProvider(getConfig(PrincipalConfiguration.class).getPrincipalProvider(root,
getNamePathMapper()));
+ }
}
+ };
+ lm.initialize(subject, new TestCallbackHandler(tp, cbh),
+ sharedState,
+ ImmutableMap.<String, Object>of());
- @Nullable
- @Override
- public TokenInfo createToken(@NotNull String userId, @NotNull
Map<String, ?> attributes) {
- return null;
+ assertTrue(lm.login());
+ assertTrue(lm.commit());
+
+ assertEquals(ImmutableSet.of(getTestUser().getPrincipal(),
EveryonePrincipal.getInstance()), subject.getPrincipals());
+ }
+
+ @Test
+ public void testReadOnlySubject() throws Exception {
+ User u = getTestUser();
+ Subject subject = new Subject();
+ subject.setReadOnly();
+
+ TokenProvider tp = spy(new TokenProviderImpl(root,
ConfigurationParameters.EMPTY, getUserConfiguration()));
+
+ SimpleCredentials sc = new SimpleCredentials(u.getID(),
u.getID().toCharArray());
+ sc.setAttribute(".token", "");
+
+ TokenLoginModule lm = new TokenLoginModule();
+ Map sharedState =
Maps.newHashMap(ImmutableMap.of(AbstractLoginModule.SHARED_KEY_CREDENTIALS,
sc));
+ lm.initialize(subject, new TestCallbackHandler(tp),
+ sharedState,
+ ImmutableMap.<String, Object>of());
+
+ assertFalse(lm.login());
+ assertFalse(lm.commit());
+ verify(tp, times(1)).createToken(sc);
+
assertTrue(subject.getPublicCredentials(TokenCredentials.class).isEmpty());
+ }
+
+ @Test
+ public void testInvalidShareCredentialsObject() throws Exception {
+ TokenProvider tp = spy(new TokenProviderImpl(root,
ConfigurationParameters.EMPTY, getUserConfiguration()));
+
+ TokenLoginModule lm = new TokenLoginModule();
+ lm.initialize(new Subject(), new TestCallbackHandler(tp),
+ ImmutableMap.of(AbstractLoginModule.SHARED_KEY_CREDENTIALS,
"notCredentialsObject"),
+ ImmutableMap.of());
+
+ assertFalse(lm.login());
+ assertFalse(lm.commit());
+ verify(tp, never()).createToken(any(Credentials.class));
+ }
+
+ @Test
+ public void testMissingShareCredentials() throws Exception {
+ TokenProvider tp = spy(new TokenProviderImpl(root,
ConfigurationParameters.EMPTY, getUserConfiguration()));
+
+ TokenLoginModule lm = new TokenLoginModule();
+ lm.initialize(new Subject(), new TestCallbackHandler(tp),
+ ImmutableMap.of(),
+ ImmutableMap.of());
+
+ assertFalse(lm.login());
+ assertFalse(lm.commit());
+ verify(tp, never()).doCreateToken(any(Credentials.class));
+ }
+
+ @Test
+ public void testMissingSecurityProvider() throws Exception {
+ CallbackHandler cbh = callbacks -> {
+ for (Callback callback : callbacks) {
+ if (callback instanceof RepositoryCallback) {
+ ((RepositoryCallback) callback).setSecurityProvider(null);
+ ((RepositoryCallback)
callback).setContentRepository(getContentRepository());
+ }
}
+ };
- @Nullable
- @Override
- public TokenInfo getTokenInfo(@NotNull String token) {
- return null;
+ SimpleCredentials sc = new SimpleCredentials(getTestUser().getID(),
getTestUser().getID().toCharArray());
+ sc.setAttribute(".token", "");
+ Map sharedState =
Maps.newHashMap(ImmutableMap.of(AbstractLoginModule.SHARED_KEY_CREDENTIALS,
sc));
+
+ TokenProvider tp = spy(new TokenProviderImpl(root,
ConfigurationParameters.EMPTY, getUserConfiguration()));
+ TokenLoginModule lm = new TokenLoginModule();
+ lm.initialize(new Subject(), new TestCallbackHandler(tp, cbh),
+ sharedState,
+ ImmutableMap.of());
+
+ assertFalse(lm.login());
+ assertFalse(lm.commit());
+ verify(tp, times(1)).createToken(sc);
+ }
+
+ @Test
+ public void testMissingRoot() throws Exception {
+ CallbackHandler cbh = callbacks -> {
+ for (Callback callback : callbacks) {
+ if (callback instanceof RepositoryCallback) {
+ ((RepositoryCallback)
callback).setSecurityProvider(getSecurityProvider());
+ ((RepositoryCallback) callback).setContentRepository(null);
+ }
}
};
+ SimpleCredentials sc = new SimpleCredentials(getTestUser().getID(),
getTestUser().getID().toCharArray());
+ sc.setAttribute(".token", "");
+ Map sharedState =
Maps.newHashMap(ImmutableMap.of(AbstractLoginModule.SHARED_KEY_CREDENTIALS,
sc));
+
+ TokenProvider tp = spy(new TokenProviderImpl(root,
ConfigurationParameters.EMPTY, getUserConfiguration()));
TokenLoginModule lm = new TokenLoginModule();
- lm.initialize(new Subject(), new TestCallbackHandler(tp),
- ImmutableMap.<String,
Object>of(AbstractLoginModule.SHARED_KEY_CREDENTIALS, new Credentials() {}),
- ImmutableMap.<String, Object>of());
+ lm.initialize(new Subject(), new TestCallbackHandler(tp, cbh),
+ sharedState,
+ ImmutableMap.of());
- lm.login();
- try {
- lm.commit();
- fail("LoginException expected");
- } catch (LoginException e) {
- // success
- }
+ assertFalse(lm.login());
+ assertFalse(lm.commit());
+ verify(tp, times(1)).createToken(sc);
}
private final class TestCallbackHandler implements CallbackHandler {
private final TokenProvider tokenProvider;
+ private final CallbackHandler base;
private final Class<? extends Exception> e;
private TestCallbackHandler(@Nullable TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
+ this.base = null;
+ this.e = null;
+ }
+
+ private TestCallbackHandler(@Nullable TokenProvider tokenProvider,
@NotNull CallbackHandler base) {
+ this.tokenProvider = tokenProvider;
+ this.base = base;
this.e = null;
}
@@ -261,6 +406,8 @@ public class TokenLoginModuleTest extend
for (Callback cb : callbacks) {
if (cb instanceof TokenProviderCallback) {
((TokenProviderCallback)
cb).setTokenProvider(tokenProvider);
+ } else if (base != null) {
+ base.handle(callbacks);
} else {
throw new UnsupportedCallbackException(cb);
}
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenNoRefreshTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenNoRefreshTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenNoRefreshTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenNoRefreshTest.java
Thu May 16 07:01:13 2019
@@ -22,6 +22,7 @@ import java.util.Date;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenInfo;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenProvider;
+import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
@@ -37,6 +38,7 @@ public class TokenNoRefreshTest extends
userId = getTestUser().getID();
}
+ @NotNull
@Override
ConfigurationParameters getTokenConfig() {
return ConfigurationParameters.of(TokenProvider.PARAM_TOKEN_REFRESH,
false);
Added:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplExceptionTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplExceptionTest.java?rev=1859352&view=auto
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplExceptionTest.java
(added)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplExceptionTest.java
Thu May 16 07:01:13 2019
@@ -0,0 +1,87 @@
+/*
+ * 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.jackrabbit.oak.security.authentication.token;
+
+import org.apache.jackrabbit.api.security.user.Authorizable;
+import org.apache.jackrabbit.api.security.user.User;
+import org.apache.jackrabbit.api.security.user.UserManager;
+import org.apache.jackrabbit.oak.api.Root;
+import org.apache.jackrabbit.oak.namepath.NamePathMapper;
+import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenInfo;
+import org.apache.jackrabbit.oak.spi.security.user.UserConfiguration;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.SimpleCredentials;
+
+import static org.junit.Assert.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class TokenProviderImplExceptionTest extends AbstractTokenTest {
+
+ private TokenProviderImpl tp;
+ private UserManager userManager;
+
+ @Before
+ @Override
+ public void before() throws Exception {
+ super.before();
+
+ userManager = mock(UserManager.class);
+ UserConfiguration uc = mock(UserConfiguration.class);
+ when(uc.getUserManager(any(Root.class),
any(NamePathMapper.class))).thenReturn(userManager);
+
+ tp = createTokenProvider(root, uc);
+ }
+
+ @Test
+ public void testCreateToken() throws Exception {
+ when(userManager.getAuthorizable(anyString())).thenThrow(new
RepositoryException());
+
+ assertNull(tp.createToken(new SimpleCredentials("uid", new char[0])));
+ verify(userManager, times(1)).getAuthorizable("uid");
+ }
+
+ @Test
+ public void testCreateTokenUserWithoutPath() throws Exception {
+ User u = when(mock(User.class).getPath()).thenThrow(new
RepositoryException()).getMock();
+ when(userManager.getAuthorizable("uid")).thenReturn(u);
+
+ assertNull(tp.createToken(new SimpleCredentials("uid", new char[0])));
+ verify(userManager, times(1)).getAuthorizable("uid");
+ verify(u, times(1)).getPath();
+ }
+
+ @Test
+ public void testGetTokenInfo() throws Exception {
+ // generate valid token
+ Authorizable user = getTestUser();
+ TokenInfo valid = createTokenInfo(tokenProvider, user.getID());
+
+ when(userManager.getAuthorizableByPath(anyString())).thenThrow(new
RepositoryException());
+
+ assertNull(tp.getTokenInfo(valid.getToken()));
+ verify(userManager, times(1)).getAuthorizableByPath(user.getPath());
+ }
+
+}
\ No newline at end of file
Propchange:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplExceptionTest.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplReadOnlyTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplReadOnlyTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplReadOnlyTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplReadOnlyTest.java
Thu May 16 07:01:13 2019
@@ -56,8 +56,19 @@ public class TokenProviderImplReadOnlyTe
readOnlyTp = new TokenProviderImpl(readOnlyRoot, getTokenConfig(),
getUserConfiguration());
}
+ @Override
+ public void after() throws Exception {
+ try {
+ if (cs != null) {
+ cs.close();
+ }
+ } finally {
+ super.after();
+ }
+ }
+
private String generateToken() throws Exception {
- TokenInfo info = tokenProvider.createToken(getTestUser().getID(),
ImmutableMap.<String, Object>of());
+ TokenInfo info = createTokenInfo(tokenProvider, getTestUser().getID());
String token = info.getToken();
readOnlyRoot.refresh();
return token;
@@ -68,7 +79,7 @@ public class TokenProviderImplReadOnlyTe
String userId = getTestUser().getID();
readOnlyRoot.refresh();
- assertNull(readOnlyTp.createToken(userId, ImmutableMap.<String,
Object>of()));
+ assertNull(readOnlyTp.createToken(userId, ImmutableMap.of()));
}
@Test
@@ -76,7 +87,7 @@ public class TokenProviderImplReadOnlyTe
// make sure user already has a token-parent node.
generateToken();
// now generate a new token with the read-only root
- assertNull(readOnlyTp.createToken(getTestUser().getID(),
ImmutableMap.<String, Object>of()));
+ assertNull(readOnlyTp.createToken(getTestUser().getID(),
ImmutableMap.of()));
}
@Test
@@ -88,12 +99,14 @@ public class TokenProviderImplReadOnlyTe
@Test
public void testRefreshToken() throws Exception {
TokenInfo readOnlyInfo = readOnlyTp.getTokenInfo(generateToken());
+ assertNotNull(readOnlyInfo);
assertFalse(readOnlyInfo.resetExpiration(System.currentTimeMillis() +
TokenProviderImpl.DEFAULT_TOKEN_EXPIRATION - 100));
}
@Test
public void testRemoveToken() throws Exception {
TokenInfo readOnlyInfo = readOnlyTp.getTokenInfo(generateToken());
+ assertNotNull(readOnlyInfo);
assertFalse(readOnlyInfo.remove());
}
}
\ No newline at end of file
Modified:
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplTest.java
URL:
http://svn.apache.org/viewvc/jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplTest.java?rev=1859352&r1=1859351&r2=1859352&view=diff
==============================================================================
---
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplTest.java
(original)
+++
jackrabbit/oak/trunk/oak-core/src/test/java/org/apache/jackrabbit/oak/security/authentication/token/TokenProviderImplTest.java
Thu May 16 07:01:13 2019
@@ -23,37 +23,52 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.jcr.Credentials;
import javax.jcr.GuestCredentials;
import javax.jcr.SimpleCredentials;
+import javax.jcr.security.AccessControlManager;
import org.apache.jackrabbit.JcrConstants;
+import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import
org.apache.jackrabbit.api.security.authentication.token.TokenCredentials;
import org.apache.jackrabbit.api.security.user.Group;
+import org.apache.jackrabbit.api.security.user.User;
+import
org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils;
import org.apache.jackrabbit.oak.api.ContentSession;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
+import org.apache.jackrabbit.oak.plugins.tree.TreeUtil;
+import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import
org.apache.jackrabbit.oak.spi.security.authentication.ImpersonationCredentials;
+import
org.apache.jackrabbit.oak.spi.security.authentication.credentials.CredentialsSupport;
+import
org.apache.jackrabbit.oak.spi.security.authentication.credentials.SimpleCredentialsSupport;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConfiguration;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConstants;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenInfo;
import
org.apache.jackrabbit.oak.spi.security.authentication.token.TokenProvider;
-import org.apache.jackrabbit.oak.util.NodeUtil;
+import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants;
+import org.apache.jackrabbit.oak.spi.security.user.UserConstants;
+import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Test;
+import static
org.apache.jackrabbit.oak.security.authentication.token.TokenProviderImpl.PARAM_TOKEN_CLEANUP_THRESHOLD;
+import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
public class TokenProviderImplTest extends AbstractTokenTest {
@@ -89,7 +104,7 @@ public class TokenProviderImplTest exten
}
@Test
- public void testCreateTokenFromInvalidCredentials() throws Exception {
+ public void testCreateTokenFromInvalidCredentials() {
List<Credentials> invalid = new ArrayList<Credentials>();
invalid.add(new GuestCredentials());
invalid.add(new TokenCredentials("sometoken"));
@@ -102,7 +117,7 @@ public class TokenProviderImplTest exten
}
@Test
- public void testCreateTokenFromCredentials() throws Exception {
+ public void testCreateTokenFromCredentials() {
SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
List<Credentials> valid = new ArrayList<Credentials>();
valid.add(sc);
@@ -115,7 +130,38 @@ public class TokenProviderImplTest exten
}
@Test
- public void testCreateTokenFromInvalidUserId() throws Exception {
+ public void testCreateTokenFromCredentialsSetsAttribute() {
+ SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
+ tokenProvider.createToken(sc);
+
+ assertArrayEquals(new String[] {TOKEN_ATTRIBUTE},
sc.getAttributeNames());
+ }
+
+ @Test
+ public void testCreateTokenCredentialsSupportDoesntSetAttribute() {
+ SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
+
+ CredentialsSupport credentialsSupport = mock(CredentialsSupport.class);
+
when(credentialsSupport.getCredentialClasses()).thenReturn(SimpleCredentialsSupport.getInstance().getCredentialClasses());
+
when(credentialsSupport.getUserId(sc)).thenReturn(SimpleCredentialsSupport.getInstance().getUserId(sc));
+ when(credentialsSupport.setAttributes(any(Credentials.class),
any(Map.class))).thenReturn(false);
+
+ TokenProvider tp = createTokenProvider(root, getTokenConfig(),
getUserConfiguration(), credentialsSupport);
+ tp.createToken(sc);
+
+ assertEquals(0, sc.getAttributeNames().length);
+ }
+
+ @Test
+ public void testCreateTokenInvalidAlgorithm() {
+ SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
+ ConfigurationParameters options =
ConfigurationParameters.of(UserConstants.PARAM_PASSWORD_HASH_ALGORITHM,
"invalid");
+ TokenProvider tp = createTokenProvider(root, options,
getUserConfiguration(), SimpleCredentialsSupport.getInstance());
+ assertNull(tp.createToken(sc));
+ }
+
+ @Test
+ public void testCreateTokenFromInvalidUserId() {
TokenInfo info = tokenProvider.createToken("unknownUserId",
Collections.<String, Object>emptyMap());
assertNull(info);
}
@@ -127,13 +173,13 @@ public class TokenProviderImplTest exten
}
@Test
- public void testCreateTokenFromUserId() throws Exception {
+ public void testCreateTokenFromUserId() {
TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
assertTokenInfo(info, userId);
}
@Test
- public void testTokenNode() throws Exception {
+ public void testTokenNode() {
Map<String, String> reserved = new HashMap<String, String>();
reserved.put(TOKEN_ATTRIBUTE, "value");
reserved.put(TOKEN_ATTRIBUTE_KEY, "value");
@@ -154,6 +200,7 @@ public class TokenProviderImplTest exten
attributes.putAll(privateAttributes);
TokenInfo info = tokenProvider.createToken(userId, attributes);
+ assertNotNull(info);
Tree tokenTree = getTokenTree(info);
PropertyState prop = tokenTree.getProperty(TOKEN_ATTRIBUTE_KEY);
assertNotNull(prop);
@@ -166,7 +213,7 @@ public class TokenProviderImplTest exten
for (String key : reserved.keySet()) {
PropertyState p = tokenTree.getProperty(key);
if (p != null) {
- assertFalse(reserved.get(key).equals(p.getValue(Type.STRING)));
+ assertNotEquals(reserved.get(key), p.getValue(Type.STRING));
}
}
@@ -180,7 +227,7 @@ public class TokenProviderImplTest exten
}
@Test
- public void testGetTokenInfoFromInvalidToken() throws Exception {
+ public void testGetTokenInfoFromInvalidToken() {
List<String> invalid = new ArrayList<String>();
invalid.add("/invalid");
invalid.add(UUID.randomUUID().toString());
@@ -199,7 +246,7 @@ public class TokenProviderImplTest exten
@Test
public void testGetTokenInfoFromDisabledUser() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
getTestUser().disable("disabled");
assertNull(tokenProvider.getTokenInfo(info.getToken()));
@@ -208,61 +255,54 @@ public class TokenProviderImplTest exten
@Test
public void testGetTokenInfoFromGroup() throws Exception {
Group gr = getUserManager(root).createGroup("gr");
- NodeUtil groupNode = new NodeUtil(root.getTree(gr.getPath()));
- NodeUtil parent = groupNode.addChild(TokenConstants.TOKENS_NODE_NAME,
TokenConstants.TOKENS_NT_NAME);
- NodeUtil tokenNode = parent.addChild("tokenName",
TokenConstants.TOKEN_NT_NAME);
+ Tree groupNode = root.getTree(gr.getPath());
+ Tree parent = TreeUtil.addChild(groupNode,
TokenConstants.TOKENS_NODE_NAME, TokenConstants.TOKENS_NT_NAME);
+ Tree tokenNode = TreeUtil.addChild(parent, "tokenName",
TokenConstants.TOKEN_NT_NAME);
String tokenUUID = UUID.randomUUID().toString();
- tokenNode.setString(JcrConstants.JCR_UUID, tokenUUID);
+ tokenNode.setProperty(JcrConstants.JCR_UUID, tokenUUID);
String token = tokenUUID + "_generatedKey";
- tokenNode.setString(TokenConstants.TOKEN_ATTRIBUTE_KEY, token);
+ tokenNode.setProperty(TokenConstants.TOKEN_ATTRIBUTE_KEY, token);
assertNull(tokenProvider.getTokenInfo(token));
}
@Test
public void testGetTokenInfoFromRegularNode() throws Exception {
- NodeUtil node = new NodeUtil(root.getTree("/")).addChild("testNode",
JcrConstants.NT_UNSTRUCTURED);
- NodeUtil parent = node.addChild(TokenConstants.TOKENS_NODE_NAME,
TokenConstants.TOKENS_NT_NAME);
- NodeUtil tokenNode = parent.addChild("tokenName",
TokenConstants.TOKEN_NT_NAME);
+ Tree node = TreeUtil.addChild(root.getTree("/"), "testNode",
JcrConstants.NT_UNSTRUCTURED);
+ Tree parent = TreeUtil.addChild(node, TokenConstants.TOKENS_NODE_NAME,
TokenConstants.TOKENS_NT_NAME);
+ Tree tokenNode = TreeUtil.addChild(parent, "tokenName",
TokenConstants.TOKEN_NT_NAME);
String tokenUUID = UUID.randomUUID().toString();
- tokenNode.setString(JcrConstants.JCR_UUID, tokenUUID);
+ tokenNode.setProperty(JcrConstants.JCR_UUID, tokenUUID);
String token = tokenUUID + "_generatedKey";
- tokenNode.setString(TokenConstants.TOKEN_ATTRIBUTE_KEY, token);
+ tokenNode.setProperty(TokenConstants.TOKEN_ATTRIBUTE_KEY, token);
assertNull(tokenProvider.getTokenInfo(token));
}
@Test
public void testGetTokenInfoFromInvalidLocation() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
- Tree tokenTree = getTokenTree(info);
-
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertNotNull(tokenProvider.getTokenInfo(info.getToken()));
- NodeUtil node = new NodeUtil(root.getTree("/")).addChild("testNode",
JcrConstants.NT_UNSTRUCTURED);
+ Tree node = TreeUtil.addChild(root.getTree("/"), "testNode",
JcrConstants.NT_UNSTRUCTURED);
try {
- createTokenTree(info, node, TOKEN_NT_NAME);
- tokenTree.remove();
-
+ replaceTokenTree(info, node, TOKEN_NT_NAME);
assertNull(tokenProvider.getTokenInfo(info.getToken()));
} finally {
- node.getTree().remove();
+ node.remove();
root.commit(CommitMarker.asCommitAttributes());
}
}
@Test
public void testGetTokenInfoFromInvalidLocation2() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
- Tree tokenTree = getTokenTree(info);
-
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertNotNull(tokenProvider.getTokenInfo(info.getToken()));
Tree userTree =
root.getTree(getUserManager(root).getAuthorizable(userId).getPath());
- NodeUtil node = new NodeUtil(userTree).addChild("testNode",
JcrConstants.NT_UNSTRUCTURED);
+ Tree node = TreeUtil.addChild(userTree, "testNode",
JcrConstants.NT_UNSTRUCTURED);
try {
- createTokenTree(info, node, TOKEN_NT_NAME);
- tokenTree.remove();
+ replaceTokenTree(info, node, TOKEN_NT_NAME);
assertNull(tokenProvider.getTokenInfo(info.getToken()));
} finally {
@@ -272,16 +312,12 @@ public class TokenProviderImplTest exten
@Test
public void testGetTokenInfoFromInvalidLocation3() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
- Tree tokenTree = getTokenTree(info);
-
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
assertNotNull(tokenProvider.getTokenInfo(info.getToken()));
Tree userTree =
root.getTree(getUserManager(root).getAuthorizable(userId).getPath());
- NodeUtil node = new NodeUtil(userTree.getChild(TOKENS_NODE_NAME));
try {
- createTokenTree(info, node, JcrConstants.NT_UNSTRUCTURED);
- tokenTree.remove();
+ replaceTokenTree(info, userTree.getChild(TOKENS_NODE_NAME),
JcrConstants.NT_UNSTRUCTURED);
assertNull(tokenProvider.getTokenInfo(info.getToken()));
} finally {
@@ -291,7 +327,7 @@ public class TokenProviderImplTest exten
@Test
public void testGetTokenInfoFromInvalidLocation4() throws Exception {
- TokenInfo info = tokenProvider.createToken(userId,
Collections.<String, Object>emptyMap());
+ TokenInfo info = createTokenInfo(tokenProvider, userId);
Tree tokenTree = getTokenTree(info);
assertNotNull(tokenProvider.getTokenInfo(info.getToken()));
@@ -299,8 +335,8 @@ public class TokenProviderImplTest exten
TokenInfo info2 = null;
try {
Tree adminTree =
root.getTree(getUserManager(root).getAuthorizable(adminSession.getAuthInfo().getUserID()).getPath());
- NodeUtil node = new
NodeUtil(adminTree).getOrAddChild(TOKENS_NODE_NAME,
JcrConstants.NT_UNSTRUCTURED);
- assertTrue(root.move(tokenTree.getPath(), node.getTree().getPath()
+ '/' + tokenTree.getName()));
+ Tree node = TreeUtil.getOrAddChild(adminTree, TOKENS_NODE_NAME,
JcrConstants.NT_UNSTRUCTURED);
+ assertTrue(root.move(tokenTree.getPath(), node.getPath() + '/' +
tokenTree.getName()));
info2 = tokenProvider.getTokenInfo(info.getToken());
assertNotNull(info2);
@@ -311,14 +347,14 @@ public class TokenProviderImplTest exten
}
@Test
- public void testGetTokenInfo() throws Exception {
- String token = tokenProvider.createToken(userId, Collections.<String,
Object>emptyMap()).getToken();
+ public void testGetTokenInfo() {
+ String token = createTokenInfo(tokenProvider, userId).getToken();
TokenInfo info = tokenProvider.getTokenInfo(token);
assertTokenInfo(info, userId);
}
@Test
- public void testCreateTokenWithExpirationParam() throws Exception {
+ public void testCreateTokenWithExpirationParam() {
SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
sc.setAttribute(TokenProvider.PARAM_TOKEN_EXPIRATION, 100000);
@@ -333,7 +369,7 @@ public class TokenProviderImplTest exten
}
@Test
- public void testCreateTokenWithInvalidExpirationParam() throws Exception {
+ public void testCreateTokenWithInvalidExpirationParam() {
SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
sc.setAttribute(TokenProvider.PARAM_TOKEN_EXPIRATION, "invalid");
@@ -345,6 +381,64 @@ public class TokenProviderImplTest exten
}
}
+ @Test
+ public void testFailingCleanupExpired() throws Exception {
+ User u = getTestUser();
+ // grant user principal access to read/create tokens but not removing
them
+ AccessControlManager acMgr = getAccessControlManager(root);
+ JackrabbitAccessControlList acl =
AccessControlUtils.getAccessControlList(acMgr, u.getPath());
+ acl.addAccessControlEntry(u.getPrincipal(),
privilegesFromNames(PrivilegeConstants.JCR_READ,
PrivilegeConstants.JCR_ADD_CHILD_NODES,
PrivilegeConstants.JCR_MODIFY_PROPERTIES));
+ acMgr.setPolicy(acl.getPath(), acl);
+ root.commit();
+
+ try (ContentSession cs = login(new SimpleCredentials(u.getID(),
u.getID().toCharArray()))) {
+ Root testRoot = cs.getLatestRoot();
+ ConfigurationParameters options =
ConfigurationParameters.of(PARAM_TOKEN_CLEANUP_THRESHOLD, 1);
+ TokenProvider tp = createTokenProvider(testRoot, options,
getUserConfiguration(), SimpleCredentialsSupport.getInstance());
+
+ SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
+ sc.setAttribute(TokenProvider.PARAM_TOKEN_EXPIRATION, 1);
+
+ TokenInfo info = tp.createToken(sc);
+ waitUntilExpired(info);
+
+ // create new infos until the cleanup is triggered or until max
cnt has been reached.
+ // in either case the expired info must still exist
+ TokenInfo ti;
+ int cnt = 0;
+ do {
+ ti = tp.createToken(sc);
+ cnt++;
+ } while (ti.getToken().charAt(0) >= '2' && cnt < 50);
+
+ root.refresh();
+ assertTrue(getTokenTree(info).exists());
+ }
+ }
+
+ @Test
+ public void testCleanupThresholdNotReached() {
+ ConfigurationParameters options =
ConfigurationParameters.of(PARAM_TOKEN_CLEANUP_THRESHOLD, 100);
+ TokenProvider tp = createTokenProvider(root, options,
getUserConfiguration(), SimpleCredentialsSupport.getInstance());
+
+ SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
+ sc.setAttribute(TokenProvider.PARAM_TOKEN_EXPIRATION, 1);
+
+ TokenInfo info = tp.createToken(sc);
+ waitUntilExpired(info);
+
+ // create new infos until the cleanup is triggered or until max cnt
has been reached.
+ // -> since PARAM_TOKEN_CLEANUP_THRESHOLD is set to 100, the expired
token is still not removed
+ TokenInfo ti;
+ int cnt = 0;
+ do {
+ ti = tp.createToken(sc);
+ cnt++;
+ } while (ti.getToken().charAt(0) >= '2' && cnt < 50);
+
+ assertTrue(getTokenTree(info).exists());
+ }
+
/**
*@see <a
href="https://issues.apache.org/jira/browse/OAK-1697">OAK-1697</a>
*/
@@ -394,7 +488,7 @@ public class TokenProviderImplTest exten
* @see <a
href="https://issues.apache.org/jira/browse/OAK-1985">OAK-1985</a>
*/
@Test
- public void testTokenValidationIsCaseInsensitive() throws Exception {
+ public void testTokenValidationIsCaseInsensitive() {
Root root = adminSession.getLatestRoot();
TokenConfiguration tokenConfig =
getSecurityProvider().getConfiguration(TokenConfiguration.class);
TokenProvider tp = tokenConfig.getTokenProvider(root);
@@ -422,19 +516,15 @@ public class TokenProviderImplTest exten
private static class DataFuture {
public Future<TokenInfo> future;
- public DataFuture(Future<TokenInfo> future) {
+ DataFuture(Future<TokenInfo> future) {
super();
this.future = future;
}
}
-
+
+ @NotNull
private DataFuture createDataFuture(ExecutorService pool , final
TokenProvider tp,final String userId, final Map<String, ?> attributes){
- Future<TokenInfo> future = pool.submit(new Callable<TokenInfo>() {
- @Override
- public TokenInfo call() throws Exception {
- return tp.createToken(userId, attributes);
- }
- });
+ Future<TokenInfo> future = pool.submit(() -> tp.createToken(userId,
attributes));
return new DataFuture(future);
}
}
\ No newline at end of file