GUACAMOLE-1289: Refactor Duo and authentication-resumption changes to instead leverage support for updating/replacing credentials prior to auth.

This commit is contained in:
Michael Jumper
2024-04-25 12:52:27 -07:00
parent 83111616e5
commit 6dd4766da4
12 changed files with 340 additions and 486 deletions

View File

@@ -119,6 +119,18 @@ public class AuthenticationProviderFacade implements AuthenticationProvider {
}
@Override
public Credentials updateCredentials(Credentials credentials) throws GuacamoleException {
// Do nothing if underlying auth provider could not be loaded
if (authProvider == null)
return credentials;
// Delegate to underlying auth provider
return authProvider.updateCredentials(credentials);
}
/**
* Returns whether this authentication provider should tolerate internal
* failures during the authentication process, allowing other

View File

@@ -21,11 +21,8 @@ package org.apache.guacamole.rest.auth;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleSecurityException;
@@ -47,7 +44,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Singleton;
import java.util.Iterator;
/**
* A service for performing authentication checks in REST endpoints.
@@ -103,11 +99,6 @@ public class AuthenticationService {
*/
public static final String TOKEN_PARAMETER_NAME = "token";
/**
* Map to store resumable authentication states with an expiration time.
*/
private Map<String, ResumableAuthenticationState> resumableStateMap = new ConcurrentHashMap<>();
/**
* Attempts authentication against all AuthenticationProviders, in order,
* using the provided credentials. The first authentication failure takes
@@ -322,20 +313,6 @@ public class AuthenticationService {
try {
userContext = authProvider.getUserContext(authenticatedUser);
}
catch (GuacamoleInsufficientCredentialsException e) {
// Store state and expiration
String state = e.getState();
long expiration = e.getExpires();
String queryIdentifier = e.getQueryIdentifier();
String providerIdentifier = e.getProviderIdentifier();
resumableStateMap.put(state, new ResumableAuthenticationState(providerIdentifier,
queryIdentifier, expiration, credentials));
throw new GuacamoleAuthenticationProcessException("User "
+ "authentication aborted during initial "
+ "UserContext creation.", authProvider, e);
}
catch (GuacamoleException | RuntimeException | Error e) {
throw new GuacamoleAuthenticationProcessException("User "
+ "authentication aborted during initial "
@@ -354,81 +331,42 @@ public class AuthenticationService {
return userContexts;
}
/**
* Resumes authentication using given credentials if a matching resumable
* state is found.
* Performs arbitrary and optional updates to the credentials supplied by
* the authenticating user as dictated by the {@link AuthenticationProvider#updateCredentials(org.apache.guacamole.net.auth.Credentials)}
* functions of any installed AuthenticationProvider. Each installed
* AuthenticationProvider is given the opportunity, in order, to make
* updates to the supplied credentials.
*
* @param credentials
* The initial credentials containing the request object.
* @param credentials
* The credentials to be updated.
*
* @return
* Resumed credentials if a valid resumable state is found; otherwise,
* returns null.
* @return
* The set of credentials that should be provided to all
* AuthenticationProviders during authentication, now possibly updated
* (or even replaced) by any number of installed
* AuthenticationProviders.
*
* @throws GuacamoleAuthenticationProcessException
* If an error occurs while updating the supplied credentials.
*/
private Credentials resumeAuthentication(Credentials credentials) {
Credentials resumedCredentials = null;
private Credentials getUpdatedCredentials(Credentials credentials)
throws GuacamoleAuthenticationProcessException {
// Retrieve signed State from the request
HttpServletRequest request = credentials.getRequest();
// Retrieve the provider id from the query parameters
String resumableProviderId = request.getParameter(Credentials.RESUME_QUERY);
// Check if a provider id is set
if (resumableProviderId == null || resumableProviderId.isEmpty()) {
// Return if a provider id is not set
return null;
}
// Use an iterator to safely remove entries while iterating
Iterator<Map.Entry<String, ResumableAuthenticationState>> iterator = resumableStateMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, ResumableAuthenticationState> entry = iterator.next();
ResumableAuthenticationState resumableState = entry.getValue();
// Check if the provider ID from the request matches the one in the map entry
boolean providerMatches = resumableProviderId.equals(resumableState.getProviderIdentifier());
if (!providerMatches) {
// If the provider doesn't match, skip to the next entry
continue;
for (AuthenticationProvider authProvider : authProviders) {
try {
credentials = authProvider.updateCredentials(credentials);
}
// Use the query identifier from the entry to retrieve the corresponding state parameter
String stateQueryParameter = resumableState.getQueryIdentifier();
String stateFromParameter = request.getParameter(stateQueryParameter);
// Check if a state parameter is set
if (stateFromParameter == null || stateFromParameter.isEmpty()) {
// Remove and continue if`state is not provided or is empty
iterator.remove();
continue;
}
// If the key in the entry (state) matches the state parameter provided in the request
if (entry.getKey().equals(stateFromParameter)) {
// Remove the current entry from the map
iterator.remove();
// Check if the resumableState has expired
if (!resumableState.isExpired()) {
// Set the actualCredentials to the credentials from the matched entry
resumedCredentials = resumableState.getCredentials();
if (resumedCredentials != null) {
resumedCredentials.setRequest(request);
}
}
// Exit the loop since we've found the matching state and it's unique
break;
catch (GuacamoleException | RuntimeException | Error e) {
throw new GuacamoleAuthenticationProcessException("User "
+ "authentication aborted during credential "
+ "update/revision.", authProvider, e);
}
}
return resumedCredentials;
return credentials;
}
/**
@@ -469,16 +407,15 @@ public class AuthenticationService {
AuthenticatedUser authenticatedUser;
String authToken;
// Retrieve credentials if resuming authentication
Credentials actualCredentials = resumeAuthentication(credentials);
if (actualCredentials == null)
actualCredentials = credentials;
try {
// Allow extensions to make updated to credentials prior to
// actual authentication
Credentials updatedCredentials = getUpdatedCredentials(credentials);
// Get up-to-date AuthenticatedUser and associated UserContexts
authenticatedUser = getAuthenticatedUser(existingSession, actualCredentials);
List<DecoratedUserContext> userContexts = getUserContexts(existingSession, authenticatedUser, actualCredentials);
authenticatedUser = getAuthenticatedUser(existingSession, updatedCredentials);
List<DecoratedUserContext> userContexts = getUserContexts(existingSession, authenticatedUser, updatedCredentials);
// Update existing session, if it exists
if (existingSession != null) {
@@ -508,7 +445,7 @@ public class AuthenticationService {
// Log and rethrow any authentication errors
catch (GuacamoleAuthenticationProcessException e) {
listenerService.handleEvent(new AuthenticationFailureEvent(actualCredentials,
listenerService.handleEvent(new AuthenticationFailureEvent(credentials,
e.getAuthenticationProvider(), e.getCause()));
// Rethrow exception

View File

@@ -1,128 +0,0 @@
/*
* 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.guacamole.rest.auth;
import org.apache.guacamole.net.auth.Credentials;
/**
* Encapsulates the state information required for resuming an authentication
* process. This includes an expiration timestamp to determine state validity
* and the original credentials submitted by the user.
*/
public class ResumableAuthenticationState {
/**
* The timestamp at which this state should no longer be considered valid,
* measured in milliseconds since the Unix epoch.
*/
private long expirationTimestamp;
/**
* The original user credentials that were submitted at the start of the
* authentication process.
*/
private Credentials credentials;
/**
* A unique string identifying the authentication provider related to the state.
* This field allows the client to know which provider's authentication process
* should be resumed using this state.
*/
private String providerIdentifier;
/**
* A unique string that can be used to identify a specific query within the
* authentication process for the identified provider. This identifier can
* help the resumption of an authentication process.
*/
private String queryIdentifier;
/**
* Constructs a new ResumableAuthenticationState object with the specified
* expiration timestamp and user credentials.
*
* @param providerIdentifier
* The identifier of the authentication provider to which this resumable state pertains.
*
* @param queryIdenifier
* The identifier of the specific query within the provider's
* authentication process that this state corresponds to.
*
* @param expirationTimestamp
* The timestamp in milliseconds since the Unix epoch when this state
* expires and can no longer be used to resume authentication.
*
* @param credentials
* The Credentials object initially submitted by the user and associated
* with this resumable state.
*/
public ResumableAuthenticationState(String providerIdentifier, String queryIdentifier,
long expirationTimestamp, Credentials credentials) {
this.expirationTimestamp = expirationTimestamp;
this.credentials = credentials;
this.providerIdentifier = providerIdentifier;
this.queryIdentifier = queryIdentifier;
}
/**
* Checks if this resumable state has expired based on the stored expiration
* timestamp and the current system time.
*
* @return
* True if the current system time is after the expiration timestamp,
* indicating that the state is expired; false otherwise.
*/
public boolean isExpired() {
return System.currentTimeMillis() >= expirationTimestamp;
}
/**
* Retrieves the original credentials associated with this resumable state.
*
* @return
* The Credentials object containing user details that were submitted
* when the state was created.
*/
public Credentials getCredentials() {
return this.credentials;
}
/**
* Retrieves the identifier of the authentication provider associated with this state.
*
* @return
* The identifier of the authentication provider, providing context for this state
* within the overall authentication sequence.
*/
public String getProviderIdentifier() {
return this.providerIdentifier;
}
/**
* Retrieves the identifier for a specific query in the authentication
* process that is associated with this state.
*
* @return
* The query identifier used for retrieving a value representing the state within
* the provider's authentication process that should be resumed.
*/
public String getQueryIdentifier() {
return this.queryIdentifier;
}
}