[
https://issues.apache.org/jira/browse/KNOX-2778?focusedWorklogId=797959&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-797959
]
ASF GitHub Bot logged work on KNOX-2778:
----------------------------------------
Author: ASF GitHub Bot
Created on: 04/Aug/22 12:03
Start Date: 04/Aug/22 12:03
Worklog Time Spent: 10m
Work Description: zeroflag commented on code in PR #615:
URL: https://github.com/apache/knox/pull/615#discussion_r937682920
##########
gateway-server/src/main/java/org/apache/knox/gateway/session/control/InMemoryConcurrentSessionVerifier.java:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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.knox.gateway.session.control;
+
+
+import org.apache.knox.gateway.config.GatewayConfig;
+import org.apache.knox.gateway.services.ServiceLifecycleException;
+import org.apache.knox.gateway.services.security.token.impl.JWT;
+
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class InMemoryConcurrentSessionVerifier implements
ConcurrentSessionVerifier {
+ private Set<String> privilegedUsers;
+ private Set<String> nonPrivilegedUsers;
+ private int privilegedUserConcurrentSessionLimit;
+ private int nonPrivilegedUserConcurrentSessionLimit;
+ private Map<String, Set<SessionJWT>> concurrentSessionCounter;
+ private final Lock sessionCountModifyLock = new ReentrantLock();
+
+ @Override
+ public boolean verifySessionForUser(String username, JWT JWToken) {
+ if (!privilegedUsers.contains(username) &&
!nonPrivilegedUsers.contains(username)) {
+ return true;
+ }
+
+ sessionCountModifyLock.lock();
+ try {
+ int validTokenNumber = countValidTokensForUser(username);
+ if (privilegedUserCheckLimitReached(username, validTokenNumber) ||
nonPrivilegedUserCheckLimitReached(username, validTokenNumber)) {
+ return false;
+ }
+ concurrentSessionCounter.putIfAbsent(username, new HashSet<>());
+ concurrentSessionCounter.compute(username, (key, sessionTokenSet) ->
addTokenForUser(sessionTokenSet, JWToken));
+ } finally {
+ sessionCountModifyLock.unlock();
+ }
+ return true;
+ }
+
+ private int countValidTokensForUser(String username) {
+ int result = 0;
+ Set<SessionJWT> tokens = concurrentSessionCounter.getOrDefault(username,
Collections.emptySet());
+ for (SessionJWT token : tokens) {
+ if (!token.hasExpired()) {
+ result++;
+ }
+ }
+ return result;
+ }
+
+ private boolean privilegedUserCheckLimitReached(String username, int
validTokenNumber) {
+ if (privilegedUserConcurrentSessionLimit < 0) {
+ return false;
+ }
+ return privilegedUsers.contains(username) && (validTokenNumber >=
privilegedUserConcurrentSessionLimit);
+ }
+
+ private boolean nonPrivilegedUserCheckLimitReached(String username, int
validTokenNumber) {
+ if (nonPrivilegedUserConcurrentSessionLimit < 0) {
+ return false;
+ }
+ return nonPrivilegedUsers.contains(username) && (validTokenNumber >=
nonPrivilegedUserConcurrentSessionLimit);
+ }
+
+ @Override
+ public void sessionEndedForUser(String username, String token) {
+ if (!token.isEmpty()) {
+ sessionCountModifyLock.lock();
+ try {
+ concurrentSessionCounter.computeIfPresent(username, (key,
sessionTokenSet) -> removeTokenFromUser(sessionTokenSet, token));
+ } finally {
+ sessionCountModifyLock.unlock();
+ }
+ }
+ }
+
+ private Set<SessionJWT> removeTokenFromUser(Set<SessionJWT> sessionTokenSet,
String token) {
+ sessionTokenSet.removeIf(sessionToken ->
sessionToken.getToken().equals(token));
+ if (sessionTokenSet.isEmpty()) {
+ return null;
+ }
+ return sessionTokenSet;
+ }
+
+ private Set<SessionJWT> addTokenForUser(Set<SessionJWT> sessionTokenSet, JWT
JWToken) {
+ sessionTokenSet.add(new SessionJWT(JWToken));
+ return sessionTokenSet;
+ }
+
+ @Override
+ public void init(GatewayConfig config, Map<String, String> options) throws
ServiceLifecycleException {
+ this.privilegedUsers = config.getPrivilegedUsers();
+ this.nonPrivilegedUsers = config.getNonPrivilegedUsers();
+ this.privilegedUserConcurrentSessionLimit =
config.getPrivilegedUsersConcurrentSessionLimit();
+ this.nonPrivilegedUserConcurrentSessionLimit =
config.getNonPrivilegedUsersConcurrentSessionLimit();
+ this.concurrentSessionCounter = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public void start() throws ServiceLifecycleException {
+
+ }
+
+ @Override
+ public void stop() throws ServiceLifecycleException {
+
+ }
+
+ Integer getUserConcurrentSessionCount(String username) {
+ int result = countValidTokensForUser(username);
+ return (result == 0) ? null : result;
+ }
+
+ public static class SessionJWT {
Review Comment:
We should add (generate) equals/hashCode methods for this. In IntelliJ you
can click on Code / Generate and select Equals and Hash Code. The only field we
need to include is `String token`.
##########
gateway-server/src/main/java/org/apache/knox/gateway/session/control/InMemoryConcurrentSessionVerifier.java:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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.knox.gateway.session.control;
+
+
+import org.apache.knox.gateway.config.GatewayConfig;
+import org.apache.knox.gateway.services.ServiceLifecycleException;
+import org.apache.knox.gateway.services.security.token.impl.JWT;
+
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class InMemoryConcurrentSessionVerifier implements
ConcurrentSessionVerifier {
+ private Set<String> privilegedUsers;
+ private Set<String> nonPrivilegedUsers;
+ private int privilegedUserConcurrentSessionLimit;
+ private int nonPrivilegedUserConcurrentSessionLimit;
+ private Map<String, Set<SessionJWT>> concurrentSessionCounter;
+ private final Lock sessionCountModifyLock = new ReentrantLock();
+
+ @Override
+ public boolean verifySessionForUser(String username, JWT JWToken) {
+ if (!privilegedUsers.contains(username) &&
!nonPrivilegedUsers.contains(username)) {
+ return true;
+ }
+
+ sessionCountModifyLock.lock();
+ try {
+ int validTokenNumber = countValidTokensForUser(username);
+ if (privilegedUserCheckLimitReached(username, validTokenNumber) ||
nonPrivilegedUserCheckLimitReached(username, validTokenNumber)) {
+ return false;
+ }
+ concurrentSessionCounter.putIfAbsent(username, new HashSet<>());
+ concurrentSessionCounter.compute(username, (key, sessionTokenSet) ->
addTokenForUser(sessionTokenSet, JWToken));
+ } finally {
+ sessionCountModifyLock.unlock();
+ }
+ return true;
+ }
+
+ private int countValidTokensForUser(String username) {
Review Comment:
I think it's a matter of preference but with the stream API this would look
like this.
```java
return (int) concurrentSessionCounter
.getOrDefault(username, Collections.emptySet())
.stream()
.filter(each -> !each.hasExpired())
.count();
```
But for loop if fine too.
##########
gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/WebSSOutResource.java:
##########
@@ -106,6 +111,21 @@ private boolean
removeAuthenticationToken(HttpServletResponse response) {
}
response.addCookie(c);
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null) {
+ Optional<Cookie> SSOCookie = Arrays.stream(cookies).filter(cookie ->
cookie.getName().equals(cookieName)).findFirst();
Review Comment:
I know it looks weird in both way, but I would rather name it `ssoCookie`
than `SSOCookie`. It's still a local variable.
##########
gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOutMessages.java:
##########
@@ -25,4 +25,7 @@
public interface KnoxSSOutMessages {
@Message( level = MessageLevel.INFO, text = "There was a problem determining
the SSO cookie domain - using default domain.")
void problemWithCookieDomainUsingDefault();
+
+ @Message(level = MessageLevel.DEBUG, text = "Could not find cookie with the
name: {0} in the request to be removed from the concurrent session counter for
user: {1}. ")
+ void couldNotFindCookieWithTokenToRemove(String cookieName, String username);
Review Comment:
I think this should be at least INFO or WARNING.
##########
gateway-server/src/main/java/org/apache/knox/gateway/session/control/InMemoryConcurrentSessionVerifier.java:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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.knox.gateway.session.control;
+
+
+import org.apache.knox.gateway.config.GatewayConfig;
+import org.apache.knox.gateway.services.ServiceLifecycleException;
+import org.apache.knox.gateway.services.security.token.impl.JWT;
+
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class InMemoryConcurrentSessionVerifier implements
ConcurrentSessionVerifier {
+ private Set<String> privilegedUsers;
+ private Set<String> nonPrivilegedUsers;
+ private int privilegedUserConcurrentSessionLimit;
+ private int nonPrivilegedUserConcurrentSessionLimit;
+ private Map<String, Set<SessionJWT>> concurrentSessionCounter;
+ private final Lock sessionCountModifyLock = new ReentrantLock();
+
+ @Override
+ public boolean verifySessionForUser(String username, JWT JWToken) {
+ if (!privilegedUsers.contains(username) &&
!nonPrivilegedUsers.contains(username)) {
+ return true;
+ }
+
+ sessionCountModifyLock.lock();
+ try {
+ int validTokenNumber = countValidTokensForUser(username);
+ if (privilegedUserCheckLimitReached(username, validTokenNumber) ||
nonPrivilegedUserCheckLimitReached(username, validTokenNumber)) {
+ return false;
+ }
+ concurrentSessionCounter.putIfAbsent(username, new HashSet<>());
+ concurrentSessionCounter.compute(username, (key, sessionTokenSet) ->
addTokenForUser(sessionTokenSet, JWToken));
+ } finally {
+ sessionCountModifyLock.unlock();
+ }
+ return true;
+ }
+
+ private int countValidTokensForUser(String username) {
+ int result = 0;
+ Set<SessionJWT> tokens = concurrentSessionCounter.getOrDefault(username,
Collections.emptySet());
+ for (SessionJWT token : tokens) {
+ if (!token.hasExpired()) {
+ result++;
+ }
+ }
+ return result;
+ }
+
+ private boolean privilegedUserCheckLimitReached(String username, int
validTokenNumber) {
+ if (privilegedUserConcurrentSessionLimit < 0) {
+ return false;
+ }
+ return privilegedUsers.contains(username) && (validTokenNumber >=
privilegedUserConcurrentSessionLimit);
+ }
+
+ private boolean nonPrivilegedUserCheckLimitReached(String username, int
validTokenNumber) {
+ if (nonPrivilegedUserConcurrentSessionLimit < 0) {
+ return false;
+ }
+ return nonPrivilegedUsers.contains(username) && (validTokenNumber >=
nonPrivilegedUserConcurrentSessionLimit);
+ }
+
+ @Override
+ public void sessionEndedForUser(String username, String token) {
+ if (!token.isEmpty()) {
+ sessionCountModifyLock.lock();
+ try {
+ concurrentSessionCounter.computeIfPresent(username, (key,
sessionTokenSet) -> removeTokenFromUser(sessionTokenSet, token));
+ } finally {
+ sessionCountModifyLock.unlock();
+ }
+ }
+ }
+
+ private Set<SessionJWT> removeTokenFromUser(Set<SessionJWT> sessionTokenSet,
String token) {
+ sessionTokenSet.removeIf(sessionToken ->
sessionToken.getToken().equals(token));
+ if (sessionTokenSet.isEmpty()) {
+ return null;
+ }
+ return sessionTokenSet;
+ }
+
+ private Set<SessionJWT> addTokenForUser(Set<SessionJWT> sessionTokenSet, JWT
JWToken) {
+ sessionTokenSet.add(new SessionJWT(JWToken));
+ return sessionTokenSet;
+ }
+
+ @Override
+ public void init(GatewayConfig config, Map<String, String> options) throws
ServiceLifecycleException {
+ this.privilegedUsers = config.getPrivilegedUsers();
+ this.nonPrivilegedUsers = config.getNonPrivilegedUsers();
+ this.privilegedUserConcurrentSessionLimit =
config.getPrivilegedUsersConcurrentSessionLimit();
+ this.nonPrivilegedUserConcurrentSessionLimit =
config.getNonPrivilegedUsersConcurrentSessionLimit();
+ this.concurrentSessionCounter = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public void start() throws ServiceLifecycleException {
+
+ }
+
+ @Override
+ public void stop() throws ServiceLifecycleException {
+
+ }
+
+ Integer getUserConcurrentSessionCount(String username) {
+ int result = countValidTokensForUser(username);
+ return (result == 0) ? null : result;
+ }
+
+ public static class SessionJWT {
+ private final Date expiry;
+ private final String token;
+
+ public SessionJWT(JWT token) {
+ this.expiry = token.getExpiresDate();
+ this.token = token.toString();
+ }
+
+ public Date getExpiry() {
Review Comment:
If this isn't used, let's remove it.
##########
gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/WebSSOutResource.java:
##########
@@ -106,6 +111,21 @@ private boolean
removeAuthenticationToken(HttpServletResponse response) {
}
response.addCookie(c);
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null) {
+ Optional<Cookie> SSOCookie = Arrays.stream(cookies).filter(cookie ->
cookie.getName().equals(cookieName)).findFirst();
+ if (SSOCookie.isPresent()) {
+ GatewayServices gwServices =
+ (GatewayServices)
request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+ if (gwServices != null) {
+ ConcurrentSessionVerifier verifier =
gwServices.getService(ServiceType.CONCURRENT_SESSION_VERIFIER);
+ verifier.sessionEndedForUser(request.getUserPrincipal().getName(),
SSOCookie.get().getValue());
Review Comment:
Do we always have a ConcurrentSessionVerifier? I see at other places we
check if it's null or not. Probably we need to add a null check here too.
Issue Time Tracking
-------------------
Worklog Id: (was: 797959)
Time Spent: 1h 50m (was: 1h 40m)
> Enforce concurrent session limit in KnoxSSO
> -------------------------------------------
>
> Key: KNOX-2778
> URL: https://issues.apache.org/jira/browse/KNOX-2778
> Project: Apache Knox
> Issue Type: Sub-task
> Components: Server
> Affects Versions: 2.0.0
> Reporter: Sandor Molnar
> Assignee: Balazs Marton
> Priority: Major
> Fix For: 2.0.0
>
> Time Spent: 1h 50m
> Remaining Estimate: 0h
>
> Once, KNOX-2777 is ready, the next step is to wire that verifier
> implementation into the KnoxSSO flow such as it throws an authorization error
> (FORBIDDEN; 403) when a user tries to log in to UIs (both Knox's own UIs or
> UIs proxied by Knox) but that user exceeds the configured concurrent session
> limit.
> Basic logout handling should be covered too:
> * manually clicking on the logout button
> * subscribing to a session timeout event (you may want to talk to [~smore]
> about this)
--
This message was sent by Atlassian Jira
(v8.20.10#820010)