repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixin.java | /*
* Copyright 2015-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.cas.jackson2;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.apereo.cas.client.validation.Assertion;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
* Mixin class which helps in deserialize
* {@link org.springframework.security.cas.authentication.CasAuthenticationToken} using
* jackson. Two more dependent classes needs to register along with this mixin class.
* <ol>
* <li>{@link org.springframework.security.cas.jackson2.AssertionImplMixin}</li>
* <li>{@link org.springframework.security.cas.jackson2.AttributePrincipalImplMixin}</li>
* </ol>
*
* <p>
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @since 4.2
* @see CasJackson2Module
* @see org.springframework.security.jackson2.SecurityJackson2Modules
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, isGetterVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY)
@JsonIgnoreProperties(ignoreUnknown = true)
class CasAuthenticationTokenMixin {
/**
* Mixin Constructor helps in deserialize {@link CasAuthenticationToken}
* @param keyHash hashCode of provided key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param credentials the service/proxy ticket ID from CAS (cannot be
* <code>null</code>)
* @param authorities the authorities granted to the user (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param userDetails the user details (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
*/
@JsonCreator
CasAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash, @JsonProperty("principal") Object principal,
@JsonProperty("credentials") Object credentials,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities,
@JsonProperty("userDetails") UserDetails userDetails, @JsonProperty("assertion") Assertion assertion) {
}
}
| 3,644 | 42.392857 | 117 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/jackson2/AssertionImplMixin.java | /*
* Copyright 2015-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.cas.jackson2;
import java.util.Date;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.apereo.cas.client.authentication.AttributePrincipal;
/**
* Helps in jackson deserialization of class
* {@link org.apereo.cas.client.validation.AssertionImpl}, which is used with
* {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. To use
* this class we need to register with
* {@link com.fasterxml.jackson.databind.ObjectMapper}. Type information will be stored
* in @class property.
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @since 4.2
* @see CasJackson2Module
* @see org.springframework.security.jackson2.SecurityJackson2Modules
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
class AssertionImplMixin {
/**
* Mixin Constructor helps in deserialize
* {@link org.apereo.cas.client.validation.AssertionImpl}
* @param principal the Principal to associate with the Assertion.
* @param validFromDate when the assertion is valid from.
* @param validUntilDate when the assertion is valid to.
* @param authenticationDate when the assertion is authenticated.
* @param attributes the key/value pairs for this attribute.
*/
@JsonCreator
AssertionImplMixin(@JsonProperty("principal") AttributePrincipal principal,
@JsonProperty("validFromDate") Date validFromDate, @JsonProperty("validUntilDate") Date validUntilDate,
@JsonProperty("authenticationDate") Date authenticationDate,
@JsonProperty("attributes") Map<String, Object> attributes) {
}
}
| 2,786 | 38.814286 | 115 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java | /*
* Copyright 2015-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.cas.jackson2;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.apereo.cas.client.authentication.AttributePrincipalImpl;
import org.apereo.cas.client.validation.AssertionImpl;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.jackson2.SecurityJackson2Modules;
/**
* Jackson module for spring-security-cas. This module register
* {@link AssertionImplMixin}, {@link AttributePrincipalImplMixin} and
* {@link CasAuthenticationTokenMixin}. If no default typing enabled by default then it'll
* enable it because typing info is needed to properly serialize/deserialize objects. In
* order to use this module just add this module into your ObjectMapper configuration.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CasJackson2Module());
* </pre> <b>Note: use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get list
* of all security modules on the classpath.</b>
*
* @author Jitendra Singh.
* @since 4.2
* @see org.springframework.security.jackson2.SecurityJackson2Modules
*/
public class CasJackson2Module extends SimpleModule {
public CasJackson2Module() {
super(CasJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null));
}
@Override
public void setupModule(SetupContext context) {
SecurityJackson2Modules.enableDefaultTyping(context.getOwner());
context.setMixInAnnotations(AssertionImpl.class, AssertionImplMixin.class);
context.setMixInAnnotations(AttributePrincipalImpl.class, AttributePrincipalImplMixin.class);
context.setMixInAnnotations(CasAuthenticationToken.class, CasAuthenticationTokenMixin.class);
}
}
| 2,407 | 39.813559 | 95 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/authentication/package-info.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.
*/
/**
* An {@code AuthenticationProvider} that can process CAS service tickets and proxy
* tickets.
*/
package org.springframework.security.cas.authentication;
| 784 | 34.681818 | 83 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/authentication/CasServiceTicketAuthenticationToken.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.cas.authentication;
import java.io.Serial;
import java.util.Collection;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;
/**
* An {@link org.springframework.security.core.Authentication} implementation that is
* designed to process CAS service ticket.
*
* @author Hal Deadman
* @since 6.1
*/
public class CasServiceTicketAuthenticationToken extends AbstractAuthenticationToken {
static final String CAS_STATELESS_IDENTIFIER = "_cas_stateless_";
static final String CAS_STATEFUL_IDENTIFIER = "_cas_stateful_";
@Serial
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final String identifier;
private Object credentials;
/**
* This constructor can be safely used by any code that wishes to create a
* <code>CasServiceTicketAuthenticationToken</code>, as the {@link #isAuthenticated()}
* will return <code>false</code>.
*
*/
public CasServiceTicketAuthenticationToken(String identifier, Object credentials) {
super(null);
this.identifier = identifier;
this.credentials = credentials;
setAuthenticated(false);
}
/**
* This constructor should only be used by <code>AuthenticationManager</code> or
* <code>AuthenticationProvider</code> implementations that are satisfied with
* producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
* authentication token.
* @param identifier
* @param credentials
* @param authorities
*/
public CasServiceTicketAuthenticationToken(String identifier, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.identifier = identifier;
this.credentials = credentials;
super.setAuthenticated(true);
}
public static CasServiceTicketAuthenticationToken stateful(Object credentials) {
return new CasServiceTicketAuthenticationToken(CAS_STATEFUL_IDENTIFIER, credentials);
}
public static CasServiceTicketAuthenticationToken stateless(Object credentials) {
return new CasServiceTicketAuthenticationToken(CAS_STATELESS_IDENTIFIER, credentials);
}
public boolean isStateless() {
return CAS_STATELESS_IDENTIFIER.equals(this.identifier);
}
@Override
public Object getCredentials() {
return this.credentials;
}
@Override
public Object getPrincipal() {
return this.identifier;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
Assert.isTrue(!isAuthenticated,
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
this.credentials = null;
}
}
| 3,541 | 30.345133 | 102 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/authentication/StatelessTicketCache.java | /*
* Copyright 2004 Acegi Technology Pty Limited
*
* Licensed 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
*
* https://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.springframework.security.cas.authentication;
/**
* Caches CAS service tickets and CAS proxy tickets for stateless connections.
*
* <p>
* When a service ticket or proxy ticket is validated against the CAS server, it is unable
* to be used again. Most types of callers are stateful and are associated with a given
* <code>HttpSession</code>. This allows the affirmative CAS validation outcome to be
* stored in the <code>HttpSession</code>, meaning the removal of the ticket from the CAS
* server is not an issue.
* </p>
*
* <P>
* Stateless callers, such as remoting protocols, cannot take advantage of
* <code>HttpSession</code>. If the stateless caller is located a significant network
* distance from the CAS server, acquiring a fresh service ticket or proxy ticket for each
* invocation would be expensive.
* </p>
*
* <P>
* To avoid this issue with stateless callers, it is expected stateless callers will
* obtain a single service ticket or proxy ticket, and then present this same ticket to
* the Spring Security secured application on each occasion. As no
* <code>HttpSession</code> is available for such callers, the affirmative CAS validation
* outcome cannot be stored in this location.
* </p>
*
* <P>
* The <code>StatelessTicketCache</code> enables the service tickets and proxy tickets
* belonging to stateless callers to be placed in a cache. This in-memory cache stores the
* <code>CasAuthenticationToken</code>, effectively providing the same capability as a
* <code>HttpSession</code> with the ticket identifier being the key rather than a session
* identifier.
* </p>
*
* <P>
* Implementations should provide a reasonable timeout on stored entries, such that the
* stateless caller are not required to unnecessarily acquire fresh CAS service tickets or
* proxy tickets.
* </p>
*
* @author Ben Alex
*/
public interface StatelessTicketCache {
/**
* Retrieves the <code>CasAuthenticationToken</code> associated with the specified
* ticket.
*
* <P>
* If not found, returns a <code>null</code><code>CasAuthenticationToken</code>.
* </p>
* @return the fully populated authentication token
*/
CasAuthenticationToken getByTicketId(String serviceTicket);
/**
* Adds the specified <code>CasAuthenticationToken</code> to the cache.
*
* <P>
* The {@link CasAuthenticationToken#getCredentials()} method is used to retrieve the
* service ticket number.
* </p>
* @param token to be added to the cache
*/
void putTicketInCache(CasAuthenticationToken token);
/**
* Removes the specified ticket from the cache, as per
* {@link #removeTicketFromCache(String)}.
*
* <P>
* Implementations should use {@link CasAuthenticationToken#getCredentials()} to
* obtain the ticket and then delegate to the {@link #removeTicketFromCache(String)}
* method.
* </p>
* @param token to be removed
*/
void removeTicketFromCache(CasAuthenticationToken token);
/**
* Removes the specified ticket from the cache, meaning that future calls will require
* a new service ticket.
*
* <P>
* This is in case applications wish to provide a session termination capability for
* their stateless clients.
* </p>
* @param serviceTicket to be removed
*/
void removeTicketFromCache(String serviceTicket);
}
| 3,920 | 34.324324 | 90 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.cas.authentication;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.Cache;
import org.springframework.core.log.LogMessage;
import org.springframework.util.Assert;
/**
* Caches tickets using a Spring IoC defined {@link Cache}.
*
* @author Marten Deinum
* @since 3.2
*
*/
public class SpringCacheBasedTicketCache implements StatelessTicketCache {
private static final Log logger = LogFactory.getLog(SpringCacheBasedTicketCache.class);
private final Cache cache;
public SpringCacheBasedTicketCache(Cache cache) {
Assert.notNull(cache, "cache mandatory");
this.cache = cache;
}
@Override
public CasAuthenticationToken getByTicketId(final String serviceTicket) {
final Cache.ValueWrapper element = (serviceTicket != null) ? this.cache.get(serviceTicket) : null;
logger.debug(LogMessage.of(() -> "Cache hit: " + (element != null) + "; service ticket: " + serviceTicket));
return (element != null) ? (CasAuthenticationToken) element.get() : null;
}
@Override
public void putTicketInCache(final CasAuthenticationToken token) {
String key = token.getCredentials().toString();
logger.debug(LogMessage.of(() -> "Cache put: " + key));
this.cache.put(key, token);
}
@Override
public void removeTicketFromCache(final CasAuthenticationToken token) {
logger.debug(LogMessage.of(() -> "Cache remove: " + token.getCredentials().toString()));
this.removeTicketFromCache(token.getCredentials().toString());
}
@Override
public void removeTicketFromCache(final String serviceTicket) {
this.cache.evict(serviceTicket);
}
}
| 2,285 | 31.657143 | 110 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/authentication/NullStatelessTicketCache.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed 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
*
* https://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.springframework.security.cas.authentication;
/**
* Implementation of @link {@link StatelessTicketCache} that has no backing cache. Useful
* in instances where storing of tickets for stateless session management is not required.
* <p>
* This is the default StatelessTicketCache of the @link {@link CasAuthenticationProvider}
* to eliminate the unnecessary dependency on EhCache that applications have even if they
* are not using the stateless session management.
*
* @author Scott Battaglia
* @see CasAuthenticationProvider
*/
public final class NullStatelessTicketCache implements StatelessTicketCache {
/**
* @return null since we are not storing any tickets.
*/
@Override
public CasAuthenticationToken getByTicketId(final String serviceTicket) {
return null;
}
/**
* This is a no-op since we are not storing tickets.
*/
@Override
public void putTicketInCache(final CasAuthenticationToken token) {
// nothing to do
}
/**
* This is a no-op since we are not storing tickets.
*/
@Override
public void removeTicketFromCache(final CasAuthenticationToken token) {
// nothing to do
}
/**
* This is a no-op since we are not storing tickets.
*/
@Override
public void removeTicketFromCache(final String serviceTicket) {
// nothing to do
}
}
| 1,928 | 28.676923 | 90 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/authentication/CasAssertionAuthenticationToken.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed 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
*
* https://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.springframework.security.cas.authentication;
import java.util.ArrayList;
import org.apereo.cas.client.validation.Assertion;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.SpringSecurityCoreVersion;
/**
* Temporary authentication object needed to load the user details service.
*
* @author Scott Battaglia
* @since 3.0
*/
public final class CasAssertionAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Assertion assertion;
private final String ticket;
public CasAssertionAuthenticationToken(final Assertion assertion, final String ticket) {
super(new ArrayList<>());
this.assertion = assertion;
this.ticket = ticket;
}
@Override
public Object getPrincipal() {
return this.assertion.getPrincipal().getName();
}
@Override
public Object getCredentials() {
return this.ticket;
}
public Assertion getAssertion() {
return this.assertion;
}
}
| 1,704 | 26.95082 | 91 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationProvider.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed 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
*
* https://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.springframework.security.cas.authentication;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apereo.cas.client.validation.Assertion;
import org.apereo.cas.client.validation.TicketValidationException;
import org.apereo.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.Assert;
/**
* An {@link AuthenticationProvider} implementation that integrates with JA-SIG Central
* Authentication Service (CAS).
* <p>
* This <code>AuthenticationProvider</code> is capable of validating
* {@link CasServiceTicketAuthenticationToken} requests which contain a
* <code>principal</code> name equal to either
* {@link CasServiceTicketAuthenticationToken#CAS_STATEFUL_IDENTIFIER} or
* {@link CasServiceTicketAuthenticationToken#CAS_STATELESS_IDENTIFIER}. It can also
* validate a previously created {@link CasAuthenticationToken}.
*
* @author Ben Alex
* @author Scott Battaglia
*/
public class CasAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
private static final Log logger = LogFactory.getLog(CasAuthenticationProvider.class);
private AuthenticationUserDetailsService<CasAssertionAuthenticationToken> authenticationUserDetailsService;
private final UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private StatelessTicketCache statelessTicketCache = new NullStatelessTicketCache();
private String key;
private TicketValidator ticketValidator;
private ServiceProperties serviceProperties;
private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
@Override
public void afterPropertiesSet() {
Assert.notNull(this.authenticationUserDetailsService, "An authenticationUserDetailsService must be set");
Assert.notNull(this.ticketValidator, "A ticketValidator must be set");
Assert.notNull(this.statelessTicketCache, "A statelessTicketCache must be set");
Assert.hasText(this.key,
"A Key is required so CasAuthenticationProvider can identify tokens it previously authenticated");
Assert.notNull(this.messages, "A message source must be set");
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
// If an existing CasAuthenticationToken, just check we created it
if (authentication instanceof CasAuthenticationToken) {
if (this.key.hashCode() != ((CasAuthenticationToken) authentication).getKeyHash()) {
throw new BadCredentialsException(this.messages.getMessage("CasAuthenticationProvider.incorrectKey",
"The presented CasAuthenticationToken does not contain the expected key"));
}
return authentication;
}
// Ensure credentials are presented
if ((authentication.getCredentials() == null) || "".equals(authentication.getCredentials())) {
throw new BadCredentialsException(this.messages.getMessage("CasAuthenticationProvider.noServiceTicket",
"Failed to provide a CAS service ticket to validate"));
}
boolean stateless = (authentication instanceof CasServiceTicketAuthenticationToken token && token.isStateless());
CasAuthenticationToken result = null;
if (stateless) {
// Try to obtain from cache
result = this.statelessTicketCache.getByTicketId(authentication.getCredentials().toString());
}
if (result == null) {
result = this.authenticateNow(authentication);
result.setDetails(authentication.getDetails());
}
if (stateless) {
// Add to cache
this.statelessTicketCache.putTicketInCache(result);
}
return result;
}
private CasAuthenticationToken authenticateNow(final Authentication authentication) throws AuthenticationException {
try {
Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(),
getServiceUrl(authentication));
UserDetails userDetails = loadUserByAssertion(assertion);
this.userDetailsChecker.check(userDetails);
return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(),
this.authoritiesMapper.mapAuthorities(userDetails.getAuthorities()), userDetails, assertion);
}
catch (TicketValidationException ex) {
throw new BadCredentialsException(ex.getMessage(), ex);
}
}
/**
* Gets the serviceUrl. If the {@link Authentication#getDetails()} is an instance of
* {@link ServiceAuthenticationDetails}, then
* {@link ServiceAuthenticationDetails#getServiceUrl()} is used. Otherwise, the
* {@link ServiceProperties#getService()} is used.
* @param authentication
* @return
*/
private String getServiceUrl(Authentication authentication) {
String serviceUrl;
if (authentication.getDetails() instanceof ServiceAuthenticationDetails) {
return ((ServiceAuthenticationDetails) authentication.getDetails()).getServiceUrl();
}
Assert.state(this.serviceProperties != null,
"serviceProperties cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails.");
Assert.state(this.serviceProperties.getService() != null,
"serviceProperties.getService() cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails.");
serviceUrl = this.serviceProperties.getService();
logger.debug(LogMessage.format("serviceUrl = %s", serviceUrl));
return serviceUrl;
}
/**
* Template method for retrieving the UserDetails based on the assertion. Default is
* to call configured userDetailsService and pass the username. Deployers can override
* this method and retrieve the user based on any criteria they desire.
* @param assertion The CAS Assertion.
* @return the UserDetails.
*/
protected UserDetails loadUserByAssertion(final Assertion assertion) {
final CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, "");
return this.authenticationUserDetailsService.loadUserDetails(token);
}
@SuppressWarnings("unchecked")
/**
* Sets the UserDetailsService to use. This is a convenience method to invoke
*/
public void setUserDetailsService(final UserDetailsService userDetailsService) {
this.authenticationUserDetailsService = new UserDetailsByNameServiceWrapper(userDetailsService);
}
public void setAuthenticationUserDetailsService(
final AuthenticationUserDetailsService<CasAssertionAuthenticationToken> authenticationUserDetailsService) {
this.authenticationUserDetailsService = authenticationUserDetailsService;
}
public void setServiceProperties(final ServiceProperties serviceProperties) {
this.serviceProperties = serviceProperties;
}
protected String getKey() {
return this.key;
}
public void setKey(String key) {
this.key = key;
}
public StatelessTicketCache getStatelessTicketCache() {
return this.statelessTicketCache;
}
protected TicketValidator getTicketValidator() {
return this.ticketValidator;
}
@Override
public void setMessageSource(final MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setStatelessTicketCache(final StatelessTicketCache statelessTicketCache) {
this.statelessTicketCache = statelessTicketCache;
}
public void setTicketValidator(final TicketValidator ticketValidator) {
this.ticketValidator = ticketValidator;
}
public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
this.authoritiesMapper = authoritiesMapper;
}
@Override
public boolean supports(final Class<?> authentication) {
return (CasServiceTicketAuthenticationToken.class.isAssignableFrom(authentication))
|| (CasAuthenticationToken.class.isAssignableFrom(authentication))
|| (CasAssertionAuthenticationToken.class.isAssignableFrom(authentication));
}
}
| 9,881 | 41.051064 | 129 | java |
null | spring-security-main/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed 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
*
* https://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.springframework.security.cas.authentication;
import java.io.Serializable;
import java.util.Collection;
import org.apereo.cas.client.validation.Assertion;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* Represents a successful CAS <code>Authentication</code>.
*
* @author Ben Alex
* @author Scott Battaglia
*/
public class CasAuthenticationToken extends AbstractAuthenticationToken implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object credentials;
private final Object principal;
private final UserDetails userDetails;
private final int keyHash;
private final Assertion assertion;
/**
* Constructor.
* @param key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param credentials the service/proxy ticket ID from CAS (cannot be
* <code>null</code>)
* @param authorities the authorities granted to the user (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param userDetails the user details (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public CasAuthenticationToken(final String key, final Object principal, final Object credentials,
final Collection<? extends GrantedAuthority> authorities, final UserDetails userDetails,
final Assertion assertion) {
this(extractKeyHash(key), principal, credentials, authorities, userDetails, assertion);
}
/**
* Private constructor for Jackson Deserialization support
* @param keyHash hashCode of provided key to identify if this object made by a given
* {@link CasAuthenticationProvider}
* @param principal typically the UserDetails object (cannot be <code>null</code>)
* @param credentials the service/proxy ticket ID from CAS (cannot be
* <code>null</code>)
* @param authorities the authorities granted to the user (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param userDetails the user details (from the
* {@link org.springframework.security.core.userdetails.UserDetailsService}) (cannot
* be <code>null</code>)
* @param assertion the assertion returned from the CAS servers. It contains the
* principal and how to obtain a proxy ticket for the user.
* @throws IllegalArgumentException if a <code>null</code> was passed
* @since 4.2
*/
private CasAuthenticationToken(final Integer keyHash, final Object principal, final Object credentials,
final Collection<? extends GrantedAuthority> authorities, final UserDetails userDetails,
final Assertion assertion) {
super(authorities);
if ((principal == null) || "".equals(principal) || (credentials == null) || "".equals(credentials)
|| (authorities == null) || (userDetails == null) || (assertion == null)) {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
this.keyHash = keyHash;
this.principal = principal;
this.credentials = credentials;
this.userDetails = userDetails;
this.assertion = assertion;
setAuthenticated(true);
}
private static Integer extractKeyHash(String key) {
Assert.hasLength(key, "key cannot be null or empty");
return key.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (!super.equals(obj)) {
return false;
}
if (obj instanceof CasAuthenticationToken) {
CasAuthenticationToken test = (CasAuthenticationToken) obj;
if (!this.assertion.equals(test.getAssertion())) {
return false;
}
if (this.getKeyHash() != test.getKeyHash()) {
return false;
}
return true;
}
return false;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + this.credentials.hashCode();
result = 31 * result + this.principal.hashCode();
result = 31 * result + this.userDetails.hashCode();
result = 31 * result + this.keyHash;
result = 31 * result + ObjectUtils.nullSafeHashCode(this.assertion);
return result;
}
@Override
public Object getCredentials() {
return this.credentials;
}
public int getKeyHash() {
return this.keyHash;
}
@Override
public Object getPrincipal() {
return this.principal;
}
public Assertion getAssertion() {
return this.assertion;
}
public UserDetails getUserDetails() {
return this.userDetails;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append(" Assertion: ").append(this.assertion);
sb.append(" Credentials (Service/Proxy Ticket): ").append(this.credentials);
return (sb.toString());
}
}
| 5,983 | 33.390805 | 104 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/core/CaptureSecurityContextSocketAcceptor.java | /*
* Copyright 2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import io.rsocket.ConnectionSetupPayload;
import io.rsocket.RSocket;
import io.rsocket.SocketAcceptor;
import reactor.core.publisher.Mono;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
/**
* A {@link SocketAcceptor} that captures the {@link SecurityContext} and then continues
* with the {@link RSocket}
*
* @author Rob Winch
*/
class CaptureSecurityContextSocketAcceptor implements SocketAcceptor {
private final RSocket accept;
private SecurityContext securityContext;
CaptureSecurityContextSocketAcceptor(RSocket accept) {
this.accept = accept;
}
@Override
public Mono<RSocket> accept(ConnectionSetupPayload setup, RSocket sendingSocket) {
return ReactiveSecurityContextHolder.getContext()
.doOnNext((securityContext) -> this.securityContext = securityContext).thenReturn(this.accept);
}
SecurityContext getSecurityContext() {
return this.securityContext;
}
}
| 1,665 | 29.851852 | 99 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import io.rsocket.ConnectionSetupPayload;
import io.rsocket.Payload;
import io.rsocket.RSocket;
import io.rsocket.SocketAcceptor;
import io.rsocket.metadata.WellKnownMimeType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class PayloadSocketAcceptorTests {
private PayloadSocketAcceptor acceptor;
private List<PayloadInterceptor> interceptors;
@Mock
private SocketAcceptor delegate;
@Mock
private PayloadInterceptor interceptor;
@Mock
private ConnectionSetupPayload setupPayload;
@Mock
private RSocket rSocket;
@Mock
private Payload payload;
@BeforeEach
public void setup() {
this.interceptors = Arrays.asList(this.interceptor);
this.acceptor = new PayloadSocketAcceptor(this.delegate, this.interceptors);
}
@Test
public void constructorWhenNullDelegateThenException() {
this.delegate = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors));
}
@Test
public void constructorWhenNullInterceptorsThenException() {
this.interceptors = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors));
}
@Test
public void constructorWhenEmptyInterceptorsThenException() {
this.interceptors = Collections.emptyList();
assertThatIllegalArgumentException()
.isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors));
}
@Test
public void acceptWhenDataMimeTypeNullThenException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.acceptor.accept(this.setupPayload, this.rSocket).block());
}
@Test
public void acceptWhenDefaultMetadataMimeTypeThenDefaulted() {
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType().toString())
.isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
public void acceptWhenDefaultMetadataMimeTypeOverrideThenDefaulted() {
this.acceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON);
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
public void acceptWhenDefaultDataMimeTypeThenDefaulted() {
this.acceptor.setDefaultDataMimeType(MediaType.APPLICATION_JSON);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType().toString())
.isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
public void acceptWhenExplicitMimeTypeThenThenOverrideDefault() {
given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE);
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.TEXT_PLAIN);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
// gh-8654
public void acceptWhenDelegateAcceptRequiresReactiveSecurityContext() {
given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE);
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
SecurityContext expectedSecurityContext = new SecurityContextImpl(
new TestingAuthenticationToken("user", "password", "ROLE_USER"));
CaptureSecurityContextSocketAcceptor captureSecurityContext = new CaptureSecurityContextSocketAcceptor(
this.rSocket);
PayloadInterceptor authenticateInterceptor = (exchange, chain) -> {
Context withSecurityContext = ReactiveSecurityContextHolder
.withSecurityContext(Mono.just(expectedSecurityContext));
return chain.next(exchange).contextWrite(withSecurityContext);
};
List<PayloadInterceptor> interceptors = Arrays.asList(authenticateInterceptor);
this.acceptor = new PayloadSocketAcceptor(captureSecurityContext, interceptors);
this.acceptor.accept(this.setupPayload, this.rSocket).block();
assertThat(captureSecurityContext.getSecurityContext()).isEqualTo(expectedSecurityContext);
}
private PayloadExchange captureExchange() {
given(this.delegate.accept(any(), any())).willReturn(Mono.just(this.rSocket));
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
RSocket result = this.acceptor.accept(this.setupPayload, this.rSocket).block();
assertThat(result).isInstanceOf(PayloadInterceptorRSocket.class);
given(this.rSocket.fireAndForget(any())).willReturn(Mono.empty());
result.fireAndForget(this.payload).block();
ArgumentCaptor<PayloadExchange> exchangeArg = ArgumentCaptor.forClass(PayloadExchange.class);
verify(this.interceptor, times(2)).intercept(exchangeArg.capture(), any());
return exchangeArg.getValue();
}
}
| 7,040 | 38.335196 | 105 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import io.rsocket.Payload;
import io.rsocket.RSocket;
import io.rsocket.metadata.WellKnownMimeType;
import io.rsocket.util.ByteBufPayload;
import io.rsocket.util.DefaultPayload;
import io.rsocket.util.RSocketProxy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.test.publisher.PublisherProbe;
import reactor.test.publisher.TestPublisher;
import reactor.util.context.Context;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadExchangeType;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.security.rsocket.api.PayloadInterceptorChain;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class PayloadInterceptorRSocketTests {
static final MimeType COMPOSITE_METADATA = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
@Mock
RSocket delegate;
@Mock
PayloadInterceptor interceptor;
@Mock
PayloadInterceptor interceptor2;
@Mock
Payload payload;
@Captor
private ArgumentCaptor<PayloadExchange> exchange;
PublisherProbe<Void> voidResult = PublisherProbe.empty();
TestPublisher<Payload> payloadResult = TestPublisher.createCold();
private MimeType metadataMimeType = COMPOSITE_METADATA;
private MimeType dataMimeType = MediaType.APPLICATION_JSON;
@Test
public void constructorWhenNullDelegateThenException() {
this.delegate = null;
List<PayloadInterceptor> interceptors = Arrays.asList(this.interceptor);
assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors,
this.metadataMimeType, this.dataMimeType));
}
@Test
public void constructorWhenNullInterceptorsThenException() {
List<PayloadInterceptor> interceptors = null;
assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors,
this.metadataMimeType, this.dataMimeType));
}
@Test
public void constructorWhenEmptyInterceptorsThenException() {
List<PayloadInterceptor> interceptors = Collections.emptyList();
assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors,
this.metadataMimeType, this.dataMimeType));
}
// single interceptor
@Test
public void fireAndForgetWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.fireAndForget(this.payload)).then(() -> this.voidResult.assertWasSubscribed())
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void fireAndForgetWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.fireAndForget(this.payload))
.then(() -> this.voidResult.assertWasNotSubscribed())
.verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void fireAndForgetWhenSecurityContextThenDelegateContext() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.fireAndForget(any())).willReturn(Mono.empty());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Mono<Void> fireAndForget(Payload payload) {
return assertAuthentication(authentication).flatMap((a) -> super.fireAndForget(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).fireAndForget(this.payload);
}
@Test
public void requestResponseWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestResponse(any())).willReturn(this.payloadResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestResponse(this.payload))
.then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestResponse(this.payload);
}
@Test
public void requestResponseWhenInterceptorErrorsThenDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> interceptor.requestResponse(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verifyNoMoreInteractions(this.delegate);
}
@Test
public void requestResponseWhenSecurityContextThenDelegateContext() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.requestResponse(any())).willReturn(this.payloadResult.mono());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Mono<Payload> requestResponse(Payload payload) {
return assertAuthentication(authentication).flatMap((a) -> super.requestResponse(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestResponse(this.payload))
.then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestResponse(this.payload);
}
@Test
public void requestStreamWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestStream(any())).willReturn(this.payloadResult.flux());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload)).then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void requestStreamWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload))
.then(() -> this.payloadResult.assertNoSubscribers())
.verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void requestStreamWhenSecurityContextThenDelegateContext() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.requestStream(any())).willReturn(this.payloadResult.flux());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Flux<Payload> requestStream(Payload payload) {
return assertAuthentication(authentication).flatMapMany((a) -> super.requestStream(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload)).then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestStream(this.payload);
}
@Test
public void requestChannelWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestChannel(any())).willReturn(this.payloadResult.flux());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(Flux.just(this.payload)))
.then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestChannel(any());
}
// gh-9345
@Test
public void requestChannelWhenInterceptorCompletesThenAllPayloadsRetained() {
ExecutorService executors = Executors.newSingleThreadExecutor();
Payload payload = ByteBufPayload.create("data");
Payload payloadTwo = ByteBufPayload.create("moredata");
Payload payloadThree = ByteBufPayload.create("stillmoredata");
Context ctx = Context.empty();
Flux<Payload> payloads = this.payloadResult.flux();
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty())
.willReturn(Mono.error(() -> new AccessDeniedException("Access Denied")));
given(this.delegate.requestChannel(any())).willAnswer((invocation) -> {
Flux<Payload> input = invocation.getArgument(0);
return Flux.from(input).switchOnFirst((signal, innerFlux) -> innerFlux.map(Payload::getDataUtf8)
.transform((data) -> Flux.<String>create((emitter) -> {
Runnable run = () -> data.subscribe(new CoreSubscriber<String>() {
@Override
public void onSubscribe(Subscription s) {
s.request(3);
}
@Override
public void onNext(String s) {
emitter.next(s);
}
@Override
public void onError(Throwable t) {
emitter.error(t);
}
@Override
public void onComplete() {
emitter.complete();
}
});
executors.execute(run);
})).map(DefaultPayload::create));
});
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType, ctx);
StepVerifier.create(interceptor.requestChannel(payloads).doOnDiscard(Payload.class, Payload::release))
.then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(payload, payloadTwo, payloadThree))
.assertNext((next) -> assertThat(next.getDataUtf8()).isEqualTo(payload.getDataUtf8()))
.verifyError(AccessDeniedException.class);
verify(this.interceptor, times(2)).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(payloadTwo);
verify(this.delegate).requestChannel(any());
}
@Test
public void requestChannelWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(Flux.just(this.payload)))
.then(() -> this.payloadResult.assertNoSubscribers())
.verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void requestChannelWhenSecurityContextThenDelegateContext() {
Mono<Payload> payload = Mono.just(this.payload);
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.requestChannel(any())).willReturn(this.payloadResult.flux());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Flux<Payload> requestChannel(Publisher<Payload> payload) {
return assertAuthentication(authentication).flatMapMany((a) -> super.requestChannel(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(payload)).then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestChannel(any());
}
@Test
public void metadataPushWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.metadataPush(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload)).then(() -> this.voidResult.assertWasSubscribed())
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void metadataPushWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload)).then(() -> this.voidResult.assertWasNotSubscribed())
.verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void metadataPushWhenSecurityContextThenDelegateContext() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.metadataPush(any())).willReturn(this.voidResult.mono());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Mono<Void> metadataPush(Payload payload) {
return assertAuthentication(authentication).flatMap((a) -> super.metadataPush(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload)).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).metadataPush(this.payload);
this.voidResult.assertWasSubscribed();
}
// multiple interceptors
@Test
public void fireAndForgetWhenInterceptorsCompleteThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
this.voidResult.assertWasSubscribed();
}
@Test
public void fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
verify(this.delegate).fireAndForget(eq(this.payload));
this.voidResult.assertWasSubscribed();
}
@Test
public void fireAndForgetWhenInterceptor1ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verifyNoMoreInteractions(this.interceptor2);
this.voidResult.assertWasNotSubscribed();
}
@Test
public void fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
this.voidResult.assertWasNotSubscribed();
}
private Mono<Authentication> assertAuthentication(Authentication authentication) {
return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
.doOnNext((a) -> assertThat(a).isEqualTo(authentication));
}
private Answer<Object> withAuthenticated(Authentication authentication) {
return (invocation) -> {
PayloadInterceptorChain c = (PayloadInterceptorChain) invocation.getArguments()[1];
return c.next(new DefaultPayloadExchange(PayloadExchangeType.REQUEST_CHANNEL, this.payload,
this.metadataMimeType, this.dataMimeType))
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
};
}
private static Answer<Mono<Void>> withChainNext() {
return (invocation) -> {
PayloadExchange exchange = (PayloadExchange) invocation.getArguments()[0];
PayloadInterceptorChain chain = (PayloadInterceptorChain) invocation.getArguments()[1];
return chain.next(exchange);
};
}
}
| 24,272 | 48.841889 | 114 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorInterceptorTests.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import java.util.Arrays;
import java.util.List;
import io.rsocket.ConnectionSetupPayload;
import io.rsocket.Payload;
import io.rsocket.RSocket;
import io.rsocket.SocketAcceptor;
import io.rsocket.metadata.WellKnownMimeType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.http.MediaType;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class PayloadSocketAcceptorInterceptorTests {
@Mock
private PayloadInterceptor interceptor;
@Mock
private SocketAcceptor socketAcceptor;
@Mock
private ConnectionSetupPayload setupPayload;
@Mock
private RSocket rSocket;
@Mock
private Payload payload;
private List<PayloadInterceptor> interceptors;
private PayloadSocketAcceptorInterceptor acceptorInterceptor;
@BeforeEach
public void setup() {
this.interceptors = Arrays.asList(this.interceptor);
this.acceptorInterceptor = new PayloadSocketAcceptorInterceptor(this.interceptors);
}
@Test
public void applyWhenDefaultMetadataMimeTypeThenDefaulted() {
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType().toString())
.isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
public void acceptWhenDefaultMetadataMimeTypeOverrideThenDefaulted() {
this.acceptorInterceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON);
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
@Test
public void acceptWhenDefaultDataMimeTypeThenDefaulted() {
this.acceptorInterceptor.setDefaultDataMimeType(MediaType.APPLICATION_JSON);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType().toString())
.isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
private PayloadExchange captureExchange() {
given(this.socketAcceptor.accept(any(), any())).willReturn(Mono.just(this.rSocket));
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
SocketAcceptor wrappedAcceptor = this.acceptorInterceptor.apply(this.socketAcceptor);
RSocket result = wrappedAcceptor.accept(this.setupPayload, this.rSocket).block();
assertThat(result).isInstanceOf(PayloadInterceptorRSocket.class);
given(this.rSocket.fireAndForget(any())).willReturn(Mono.empty());
result.fireAndForget(this.payload).block();
ArgumentCaptor<PayloadExchange> exchangeArg = ArgumentCaptor.forClass(PayloadExchange.class);
verify(this.interceptor, times(2)).intercept(exchangeArg.capture(), any());
return exchangeArg.getValue();
}
}
| 4,299 | 35.752137 | 95 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/util/matcher/RoutePayloadExchangeMatcherTests.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.util.matcher;
import java.util.Collections;
import java.util.Map;
import io.rsocket.Payload;
import io.rsocket.metadata.WellKnownMimeType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.messaging.rsocket.MetadataExtractor;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadExchangeType;
import org.springframework.security.rsocket.core.DefaultPayloadExchange;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.RouteMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class RoutePayloadExchangeMatcherTests {
static final MimeType COMPOSITE_METADATA = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
@Mock
private MetadataExtractor metadataExtractor;
@Mock
private RouteMatcher routeMatcher;
private PayloadExchange exchange;
@Mock
private Payload payload;
@Mock
private RouteMatcher.Route route;
private String pattern;
private RoutePayloadExchangeMatcher matcher;
@BeforeEach
public void setup() {
this.pattern = "a.b";
this.matcher = new RoutePayloadExchangeMatcher(this.metadataExtractor, this.routeMatcher, this.pattern);
this.exchange = new DefaultPayloadExchange(PayloadExchangeType.REQUEST_CHANNEL, this.payload,
COMPOSITE_METADATA, MediaType.APPLICATION_JSON);
}
@Test
public void matchesWhenNoRouteThenNotMatch() {
given(this.metadataExtractor.extract(any(), any())).willReturn(Collections.emptyMap());
PayloadExchangeMatcher.MatchResult result = this.matcher.matches(this.exchange).block();
assertThat(result.isMatch()).isFalse();
}
@Test
public void matchesWhenNotMatchThenNotMatch() {
String route = "route";
given(this.metadataExtractor.extract(any(), any()))
.willReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route));
PayloadExchangeMatcher.MatchResult result = this.matcher.matches(this.exchange).block();
assertThat(result.isMatch()).isFalse();
}
@Test
public void matchesWhenMatchAndNoVariablesThenMatch() {
String route = "route";
given(this.metadataExtractor.extract(any(), any()))
.willReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route));
given(this.routeMatcher.parseRoute(any())).willReturn(this.route);
given(this.routeMatcher.matchAndExtract(any(), any())).willReturn(Collections.emptyMap());
PayloadExchangeMatcher.MatchResult result = this.matcher.matches(this.exchange).block();
assertThat(result.isMatch()).isTrue();
}
@Test
public void matchesWhenMatchAndVariablesThenMatchAndVariables() {
String route = "route";
Map<String, String> variables = Collections.singletonMap("a", "b");
given(this.metadataExtractor.extract(any(), any()))
.willReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route));
given(this.routeMatcher.parseRoute(any())).willReturn(this.route);
given(this.routeMatcher.matchAndExtract(any(), any())).willReturn(variables);
PayloadExchangeMatcher.MatchResult result = this.matcher.matches(this.exchange).block();
assertThat(result.isMatch()).isTrue();
assertThat(result.getVariables()).containsAllEntriesOf(variables);
}
}
| 4,285 | 35.016807 | 106 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorChain.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadInterceptorChain;
/**
* @author Rob Winch
*/
class AuthenticationPayloadInterceptorChain implements PayloadInterceptorChain {
private Authentication authentication;
@Override
public Mono<Void> next(PayloadExchange exchange) {
return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
.doOnNext((a) -> this.setAuthentication(a)).then();
}
Authentication getAuthentication() {
return this.authentication;
}
void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
}
| 1,601 | 31.693878 | 91 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AnonymousPayloadInterceptorTests.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.rsocket.api.PayloadExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class AnonymousPayloadInterceptorTests {
@Mock
private PayloadExchange exchange;
private AnonymousPayloadInterceptor interceptor;
@BeforeEach
public void setup() {
this.interceptor = new AnonymousPayloadInterceptor("key");
}
@Test
public void constructorKeyWhenKeyNullThenException() {
String key = null;
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousPayloadInterceptor(key));
}
@Test
public void constructorKeyPrincipalAuthoritiesWhenKeyNullThenException() {
String key = null;
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousPayloadInterceptor(key, "principal",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
}
@Test
public void constructorKeyPrincipalAuthoritiesWhenPrincipalNullThenException() {
Object principal = null;
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousPayloadInterceptor("key", principal,
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
}
@Test
public void constructorKeyPrincipalAuthoritiesWhenAuthoritiesNullThenException() {
List<GrantedAuthority> authorities = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new AnonymousPayloadInterceptor("key", "principal", authorities));
}
@Test
public void interceptWhenNoAuthenticationThenAnonymousAuthentication() {
AuthenticationPayloadInterceptorChain chain = new AuthenticationPayloadInterceptorChain();
this.interceptor.intercept(this.exchange, chain).block();
Authentication authentication = chain.getAuthentication();
assertThat(authentication).isInstanceOf(AnonymousAuthenticationToken.class);
}
@Test
public void interceptWhenAuthenticationThenOriginalAuthentication() {
AuthenticationPayloadInterceptorChain chain = new AuthenticationPayloadInterceptorChain();
TestingAuthenticationToken expected = new TestingAuthenticationToken("test", "password");
this.interceptor.intercept(this.exchange, chain)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(expected)).block();
Authentication authentication = chain.getAuthentication();
assertThat(authentication).isEqualTo(expected);
}
}
| 3,754 | 36.55 | 105 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java | /*
* Copyright 2019-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import java.util.Map;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;
import io.rsocket.Payload;
import io.rsocket.metadata.CompositeMetadataCodec;
import io.rsocket.metadata.WellKnownMimeType;
import io.rsocket.util.DefaultPayload;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.test.publisher.PublisherProbe;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadExchangeType;
import org.springframework.security.rsocket.api.PayloadInterceptorChain;
import org.springframework.security.rsocket.core.DefaultPayloadExchange;
import org.springframework.security.rsocket.metadata.BasicAuthenticationEncoder;
import org.springframework.security.rsocket.metadata.UsernamePasswordMetadata;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class AuthenticationPayloadInterceptorTests {
static final MimeType COMPOSITE_METADATA = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
@Mock
ReactiveAuthenticationManager authenticationManager;
@Captor
ArgumentCaptor<Authentication> authenticationArg;
@Test
public void constructorWhenAuthenticationManagerNullThenException() {
assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationPayloadInterceptor(null));
}
@Test
public void interceptWhenBasicCredentialsThenAuthenticates() {
AuthenticationPayloadInterceptor interceptor = new AuthenticationPayloadInterceptor(this.authenticationManager);
PayloadExchange exchange = createExchange();
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password");
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(expectedAuthentication));
AuthenticationPayloadInterceptorChain authenticationPayloadChain = new AuthenticationPayloadInterceptorChain();
interceptor.intercept(exchange, authenticationPayloadChain).block();
Authentication authentication = authenticationPayloadChain.getAuthentication();
verify(this.authenticationManager).authenticate(this.authenticationArg.capture());
assertThat(this.authenticationArg.getValue()).usingRecursiveComparison()
.isEqualTo(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
assertThat(authentication).isEqualTo(expectedAuthentication);
}
@Test
public void interceptWhenAuthenticationSuccessThenChainSubscribedOnce() {
AuthenticationPayloadInterceptor interceptor = new AuthenticationPayloadInterceptor(this.authenticationManager);
PayloadExchange exchange = createExchange();
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password");
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(expectedAuthentication));
PublisherProbe<Void> voidResult = PublisherProbe.empty();
PayloadInterceptorChain chain = mock(PayloadInterceptorChain.class);
given(chain.next(any())).willReturn(voidResult.mono());
StepVerifier.create(interceptor.intercept(exchange, chain))
.then(() -> assertThat(voidResult.subscribeCount()).isEqualTo(1)).verifyComplete();
}
private Payload createRequestPayload() {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
BasicAuthenticationEncoder encoder = new BasicAuthenticationEncoder();
DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
ResolvableType elementType = ResolvableType.forClass(UsernamePasswordMetadata.class);
MimeType mimeType = UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE;
Map<String, Object> hints = null;
DataBuffer dataBuffer = encoder.encodeValue(credentials, factory, elementType, mimeType, hints);
ByteBufAllocator allocator = ByteBufAllocator.DEFAULT;
CompositeByteBuf metadata = allocator.compositeBuffer();
CompositeMetadataCodec.encodeAndAddMetadata(metadata, allocator, mimeType.toString(),
NettyDataBufferFactory.toByteBuf(dataBuffer));
return DefaultPayload.create(allocator.buffer(), metadata);
}
private PayloadExchange createExchange() {
return new DefaultPayloadExchange(PayloadExchangeType.REQUEST_RESPONSE, createRequestPayload(),
COMPOSITE_METADATA, MediaType.APPLICATION_JSON);
}
}
| 6,214 | 46.442748 | 114 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/authorization/PayloadExchangeMatcherReactiveAuthorizationManagerTests.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authorization;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.util.matcher.PayloadExchangeAuthorizationContext;
import org.springframework.security.rsocket.util.matcher.PayloadExchangeMatcher;
import org.springframework.security.rsocket.util.matcher.PayloadExchangeMatcherEntry;
import org.springframework.security.rsocket.util.matcher.PayloadExchangeMatchers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class PayloadExchangeMatcherReactiveAuthorizationManagerTests {
@Mock
private ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> authz;
@Mock
private ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> authz2;
@Mock
private PayloadExchange exchange;
@Test
public void checkWhenGrantedThenGranted() {
AuthorizationDecision expected = new AuthorizationDecision(true);
given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager
.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz))
.build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
@Test
public void checkWhenDeniedThenDenied() {
AuthorizationDecision expected = new AuthorizationDecision(false);
given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager
.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz))
.build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
@Test
public void checkWhenFirstMatchThenSecondUsed() {
AuthorizationDecision expected = new AuthorizationDecision(true);
given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager
.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz))
.add(new PayloadExchangeMatcherEntry<>((e) -> PayloadExchangeMatcher.MatchResult.notMatch(),
this.authz2))
.build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
@Test
public void checkWhenSecondMatchThenSecondUsed() {
AuthorizationDecision expected = new AuthorizationDecision(true);
given(this.authz2.check(any(), any())).willReturn(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager
.builder()
.add(new PayloadExchangeMatcherEntry<>((e) -> PayloadExchangeMatcher.MatchResult.notMatch(),
this.authz))
.add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz2)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
}
| 4,265 | 42.979381 | 113 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authorization;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.test.publisher.PublisherProbe;
import reactor.util.context.Context;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager;
import org.springframework.security.authorization.AuthorityReactiveAuthorizationManager;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadInterceptorChain;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class AuthorizationPayloadInterceptorTests {
@Mock
private ReactiveAuthorizationManager<PayloadExchange> authorizationManager;
@Mock
private PayloadExchange exchange;
@Mock
private PayloadInterceptorChain chain;
private PublisherProbe<Void> managerResult = PublisherProbe.empty();
private PublisherProbe<Void> chainResult = PublisherProbe.empty();
@Test
public void interceptWhenAuthenticationEmptyAndSubscribedThenException() {
given(this.chain.next(any())).willReturn(this.chainResult.mono());
AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(
AuthenticatedReactiveAuthorizationManager.authenticated());
StepVerifier.create(interceptor.intercept(this.exchange, this.chain))
.then(() -> this.chainResult.assertWasNotSubscribed())
.verifyError(AuthenticationCredentialsNotFoundException.class);
}
@Test
public void interceptWhenAuthenticationNotSubscribedAndEmptyThenCompletes() {
given(this.chain.next(any())).willReturn(this.chainResult.mono());
given(this.authorizationManager.verify(any(), any())).willReturn(this.managerResult.mono());
AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(this.authorizationManager);
StepVerifier.create(interceptor.intercept(this.exchange, this.chain))
.then(() -> this.chainResult.assertWasSubscribed()).verifyComplete();
}
@Test
public void interceptWhenNotAuthorizedThenException() {
given(this.chain.next(any())).willReturn(this.chainResult.mono());
AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(
AuthorityReactiveAuthorizationManager.hasRole("USER"));
Context userContext = ReactiveSecurityContextHolder
.withAuthentication(new TestingAuthenticationToken("user", "password"));
Mono<Void> intercept = interceptor.intercept(this.exchange, this.chain).contextWrite(userContext);
StepVerifier.create(intercept).then(() -> this.chainResult.assertWasNotSubscribed())
.verifyError(AccessDeniedException.class);
}
@Test
public void interceptWhenAuthorizedThenContinues() {
given(this.chain.next(any())).willReturn(this.chainResult.mono());
AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(
AuthenticatedReactiveAuthorizationManager.authenticated());
Context userContext = ReactiveSecurityContextHolder
.withAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
Mono<Void> intercept = interceptor.intercept(this.exchange, this.chain).contextWrite(userContext);
StepVerifier.create(intercept).then(() -> this.chainResult.assertWasSubscribed()).verifyComplete();
}
}
| 4,539 | 43.07767 | 111 | java |
null | spring-security-main/rsocket/src/test/java/org/springframework/security/rsocket/metadata/BasicAuthenticationDecoderTests.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.metadata;
import java.util.Map;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.util.MimeType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
*/
public class BasicAuthenticationDecoderTests {
@Test
public void basicAuthenticationWhenEncodedThenDecodes() {
BasicAuthenticationEncoder encoder = new BasicAuthenticationEncoder();
BasicAuthenticationDecoder decoder = new BasicAuthenticationDecoder();
UsernamePasswordMetadata expectedCredentials = new UsernamePasswordMetadata("rob", "password");
DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
ResolvableType elementType = ResolvableType.forClass(UsernamePasswordMetadata.class);
MimeType mimeType = UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE;
Map<String, Object> hints = null;
DataBuffer dataBuffer = encoder.encodeValue(expectedCredentials, factory, elementType, mimeType, hints);
UsernamePasswordMetadata actualCredentials = decoder
.decodeToMono(Mono.just(dataBuffer), elementType, mimeType, hints).block();
assertThat(actualCredentials).usingRecursiveComparison().isEqualTo(expectedCredentials);
}
}
| 2,039 | 38.230769 | 106 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/core/ContextPayloadInterceptorChain.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import java.util.List;
import java.util.ListIterator;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.security.rsocket.api.PayloadInterceptorChain;
/**
* A {@link PayloadInterceptorChain} which exposes the Reactor {@link Context} via a
* member variable. This class is not Thread safe, so a new instance must be created for
* each Thread.
*
* Internally {@code ContextPayloadInterceptorChain} is used to ensure that the Reactor
* {@code Context} is captured so it can be transferred to subscribers outside of this
* {@code Context} in {@code PayloadSocketAcceptor}.
*
* @author Rob Winch
* @since 5.2
* @see PayloadSocketAcceptor
*/
class ContextPayloadInterceptorChain implements PayloadInterceptorChain {
private final PayloadInterceptor currentInterceptor;
private final ContextPayloadInterceptorChain next;
private Context context;
ContextPayloadInterceptorChain(List<PayloadInterceptor> interceptors) {
if (interceptors == null) {
throw new IllegalArgumentException("interceptors cannot be null");
}
if (interceptors.isEmpty()) {
throw new IllegalArgumentException("interceptors cannot be empty");
}
ContextPayloadInterceptorChain interceptor = init(interceptors);
this.currentInterceptor = interceptor.currentInterceptor;
this.next = interceptor.next;
}
private static ContextPayloadInterceptorChain init(List<PayloadInterceptor> interceptors) {
ContextPayloadInterceptorChain interceptor = new ContextPayloadInterceptorChain(null, null);
ListIterator<? extends PayloadInterceptor> iterator = interceptors.listIterator(interceptors.size());
while (iterator.hasPrevious()) {
interceptor = new ContextPayloadInterceptorChain(iterator.previous(), interceptor);
}
return interceptor;
}
private ContextPayloadInterceptorChain(PayloadInterceptor currentInterceptor, ContextPayloadInterceptorChain next) {
this.currentInterceptor = currentInterceptor;
this.next = next;
}
@Override
public Mono<Void> next(PayloadExchange exchange) {
return Mono.defer(() -> shouldIntercept() ? this.currentInterceptor.intercept(exchange, this.next)
: Mono.deferContextual(Mono::just).cast(Context.class).doOnNext((c) -> this.context = c).then());
}
Context getContext() {
if (this.next == null) {
return this.context;
}
return this.next.getContext();
}
private boolean shouldIntercept() {
return this.currentInterceptor != null && this.next != null;
}
@Override
public String toString() {
return getClass().getSimpleName() + "[currentInterceptor=" + this.currentInterceptor + "]";
}
}
| 3,423 | 33.585859 | 117 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorInterceptor.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import java.util.List;
import io.rsocket.SocketAcceptor;
import io.rsocket.metadata.WellKnownMimeType;
import io.rsocket.plugins.SocketAcceptorInterceptor;
import org.springframework.lang.Nullable;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
/**
* A {@link SocketAcceptorInterceptor} that applies the {@link PayloadInterceptor}s
*
* @author Rob Winch
* @since 5.2
*/
public class PayloadSocketAcceptorInterceptor implements SocketAcceptorInterceptor {
private final List<PayloadInterceptor> interceptors;
@Nullable
private MimeType defaultDataMimeType;
private MimeType defaultMetadataMimeType = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
public PayloadSocketAcceptorInterceptor(List<PayloadInterceptor> interceptors) {
this.interceptors = interceptors;
}
@Override
public SocketAcceptor apply(SocketAcceptor socketAcceptor) {
PayloadSocketAcceptor acceptor = new PayloadSocketAcceptor(socketAcceptor, this.interceptors);
acceptor.setDefaultDataMimeType(this.defaultDataMimeType);
acceptor.setDefaultMetadataMimeType(this.defaultMetadataMimeType);
return acceptor;
}
public void setDefaultDataMimeType(@Nullable MimeType defaultDataMimeType) {
this.defaultDataMimeType = defaultDataMimeType;
}
public void setDefaultMetadataMimeType(MimeType defaultMetadataMimeType) {
Assert.notNull(defaultMetadataMimeType, "defaultMetadataMimeType cannot be null");
this.defaultMetadataMimeType = defaultMetadataMimeType;
}
}
| 2,336 | 32.869565 | 96 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/core/SecuritySocketAcceptorInterceptor.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import io.rsocket.SocketAcceptor;
import io.rsocket.plugins.SocketAcceptorInterceptor;
import org.springframework.util.Assert;
/**
* A SocketAcceptorInterceptor that applies Security through a delegate
* {@link SocketAcceptorInterceptor}. This allows security to be applied lazily to an
* application.
*
* @author Rob Winch
* @since 5.2
*/
public class SecuritySocketAcceptorInterceptor implements SocketAcceptorInterceptor {
private final SocketAcceptorInterceptor acceptorInterceptor;
public SecuritySocketAcceptorInterceptor(SocketAcceptorInterceptor acceptorInterceptor) {
Assert.notNull(acceptorInterceptor, "acceptorInterceptor cannot be null");
this.acceptorInterceptor = acceptorInterceptor;
}
@Override
public SocketAcceptor apply(SocketAcceptor socketAcceptor) {
return this.acceptorInterceptor.apply(socketAcceptor);
}
}
| 1,527 | 31.510638 | 90 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocket.java | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import java.util.List;
import io.rsocket.Payload;
import io.rsocket.RSocket;
import io.rsocket.util.RSocketProxy;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.security.rsocket.api.PayloadExchangeType;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.util.MimeType;
/**
* Combines the {@link PayloadInterceptor} with an {@link RSocketProxy}
*
* @author Rob Winch
* @since 5.2
*/
class PayloadInterceptorRSocket extends RSocketProxy {
private final List<PayloadInterceptor> interceptors;
private final MimeType metadataMimeType;
private final MimeType dataMimeType;
private final Context context;
PayloadInterceptorRSocket(RSocket delegate, List<PayloadInterceptor> interceptors, MimeType metadataMimeType,
MimeType dataMimeType) {
this(delegate, interceptors, metadataMimeType, dataMimeType, Context.empty());
}
PayloadInterceptorRSocket(RSocket delegate, List<PayloadInterceptor> interceptors, MimeType metadataMimeType,
MimeType dataMimeType, Context context) {
super(delegate);
this.metadataMimeType = metadataMimeType;
this.dataMimeType = dataMimeType;
if (delegate == null) {
throw new IllegalArgumentException("delegate cannot be null");
}
if (interceptors == null) {
throw new IllegalArgumentException("interceptors cannot be null");
}
if (interceptors.isEmpty()) {
throw new IllegalArgumentException("interceptors cannot be empty");
}
this.interceptors = interceptors;
this.context = context;
}
@Override
public Mono<Void> fireAndForget(Payload payload) {
return intercept(PayloadExchangeType.FIRE_AND_FORGET, payload)
.flatMap((context) -> this.source.fireAndForget(payload).contextWrite(context));
}
@Override
public Mono<Payload> requestResponse(Payload payload) {
return intercept(PayloadExchangeType.REQUEST_RESPONSE, payload)
.flatMap((context) -> this.source.requestResponse(payload).contextWrite(context));
}
@Override
public Flux<Payload> requestStream(Payload payload) {
return intercept(PayloadExchangeType.REQUEST_STREAM, payload)
.flatMapMany((context) -> this.source.requestStream(payload).contextWrite(context));
}
@Override
public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
return Flux.from(payloads).switchOnFirst((signal, innerFlux) -> {
Payload firstPayload = signal.get();
return intercept(PayloadExchangeType.REQUEST_CHANNEL, firstPayload).flatMapMany(
(context) -> innerFlux.index().concatMap((tuple) -> justOrIntercept(tuple.getT1(), tuple.getT2()))
.transform(this.source::requestChannel).contextWrite(context));
});
}
private Mono<Payload> justOrIntercept(Long index, Payload payload) {
return (index == 0) ? Mono.just(payload) : intercept(PayloadExchangeType.PAYLOAD, payload).thenReturn(payload);
}
@Override
public Mono<Void> metadataPush(Payload payload) {
return intercept(PayloadExchangeType.METADATA_PUSH, payload)
.flatMap((c) -> this.source.metadataPush(payload).contextWrite(c));
}
private Mono<Context> intercept(PayloadExchangeType type, Payload payload) {
return Mono.defer(() -> {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors);
DefaultPayloadExchange exchange = new DefaultPayloadExchange(type, payload, this.metadataMimeType,
this.dataMimeType);
return chain.next(exchange).then(Mono.fromCallable(chain::getContext)).defaultIfEmpty(Context.empty())
.contextWrite(this.context);
});
}
@Override
public String toString() {
return getClass().getSimpleName() + "[source=" + this.source + ",interceptors=" + this.interceptors + "]";
}
}
| 4,458 | 34.388889 | 113 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/core/DefaultPayloadExchange.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import io.rsocket.Payload;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadExchangeType;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
/**
* Default implementation of {@link PayloadExchange}
*
* @author Rob Winch
* @since 5.2
*/
public class DefaultPayloadExchange implements PayloadExchange {
private final PayloadExchangeType type;
private final Payload payload;
private final MimeType metadataMimeType;
private final MimeType dataMimeType;
public DefaultPayloadExchange(PayloadExchangeType type, Payload payload, MimeType metadataMimeType,
MimeType dataMimeType) {
Assert.notNull(type, "type cannot be null");
Assert.notNull(payload, "payload cannot be null");
Assert.notNull(metadataMimeType, "metadataMimeType cannot be null");
Assert.notNull(dataMimeType, "dataMimeType cannot be null");
this.type = type;
this.payload = payload;
this.metadataMimeType = metadataMimeType;
this.dataMimeType = dataMimeType;
}
@Override
public PayloadExchangeType getType() {
return this.type;
}
@Override
public Payload getPayload() {
return this.payload;
}
@Override
public MimeType getMetadataMimeType() {
return this.metadataMimeType;
}
@Override
public MimeType getDataMimeType() {
return this.dataMimeType;
}
}
| 2,044 | 26.266667 | 100 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/core/PayloadSocketAcceptor.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.core;
import java.util.List;
import io.rsocket.ConnectionSetupPayload;
import io.rsocket.Payload;
import io.rsocket.RSocket;
import io.rsocket.SocketAcceptor;
import io.rsocket.metadata.WellKnownMimeType;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.lang.Nullable;
import org.springframework.security.rsocket.api.PayloadExchangeType;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;
/**
* @author Rob Winch
* @since 5.2
*/
class PayloadSocketAcceptor implements SocketAcceptor {
private final SocketAcceptor delegate;
private final List<PayloadInterceptor> interceptors;
@Nullable
private MimeType defaultDataMimeType;
private MimeType defaultMetadataMimeType = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
PayloadSocketAcceptor(SocketAcceptor delegate, List<PayloadInterceptor> interceptors) {
Assert.notNull(delegate, "delegate cannot be null");
if (interceptors == null) {
throw new IllegalArgumentException("interceptors cannot be null");
}
if (interceptors.isEmpty()) {
throw new IllegalArgumentException("interceptors cannot be empty");
}
this.delegate = delegate;
this.interceptors = interceptors;
}
@Override
public Mono<RSocket> accept(ConnectionSetupPayload setup, RSocket sendingSocket) {
MimeType dataMimeType = parseMimeType(setup.dataMimeType(), this.defaultDataMimeType);
Assert.notNull(dataMimeType, "No `dataMimeType` in ConnectionSetupPayload and no default value");
MimeType metadataMimeType = parseMimeType(setup.metadataMimeType(), this.defaultMetadataMimeType);
Assert.notNull(metadataMimeType, "No `metadataMimeType` in ConnectionSetupPayload and no default value");
// FIXME do we want to make the sendingSocket available in the PayloadExchange
return intercept(setup, dataMimeType,
metadataMimeType)
.flatMap(
(ctx) -> this.delegate.accept(setup, sendingSocket)
.map((acceptingSocket) -> new PayloadInterceptorRSocket(acceptingSocket,
this.interceptors, metadataMimeType, dataMimeType, ctx))
.contextWrite(ctx));
}
private Mono<Context> intercept(Payload payload, MimeType dataMimeType, MimeType metadataMimeType) {
return Mono.defer(() -> {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors);
DefaultPayloadExchange exchange = new DefaultPayloadExchange(PayloadExchangeType.SETUP, payload,
metadataMimeType, dataMimeType);
return chain.next(exchange).then(Mono.fromCallable(chain::getContext)).defaultIfEmpty(Context.empty());
});
}
private MimeType parseMimeType(String str, MimeType defaultMimeType) {
return StringUtils.hasText(str) ? MimeTypeUtils.parseMimeType(str) : defaultMimeType;
}
void setDefaultDataMimeType(@Nullable MimeType defaultDataMimeType) {
this.defaultDataMimeType = defaultDataMimeType;
}
void setDefaultMetadataMimeType(MimeType defaultMetadataMimeType) {
Assert.notNull(defaultMetadataMimeType, "defaultMetadataMimeType cannot be null");
this.defaultMetadataMimeType = defaultMetadataMimeType;
}
}
| 4,000 | 37.471154 | 107 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/api/PayloadInterceptor.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.api;
import reactor.core.publisher.Mono;
/**
* Contract for interception-style, chained processing of Payloads that may be used to
* implement cross-cutting, application-agnostic requirements such as security, timeouts,
* and others.
*
* @author Rob Winch
* @since 5.2
*/
public interface PayloadInterceptor {
/**
* Process the Web request and (optionally) delegate to the next
* {@code PayloadInterceptor} through the given {@link PayloadInterceptorChain}.
* @param exchange the current payload exchange
* @param chain provides a way to delegate to the next interceptor
* @return {@code Mono<Void>} to indicate when payload processing is complete
*/
Mono<Void> intercept(PayloadExchange exchange, PayloadInterceptorChain chain);
}
| 1,420 | 33.658537 | 89 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/api/PayloadExchange.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.api;
import io.rsocket.Payload;
import org.springframework.util.MimeType;
/**
* Contract for a Payload interaction.
*
* @author Rob Winch
* @since 5.2
*/
public interface PayloadExchange {
PayloadExchangeType getType();
Payload getPayload();
MimeType getDataMimeType();
MimeType getMetadataMimeType();
}
| 984 | 23.625 | 75 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/api/PayloadExchangeType.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.api;
/**
* The {@link PayloadExchange} type
*
* @author Rob Winch
* @since 5.2
*/
public enum PayloadExchangeType {
/**
* The <a href="https://rsocket.io/docs/Protocol#setup-frame-0x01">Setup</a>. Can be
* used to determine if a Payload is part of the connection
*/
SETUP(false),
/**
* A <a href="https://rsocket.io/docs/Protocol#frame-fnf">Fire and Forget</a>
* exchange.
*/
FIRE_AND_FORGET(true),
/**
* A <a href="https://rsocket.io/docs/Protocol#frame-request-response">Request
* Response</a> exchange.
*/
REQUEST_RESPONSE(true),
/**
* A <a href="https://rsocket.io/docs/Protocol#request-stream-frame">Request
* Stream</a> exchange. This is only represents the request portion. The
* {@link #PAYLOAD} type represents the data that submitted.
*/
REQUEST_STREAM(true),
/**
* A <a href="https://rsocket.io/docs/Protocol#request-channel-frame">Request
* Channel</a> exchange.
*/
REQUEST_CHANNEL(true),
/**
* A <a href="https://rsocket.io/docs/Protocol#payload-frame">Payload</a> exchange.
*/
PAYLOAD(false),
/**
* A <a href="https://rsocket.io/docs/Protocol#frame-metadata-push">Metadata Push</a>
* exchange.
*/
METADATA_PUSH(true);
private final boolean isRequest;
PayloadExchangeType(boolean isRequest) {
this.isRequest = isRequest;
}
/**
* Determines if this exchange is a type of request (i.e. the initial frame).
* @return true if it is a request, else false
*/
public boolean isRequest() {
return this.isRequest;
}
}
| 2,174 | 24.892857 | 86 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/api/PayloadInterceptorChain.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.api;
import reactor.core.publisher.Mono;
/**
* Contract to allow a {@link PayloadInterceptor} to delegate to the next in the chain. *
*
* @author Rob Winch
* @since 5.2
*/
public interface PayloadInterceptorChain {
/**
* Process the payload exchange.
* @param exchange the current server exchange
* @return {@code Mono<Void>} to indicate when request processing is complete
*/
Mono<Void> next(PayloadExchange exchange);
}
| 1,104 | 28.864865 | 89 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeMatchers.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.util.matcher;
import org.springframework.security.rsocket.api.PayloadExchangeType;
/**
* @author Rob Winch
*/
public final class PayloadExchangeMatchers {
private PayloadExchangeMatchers() {
}
public static PayloadExchangeMatcher setup() {
return (exchange) -> PayloadExchangeType.SETUP.equals(exchange.getType())
? PayloadExchangeMatcher.MatchResult.match() : PayloadExchangeMatcher.MatchResult.notMatch();
}
public static PayloadExchangeMatcher anyRequest() {
return (exchange) -> exchange.getType().isRequest() ? PayloadExchangeMatcher.MatchResult.match()
: PayloadExchangeMatcher.MatchResult.notMatch();
}
public static PayloadExchangeMatcher anyExchange() {
return (exchange) -> PayloadExchangeMatcher.MatchResult.match();
}
}
| 1,426 | 31.431818 | 98 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeAuthorizationContext.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.util.matcher;
import java.util.Collections;
import java.util.Map;
import org.springframework.security.rsocket.api.PayloadExchange;
/**
* @author Rob Winch
* @since 5.2
*/
public class PayloadExchangeAuthorizationContext {
private final PayloadExchange exchange;
private final Map<String, Object> variables;
public PayloadExchangeAuthorizationContext(PayloadExchange exchange) {
this(exchange, Collections.emptyMap());
}
public PayloadExchangeAuthorizationContext(PayloadExchange exchange, Map<String, Object> variables) {
this.exchange = exchange;
this.variables = variables;
}
public PayloadExchange getExchange() {
return this.exchange;
}
public Map<String, Object> getVariables() {
return Collections.unmodifiableMap(this.variables);
}
}
| 1,437 | 26.653846 | 102 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/RoutePayloadExchangeMatcher.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.util.matcher;
import java.util.Map;
import java.util.Optional;
import reactor.core.publisher.Mono;
import org.springframework.messaging.rsocket.MetadataExtractor;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.util.Assert;
import org.springframework.util.RouteMatcher;
// FIXME: Pay attention to the package this goes into. It requires spring-messaging for the MetadataExtractor.
/**
* @author Rob Winch
* @since 5.2
*/
public class RoutePayloadExchangeMatcher implements PayloadExchangeMatcher {
private final String pattern;
private final MetadataExtractor metadataExtractor;
private final RouteMatcher routeMatcher;
public RoutePayloadExchangeMatcher(MetadataExtractor metadataExtractor, RouteMatcher routeMatcher, String pattern) {
Assert.notNull(pattern, "pattern cannot be null");
this.metadataExtractor = metadataExtractor;
this.routeMatcher = routeMatcher;
this.pattern = pattern;
}
@Override
public Mono<MatchResult> matches(PayloadExchange exchange) {
Map<String, Object> metadata = this.metadataExtractor.extract(exchange.getPayload(),
exchange.getMetadataMimeType());
return Optional.ofNullable((String) metadata.get(MetadataExtractor.ROUTE_KEY))
.map(this.routeMatcher::parseRoute)
.map((route) -> this.routeMatcher.matchAndExtract(this.pattern, route)).map(MatchResult::match)
.orElse(MatchResult.notMatch());
}
}
| 2,086 | 33.213115 | 117 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeMatcher.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.util.matcher;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import reactor.core.publisher.Mono;
import org.springframework.security.rsocket.api.PayloadExchange;
/**
* An interface for determining if a {@link PayloadExchangeMatcher} matches.
*
* @author Rob Winch
* @since 5.2
*/
public interface PayloadExchangeMatcher {
/**
* Determines if a request matches or not
* @param exchange
* @return
*/
Mono<MatchResult> matches(PayloadExchange exchange);
/**
* The result of matching
*/
class MatchResult {
private final boolean match;
private final Map<String, Object> variables;
private MatchResult(boolean match, Map<String, Object> variables) {
this.match = match;
this.variables = variables;
}
public boolean isMatch() {
return this.match;
}
/**
* Gets potential variables and their values
* @return
*/
public Map<String, Object> getVariables() {
return this.variables;
}
/**
* Creates an instance of {@link MatchResult} that is a match with no variables
* @return
*/
public static Mono<MatchResult> match() {
return match(Collections.emptyMap());
}
/**
*
* Creates an instance of {@link MatchResult} that is a match with the specified
* variables
* @param variables
* @return
*/
public static Mono<MatchResult> match(Map<String, ? extends Object> variables) {
MatchResult result = new MatchResult(true,
(variables != null) ? new HashMap<String, Object>(variables) : null);
return Mono.just(result);
}
/**
* Creates an instance of {@link MatchResult} that is not a match.
* @return
*/
public static Mono<MatchResult> notMatch() {
return Mono.just(new MatchResult(false, Collections.emptyMap()));
}
}
}
| 2,445 | 23.46 | 82 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeMatcherEntry.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.util.matcher;
/**
* @author Rob Winch
*/
public class PayloadExchangeMatcherEntry<T> {
private final PayloadExchangeMatcher matcher;
private final T entry;
public PayloadExchangeMatcherEntry(PayloadExchangeMatcher matcher, T entry) {
this.matcher = matcher;
this.entry = entry;
}
public PayloadExchangeMatcher getMatcher() {
return this.matcher;
}
public T getEntry() {
return this.entry;
}
}
| 1,081 | 24.761905 | 78 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/authentication/AnonymousPayloadInterceptor.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import java.util.List;
import reactor.core.publisher.Mono;
import org.springframework.core.Ordered;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.security.rsocket.api.PayloadInterceptorChain;
import org.springframework.util.Assert;
/**
* If {@link ReactiveSecurityContextHolder} is empty populates an
* {@code AnonymousAuthenticationToken}
*
* @author Rob Winch
* @since 5.2
*/
public class AnonymousPayloadInterceptor implements PayloadInterceptor, Ordered {
private final String key;
private final Object principal;
private final List<GrantedAuthority> authorities;
private int order;
/**
* Creates a filter with a principal named "anonymousUser" and the single authority
* "ROLE_ANONYMOUS".
* @param key the key to identify tokens created by this filter
*/
public AnonymousPayloadInterceptor(String key) {
this(key, "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
}
/**
* @param key key the key to identify tokens created by this filter
* @param principal the principal which will be used to represent anonymous users
* @param authorities the authority list for anonymous users
*/
public AnonymousPayloadInterceptor(String key, Object principal, List<GrantedAuthority> authorities) {
Assert.hasLength(key, "key cannot be null or empty");
Assert.notNull(principal, "Anonymous authentication principal must be set");
Assert.notNull(authorities, "Anonymous authorities must be set");
this.key = key;
this.principal = principal;
this.authorities = authorities;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public Mono<Void> intercept(PayloadExchange exchange, PayloadInterceptorChain chain) {
return ReactiveSecurityContextHolder.getContext().switchIfEmpty(Mono.defer(() -> {
AnonymousAuthenticationToken authentication = new AnonymousAuthenticationToken(this.key, this.principal,
this.authorities);
return chain.next(exchange).contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.then(Mono.empty());
})).flatMap((securityContext) -> chain.next(exchange));
}
}
| 3,261 | 34.075269 | 109 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/authentication/BasicAuthenticationPayloadExchangeConverter.java | /*
* Copyright 2019-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import io.rsocket.metadata.WellKnownMimeType;
import reactor.core.publisher.Mono;
import org.springframework.messaging.rsocket.DefaultMetadataExtractor;
import org.springframework.messaging.rsocket.MetadataExtractor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.metadata.BasicAuthenticationDecoder;
import org.springframework.security.rsocket.metadata.UsernamePasswordMetadata;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
/**
* Converts from the {@link PayloadExchange} to a
* {@link UsernamePasswordAuthenticationToken} by extracting
* {@link UsernamePasswordMetadata#BASIC_AUTHENTICATION_MIME_TYPE} from the metadata.
*
* @author Rob Winch
* @since 5.2
*/
public class BasicAuthenticationPayloadExchangeConverter implements PayloadExchangeAuthenticationConverter {
private MimeType metadataMimetype = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
private MetadataExtractor metadataExtractor = createDefaultExtractor();
@Override
public Mono<Authentication> convert(PayloadExchange exchange) {
return Mono.fromCallable(() -> this.metadataExtractor.extract(exchange.getPayload(), this.metadataMimetype))
.flatMap((metadata) -> Mono
.justOrEmpty(metadata.get(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE.toString())))
.cast(UsernamePasswordMetadata.class).map((credentials) -> UsernamePasswordAuthenticationToken
.unauthenticated(credentials.getUsername(), credentials.getPassword()));
}
private static MetadataExtractor createDefaultExtractor() {
DefaultMetadataExtractor result = new DefaultMetadataExtractor(new BasicAuthenticationDecoder());
result.metadataToExtract(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE,
UsernamePasswordMetadata.class, (String) null);
return result;
}
}
| 2,750 | 41.984375 | 110 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/authentication/PayloadExchangeAuthenticationConverter.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.rsocket.api.PayloadExchange;
/**
* Converts from a {@link PayloadExchange} to an {@link Authentication}
*
* @author Rob Winch
* @since 5.2
*/
public interface PayloadExchangeAuthenticationConverter {
Mono<Authentication> convert(PayloadExchange exchange);
}
| 1,077 | 29.8 | 75 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptor.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import reactor.core.publisher.Mono;
import org.springframework.core.Ordered;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.security.rsocket.api.PayloadInterceptorChain;
import org.springframework.util.Assert;
/**
* Uses the provided {@code ReactiveAuthenticationManager} to authenticate a Payload. If
* authentication is successful, then the result is added to
* {@link ReactiveSecurityContextHolder}.
*
* @author Rob Winch
* @since 5.2
*/
public class AuthenticationPayloadInterceptor implements PayloadInterceptor, Ordered {
private final ReactiveAuthenticationManager authenticationManager;
private int order;
private PayloadExchangeAuthenticationConverter authenticationConverter = new BasicAuthenticationPayloadExchangeConverter();
/**
* Creates a new instance
* @param authenticationManager the manager to use. Cannot be null
*/
public AuthenticationPayloadInterceptor(ReactiveAuthenticationManager authenticationManager) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
this.authenticationManager = authenticationManager;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* Sets the convert to be used
* @param authenticationConverter
*/
public void setAuthenticationConverter(PayloadExchangeAuthenticationConverter authenticationConverter) {
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
this.authenticationConverter = authenticationConverter;
}
@Override
public Mono<Void> intercept(PayloadExchange exchange, PayloadInterceptorChain chain) {
return this.authenticationConverter.convert(exchange).switchIfEmpty(chain.next(exchange).then(Mono.empty()))
.flatMap((a) -> this.authenticationManager.authenticate(a))
.flatMap((a) -> onAuthenticationSuccess(chain.next(exchange), a));
}
private Mono<Void> onAuthenticationSuccess(Mono<Void> payload, Authentication authentication) {
return payload.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
}
}
| 3,107 | 35.564706 | 124 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/authentication/BearerPayloadExchangeConverter.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import java.nio.charset.StandardCharsets;
import io.netty.buffer.ByteBuf;
import io.rsocket.metadata.CompositeMetadata;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.metadata.BearerTokenMetadata;
/**
* Converts from the {@link PayloadExchange} to a {@link BearerTokenAuthenticationToken}
* by extracting {@link BearerTokenMetadata#BEARER_AUTHENTICATION_MIME_TYPE} from the
* metadata.
*
* @author Rob Winch
* @since 5.2
*/
public class BearerPayloadExchangeConverter implements PayloadExchangeAuthenticationConverter {
private static final String BEARER_MIME_TYPE_VALUE = BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE.toString();
@Override
public Mono<Authentication> convert(PayloadExchange exchange) {
ByteBuf metadata = exchange.getPayload().metadata();
CompositeMetadata compositeMetadata = new CompositeMetadata(metadata, false);
for (CompositeMetadata.Entry entry : compositeMetadata) {
if (BEARER_MIME_TYPE_VALUE.equals(entry.getMimeType())) {
ByteBuf content = entry.getContent();
String token = content.toString(StandardCharsets.UTF_8);
return Mono.just(new BearerTokenAuthenticationToken(token));
}
}
return Mono.empty();
}
}
| 2,129 | 36.368421 | 117 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadExchangeConverter.java | /*
* Copyright 2019-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authentication;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.rsocket.metadata.AuthMetadataCodec;
import io.rsocket.metadata.WellKnownAuthType;
import io.rsocket.metadata.WellKnownMimeType;
import reactor.core.publisher.Mono;
import org.springframework.core.codec.ByteArrayDecoder;
import org.springframework.messaging.rsocket.DefaultMetadataExtractor;
import org.springframework.messaging.rsocket.MetadataExtractor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
/**
* Converts from the {@link PayloadExchange} for <a href=
* "https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Authentication.md">Authentication
* Extension</a>. For <a href=
* "https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Simple.md">Simple</a>
* a {@link UsernamePasswordAuthenticationToken} is returned. For <a href=
* "https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Bearer.md">Bearer</a>
* a {@link BearerTokenAuthenticationToken} is returned.
*
* @author Rob Winch
* @since 5.3
*/
public class AuthenticationPayloadExchangeConverter implements PayloadExchangeAuthenticationConverter {
private static final MimeType COMPOSITE_METADATA_MIME_TYPE = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
private static final MimeType AUTHENTICATION_MIME_TYPE = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
private final MetadataExtractor metadataExtractor = createDefaultExtractor();
@Override
public Mono<Authentication> convert(PayloadExchange exchange) {
return Mono
.fromCallable(() -> this.metadataExtractor.extract(exchange.getPayload(),
AuthenticationPayloadExchangeConverter.COMPOSITE_METADATA_MIME_TYPE))
.flatMap((metadata) -> Mono.justOrEmpty(authentication(metadata)));
}
private Authentication authentication(Map<String, Object> metadata) {
byte[] authenticationMetadata = (byte[]) metadata.get("authentication");
if (authenticationMetadata == null) {
return null;
}
ByteBuf rawAuthentication = ByteBufAllocator.DEFAULT.buffer();
try {
rawAuthentication.writeBytes(authenticationMetadata);
if (!AuthMetadataCodec.isWellKnownAuthType(rawAuthentication)) {
return null;
}
WellKnownAuthType wellKnownAuthType = AuthMetadataCodec.readWellKnownAuthType(rawAuthentication);
if (WellKnownAuthType.SIMPLE.equals(wellKnownAuthType)) {
return simple(rawAuthentication);
}
if (WellKnownAuthType.BEARER.equals(wellKnownAuthType)) {
return bearer(rawAuthentication);
}
throw new IllegalArgumentException("Unknown Mime Type " + wellKnownAuthType);
}
finally {
rawAuthentication.release();
}
}
private Authentication simple(ByteBuf rawAuthentication) {
ByteBuf rawUsername = AuthMetadataCodec.readUsername(rawAuthentication);
String username = rawUsername.toString(StandardCharsets.UTF_8);
ByteBuf rawPassword = AuthMetadataCodec.readPassword(rawAuthentication);
String password = rawPassword.toString(StandardCharsets.UTF_8);
return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
}
private Authentication bearer(ByteBuf rawAuthentication) {
char[] rawToken = AuthMetadataCodec.readBearerTokenAsCharArray(rawAuthentication);
String token = new String(rawToken);
return new BearerTokenAuthenticationToken(token);
}
private static MetadataExtractor createDefaultExtractor() {
DefaultMetadataExtractor result = new DefaultMetadataExtractor(new ByteArrayDecoder());
result.metadataToExtract(AUTHENTICATION_MIME_TYPE, byte[].class, "authentication");
return result;
}
}
| 4,876 | 41.408696 | 138 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/authorization/PayloadExchangeMatcherReactiveAuthorizationManager.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authorization;
import java.util.ArrayList;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.util.matcher.PayloadExchangeAuthorizationContext;
import org.springframework.security.rsocket.util.matcher.PayloadExchangeMatcher;
import org.springframework.security.rsocket.util.matcher.PayloadExchangeMatcher.MatchResult;
import org.springframework.security.rsocket.util.matcher.PayloadExchangeMatcherEntry;
import org.springframework.util.Assert;
/**
* Maps a @{code List} of {@link PayloadExchangeMatcher} instances to
*
* @{code ReactiveAuthorizationManager} instances.
* @author Rob Winch
* @since 5.2
*/
public final class PayloadExchangeMatcherReactiveAuthorizationManager
implements ReactiveAuthorizationManager<PayloadExchange> {
private final List<PayloadExchangeMatcherEntry<ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext>>> mappings;
private PayloadExchangeMatcherReactiveAuthorizationManager(
List<PayloadExchangeMatcherEntry<ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext>>> mappings) {
Assert.notEmpty(mappings, "mappings cannot be null");
this.mappings = mappings;
}
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, PayloadExchange exchange) {
return Flux.fromIterable(this.mappings)
.concatMap((mapping) -> mapping.getMatcher().matches(exchange)
.filter(PayloadExchangeMatcher.MatchResult::isMatch).map(MatchResult::getVariables)
.flatMap((variables) -> mapping.getEntry().check(authentication,
new PayloadExchangeAuthorizationContext(exchange, variables))))
.next().switchIfEmpty(Mono.fromCallable(() -> new AuthorizationDecision(false)));
}
public static PayloadExchangeMatcherReactiveAuthorizationManager.Builder builder() {
return new PayloadExchangeMatcherReactiveAuthorizationManager.Builder();
}
public static final class Builder {
private final List<PayloadExchangeMatcherEntry<ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext>>> mappings = new ArrayList<>();
private Builder() {
}
public PayloadExchangeMatcherReactiveAuthorizationManager.Builder add(
PayloadExchangeMatcherEntry<ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext>> entry) {
this.mappings.add(entry);
return this;
}
public PayloadExchangeMatcherReactiveAuthorizationManager build() {
return new PayloadExchangeMatcherReactiveAuthorizationManager(this.mappings);
}
}
}
| 3,486 | 39.08046 | 146 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptor.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.authorization;
import reactor.core.publisher.Mono;
import org.springframework.core.Ordered;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.rsocket.api.PayloadExchange;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.security.rsocket.api.PayloadInterceptorChain;
import org.springframework.util.Assert;
/**
* Provides authorization of the {@link PayloadExchange}.
*
* @author Rob Winch
* @since 5.2
*/
public class AuthorizationPayloadInterceptor implements PayloadInterceptor, Ordered {
private final ReactiveAuthorizationManager<PayloadExchange> authorizationManager;
private int order;
public AuthorizationPayloadInterceptor(ReactiveAuthorizationManager<PayloadExchange> authorizationManager) {
Assert.notNull(authorizationManager, "authorizationManager cannot be null");
this.authorizationManager = authorizationManager;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public Mono<Void> intercept(PayloadExchange exchange, PayloadInterceptorChain chain) {
return ReactiveSecurityContextHolder.getContext().filter((c) -> c.getAuthentication() != null)
.map(SecurityContext::getAuthentication)
.switchIfEmpty(Mono.error(() -> new AuthenticationCredentialsNotFoundException(
"An Authentication (possibly AnonymousAuthenticationToken) is required.")))
.as((authentication) -> this.authorizationManager.verify(authentication, exchange))
.then(chain.next(exchange));
}
}
| 2,522 | 36.102941 | 109 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/metadata/BasicAuthenticationDecoder.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.metadata;
import java.util.Map;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.AbstractDecoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.util.MimeType;
/**
* Decodes {@link UsernamePasswordMetadata#BASIC_AUTHENTICATION_MIME_TYPE}
*
* @author Rob Winch
* @since 5.2
* @deprecated Basic Authentication did not evolve into a standard. Use Simple
* Authentication instead.
*/
@Deprecated
public class BasicAuthenticationDecoder extends AbstractDecoder<UsernamePasswordMetadata> {
public BasicAuthenticationDecoder() {
super(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE);
}
@Override
public Flux<UsernamePasswordMetadata> decode(Publisher<DataBuffer> input, ResolvableType elementType,
MimeType mimeType, Map<String, Object> hints) {
return Flux.from(input).map(DataBuffer::asByteBuffer).map((byteBuffer) -> {
byte[] sizeBytes = new byte[4];
byteBuffer.get(sizeBytes);
int usernameSize = 4;
byte[] usernameBytes = new byte[usernameSize];
byteBuffer.get(usernameBytes);
byte[] passwordBytes = new byte[byteBuffer.remaining()];
byteBuffer.get(passwordBytes);
String username = new String(usernameBytes);
String password = new String(passwordBytes);
return new UsernamePasswordMetadata(username, password);
});
}
@Override
public Mono<UsernamePasswordMetadata> decodeToMono(Publisher<DataBuffer> input, ResolvableType elementType,
MimeType mimeType, Map<String, Object> hints) {
return Mono.from(input).map(DataBuffer::asByteBuffer).map((byteBuffer) -> {
int usernameSize = byteBuffer.getInt();
byte[] usernameBytes = new byte[usernameSize];
byteBuffer.get(usernameBytes);
byte[] passwordBytes = new byte[byteBuffer.remaining()];
byteBuffer.get(passwordBytes);
String username = new String(usernameBytes);
String password = new String(passwordBytes);
return new UsernamePasswordMetadata(username, password);
});
}
}
| 2,764 | 34.448718 | 108 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/metadata/UsernamePasswordMetadata.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.metadata;
import io.rsocket.Payload;
import org.springframework.http.MediaType;
import org.springframework.util.MimeType;
/**
* Represents a username and password that have been encoded into a
* {@link Payload#metadata()}.
*
* @author Rob Winch
* @since 5.2
*/
public final class UsernamePasswordMetadata {
/**
* Represents a username password which is encoded as
* {@code ${username-bytes-length}${username-bytes}${password-bytes}}.
*
* See <a href="https://github.com/rsocket/rsocket/issues/272">rsocket/rsocket#272</a>
* @deprecated Basic did not evolve into the standard. Instead use Simple
* Authentication
* MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString())
*/
@Deprecated
public static final MimeType BASIC_AUTHENTICATION_MIME_TYPE = new MediaType("message",
"x.rsocket.authentication.basic.v0");
private final String username;
private final String password;
public UsernamePasswordMetadata(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return this.username;
}
public String getPassword() {
return this.password;
}
}
| 1,855 | 28 | 93 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/metadata/BearerTokenMetadata.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.metadata;
import org.springframework.http.MediaType;
import org.springframework.util.MimeType;
/**
* Represents a bearer token that has been encoded into a
* {@link io.rsocket.Payload#metadata() Payload#metadata()}.
*
* @author Rob Winch
* @since 5.2
*/
public class BearerTokenMetadata {
/**
* Represents a bearer token which is encoded as a String.
*
* See <a href="https://github.com/rsocket/rsocket/issues/272">rsocket/rsocket#272</a>
* @deprecated Basic did not evolve into the standard. Instead use Simple
* Authentication
* MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString())
*/
@Deprecated
public static final MimeType BEARER_AUTHENTICATION_MIME_TYPE = new MediaType("message",
"x.rsocket.authentication.bearer.v0");
private final String token;
public BearerTokenMetadata(String token) {
this.token = token;
}
public String getToken() {
return this.token;
}
}
| 1,611 | 28.851852 | 93 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/metadata/BasicAuthenticationEncoder.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.metadata;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.AbstractEncoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.util.MimeType;
/**
* Encodes {@link UsernamePasswordMetadata#BASIC_AUTHENTICATION_MIME_TYPE}
*
* @author Rob Winch
* @since 5.2
* @deprecated Basic Authentication did not evolve into a standard. use
* {@link SimpleAuthenticationEncoder}
*/
@Deprecated
public class BasicAuthenticationEncoder extends AbstractEncoder<UsernamePasswordMetadata> {
public BasicAuthenticationEncoder() {
super(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE);
}
@Override
public Flux<DataBuffer> encode(Publisher<? extends UsernamePasswordMetadata> inputStream,
DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
return Flux.from(inputStream)
.map((credentials) -> encodeValue(credentials, bufferFactory, elementType, mimeType, hints));
}
@Override
public DataBuffer encodeValue(UsernamePasswordMetadata credentials, DataBufferFactory bufferFactory,
ResolvableType valueType, MimeType mimeType, Map<String, Object> hints) {
String username = credentials.getUsername();
String password = credentials.getPassword();
byte[] usernameBytes = username.getBytes(StandardCharsets.UTF_8);
byte[] usernameBytesLengthBytes = ByteBuffer.allocate(4).putInt(usernameBytes.length).array();
DataBuffer metadata = bufferFactory.allocateBuffer();
boolean release = true;
try {
metadata.write(usernameBytesLengthBytes);
metadata.write(usernameBytes);
metadata.write(password.getBytes(StandardCharsets.UTF_8));
release = false;
return metadata;
}
finally {
if (release) {
DataBufferUtils.release(metadata);
}
}
}
}
| 2,764 | 34 | 111 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/metadata/SimpleAuthenticationEncoder.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.metadata;
import java.util.Map;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.rsocket.metadata.AuthMetadataCodec;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.AbstractEncoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
/**
* Encodes <a href=
* "https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Simple.md">Simple</a>
* Authentication.
*
* @author Rob Winch
* @since 5.3
*/
public class SimpleAuthenticationEncoder extends AbstractEncoder<UsernamePasswordMetadata> {
private static final MimeType AUTHENTICATION_MIME_TYPE = MimeTypeUtils
.parseMimeType("message/x.rsocket.authentication.v0");
private NettyDataBufferFactory defaultBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
public SimpleAuthenticationEncoder() {
super(AUTHENTICATION_MIME_TYPE);
}
@Override
public Flux<DataBuffer> encode(Publisher<? extends UsernamePasswordMetadata> inputStream,
DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
return Flux.from(inputStream)
.map((credentials) -> encodeValue(credentials, bufferFactory, elementType, mimeType, hints));
}
@Override
public DataBuffer encodeValue(UsernamePasswordMetadata credentials, DataBufferFactory bufferFactory,
ResolvableType valueType, MimeType mimeType, Map<String, Object> hints) {
String username = credentials.getUsername();
String password = credentials.getPassword();
NettyDataBufferFactory factory = nettyFactory(bufferFactory);
ByteBufAllocator allocator = factory.getByteBufAllocator();
ByteBuf simpleAuthentication = AuthMetadataCodec.encodeSimpleMetadata(allocator, username.toCharArray(),
password.toCharArray());
return factory.wrap(simpleAuthentication);
}
private NettyDataBufferFactory nettyFactory(DataBufferFactory bufferFactory) {
if (bufferFactory instanceof NettyDataBufferFactory) {
return (NettyDataBufferFactory) bufferFactory;
}
return this.defaultBufferFactory;
}
}
| 3,067 | 36.876543 | 126 | java |
null | spring-security-main/rsocket/src/main/java/org/springframework/security/rsocket/metadata/BearerTokenAuthenticationEncoder.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.rsocket.metadata;
import java.util.Map;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.rsocket.metadata.AuthMetadataCodec;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.AbstractEncoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
/**
* Encodes <a href=
* "https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Bearer.md">Bearer
* Authentication</a>.
*
* @author Rob Winch
* @since 5.3
*/
public class BearerTokenAuthenticationEncoder extends AbstractEncoder<BearerTokenMetadata> {
private static final MimeType AUTHENTICATION_MIME_TYPE = MimeTypeUtils
.parseMimeType("message/x.rsocket.authentication.v0");
private NettyDataBufferFactory defaultBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
public BearerTokenAuthenticationEncoder() {
super(AUTHENTICATION_MIME_TYPE);
}
@Override
public Flux<DataBuffer> encode(Publisher<? extends BearerTokenMetadata> inputStream,
DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
return Flux.from(inputStream)
.map((credentials) -> encodeValue(credentials, bufferFactory, elementType, mimeType, hints));
}
@Override
public DataBuffer encodeValue(BearerTokenMetadata credentials, DataBufferFactory bufferFactory,
ResolvableType valueType, MimeType mimeType, Map<String, Object> hints) {
String token = credentials.getToken();
NettyDataBufferFactory factory = nettyFactory(bufferFactory);
ByteBufAllocator allocator = factory.getByteBufAllocator();
ByteBuf simpleAuthentication = AuthMetadataCodec.encodeBearerMetadata(allocator, token.toCharArray());
return factory.wrap(simpleAuthentication);
}
private NettyDataBufferFactory nettyFactory(DataBufferFactory bufferFactory) {
if (bufferFactory instanceof NettyDataBufferFactory) {
return (NettyDataBufferFactory) bufferFactory;
}
return this.defaultBufferFactory;
}
}
| 2,978 | 36.708861 | 122 | java |
null | spring-security-main/data/src/test/java/org/springframework/security/data/repository/query/SecurityEvaluationContextExtensionTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.data.repository.query;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.DenyAllPermissionEvaluator;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.hierarchicalroles.NullRoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class SecurityEvaluationContextExtensionTests {
SecurityEvaluationContextExtension securityExtension;
@BeforeEach
public void setup() {
this.securityExtension = new SecurityEvaluationContextExtension();
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void getRootObjectSecurityContextHolderAuthenticationNull() {
assertThatIllegalArgumentException().isThrownBy(() -> getRoot().getAuthentication());
}
@Test
public void getRootObjectSecurityContextHolderAuthentication() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authentication);
assertThat(getRoot().getAuthentication()).isSameAs(authentication);
}
@Test
public void getRootObjectUseSecurityContextHolderStrategy() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
this.securityExtension.setSecurityContextHolderStrategy(strategy);
assertThat(getRoot().getAuthentication()).isSameAs(authentication);
verify(strategy).getContext();
}
@Test
public void getRootObjectExplicitAuthenticationOverridesSecurityContextHolder() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authentication);
assertThat(getRoot().getAuthentication()).isSameAs(explicit);
}
@Test
public void getRootObjectExplicitAuthentication() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
assertThat(getRoot().getAuthentication()).isSameAs(explicit);
}
@Test
public void setTrustResolverWhenNullThenIllegalArgumentException() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
assertThatIllegalArgumentException().isThrownBy(() -> this.securityExtension.setTrustResolver(null))
.withMessage("trustResolver cannot be null");
}
@Test
public void setTrustResolverWhenNotNullThenVerifyRootObject() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
this.securityExtension.setTrustResolver(trustResolver);
assertThat(getRoot()).extracting("trustResolver").isEqualTo(trustResolver);
}
@Test
public void setRoleHierarchyWhenNullThenIllegalArgumentException() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
assertThatIllegalArgumentException().isThrownBy(() -> this.securityExtension.setRoleHierarchy(null))
.withMessage("roleHierarchy cannot be null");
}
@Test
public void setRoleHierarchyWhenNotNullThenVerifyRootObject() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
RoleHierarchy roleHierarchy = new NullRoleHierarchy();
this.securityExtension.setRoleHierarchy(roleHierarchy);
assertThat(getRoot()).extracting("roleHierarchy").isEqualTo(roleHierarchy);
}
@Test
public void setPermissionEvaluatorWhenNullThenIllegalArgumentException() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
assertThatIllegalArgumentException().isThrownBy(() -> this.securityExtension.setPermissionEvaluator(null))
.withMessage("permissionEvaluator cannot be null");
}
@Test
public void setPermissionEvaluatorWhenNotNullThenVerifyRootObject() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
PermissionEvaluator permissionEvaluator = new DenyAllPermissionEvaluator();
this.securityExtension.setPermissionEvaluator(permissionEvaluator);
assertThat(getRoot()).extracting("permissionEvaluator").isEqualTo(permissionEvaluator);
}
@Test
public void setDefaultRolePrefixWhenCustomThenVerifyRootObject() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
String defaultRolePrefix = "CUSTOM_";
this.securityExtension.setDefaultRolePrefix(defaultRolePrefix);
assertThat(getRoot()).extracting("defaultRolePrefix").isEqualTo(defaultRolePrefix);
}
@Test
public void getRootObjectWhenAdditionalFieldsNotSetThenVerifyDefaults() {
TestingAuthenticationToken explicit = new TestingAuthenticationToken("explicit", "password", "ROLE_EXPLICIT");
this.securityExtension = new SecurityEvaluationContextExtension(explicit);
SecurityExpressionRoot root = getRoot();
assertThat(root).extracting("trustResolver").isInstanceOf(AuthenticationTrustResolverImpl.class);
assertThat(root).extracting("roleHierarchy").isInstanceOf(NullRoleHierarchy.class);
assertThat(root).extracting("permissionEvaluator").isInstanceOf(DenyAllPermissionEvaluator.class);
assertThat(root).extracting("defaultRolePrefix").isEqualTo("ROLE_");
}
private SecurityExpressionRoot getRoot() {
return this.securityExtension.getRootObject();
}
}
| 8,074 | 46.781065 | 112 | java |
null | spring-security-main/data/src/main/java/org/springframework/security/data/repository/query/SecurityEvaluationContextExtension.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.data.repository.query;
import org.springframework.data.spel.spi.EvaluationContextExtension;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.DenyAllPermissionEvaluator;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.hierarchicalroles.NullRoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
/**
* <p>
* By defining this object as a Bean, Spring Security is exposed as SpEL expressions for
* creating Spring Data queries.
*
* <p>
* With Java based configuration, we can define the bean using the following:
*
* <p>
* For example, if you return a UserDetails that extends the following User object:
*
* <pre>
* @Entity
* public class User {
* @GeneratedValue(strategy = GenerationType.AUTO)
* @Id
* private Long id;
*
* ...
* }
* </pre>
*
* <p>
* And you have a Message object that looks like the following:
*
* <pre>
* @Entity
* public class Message {
* @Id
* @GeneratedValue(strategy = GenerationType.AUTO)
* private Long id;
*
* @OneToOne
* private User to;
*
* ...
* }
* </pre>
*
* You can use the following {@code Query} annotation to search for only messages that are
* to the current user:
*
* <pre>
* @Repository
* public interface SecurityMessageRepository extends MessageRepository {
*
* @Query("select m from Message m where m.to.id = ?#{ principal?.id }")
* List<Message> findAll();
* }
* </pre>
*
* This works because the principal in this instance is a User which has an id field on
* it.
*
* @author Rob Winch
* @author Evgeniy Cheban
* @since 4.0
*/
public class SecurityEvaluationContextExtension implements EvaluationContextExtension {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private Authentication authentication;
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private RoleHierarchy roleHierarchy = new NullRoleHierarchy();
private PermissionEvaluator permissionEvaluator = new DenyAllPermissionEvaluator();
private String defaultRolePrefix = "ROLE_";
/**
* Creates a new instance that uses the current {@link Authentication} found on the
* {@link org.springframework.security.core.context.SecurityContextHolder}.
*/
public SecurityEvaluationContextExtension() {
}
/**
* Creates a new instance that always uses the same {@link Authentication} object.
* @param authentication the {@link Authentication} to use
*/
public SecurityEvaluationContextExtension(Authentication authentication) {
this.authentication = authentication;
}
@Override
public String getExtensionId() {
return "security";
}
@Override
public SecurityExpressionRoot getRootObject() {
Authentication authentication = getAuthentication();
SecurityExpressionRoot root = new SecurityExpressionRoot(authentication) {
};
root.setTrustResolver(this.trustResolver);
root.setRoleHierarchy(this.roleHierarchy);
root.setPermissionEvaluator(this.permissionEvaluator);
root.setDefaultRolePrefix(this.defaultRolePrefix);
return root;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
private Authentication getAuthentication() {
if (this.authentication != null) {
return this.authentication;
}
SecurityContext context = this.securityContextHolderStrategy.getContext();
return context.getAuthentication();
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. Default is
* {@link AuthenticationTrustResolverImpl}. Cannot be null.
* @param trustResolver the {@link AuthenticationTrustResolver} to use
* @since 5.8
*/
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
}
/**
* Sets the {@link RoleHierarchy} to be used. Default is {@link NullRoleHierarchy}.
* Cannot be null.
* @param roleHierarchy the {@link RoleHierarchy} to use
* @since 5.8
*/
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
Assert.notNull(roleHierarchy, "roleHierarchy cannot be null");
this.roleHierarchy = roleHierarchy;
}
/**
* Sets the {@link PermissionEvaluator} to be used. Default is
* {@link DenyAllPermissionEvaluator}. Cannot be null.
* @param permissionEvaluator the {@link PermissionEvaluator} to use
* @since 5.8
*/
public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) {
Assert.notNull(permissionEvaluator, "permissionEvaluator cannot be null");
this.permissionEvaluator = permissionEvaluator;
}
/**
* Sets the default prefix to be added to
* {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasAnyRole(String...)}
* or
* {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasRole(String)}.
* For example, if hasRole("ADMIN") or hasRole("ROLE_ADMIN") is passed in, then the
* role ROLE_ADMIN will be used when the defaultRolePrefix is "ROLE_" (default).
* @param defaultRolePrefix the default prefix to add to roles. The default is
* "ROLE_".
* @since 5.8
*/
public void setDefaultRolePrefix(String defaultRolePrefix) {
this.defaultRolePrefix = defaultRolePrefix;
}
}
| 7,041 | 33.184466 | 108 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptorTests.java | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.web.csrf;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@ExtendWith(MockitoExtension.class)
public class CsrfChannelInterceptorTests {
@Mock
MessageChannel channel;
SimpMessageHeaderAccessor messageHeaders;
CsrfToken token;
CsrfChannelInterceptor interceptor;
@BeforeEach
public void setup() {
this.token = new DefaultCsrfToken("header", "param", "token");
this.interceptor = new CsrfChannelInterceptor();
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
this.messageHeaders.setNativeHeader(this.token.getHeaderName(), this.token.getToken());
this.messageHeaders.setSessionAttributes(new HashMap<>());
this.messageHeaders.getSessionAttributes().put(CsrfToken.class.getName(), this.token);
}
@Test
public void preSendValidToken() {
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendIgnoresConnectAck() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendIgnoresDisconnect() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendIgnoresDisconnectAck() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT_ACK);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendIgnoresHeartbeat() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.HEARTBEAT);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendIgnoresMessage() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendIgnoresOther() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.OTHER);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendIgnoresSubscribe() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.SUBSCRIBE);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendIgnoresUnsubscribe() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.UNSUBSCRIBE);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendNoToken() {
this.messageHeaders.removeNativeHeader(this.token.getHeaderName());
assertThatExceptionOfType(InvalidCsrfTokenException.class)
.isThrownBy(() -> this.interceptor.preSend(message(), this.channel));
}
@Test
public void preSendInvalidToken() {
this.messageHeaders.setNativeHeader(this.token.getHeaderName(), this.token.getToken() + "invalid");
assertThatExceptionOfType(InvalidCsrfTokenException.class)
.isThrownBy(() -> this.interceptor.preSend(message(), this.channel));
}
@Test
public void preSendMissingToken() {
this.messageHeaders.getSessionAttributes().clear();
assertThatExceptionOfType(MissingCsrfTokenException.class)
.isThrownBy(() -> this.interceptor.preSend(message(), this.channel));
}
@Test
public void preSendMissingTokenNullSessionAttributes() {
this.messageHeaders.setSessionAttributes(null);
assertThatExceptionOfType(MissingCsrfTokenException.class)
.isThrownBy(() -> this.interceptor.preSend(message(), this.channel));
}
private Message<String> message() {
Map<String, Object> headersToCopy = this.messageHeaders.toMap();
return MessageBuilder.withPayload("hi").copyHeaders(headersToCopy).build();
}
}
| 5,090 | 33.167785 | 101 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/web/csrf/XorCsrfChannelInterceptorTests.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.web.csrf;
import java.util.HashMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link XorCsrfChannelInterceptor}.
*
* @author Steve Riesenberg
*/
public class XorCsrfChannelInterceptorTests {
private static final String XOR_CSRF_TOKEN_VALUE = "wpe7zB62-NCpcA==";
private static final String INVALID_XOR_CSRF_TOKEN_VALUE = "KneoaygbRZtfHQ==";
private CsrfToken token;
private SimpMessageHeaderAccessor messageHeaders;
private MessageChannel channel;
private XorCsrfChannelInterceptor interceptor;
@BeforeEach
public void setup() {
this.token = new DefaultCsrfToken("header", "param", "token");
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
this.messageHeaders.setSessionAttributes(new HashMap<>());
this.channel = mock(MessageChannel.class);
this.interceptor = new XorCsrfChannelInterceptor();
}
@Test
public void preSendWhenConnectWithValidTokenThenSuccess() {
this.messageHeaders.setNativeHeader(this.token.getHeaderName(), XOR_CSRF_TOKEN_VALUE);
this.messageHeaders.getSessionAttributes().put(CsrfToken.class.getName(), this.token);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendWhenConnectWithInvalidTokenThenThrowsInvalidCsrfTokenException() {
this.messageHeaders.setNativeHeader(this.token.getHeaderName(), INVALID_XOR_CSRF_TOKEN_VALUE);
this.messageHeaders.getSessionAttributes().put(CsrfToken.class.getName(), this.token);
// @formatter:off
assertThatExceptionOfType(InvalidCsrfTokenException.class)
.isThrownBy(() -> this.interceptor.preSend(message(), mock(MessageChannel.class)));
// @formatter:on
}
@Test
public void preSendWhenConnectWithNoTokenThenThrowsInvalidCsrfTokenException() {
this.messageHeaders.getSessionAttributes().put(CsrfToken.class.getName(), this.token);
// @formatter:off
assertThatExceptionOfType(InvalidCsrfTokenException.class)
.isThrownBy(() -> this.interceptor.preSend(message(), mock(MessageChannel.class)));
// @formatter:on
}
@Test
public void preSendWhenConnectWithMissingTokenThenThrowsMissingCsrfTokenException() {
// @formatter:off
assertThatExceptionOfType(MissingCsrfTokenException.class)
.isThrownBy(() -> this.interceptor.preSend(message(), mock(MessageChannel.class)));
// @formatter:on
}
@Test
public void preSendWhenConnectWithNullSessionAttributesThenThrowsMissingCsrfTokenException() {
this.messageHeaders.setSessionAttributes(null);
// @formatter:off
assertThatExceptionOfType(MissingCsrfTokenException.class)
.isThrownBy(() -> this.interceptor.preSend(message(), mock(MessageChannel.class)));
// @formatter:on
}
@Test
public void preSendWhenAckThenIgnores() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendWhenDisconnectThenIgnores() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendWhenHeartbeatThenIgnores() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.HEARTBEAT);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendWhenMessageThenIgnores() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendWhenOtherThenIgnores() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.OTHER);
this.interceptor.preSend(message(), this.channel);
}
@Test
public void preSendWhenUnsubscribeThenIgnores() {
this.messageHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.UNSUBSCRIBE);
this.interceptor.preSend(message(), this.channel);
}
private Message<String> message() {
return MessageBuilder.withPayload("message").copyHeaders(this.messageHeaders.toMap()).build();
}
}
| 5,343 | 34.865772 | 96 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/web/socket/server/CsrfTokenHandshakeInterceptorTests.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.web.socket.server;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.security.web.csrf.DeferredCsrfToken;
import org.springframework.web.socket.WebSocketHandler;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
*/
@ExtendWith(MockitoExtension.class)
public class CsrfTokenHandshakeInterceptorTests {
@Mock
WebSocketHandler wsHandler;
@Mock
ServerHttpResponse response;
Map<String, Object> attributes;
ServerHttpRequest request;
MockHttpServletRequest httpRequest;
CsrfTokenHandshakeInterceptor interceptor;
@BeforeEach
public void setup() {
this.httpRequest = new MockHttpServletRequest();
this.attributes = new HashMap<>();
this.request = new ServletServerHttpRequest(this.httpRequest);
this.interceptor = new CsrfTokenHandshakeInterceptor();
}
@Test
public void beforeHandshakeNoAttribute() throws Exception {
this.interceptor.beforeHandshake(this.request, this.response, this.wsHandler, this.attributes);
assertThat(this.attributes).isEmpty();
}
@Test
public void beforeHandshake() throws Exception {
CsrfToken token = new DefaultCsrfToken("header", "param", "token");
this.httpRequest.setAttribute(DeferredCsrfToken.class.getName(), new TestDeferredCsrfToken(token));
this.interceptor.beforeHandshake(this.request, this.response, this.wsHandler, this.attributes);
assertThat(this.attributes.keySet()).containsOnly(CsrfToken.class.getName());
CsrfToken csrfToken = (CsrfToken) this.attributes.get(CsrfToken.class.getName());
assertThat(csrfToken.getHeaderName()).isEqualTo(token.getHeaderName());
assertThat(csrfToken.getParameterName()).isEqualTo(token.getParameterName());
assertThat(csrfToken.getToken()).isEqualTo(token.getToken());
// Ensure the values of the CsrfToken are copied into a new token so the old token
// is available for garbage collection.
// This is required because the original token could hold a reference to the
// HttpServletRequest/Response of the handshake request.
assertThat(csrfToken).isNotSameAs(token);
}
private static final class TestDeferredCsrfToken implements DeferredCsrfToken {
private final CsrfToken csrfToken;
private TestDeferredCsrfToken(CsrfToken csrfToken) {
this.csrfToken = csrfToken;
}
@Override
public CsrfToken get() {
return this.csrfToken;
}
@Override
public boolean isGenerated() {
return false;
}
}
}
| 3,659 | 31.972973 | 101 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/util/matcher/OrMessageMatcherTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.Message;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.mockito.BDDMockito.given;
@ExtendWith(MockitoExtension.class)
public class OrMessageMatcherTests {
@Mock
private MessageMatcher<Object> delegate;
@Mock
private MessageMatcher<Object> delegate2;
@Mock
private Message<Object> message;
private MessageMatcher<Object> matcher;
@Test
public void constructorNullArray() {
assertThatNullPointerException().isThrownBy(() -> new OrMessageMatcher<>((MessageMatcher<Object>[]) null));
}
@Test
public void constructorArrayContainsNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new OrMessageMatcher<>((MessageMatcher<Object>) null));
}
@Test
@SuppressWarnings("unchecked")
public void constructorEmptyArray() {
assertThatIllegalArgumentException().isThrownBy(() -> new OrMessageMatcher<>(new MessageMatcher[0]));
}
@Test
public void constructorNullList() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OrMessageMatcher<>((List<MessageMatcher<Object>>) null));
}
@Test
public void constructorListContainsNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OrMessageMatcher<>(Arrays.asList((MessageMatcher<Object>) null)));
}
@Test
public void constructorEmptyList() {
assertThatIllegalArgumentException().isThrownBy(() -> new OrMessageMatcher<>(Collections.emptyList()));
}
@Test
public void matchesSingleTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
}
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
@Test
public void matchesSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
}
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
}
| 3,773 | 30.714286 | 111 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.Message;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.mockito.BDDMockito.given;
@ExtendWith(MockitoExtension.class)
public class AndMessageMatcherTests {
@Mock
private MessageMatcher<Object> delegate;
@Mock
private MessageMatcher<Object> delegate2;
@Mock
private Message<Object> message;
private MessageMatcher<Object> matcher;
@Test
public void constructorNullArray() {
assertThatNullPointerException().isThrownBy(() -> new AndMessageMatcher<>((MessageMatcher<Object>[]) null));
}
@Test
public void constructorArrayContainsNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new AndMessageMatcher<>((MessageMatcher<Object>) null));
}
@Test
@SuppressWarnings("unchecked")
public void constructorEmptyArray() {
assertThatIllegalArgumentException().isThrownBy(() -> new AndMessageMatcher<>(new MessageMatcher[0]));
}
@Test
public void constructorNullList() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new AndMessageMatcher<>((List<MessageMatcher<Object>>) null));
}
@Test
public void constructorListContainsNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new AndMessageMatcher<>(Arrays.asList((MessageMatcher<Object>) null)));
}
@Test
public void constructorEmptyList() {
assertThatIllegalArgumentException().isThrownBy(() -> new AndMessageMatcher<>(Collections.emptyList()));
}
@Test
public void matchesSingleTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new AndMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
}
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
given(this.delegate2.matches(this.message)).willReturn(true);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
@Test
public void matchesSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
}
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(true);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
}
| 3,850 | 31.091667 | 112 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcherTests.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class SimpDestinationMessageMatcherTests {
MessageBuilder<String> messageBuilder;
SimpDestinationMessageMatcher matcher;
PathMatcher pathMatcher;
@BeforeEach
public void setup() {
this.messageBuilder = MessageBuilder.withPayload("M");
this.matcher = new SimpDestinationMessageMatcher("/**");
this.pathMatcher = new AntPathMatcher();
}
@Test
public void constructorPatternNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new SimpDestinationMessageMatcher(null));
}
public void constructorOnlyPathNoError() {
new SimpDestinationMessageMatcher("/path");
}
@Test
public void matchesDoesNotMatchNullDestination() {
assertThat(this.matcher.matches(this.messageBuilder.build())).isFalse();
}
@Test
public void matchesAllWithDestination() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/destination/1");
assertThat(this.matcher.matches(this.messageBuilder.build())).isTrue();
}
@Test
public void matchesSpecificWithDestination() {
this.matcher = new SimpDestinationMessageMatcher("/destination/1");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/destination/1");
assertThat(this.matcher.matches(this.messageBuilder.build())).isTrue();
}
@Test
public void matchesFalseWithDestination() {
this.matcher = new SimpDestinationMessageMatcher("/nomatch");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/destination/1");
assertThat(this.matcher.matches(this.messageBuilder.build())).isFalse();
}
@Test
public void matchesFalseMessageTypeNotDisconnectType() {
this.matcher = SimpDestinationMessageMatcher.createMessageMatcher("/match", this.pathMatcher);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.DISCONNECT);
assertThat(this.matcher.matches(this.messageBuilder.build())).isFalse();
}
@Test
public void matchesTrueMessageType() {
this.matcher = SimpDestinationMessageMatcher.createMessageMatcher("/match", this.pathMatcher);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/match");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE);
assertThat(this.matcher.matches(this.messageBuilder.build())).isTrue();
}
@Test
public void matchesTrueSubscribeType() {
this.matcher = SimpDestinationMessageMatcher.createSubscribeMatcher("/match", this.pathMatcher);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/match");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.SUBSCRIBE);
assertThat(this.matcher.matches(this.messageBuilder.build())).isTrue();
}
@Test
public void matchesNullMessageType() {
this.matcher = new SimpDestinationMessageMatcher("/match");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/match");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE);
assertThat(this.matcher.matches(this.messageBuilder.build())).isTrue();
}
@Test
public void extractPathVariablesFromDestination() {
this.matcher = new SimpDestinationMessageMatcher("/topics/{topic}/**");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/topics/someTopic/sub1");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE);
assertThat(this.matcher.extractPathVariables(this.messageBuilder.build()).get("topic")).isEqualTo("someTopic");
}
@Test
public void extractedVariablesAreEmptyInNullDestination() {
this.matcher = new SimpDestinationMessageMatcher("/topics/{topic}/**");
assertThat(this.matcher.extractPathVariables(this.messageBuilder.build())).isEmpty();
}
@Test
public void typeConstructorParameterIsTransmitted() {
this.matcher = SimpDestinationMessageMatcher.createMessageMatcher("/match", this.pathMatcher);
MessageMatcher<Object> expectedTypeMatcher = new SimpMessageTypeMatcher(SimpMessageType.MESSAGE);
assertThat(this.matcher.getMessageTypeMatcher()).isEqualTo(expectedTypeMatcher);
}
}
| 5,355 | 39.270677 | 113 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/util/matcher/SimpMessageTypeMatcherTests.java | /*
* Copyright 2002-2013 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class SimpMessageTypeMatcherTests {
private SimpMessageTypeMatcher matcher;
@BeforeEach
public void setup() {
this.matcher = new SimpMessageTypeMatcher(SimpMessageType.MESSAGE);
}
@Test
public void constructorNullType() {
assertThatIllegalArgumentException().isThrownBy(() -> new SimpMessageTypeMatcher(null));
}
@Test
public void matchesMessageMessageTrue() {
// @formatter:off
Message<String> message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE)
.build();
// @formatter:on
assertThat(this.matcher.matches(message)).isTrue();
}
@Test
public void matchesMessageConnectFalse() {
// @formatter:off
Message<String> message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.CONNECT)
.build();
// @formatter:on
assertThat(this.matcher.matches(message)).isFalse();
}
@Test
public void matchesMessageNullFalse() {
Message<String> message = MessageBuilder.withPayload("Hi").build();
assertThat(this.matcher.matches(message)).isFalse();
}
}
| 2,273 | 31.028169 | 90 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.context;
import java.security.Principal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
public class SecurityContextChannelInterceptorTests {
@Mock
MessageChannel channel;
@Mock
MessageHandler handler;
@Mock
Principal principal;
MessageBuilder<String> messageBuilder;
Authentication authentication;
SecurityContextChannelInterceptor interceptor;
AnonymousAuthenticationToken expectedAnonymous;
@BeforeEach
public void setup() {
this.authentication = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
this.messageBuilder = MessageBuilder.withPayload("payload");
this.expectedAnonymous = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
this.interceptor = new SecurityContextChannelInterceptor();
}
@AfterEach
public void cleanup() {
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
SecurityContextHolder.clearContext();
}
@Test
public void constructorNullHeader() {
assertThatIllegalArgumentException().isThrownBy(() -> new SecurityContextChannelInterceptor(null));
}
@Test
public void preSendCustomHeader() {
String headerName = "header";
this.interceptor = new SecurityContextChannelInterceptor(headerName);
this.messageBuilder.setHeader(headerName, this.authentication);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
}
@Test
public void preSendUserSet() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
}
@Test
public void preSendWhenCustomSecurityContextHolderStrategyThenUserSet() {
SecurityContextHolderStrategy strategy = spy(SecurityContextHolder.getContextHolderStrategy());
strategy.setContext(new SecurityContextImpl(this.authentication));
this.interceptor.setSecurityContextHolderStrategy(strategy);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
verify(strategy).getContext();
assertThat(strategy.getContext().getAuthentication()).isSameAs(this.authentication);
}
@Test
public void setAnonymousAuthenticationNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.setAnonymousAuthentication(null));
}
@Test
public void preSendUsesCustomAnonymous() {
this.expectedAnonymous = new AnonymousAuthenticationToken("customKey", "customAnonymous",
AuthorityUtils.createAuthorityList("ROLE_CUSTOM"));
this.interceptor.setAnonymousAuthentication(this.expectedAnonymous);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertAnonymous();
}
// SEC-2845
@Test
public void preSendUserNotAuthentication() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.principal);
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertAnonymous();
}
// SEC-2845
@Test
public void preSendUserNotSet() {
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertAnonymous();
}
// SEC-2845
@Test
public void preSendUserNotSetCustomAnonymous() {
this.interceptor.preSend(this.messageBuilder.build(), this.channel);
assertAnonymous();
}
@Test
public void afterSendCompletion() {
SecurityContextHolder.getContext().setAuthentication(this.authentication);
this.interceptor.afterSendCompletion(this.messageBuilder.build(), this.channel, true, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterSendCompletionNullAuthentication() {
this.interceptor.afterSendCompletion(this.messageBuilder.build(), this.channel, true, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterSendCompletionWhenCustomSecurityContextHolderStrategyThenNullAuthentication() {
SecurityContextHolderStrategy strategy = spy(SecurityContextHolder.getContextHolderStrategy());
strategy.setContext(new SecurityContextImpl(this.authentication));
this.interceptor.setSecurityContextHolderStrategy(strategy);
this.interceptor.afterSendCompletion(this.messageBuilder.build(), this.channel, true, null);
verify(strategy).clearContext();
assertThat(strategy.getContext().getAuthentication()).isNull();
}
@Test
public void beforeHandleUserSet() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
}
@Test
public void beforeHandleWhenCustomSecurityContextHolderStrategyThenUserSet() {
SecurityContextHolderStrategy strategy = spy(SecurityContextHolder.getContextHolderStrategy());
strategy.setContext(new SecurityContextImpl(this.authentication));
this.interceptor.setSecurityContextHolderStrategy(strategy);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
verify(strategy).getContext();
assertThat(strategy.getContext().getAuthentication()).isSameAs(this.authentication);
}
// SEC-2845
@Test
public void beforeHandleUserNotAuthentication() {
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.principal);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertAnonymous();
}
// SEC-2845
@Test
public void beforeHandleUserNotSet() {
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertAnonymous();
}
@Test
public void afterMessageHandledUserNotSet() {
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterMessageHandled() {
SecurityContextHolder.getContext().setAuthentication(this.authentication);
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void afterMessageHandledWhenCustomSecurityContextHolderStrategyThenUses() {
SecurityContextHolderStrategy strategy = spy(SecurityContextHolder.getContextHolderStrategy());
strategy.setContext(new SecurityContextImpl(this.authentication));
this.interceptor.setSecurityContextHolderStrategy(strategy);
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
verify(strategy).clearContext();
}
// SEC-2829
@Test
public void restoresOriginalContext() {
TestingAuthenticationToken original = new TestingAuthenticationToken("original", "original", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(original);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(original);
}
/**
* If a user sends a websocket when processing another websocket
*
*/
@Test
public void restoresOriginalContextNestedThreeDeep() {
AnonymousAuthenticationToken anonymous = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_USER"));
TestingAuthenticationToken origional = new TestingAuthenticationToken("original", "origional", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(origional);
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, this.authentication);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
// start send websocket
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.USER_HEADER, null);
this.interceptor.beforeHandle(this.messageBuilder.build(), this.channel, this.handler);
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo(anonymous.getName());
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.authentication);
// end send websocket
this.interceptor.afterMessageHandled(this.messageBuilder.build(), this.channel, this.handler, null);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(origional);
}
private void assertAnonymous() {
Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
assertThat(currentAuthentication).isInstanceOf(AnonymousAuthenticationToken.class);
AnonymousAuthenticationToken anonymous = (AnonymousAuthenticationToken) currentAuthentication;
assertThat(anonymous.getName()).isEqualTo(this.expectedAnonymous.getName());
assertThat(anonymous.getAuthorities()).containsOnlyElementsOf(this.expectedAnonymous.getAuthorities());
assertThat(anonymous.getKeyHash()).isEqualTo(this.expectedAnonymous.getKeyHash());
}
}
| 11,679 | 41.941176 | 110 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/context/AuthenticationPrincipalArgumentResolverTests.java | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.context;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.MethodParameter;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
*
*/
public class AuthenticationPrincipalArgumentResolverTests {
private Object expectedPrincipal;
private AuthenticationPrincipalArgumentResolver resolver;
@BeforeEach
public void setup() {
this.resolver = new AuthenticationPrincipalArgumentResolver();
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void supportsParameterNoAnnotation() {
assertThat(this.resolver.supportsParameter(showUserNoAnnotation())).isFalse();
}
@Test
public void supportsParameterAnnotation() {
assertThat(this.resolver.supportsParameter(showUserAnnotationObject())).isTrue();
}
@Test
public void supportsParameterCustomAnnotation() {
assertThat(this.resolver.supportsParameter(showUserCustomAnnotation())).isTrue();
}
@Test
public void resolveArgumentNullAuthentication() throws Exception {
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null)).isNull();
}
@Test
public void resolveArgumentNullPrincipal() throws Exception {
setAuthenticationPrincipal(null);
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null)).isNull();
}
@Test
public void resolveArgumentString() throws Exception {
setAuthenticationPrincipal("john");
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null)).isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentPrincipalStringOnObject() throws Exception {
setAuthenticationPrincipal("john");
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null)).isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentUserDetails() throws Exception {
setAuthenticationPrincipal(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
assertThat(this.resolver.resolveArgument(showUserAnnotationUserDetails(), null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomUserPrincipal() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(this.resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomAnnotation() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(this.resolver.resolveArgument(showUserCustomAnnotation(), null)).isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentSpel() throws Exception {
CustomUserPrincipal principal = new CustomUserPrincipal();
setAuthenticationPrincipal(principal);
this.expectedPrincipal = principal.property;
assertThat(this.resolver.resolveArgument(showUserSpel(), null)).isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentSpelCopy() throws Exception {
CopyUserPrincipal principal = new CopyUserPrincipal("property");
setAuthenticationPrincipal(principal);
Object resolveArgument = this.resolver.resolveArgument(showUserSpelCopy(), null);
assertThat(resolveArgument).isEqualTo(principal);
assertThat(resolveArgument).isNotSameAs(principal);
}
@Test
public void resolveArgumentSpelPrimitive() throws Exception {
CustomUserPrincipal principal = new CustomUserPrincipal();
setAuthenticationPrincipal(principal);
this.expectedPrincipal = principal.id;
assertThat(this.resolver.resolveArgument(showUserSpelPrimitive(), null)).isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentNullOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null)).isNull();
}
@Test
public void resolveArgumentErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThatExceptionOfType(ClassCastException.class)
.isThrownBy(() -> this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null));
}
@Test
public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThatExceptionOfType(ClassCastException.class).isThrownBy(
() -> this.resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null));
}
@Test
public void resolveArgumentObject() throws Exception {
setAuthenticationPrincipal(new Object());
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null)).isEqualTo(this.expectedPrincipal);
}
private MethodParameter showUserNoAnnotation() {
return getMethodParameter("showUserNoAnnotation", String.class);
}
private MethodParameter showUserAnnotationString() {
return getMethodParameter("showUserAnnotation", String.class);
}
private MethodParameter showUserAnnotationErrorOnInvalidType() {
return getMethodParameter("showUserAnnotationErrorOnInvalidType", String.class);
}
private MethodParameter showUserAnnotationCurrentUserErrorOnInvalidType() {
return getMethodParameter("showUserAnnotationCurrentUserErrorOnInvalidType", String.class);
}
private MethodParameter showUserAnnotationUserDetails() {
return getMethodParameter("showUserAnnotation", UserDetails.class);
}
private MethodParameter showUserAnnotationCustomUserPrincipal() {
return getMethodParameter("showUserAnnotation", CustomUserPrincipal.class);
}
private MethodParameter showUserCustomAnnotation() {
return getMethodParameter("showUserCustomAnnotation", CustomUserPrincipal.class);
}
private MethodParameter showUserSpel() {
return getMethodParameter("showUserSpel", String.class);
}
private MethodParameter showUserSpelCopy() {
return getMethodParameter("showUserSpelCopy", CopyUserPrincipal.class);
}
private MethodParameter showUserSpelPrimitive() {
return getMethodParameter("showUserSpelPrimitive", int.class);
}
private MethodParameter showUserAnnotationObject() {
return getMethodParameter("showUserAnnotation", Object.class);
}
private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) {
Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes);
return new MethodParameter(method, 0);
}
private void setAuthenticationPrincipal(Object principal) {
this.expectedPrincipal = principal;
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER"));
}
@Target({ ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal
static @interface CurrentUser {
}
@Target({ ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal(errorOnInvalidType = true)
static @interface CurrentUserErrorOnInvalidType {
}
public static class TestController {
public void showUserNoAnnotation(String user) {
}
public void showUserAnnotation(@AuthenticationPrincipal String user) {
}
public void showUserAnnotationErrorOnInvalidType(
@AuthenticationPrincipal(errorOnInvalidType = true) String user) {
}
public void showUserAnnotationCurrentUserErrorOnInvalidType(@CurrentUserErrorOnInvalidType String user) {
}
public void showUserAnnotation(@AuthenticationPrincipal UserDetails user) {
}
public void showUserAnnotation(@AuthenticationPrincipal CustomUserPrincipal user) {
}
public void showUserCustomAnnotation(@CurrentUser CustomUserPrincipal user) {
}
public void showUserAnnotation(@AuthenticationPrincipal Object user) {
}
public void showUserSpel(@AuthenticationPrincipal(expression = "property") String user) {
}
public void showUserSpelCopy(@AuthenticationPrincipal(
expression = "new org.springframework.security.messaging.context.AuthenticationPrincipalArgumentResolverTests$CopyUserPrincipal(#this)") CopyUserPrincipal user) {
}
public void showUserSpelPrimitive(@AuthenticationPrincipal(expression = "id") int id) {
}
}
static class CustomUserPrincipal {
public final String property = "property";
public final int id = 1;
}
public static class CopyUserPrincipal {
public final String property;
public CopyUserPrincipal(String property) {
this.property = property;
}
public CopyUserPrincipal(CopyUserPrincipal toCopy) {
this.property = toCopy.property;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CopyUserPrincipal other = (CopyUserPrincipal) obj;
if (this.property == null) {
if (other.property != null) {
return false;
}
}
else if (!this.property.equals(other.property)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.property == null) ? 0 : this.property.hashCode());
return result;
}
}
}
| 10,581 | 30.873494 | 166 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.messaging.Message;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
public class MessageExpressionVoterTests {
@Mock
Authentication authentication;
@Mock
Message<Object> message;
Collection<ConfigAttribute> attributes;
@Mock
Expression expression;
@Mock
MessageMatcher<?> matcher;
@Mock
SecurityExpressionHandler<Message> expressionHandler;
@Mock
EvaluationContext evaluationContext;
MessageExpressionVoter voter;
@BeforeEach
public void setup() {
this.attributes = Arrays
.<ConfigAttribute>asList(new MessageExpressionConfigAttribute(this.expression, this.matcher));
this.voter = new MessageExpressionVoter();
}
@Test
public void voteGranted() {
given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(true);
assertThat(this.voter.vote(this.authentication, this.message, this.attributes))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
@Test
public void voteDenied() {
given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(false);
assertThat(this.voter.vote(this.authentication, this.message, this.attributes))
.isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
}
@Test
public void voteAbstain() {
this.attributes = Arrays.<ConfigAttribute>asList(new SecurityConfig("ROLE_USER"));
assertThat(this.voter.vote(this.authentication, this.message, this.attributes))
.isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
}
@Test
public void supportsObjectClassFalse() {
assertThat(this.voter.supports(Object.class)).isFalse();
}
@Test
public void supportsMessageClassTrue() {
assertThat(this.voter.supports(Message.class)).isTrue();
}
@Test
public void supportsSecurityConfigFalse() {
assertThat(this.voter.supports(new SecurityConfig("ROLE_USER"))).isFalse();
}
@Test
public void supportsMessageExpressionConfigAttributeTrue() {
assertThat(this.voter.supports(new MessageExpressionConfigAttribute(this.expression, this.matcher))).isTrue();
}
@Test
public void setExpressionHandlerNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.voter.setExpressionHandler(null));
}
@Test
public void customExpressionHandler() {
this.voter.setExpressionHandler(this.expressionHandler);
given(this.expressionHandler.createEvaluationContext(this.authentication, this.message))
.willReturn(this.evaluationContext);
given(this.expression.getValue(this.evaluationContext, Boolean.class)).willReturn(true);
assertThat(this.voter.vote(this.authentication, this.message, this.attributes))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
verify(this.expressionHandler).createEvaluationContext(this.authentication, this.message);
}
@Test
public void postProcessEvaluationContext() {
final MessageExpressionConfigAttribute configAttribute = mock(MessageExpressionConfigAttribute.class);
this.voter.setExpressionHandler(this.expressionHandler);
given(this.expressionHandler.createEvaluationContext(this.authentication, this.message))
.willReturn(this.evaluationContext);
given(configAttribute.getAuthorizeExpression()).willReturn(this.expression);
this.attributes = Arrays.<ConfigAttribute>asList(configAttribute);
given(configAttribute.postProcess(this.evaluationContext, this.message)).willReturn(this.evaluationContext);
given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(true);
assertThat(this.voter.vote(this.authentication, this.message, this.attributes))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
verify(configAttribute).postProcess(this.evaluationContext, this.message);
}
}
| 5,465 | 35.198675 | 112 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/access/expression/DefaultMessageSecurityExpressionHandlerTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.function.Supplier;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.TypedValue;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.ExpressionUtils;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@ExtendWith(MockitoExtension.class)
public class DefaultMessageSecurityExpressionHandlerTests {
@Mock
AuthenticationTrustResolver trustResolver;
@Mock
PermissionEvaluator permissionEvaluator;
DefaultMessageSecurityExpressionHandler<Object> handler;
Message<Object> message;
Authentication authentication;
@BeforeEach
public void setup() {
this.handler = new DefaultMessageSecurityExpressionHandler<>();
this.message = new GenericMessage<>("");
this.authentication = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
}
// SEC-2705
@Test
public void trustResolverPopulated() {
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.message);
Expression expression = this.handler.getExpressionParser().parseExpression("authenticated");
assertThat(ExpressionUtils.evaluateAsBoolean(expression, context)).isFalse();
}
@Test
public void trustResolverNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setTrustResolver(null));
}
@Test
public void trustResolverCustom() {
this.handler.setTrustResolver(this.trustResolver);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.message);
Expression expression = this.handler.getExpressionParser().parseExpression("authenticated");
given(this.trustResolver.isAnonymous(this.authentication)).willReturn(false);
assertThat(ExpressionUtils.evaluateAsBoolean(expression, context)).isTrue();
}
@Test
public void roleHierarchy() {
this.authentication = new TestingAuthenticationToken("admin", "pass", "ROLE_ADMIN");
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");
this.handler.setRoleHierarchy(roleHierarchy);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.message);
Expression expression = this.handler.getExpressionParser().parseExpression("hasRole('ROLE_USER')");
assertThat(ExpressionUtils.evaluateAsBoolean(expression, context)).isTrue();
}
@Test
public void permissionEvaluator() {
this.handler.setPermissionEvaluator(this.permissionEvaluator);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.message);
Expression expression = this.handler.getExpressionParser().parseExpression("hasPermission(message, 'read')");
given(this.permissionEvaluator.hasPermission(this.authentication, this.message, "read")).willReturn(true);
assertThat(ExpressionUtils.evaluateAsBoolean(expression, context)).isTrue();
}
@Test
public void createEvaluationContextSupplierAuthentication() {
Supplier<Authentication> mockAuthenticationSupplier = mock(Supplier.class);
given(mockAuthenticationSupplier.get()).willReturn(this.authentication);
EvaluationContext context = this.handler.createEvaluationContext(mockAuthenticationSupplier, this.message);
verifyNoInteractions(mockAuthenticationSupplier);
assertThat(context.getRootObject()).extracting(TypedValue::getValue)
.asInstanceOf(InstanceOfAssertFactories.type(MessageSecurityExpressionRoot.class))
.extracting(SecurityExpressionRoot::getAuthentication).isEqualTo(this.authentication);
verify(mockAuthenticationSupplier).get();
}
}
| 5,552 | 42.382813 | 111 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionConfigAttributeTests.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
public class MessageExpressionConfigAttributeTests {
@Mock
Expression expression;
@Mock
MessageMatcher<?> matcher;
MessageExpressionConfigAttribute attribute;
@BeforeEach
public void setup() {
this.attribute = new MessageExpressionConfigAttribute(this.expression, this.matcher);
}
@Test
public void constructorNullExpression() {
assertThatIllegalArgumentException().isThrownBy(() -> new MessageExpressionConfigAttribute(null, this.matcher));
}
@Test
public void constructorNullMatcher() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new MessageExpressionConfigAttribute(this.expression, null));
}
@Test
public void getAuthorizeExpression() {
assertThat(this.attribute.getAuthorizeExpression()).isSameAs(this.expression);
}
@Test
public void getAttribute() {
assertThat(this.attribute.getAttribute()).isNull();
}
@Test
public void toStringUsesExpressionString() {
given(this.expression.getExpressionString()).willReturn("toString");
assertThat(this.attribute.toString()).isEqualTo(this.expression.getExpressionString());
}
@Test
public void postProcessContext() {
SimpDestinationMessageMatcher matcher = new SimpDestinationMessageMatcher("/topics/{topic}/**");
// @formatter:off
Message<?> message = MessageBuilder.withPayload("M")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/topics/someTopic/sub1")
.build();
// @formatter:on
EvaluationContext context = mock(EvaluationContext.class);
this.attribute = new MessageExpressionConfigAttribute(this.expression, matcher);
this.attribute.postProcess(context, message);
verify(context).setVariable("topic", "someTopic");
}
}
| 3,318 | 33.216495 | 114 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/access/expression/ExpressionBasedMessageSecurityMetadataSourceFactoryTests.java | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.Collection;
import java.util.LinkedHashMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@ExtendWith(MockitoExtension.class)
public class ExpressionBasedMessageSecurityMetadataSourceFactoryTests {
@Mock
MessageMatcher<Object> matcher1;
@Mock
MessageMatcher<Object> matcher2;
@Mock
Message<Object> message;
@Mock
Authentication authentication;
String expression1;
String expression2;
LinkedHashMap<MessageMatcher<?>, String> matcherToExpression;
MessageSecurityMetadataSource source;
MessageSecurityExpressionRoot rootObject;
@BeforeEach
public void setup() {
this.expression1 = "permitAll";
this.expression2 = "denyAll";
this.matcherToExpression = new LinkedHashMap<>();
this.matcherToExpression.put(this.matcher1, this.expression1);
this.matcherToExpression.put(this.matcher2, this.expression2);
this.source = ExpressionBasedMessageSecurityMetadataSourceFactory
.createExpressionMessageMetadataSource(this.matcherToExpression);
this.rootObject = new MessageSecurityExpressionRoot(this.authentication, this.message);
}
@Test
public void createExpressionMessageMetadataSourceNoMatch() {
Collection<ConfigAttribute> attrs = this.source.getAttributes(this.message);
assertThat(attrs).isNull();
}
@Test
public void createExpressionMessageMetadataSourceMatchFirst() {
given(this.matcher1.matches(this.message)).willReturn(true);
Collection<ConfigAttribute> attrs = this.source.getAttributes(this.message);
assertThat(attrs).hasSize(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute) attr).getAuthorizeExpression().getValue(this.rootObject))
.isEqualTo(true);
}
@Test
public void createExpressionMessageMetadataSourceMatchSecond() {
given(this.matcher2.matches(this.message)).willReturn(true);
Collection<ConfigAttribute> attrs = this.source.getAttributes(this.message);
assertThat(attrs).hasSize(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute) attr).getAuthorizeExpression().getValue(this.rootObject))
.isEqualTo(false);
}
}
| 3,557 | 33.543689 | 106 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/access/intercept/ChannelSecurityInterceptorTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.intercept.RunAsManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
@ExtendWith(MockitoExtension.class)
public class ChannelSecurityInterceptorTests {
@Mock
Message<Object> message;
@Mock
MessageChannel channel;
@Mock
MessageSecurityMetadataSource source;
@Mock
AccessDecisionManager accessDecisionManager;
@Mock
RunAsManager runAsManager;
@Mock
Authentication runAs;
Authentication originalAuth;
List<ConfigAttribute> attrs;
ChannelSecurityInterceptor interceptor;
@BeforeEach
public void setup() {
this.attrs = Arrays.<ConfigAttribute>asList(new SecurityConfig("ROLE_USER"));
this.interceptor = new ChannelSecurityInterceptor(this.source);
this.interceptor.setAccessDecisionManager(this.accessDecisionManager);
this.interceptor.setRunAsManager(this.runAsManager);
this.originalAuth = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(this.originalAuth);
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void constructorMessageSecurityMetadataSourceNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new ChannelSecurityInterceptor(null));
}
@Test
public void getSecureObjectClass() {
assertThat(this.interceptor.getSecureObjectClass()).isEqualTo(Message.class);
}
@Test
public void obtainSecurityMetadataSource() {
assertThat(this.interceptor.obtainSecurityMetadataSource()).isEqualTo(this.source);
}
@Test
public void preSendNullAttributes() {
assertThat(this.interceptor.preSend(this.message, this.channel)).isSameAs(this.message);
}
@Test
public void preSendGrant() {
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
Message<?> result = this.interceptor.preSend(this.message, this.channel);
assertThat(result).isSameAs(this.message);
}
@Test
public void preSendDeny() {
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
willThrow(new AccessDeniedException("")).given(this.accessDecisionManager).decide(any(Authentication.class),
eq(this.message), eq(this.attrs));
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.interceptor.preSend(this.message, this.channel));
}
@SuppressWarnings("unchecked")
@Test
public void preSendPostSendRunAs() {
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
given(this.runAsManager.buildRunAs(any(Authentication.class), any(), any(Collection.class)))
.willReturn(this.runAs);
Message<?> preSend = this.interceptor.preSend(this.message, this.channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.runAs);
this.interceptor.postSend(preSend, this.channel, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.originalAuth);
}
@Test
public void afterSendCompletionNotTokenMessageNoExceptionThrown() {
this.interceptor.afterSendCompletion(this.message, this.channel, true, null);
}
@SuppressWarnings("unchecked")
@Test
public void preSendFinallySendRunAs() {
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
given(this.runAsManager.buildRunAs(any(Authentication.class), any(), any(Collection.class)))
.willReturn(this.runAs);
Message<?> preSend = this.interceptor.preSend(this.message, this.channel);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.runAs);
this.interceptor.afterSendCompletion(preSend, this.channel, true, new RuntimeException());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.originalAuth);
}
@Test
public void preReceive() {
assertThat(this.interceptor.preReceive(this.channel)).isTrue();
}
@Test
public void postReceive() {
assertThat(this.interceptor.postReceive(this.message, this.channel)).isSameAs(this.message);
}
@Test
public void afterReceiveCompletionNullExceptionNoExceptionThrown() {
this.interceptor.afterReceiveCompletion(this.message, this.channel, null);
}
}
| 6,029 | 34.05814 | 110 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/access/intercept/MessageMatcherDelegatingAuthorizationManagerTests.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import java.util.Map;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link MessageMatcherDelegatingAuthorizationManager}
*/
public final class MessageMatcherDelegatingAuthorizationManagerTests {
@Test
void checkWhenPermitAllThenPermits() {
AuthorizationManager<Message<?>> authorizationManager = builder().anyMessage().permitAll().build();
Message<?> message = new GenericMessage<>(new Object());
assertThat(authorizationManager.check(mock(Supplier.class), message).isGranted()).isTrue();
}
@Test
void checkWhenAnyMessageHasRoleThenRequires() {
AuthorizationManager<Message<?>> authorizationManager = builder().anyMessage().hasRole("USER").build();
Message<?> message = new GenericMessage<>(new Object());
Authentication user = new TestingAuthenticationToken("user", "password", "ROLE_USER");
assertThat(authorizationManager.check(() -> user, message).isGranted()).isTrue();
Authentication admin = new TestingAuthenticationToken("user", "password", "ROLE_ADMIN");
assertThat(authorizationManager.check(() -> admin, message).isGranted()).isFalse();
}
@Test
void checkWhenSimpDestinationMatchesThenUses() {
AuthorizationManager<Message<?>> authorizationManager = builder().simpDestMatchers("destination").permitAll()
.anyMessage().denyAll().build();
MessageHeaders headers = new MessageHeaders(
Map.of(SimpMessageHeaderAccessor.DESTINATION_HEADER, "destination"));
Message<?> message = new GenericMessage<>(new Object(), headers);
assertThat(authorizationManager.check(mock(Supplier.class), message).isGranted()).isTrue();
}
@Test
void checkWhenNullDestinationHeaderMatchesThenUses() {
AuthorizationManager<Message<?>> authorizationManager = builder().nullDestMatcher().permitAll().anyMessage()
.denyAll().build();
Message<?> message = new GenericMessage<>(new Object());
assertThat(authorizationManager.check(mock(Supplier.class), message).isGranted()).isTrue();
MessageHeaders headers = new MessageHeaders(
Map.of(SimpMessageHeaderAccessor.DESTINATION_HEADER, "destination"));
message = new GenericMessage<>(new Object(), headers);
assertThat(authorizationManager.check(mock(Supplier.class), message).isGranted()).isFalse();
}
@Test
void checkWhenSimpTypeMatchesThenUses() {
AuthorizationManager<Message<?>> authorizationManager = builder().simpTypeMatchers(SimpMessageType.CONNECT)
.permitAll().anyMessage().denyAll().build();
MessageHeaders headers = new MessageHeaders(
Map.of(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.CONNECT));
Message<?> message = new GenericMessage<>(new Object(), headers);
assertThat(authorizationManager.check(mock(Supplier.class), message).isGranted()).isTrue();
}
// gh-12540
@Test
void checkWhenSimpDestinationMatchesThenVariablesExtracted() {
AuthorizationManager<Message<?>> authorizationManager = builder().simpDestMatchers("destination/{id}")
.access(variable("id").isEqualTo("3")).anyMessage().denyAll().build();
MessageHeaders headers = new MessageHeaders(
Map.of(SimpMessageHeaderAccessor.DESTINATION_HEADER, "destination/3"));
Message<?> message = new GenericMessage<>(new Object(), headers);
assertThat(authorizationManager.check(mock(Supplier.class), message).isGranted()).isTrue();
}
private MessageMatcherDelegatingAuthorizationManager.Builder builder() {
return MessageMatcherDelegatingAuthorizationManager.builder();
}
private Builder variable(String name) {
return new Builder(name);
}
private static final class Builder {
private final String name;
private Builder(String name) {
this.name = name;
}
AuthorizationManager<MessageAuthorizationContext<?>> isEqualTo(String value) {
return (authentication, object) -> {
String extracted = object.getVariables().get(this.name);
return new AuthorizationDecision(value.equals(extracted));
};
}
}
}
| 5,268 | 39.844961 | 111 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/access/intercept/DefaultMessageSecurityMetadataSourceTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@ExtendWith(MockitoExtension.class)
public class DefaultMessageSecurityMetadataSourceTests {
@Mock
MessageMatcher<Object> matcher1;
@Mock
MessageMatcher<Object> matcher2;
@Mock
Message<?> message;
@Mock
Authentication authentication;
SecurityConfig config1;
SecurityConfig config2;
LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>> messageMap;
MessageSecurityMetadataSource source;
@BeforeEach
public void setup() {
this.messageMap = new LinkedHashMap<>();
this.messageMap.put(this.matcher1, Arrays.<ConfigAttribute>asList(this.config1));
this.messageMap.put(this.matcher2, Arrays.<ConfigAttribute>asList(this.config2));
this.source = new DefaultMessageSecurityMetadataSource(this.messageMap);
}
@Test
public void getAttributesNull() {
assertThat(this.source.getAttributes(this.message)).isNull();
}
@Test
public void getAttributesFirst() {
given(this.matcher1.matches(this.message)).willReturn(true);
assertThat(this.source.getAttributes(this.message)).containsOnly(this.config1);
}
@Test
public void getAttributesSecond() {
given(this.matcher1.matches(this.message)).willReturn(true);
assertThat(this.source.getAttributes(this.message)).containsOnly(this.config2);
}
@Test
public void getAllConfigAttributes() {
assertThat(this.source.getAllConfigAttributes()).containsOnly(this.config1, this.config2);
}
@Test
public void supportsFalse() {
assertThat(this.source.supports(Object.class)).isFalse();
}
@Test
public void supportsTrue() {
assertThat(this.source.supports(Message.class)).isTrue();
}
}
| 2,966 | 28.088235 | 92 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/access/intercept/AuthorizationChannelInterceptorTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationEventPublisher;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link AuthorizationChannelInterceptor}
*/
@ExtendWith(MockitoExtension.class)
public class AuthorizationChannelInterceptorTests {
@Mock
Message<Object> message;
@Mock
MessageChannel channel;
@Mock
AuthorizationManager<Message<?>> authorizationManager;
@Mock
AuthorizationEventPublisher eventPublisher;
Authentication originalAuth;
AuthorizationChannelInterceptor interceptor;
@BeforeEach
public void setup() {
this.interceptor = new AuthorizationChannelInterceptor(this.authorizationManager);
this.originalAuth = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(this.originalAuth);
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void constructorWhenAuthorizationManagerNullThenIllegalArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizationChannelInterceptor(null));
}
@Test
public void preSendWhenAllowThenSameMessage() {
given(this.authorizationManager.check(any(), any())).willReturn(new AuthorizationDecision(true));
assertThat(this.interceptor.preSend(this.message, this.channel)).isSameAs(this.message);
}
@Test
public void preSendWhenDenyThenException() {
given(this.authorizationManager.check(any(), any())).willReturn(new AuthorizationDecision(false));
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.interceptor.preSend(this.message, this.channel));
}
@Test
public void setEventPublisherWhenNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.interceptor.setAuthorizationEventPublisher(null));
}
@Test
public void preSendWhenAuthorizationEventPublisherThenPublishes() {
this.interceptor.setAuthorizationEventPublisher(this.eventPublisher);
given(this.authorizationManager.check(any(), any())).willReturn(new AuthorizationDecision(true));
this.interceptor.preSend(this.message, this.channel);
verify(this.eventPublisher).publishAuthorizationEvent(any(), any(), any());
}
}
| 3,978 | 35.172727 | 100 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.handler.invocation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.aopalliance.intercept.MethodInterceptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.target.EmptyTargetSource;
import org.springframework.cglib.core.SpringNamingPolicy;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.objenesis.ObjenesisException;
import org.springframework.objenesis.SpringObjenesis;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
/**
* NOTE: This class is a replica of the same class in spring-web so it can be used for
* tests in spring-messaging.
*
* <p>
* Convenience class to resolve method parameters from hints.
*
* <h1>Background</h1>
*
* <p>
* When testing annotated methods we create test classes such as "TestController" with a
* diverse range of method signatures representing supported annotations and argument
* types. It becomes challenging to use naming strategies to keep track of methods and
* arguments especially in combination with variables for reflection metadata.
*
* <p>
* The idea with {@link ResolvableMethod} is NOT to rely on naming techniques but to use
* hints to zero in on method parameters. Such hints can be strongly typed and explicit
* about what is being tested.
*
* <h2>1. Declared Return Type</h2>
*
* When testing return types it's likely to have many methods with a unique return type,
* possibly with or without an annotation.
*
* <pre>
* import static org.springframework.web.method.ResolvableMethod.on;
* import static org.springframework.web.method.MvcAnnotationPredicates.requestMapping;
*
* // Return type
* on(TestController.class).resolveReturnType(Foo.class);
* on(TestController.class).resolveReturnType(List.class, Foo.class);
* on(TestController.class).resolveReturnType(Mono.class, responseEntity(Foo.class));
*
* // Annotation + return type
* on(TestController.class).annotPresent(RequestMapping.class).resolveReturnType(Bar.class);
*
* // Annotation not present
* on(TestController.class).annotNotPresent(RequestMapping.class).resolveReturnType();
*
* // Annotation with attributes
* on(TestController.class).annot(requestMapping("/foo").params("p")).resolveReturnType();
* </pre>
*
* <h2>2. Method Arguments</h2>
*
* When testing method arguments it's more likely to have one or a small number of methods
* with a wide array of argument types and parameter annotations.
*
* <pre>
* import static org.springframework.web.method.MvcAnnotationPredicates.requestParam;
*
* ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
*
* testMethod.arg(Foo.class);
* testMethod.annotPresent(RequestParam.class).arg(Integer.class);
* testMethod.annotNotPresent(RequestParam.class)).arg(Integer.class);
* testMethod.annot(requestParam().name("c").notRequired()).arg(Integer.class);
* </pre>
*
* <h3>3. Mock Handler Method Invocation</h3>
*
* Locate a method by invoking it through a proxy of the target handler:
*
* <pre>
* ResolvableMethod.on(TestController.class).mockCall((o) -> o.handle(null)).method();
* </pre>
*
* @author Rossen Stoyanchev
* @since 5.2
*/
public final class ResolvableMethod {
private static final Log logger = LogFactory.getLog(ResolvableMethod.class);
private static final SpringObjenesis objenesis = new SpringObjenesis();
private static final ParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
// Matches ValueConstants.DEFAULT_NONE (spring-web and spring-messaging)
private static final String DEFAULT_VALUE_NONE = "\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n";
private final Method method;
private ResolvableMethod(Method method) {
Assert.notNull(method, "'method' is required");
this.method = method;
}
/**
* Return the resolved method.
*/
public Method method() {
return this.method;
}
/**
* Return the declared return type of the resolved method.
*/
public MethodParameter returnType() {
return new SynthesizingMethodParameter(this.method, -1);
}
/**
* Find a unique argument matching the given type.
* @param type the expected type
* @param generics optional array of generic types
*/
public MethodParameter arg(Class<?> type, Class<?>... generics) {
return new ArgResolver().arg(type, generics);
}
/**
* Find a unique argument matching the given type.
* @param type the expected type
* @param generic at least one generic type
* @param generics optional array of generic types
*/
public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) {
return new ArgResolver().arg(type, generic, generics);
}
/**
* Find a unique argument matching the given type.
* @param type the expected type
*/
public MethodParameter arg(ResolvableType type) {
return new ArgResolver().arg(type);
}
/**
* Filter on method arguments with annotation. See
* {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final ArgResolver annot(Predicate<MethodParameter>... filter) {
return new ArgResolver(filter);
}
@SafeVarargs
public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) {
return new ArgResolver().annotPresent(annotationTypes);
}
/**
* Filter on method arguments that don't have the given annotation type(s).
* @param annotationTypes the annotation types
*/
@SafeVarargs
public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) {
return new ArgResolver().annotNotPresent(annotationTypes);
}
@Override
public String toString() {
return "ResolvableMethod=" + formatMethod();
}
private String formatMethod() {
return (method().getName() + Arrays.stream(this.method.getParameters()).map(this::formatParameter)
.collect(Collectors.joining(",\n\t", "(\n\t", "\n)")));
}
private String formatParameter(Parameter param) {
Annotation[] anns = param.getAnnotations();
return (anns.length > 0)
? Arrays.stream(anns).map(this::formatAnnotation).collect(Collectors.joining(",", "[", "]")) + " "
+ param
: param.toString();
}
private String formatAnnotation(Annotation annotation) {
Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation);
map.forEach((key, value) -> {
if (value.equals(DEFAULT_VALUE_NONE)) {
map.put(key, "NONE");
}
});
return annotation.annotationType().getName() + map;
}
private static ResolvableType toResolvableType(Class<?> type, Class<?>... generics) {
return (ObjectUtils.isEmpty(generics) ? ResolvableType.forClass(type)
: ResolvableType.forClassWithGenerics(type, generics));
}
private static ResolvableType toResolvableType(Class<?> type, ResolvableType generic, ResolvableType... generics) {
ResolvableType[] genericTypes = new ResolvableType[generics.length + 1];
genericTypes[0] = generic;
System.arraycopy(generics, 0, genericTypes, 1, generics.length);
return ResolvableType.forClassWithGenerics(type, genericTypes);
}
/**
* Create a {@code ResolvableMethod} builder for the given handler class.
*/
public static <T> Builder<T> on(Class<T> objectClass) {
return new Builder<>(objectClass);
}
@SuppressWarnings("unchecked")
private static <T> T initProxy(Class<?> type, MethodInvocationInterceptor interceptor) {
Assert.notNull(type, "'type' must not be null");
if (type.isInterface()) {
ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
factory.addInterface(type);
factory.addInterface(Supplier.class);
factory.addAdvice(interceptor);
return (T) factory.getProxy();
}
else {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(type);
enhancer.setInterfaces(new Class<?>[] { Supplier.class });
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);
Class<?> proxyClass = enhancer.createClass();
Object proxy = null;
if (objenesis.isWorthTrying()) {
try {
proxy = objenesis.newInstance(proxyClass, enhancer.getUseCache());
}
catch (ObjenesisException ex) {
logger.debug("Objenesis failed, falling back to default constructor", ex);
}
}
if (proxy == null) {
try {
proxy = ReflectionUtils.accessibleConstructor(proxyClass).newInstance();
}
catch (Throwable ex) {
throw new IllegalStateException(
"Unable to instantiate proxy " + "via both Objenesis and default constructor fails as well",
ex);
}
}
((Factory) proxy).setCallbacks(new Callback[] { interceptor });
return (T) proxy;
}
}
/**
* Builder for {@code ResolvableMethod}.
*/
public static final class Builder<T> {
private final Class<?> objectClass;
private final List<Predicate<Method>> filters = new ArrayList<>(4);
private Builder(Class<?> objectClass) {
Assert.notNull(objectClass, "Class must not be null");
this.objectClass = objectClass;
}
private void addFilter(String message, Predicate<Method> filter) {
this.filters.add(new LabeledPredicate<>(message, filter));
}
/**
* Filter on methods with the given name.
*/
public Builder<T> named(String methodName) {
addFilter("methodName=" + methodName, (method) -> method.getName().equals(methodName));
return this;
}
/**
* Filter on methods with the given parameter types.
*/
public Builder<T> argTypes(Class<?>... argTypes) {
addFilter("argTypes=" + Arrays.toString(argTypes), (method) -> ObjectUtils.isEmpty(argTypes)
? method.getParameterCount() == 0 : Arrays.equals(method.getParameterTypes(), argTypes));
return this;
}
/**
* Filter on annotated methods. See
* {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final Builder<T> annot(Predicate<Method>... filters) {
this.filters.addAll(Arrays.asList(filters));
return this;
}
/**
* Filter on methods annotated with the given annotation type.
* @see #annot(Predicate[]) See
* {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final Builder<T> annotPresent(Class<? extends Annotation>... annotationTypes) {
String message = "annotationPresent=" + Arrays.toString(annotationTypes);
addFilter(message, (candidate) -> Arrays.stream(annotationTypes)
.allMatch((annotType) -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null));
return this;
}
/**
* Filter on methods not annotated with the given annotation type.
*/
@SafeVarargs
public final Builder<T> annotNotPresent(Class<? extends Annotation>... annotationTypes) {
String message = "annotationNotPresent=" + Arrays.toString(annotationTypes);
addFilter(message, (candidate) -> {
if (annotationTypes.length != 0) {
return Arrays.stream(annotationTypes).noneMatch(
(annotType) -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null);
}
else {
return candidate.getAnnotations().length == 0;
}
});
return this;
}
/**
* Filter on methods returning the given type.
* @param returnType the return type
* @param generics optional array of generic types
*/
public Builder<T> returning(Class<?> returnType, Class<?>... generics) {
return returning(toResolvableType(returnType, generics));
}
/**
* Filter on methods returning the given type with generics.
* @param returnType the return type
* @param generic at least one generic type
* @param generics optional extra generic types
*/
public Builder<T> returning(Class<?> returnType, ResolvableType generic, ResolvableType... generics) {
return returning(toResolvableType(returnType, generic, generics));
}
/**
* Filter on methods returning the given type.
* @param returnType the return type
*/
public Builder<T> returning(ResolvableType returnType) {
String expected = returnType.toString();
String message = "returnType=" + expected;
addFilter(message, (m) -> expected.equals(ResolvableType.forMethodReturnType(m).toString()));
return this;
}
/**
* Build a {@code ResolvableMethod} from the provided filters which must resolve
* to a unique, single method.
* <p>
* See additional resolveXxx shortcut methods going directly to {@link Method} or
* return type parameter.
* @throws IllegalStateException for no match or multiple matches
*/
public ResolvableMethod method() {
Set<Method> methods = MethodIntrospector.selectMethods(this.objectClass, this::isMatch);
Assert.state(!methods.isEmpty(), () -> "No matching method: " + this);
Assert.state(methods.size() == 1, () -> "Multiple matching methods: " + this + formatMethods(methods));
return new ResolvableMethod(methods.iterator().next());
}
private boolean isMatch(Method method) {
return this.filters.stream().allMatch((p) -> p.test(method));
}
private String formatMethods(Set<Method> methods) {
return "\nMatched:\n" + methods.stream().map(Method::toGenericString)
.collect(Collectors.joining(",\n\t", "[\n\t", "\n]"));
}
public ResolvableMethod mockCall(Consumer<T> invoker) {
MethodInvocationInterceptor interceptor = new MethodInvocationInterceptor();
T proxy = initProxy(this.objectClass, interceptor);
invoker.accept(proxy);
Method method = interceptor.getInvokedMethod();
return new ResolvableMethod(method);
}
// Build & resolve shortcuts...
/**
* Resolve and return the {@code Method} equivalent to:
* <p>
* {@code build().method()}
*/
public Method resolveMethod() {
return method().method();
}
/**
* Resolve and return the {@code Method} equivalent to:
* <p>
* {@code named(methodName).build().method()}
*/
public Method resolveMethod(String methodName) {
return named(methodName).method().method();
}
/**
* Resolve and return the declared return type equivalent to:
* <p>
* {@code build().returnType()}
*/
public MethodParameter resolveReturnType() {
return method().returnType();
}
/**
* Shortcut to the unique return type equivalent to:
* <p>
* {@code returning(returnType).build().returnType()}
* @param returnType the return type
* @param generics optional array of generic types
*/
public MethodParameter resolveReturnType(Class<?> returnType, Class<?>... generics) {
return returning(returnType, generics).method().returnType();
}
/**
* Shortcut to the unique return type equivalent to:
* <p>
* {@code returning(returnType).build().returnType()}
* @param returnType the return type
* @param generic at least one generic type
* @param generics optional extra generic types
*/
public MethodParameter resolveReturnType(Class<?> returnType, ResolvableType generic,
ResolvableType... generics) {
return returning(returnType, generic, generics).method().returnType();
}
public MethodParameter resolveReturnType(ResolvableType returnType) {
return returning(returnType).method().returnType();
}
@Override
public String toString() {
return "ResolvableMethod.Builder[\n" + "\tobjectClass = " + this.objectClass.getName() + ",\n"
+ "\tfilters = " + formatFilters() + "\n]";
}
private String formatFilters() {
return this.filters.stream().map(Object::toString)
.collect(Collectors.joining(",\n\t\t", "[\n\t\t", "\n\t]"));
}
}
/**
* Predicate with a descriptive label.
*/
private static final class LabeledPredicate<T> implements Predicate<T> {
private final String label;
private final Predicate<T> delegate;
private LabeledPredicate(String label, Predicate<T> delegate) {
this.label = label;
this.delegate = delegate;
}
@Override
public boolean test(T method) {
return this.delegate.test(method);
}
@Override
public Predicate<T> and(Predicate<? super T> other) {
return this.delegate.and(other);
}
@Override
public Predicate<T> negate() {
return this.delegate.negate();
}
@Override
public Predicate<T> or(Predicate<? super T> other) {
return this.delegate.or(other);
}
@Override
public String toString() {
return this.label;
}
}
/**
* Resolver for method arguments.
*/
public final class ArgResolver {
private final List<Predicate<MethodParameter>> filters = new ArrayList<>(4);
@SafeVarargs
private ArgResolver(Predicate<MethodParameter>... filter) {
this.filters.addAll(Arrays.asList(filter));
}
/**
* Filter on method arguments with annotations. See
* {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final ArgResolver annot(Predicate<MethodParameter>... filters) {
this.filters.addAll(Arrays.asList(filters));
return this;
}
/**
* Filter on method arguments that have the given annotations.
* @param annotationTypes the annotation types
* @see #annot(Predicate[]) See
* {@link org.springframework.web.method.MvcAnnotationPredicates}.
*/
@SafeVarargs
public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) {
this.filters.add((param) -> Arrays.stream(annotationTypes).allMatch(param::hasParameterAnnotation));
return this;
}
/**
* Filter on method arguments that don't have the given annotations.
* @param annotationTypes the annotation types
*/
@SafeVarargs
public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) {
this.filters.add((param) -> (annotationTypes.length > 0)
? Arrays.stream(annotationTypes).noneMatch(param::hasParameterAnnotation)
: param.getParameterAnnotations().length == 0);
return this;
}
/**
* Resolve the argument also matching to the given type.
* @param type the expected type
*/
public MethodParameter arg(Class<?> type, Class<?>... generics) {
return arg(toResolvableType(type, generics));
}
/**
* Resolve the argument also matching to the given type.
* @param type the expected type
*/
public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) {
return arg(toResolvableType(type, generic, generics));
}
/**
* Resolve the argument also matching to the given type.
* @param type the expected type
*/
public MethodParameter arg(ResolvableType type) {
this.filters.add((p) -> type.toString().equals(ResolvableType.forMethodParameter(p).toString()));
return arg();
}
/**
* Resolve the argument.
*/
public MethodParameter arg() {
List<MethodParameter> matches = applyFilters();
Assert.state(!matches.isEmpty(), () -> "No matching arg in method\n" + formatMethod());
Assert.state(matches.size() == 1,
() -> "Multiple matching args in method\n" + formatMethod() + "\nMatches:\n\t" + matches);
return matches.get(0);
}
private List<MethodParameter> applyFilters() {
List<MethodParameter> matches = new ArrayList<>();
for (int i = 0; i < ResolvableMethod.this.method.getParameterCount(); i++) {
MethodParameter param = new SynthesizingMethodParameter(ResolvableMethod.this.method, i);
param.initParameterNameDiscovery(nameDiscoverer);
if (this.filters.stream().allMatch((p) -> p.test(param))) {
matches.add(param);
}
}
return matches;
}
}
private static class MethodInvocationInterceptor
implements org.springframework.cglib.proxy.MethodInterceptor, MethodInterceptor {
private Method invokedMethod;
Method getInvokedMethod() {
return this.invokedMethod;
}
@Override
@Nullable
public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) {
if (ReflectionUtils.isObjectMethod(method)) {
return ReflectionUtils.invokeMethod(method, object, args);
}
else {
this.invokedMethod = method;
return null;
}
}
@Override
@Nullable
public Object invoke(org.aopalliance.intercept.MethodInvocation inv) throws Throwable {
return intercept(inv.getThis(), inv.getMethod(), inv.getArguments(), null);
}
}
}
| 21,909 | 31.555721 | 116 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/reactive/AuthenticationPrincipalArgumentResolverTests.java | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.handler.invocation.reactive;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.security.authentication.TestAuthentication;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.messaging.handler.invocation.ResolvableMethod;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
*/
public class AuthenticationPrincipalArgumentResolverTests {
private AuthenticationPrincipalArgumentResolver resolver = new AuthenticationPrincipalArgumentResolver();
@Test
public void supportsParameterWhenAuthenticationPrincipalThenTrue() {
assertThat(this.resolver.supportsParameter(arg0("authenticationPrincipalOnMonoUserDetails"))).isTrue();
}
@Test
public void resolveArgumentWhenAuthenticationPrincipalAndEmptyContextThenNull() {
Object result = this.resolver.resolveArgument(arg0("authenticationPrincipalOnMonoUserDetails"), null).block();
assertThat(result).isNull();
}
@Test
public void resolveArgumentWhenAuthenticationPrincipalThenFound() {
Authentication authentication = TestAuthentication.authenticatedUser();
// @formatter:off
Mono<UserDetails> result = (Mono<UserDetails>) this.resolver
.resolveArgument(arg0("authenticationPrincipalOnMonoUserDetails"), null)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.block();
// @formatter:on
assertThat(result.block()).isEqualTo(authentication.getPrincipal());
}
@SuppressWarnings("unused")
private void authenticationPrincipalOnMonoUserDetails(@AuthenticationPrincipal Mono<UserDetails> user) {
}
@Test
public void supportsParameterWhenCurrentUserThenTrue() {
assertThat(this.resolver.supportsParameter(arg0("currentUserOnMonoUserDetails"))).isTrue();
}
@Test
public void resolveArgumentWhenMonoAndAuthenticationPrincipalThenFound() {
Authentication authentication = TestAuthentication.authenticatedUser();
// @formatter:off
Mono<UserDetails> result = (Mono<UserDetails>) this.resolver
.resolveArgument(arg0("currentUserOnMonoUserDetails"), null)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.block();
// @formatter:on
assertThat(result.block()).isEqualTo(authentication.getPrincipal());
}
@SuppressWarnings("unused")
private void currentUserOnMonoUserDetails(@CurrentUser Mono<UserDetails> user) {
}
@Test
public void resolveArgumentWhenExpressionThenFound() {
Authentication authentication = TestAuthentication.authenticatedUser();
// @formatter:off
Mono<String> result = (Mono<String>) this.resolver
.resolveArgument(arg0("authenticationPrincipalExpression"), null)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.block();
// @formatter:on
assertThat(result.block()).isEqualTo(authentication.getName());
}
@SuppressWarnings("unused")
private void authenticationPrincipalExpression(
@AuthenticationPrincipal(expression = "username") Mono<String> username) {
}
@Test
public void resolveArgumentWhenExpressionPrimitiveThenFound() {
CustomUserPrincipal principal = new CustomUserPrincipal();
// @formatter:off
Mono<Object> result = this.resolver
.resolveArgument(arg0("authenticationPrincipalExpressionPrimitive"), null)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(new TestingAuthenticationToken(principal, "password", "ROLE_USER")));
// @formatter:on
assertThat(result.block()).isEqualTo(principal.id);
}
@SuppressWarnings("unused")
private void authenticationPrincipalExpressionPrimitive(@AuthenticationPrincipal(expression = "id") int username) {
}
@Test
public void supportsParameterWhenNotAnnotatedThenFalse() {
assertThat(this.resolver.supportsParameter(arg0("monoUserDetails"))).isFalse();
}
@SuppressWarnings("unused")
private void monoUserDetails(Mono<UserDetails> user) {
}
private MethodParameter arg0(String methodName) {
ResolvableMethod method = ResolvableMethod.on(getClass()).named(methodName).method();
return new SynthesizingMethodParameter(method.method(), 0);
}
@AuthenticationPrincipal
@Retention(RetentionPolicy.RUNTIME)
@interface CurrentUser {
}
static class CustomUserPrincipal {
public final int id = 1;
}
}
| 5,463 | 35.18543 | 136 | java |
null | spring-security-main/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/reactive/CurrentSecurityContextArgumentResolverTests.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.handler.invocation.reactive;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.security.authentication.TestAuthentication;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.messaging.handler.invocation.ResolvableMethod;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
*/
public class CurrentSecurityContextArgumentResolverTests {
private CurrentSecurityContextArgumentResolver resolver = new CurrentSecurityContextArgumentResolver();
@Test
public void supportsParameterWhenAuthenticationPrincipalThenTrue() {
assertThat(this.resolver.supportsParameter(arg0("currentSecurityContextOnMonoSecurityContext"))).isTrue();
}
@Test
public void resolveArgumentWhenAuthenticationPrincipalAndEmptyContextThenNull() {
Object result = this.resolver.resolveArgument(arg0("currentSecurityContextOnMonoSecurityContext"), null)
.block();
assertThat(result).isNull();
}
@Test
public void resolveArgumentWhenAuthenticationPrincipalThenFound() {
Authentication authentication = TestAuthentication.authenticatedUser();
Mono<SecurityContext> result = (Mono<SecurityContext>) this.resolver
.resolveArgument(arg0("currentSecurityContextOnMonoSecurityContext"), null)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)).block();
assertThat(result.block().getAuthentication()).isEqualTo(authentication);
}
@SuppressWarnings("unused")
private void currentSecurityContextOnMonoSecurityContext(@CurrentSecurityContext Mono<SecurityContext> context) {
}
@Test
public void supportsParameterWhenCurrentUserThenTrue() {
assertThat(this.resolver.supportsParameter(arg0("currentUserOnMonoUserDetails"))).isTrue();
}
@Test
public void resolveArgumentWhenMonoAndAuthenticationPrincipalThenFound() {
Authentication authentication = TestAuthentication.authenticatedUser();
Mono<UserDetails> result = (Mono<UserDetails>) this.resolver
.resolveArgument(arg0("currentUserOnMonoUserDetails"), null)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)).block();
assertThat(result.block()).isEqualTo(authentication.getPrincipal());
}
@SuppressWarnings("unused")
private void currentUserOnMonoUserDetails(@CurrentUser Mono<UserDetails> user) {
}
@Test
public void resolveArgumentWhenExpressionThenFound() {
Authentication authentication = TestAuthentication.authenticatedUser();
Mono<String> result = (Mono<String>) this.resolver
.resolveArgument(arg0("authenticationPrincipalExpression"), null)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)).block();
assertThat(result.block()).isEqualTo(authentication.getName());
}
@SuppressWarnings("unused")
private void authenticationPrincipalExpression(
@CurrentSecurityContext(expression = "authentication?.principal?.username") Mono<String> username) {
}
@Test
public void supportsParameterWhenNotAnnotatedThenFalse() {
assertThat(this.resolver.supportsParameter(arg0("monoUserDetails"))).isFalse();
}
@SuppressWarnings("unused")
private void monoUserDetails(Mono<UserDetails> user) {
}
private MethodParameter arg0(String methodName) {
ResolvableMethod method = ResolvableMethod.on(getClass()).named(methodName).method();
return new SynthesizingMethodParameter(method.method(), 0);
}
@CurrentSecurityContext(expression = "authentication?.principal")
@Retention(RetentionPolicy.RUNTIME)
@interface CurrentUser {
}
}
| 4,709 | 37.606557 | 114 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/web/csrf/XorCsrfTokenUtils.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.web.csrf;
import java.util.Base64;
import org.springframework.security.crypto.codec.Utf8;
/**
* Copied from
* {@link org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler}.
*
* @see <a href=
* "https://github.com/spring-projects/spring-security/issues/12378">gh-12378</a>
*/
final class XorCsrfTokenUtils {
private XorCsrfTokenUtils() {
}
static String getTokenValue(String actualToken, String token) {
byte[] actualBytes;
try {
actualBytes = Base64.getUrlDecoder().decode(actualToken);
}
catch (Exception ex) {
return null;
}
byte[] tokenBytes = Utf8.encode(token);
int tokenSize = tokenBytes.length;
if (actualBytes.length < tokenSize) {
return null;
}
// extract token and random bytes
int randomBytesSize = actualBytes.length - tokenSize;
byte[] xoredCsrf = new byte[tokenSize];
byte[] randomBytes = new byte[randomBytesSize];
System.arraycopy(actualBytes, 0, randomBytes, 0, randomBytesSize);
System.arraycopy(actualBytes, randomBytesSize, xoredCsrf, 0, tokenSize);
byte[] csrfBytes = xorCsrf(randomBytes, xoredCsrf);
return Utf8.decode(csrfBytes);
}
private static byte[] xorCsrf(byte[] randomBytes, byte[] csrfBytes) {
int len = Math.min(randomBytes.length, csrfBytes.length);
byte[] xoredCsrf = new byte[len];
System.arraycopy(csrfBytes, 0, xoredCsrf, 0, csrfBytes.length);
for (int i = 0; i < len; i++) {
xoredCsrf[i] ^= randomBytes[i];
}
return xoredCsrf;
}
}
| 2,141 | 28.342466 | 85 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/web/csrf/XorCsrfChannelInterceptor.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.web.csrf;
import java.security.MessageDigest;
import java.util.Map;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpMessageTypeMatcher;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
/**
* {@link ChannelInterceptor} that validates a CSRF token masked by the
* {@link org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler} in
* the header of any {@link SimpMessageType#CONNECT} message.
*
* @author Steve Riesenberg
* @since 5.8
*/
public final class XorCsrfChannelInterceptor implements ChannelInterceptor {
private final MessageMatcher<Object> matcher = new SimpMessageTypeMatcher(SimpMessageType.CONNECT);
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
if (!this.matcher.matches(message)) {
return message;
}
Map<String, Object> sessionAttributes = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders());
CsrfToken expectedToken = (sessionAttributes != null)
? (CsrfToken) sessionAttributes.get(CsrfToken.class.getName()) : null;
if (expectedToken == null) {
throw new MissingCsrfTokenException(null);
}
String actualToken = SimpMessageHeaderAccessor.wrap(message)
.getFirstNativeHeader(expectedToken.getHeaderName());
String actualTokenValue = XorCsrfTokenUtils.getTokenValue(actualToken, expectedToken.getToken());
boolean csrfCheckPassed = equalsConstantTime(expectedToken.getToken(), actualTokenValue);
if (!csrfCheckPassed) {
throw new InvalidCsrfTokenException(expectedToken, actualToken);
}
return message;
}
/**
* Constant time comparison to prevent against timing attacks.
* @param expected
* @param actual
* @return
*/
private static boolean equalsConstantTime(String expected, String actual) {
if (expected == actual) {
return true;
}
if (expected == null || actual == null) {
return false;
}
// Encode after ensure that the string is not null
byte[] expectedBytes = Utf8.encode(expected);
byte[] actualBytes = Utf8.encode(actual);
return MessageDigest.isEqual(expectedBytes, actualBytes);
}
}
| 3,330 | 37.287356 | 111 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.web.csrf;
import java.util.Map;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpMessageTypeMatcher;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
/**
* {@link ChannelInterceptor} that validates that a valid CSRF is included in the header
* of any {@link SimpMessageType#CONNECT} message. The expected {@link CsrfToken} is
* populated by CsrfTokenHandshakeInterceptor.
*
* @author Rob Winch
* @since 4.0
*/
public final class CsrfChannelInterceptor implements ChannelInterceptor {
private final MessageMatcher<Object> matcher = new SimpMessageTypeMatcher(SimpMessageType.CONNECT);
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
if (!this.matcher.matches(message)) {
return message;
}
Map<String, Object> sessionAttributes = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders());
CsrfToken expectedToken = (sessionAttributes != null)
? (CsrfToken) sessionAttributes.get(CsrfToken.class.getName()) : null;
if (expectedToken == null) {
throw new MissingCsrfTokenException(null);
}
String actualTokenValue = SimpMessageHeaderAccessor.wrap(message)
.getFirstNativeHeader(expectedToken.getHeaderName());
boolean csrfCheckPassed = expectedToken.getToken().equals(actualTokenValue);
if (!csrfCheckPassed) {
throw new InvalidCsrfTokenException(expectedToken, actualTokenValue);
}
return message;
}
}
| 2,602 | 39.046154 | 111 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/web/socket/server/CsrfTokenHandshakeInterceptor.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.web.socket.server;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.security.web.csrf.DeferredCsrfToken;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
/**
* Loads a CsrfToken from the HttpServletRequest and HttpServletResponse to populate the
* WebSocket attributes. This is used as the expected CsrfToken when validating connection
* requests to ensure only the same origin connects.
*
* @author Rob Winch
* @author Steve Riesenberg
* @since 4.0
*/
public final class CsrfTokenHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) {
HttpServletRequest httpRequest = ((ServletServerHttpRequest) request).getServletRequest();
DeferredCsrfToken deferredCsrfToken = (DeferredCsrfToken) httpRequest
.getAttribute(DeferredCsrfToken.class.getName());
if (deferredCsrfToken == null) {
return true;
}
CsrfToken csrfToken = deferredCsrfToken.get();
// Ensure the values of the CsrfToken are copied into a new token so the old token
// is available for garbage collection.
// This is required because the original token could hold a reference to the
// HttpServletRequest/Response of the handshake request.
CsrfToken resolvedCsrfToken = new DefaultCsrfToken(csrfToken.getHeaderName(), csrfToken.getParameterName(),
csrfToken.getToken());
attributes.put(CsrfToken.class.getName(), resolvedCsrfToken);
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception exception) {
}
}
| 2,769 | 39.144928 | 115 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import java.util.Collections;
import java.util.Map;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
/**
* <p>
* MessageMatcher which compares a pre-defined pattern against the destination of a
* {@link Message}. There is also support for optionally matching on a specified
* {@link SimpMessageType}.
* </p>
*
* @author Rob Winch
* @since 4.0
*/
public final class SimpDestinationMessageMatcher implements MessageMatcher<Object> {
public static final MessageMatcher<Object> NULL_DESTINATION_MATCHER = (message) -> {
String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
return destination == null;
};
private final PathMatcher matcher;
/**
* The {@link MessageMatcher} that determines if the type matches. If the type was
* null, this matcher will match every Message.
*/
private final MessageMatcher<Object> messageTypeMatcher;
private final String pattern;
/**
* <p>
* Creates a new instance with the specified pattern, null {@link SimpMessageType}
* (matches any type), and a {@link AntPathMatcher} created from the default
* constructor.
*
* <p>
* The mapping matches destinations despite the using the following rules:
*
* <ul>
* <li>? matches one character</li>
* <li>* matches zero or more characters</li>
* <li>** matches zero or more 'directories' in a path</li>
* </ul>
*
* <p>
* Some examples:
*
* <ul>
* <li>{@code com/t?st.jsp} - matches {@code com/test} but also {@code com/tast} or
* {@code com/txst}</li>
* <li>{@code com/*suffix} - matches all files ending in {@code suffix} in the
* {@code com} directory</li>
* <li>{@code com/**/test} - matches all destinations ending with {@code test}
* underneath the {@code com} path</li>
* </ul>
* @param pattern the pattern to use
*/
public SimpDestinationMessageMatcher(String pattern) {
this(pattern, new AntPathMatcher());
}
/**
* <p>
* Creates a new instance with the specified pattern and {@link PathMatcher}.
* @param pattern the pattern to use
* @param pathMatcher the {@link PathMatcher} to use.
*/
public SimpDestinationMessageMatcher(String pattern, PathMatcher pathMatcher) {
this(pattern, null, pathMatcher);
}
/**
* <p>
* Creates a new instance with the specified pattern, {@link SimpMessageType}, and
* {@link PathMatcher}.
* @param pattern the pattern to use
* @param type the {@link SimpMessageType} to match on or null if any
* {@link SimpMessageType} should be matched.
* @param pathMatcher the {@link PathMatcher} to use.
*/
private SimpDestinationMessageMatcher(String pattern, SimpMessageType type, PathMatcher pathMatcher) {
Assert.notNull(pattern, "pattern cannot be null");
Assert.notNull(pathMatcher, "pathMatcher cannot be null");
Assert.isTrue(isTypeWithDestination(type),
() -> "SimpMessageType " + type + " does not contain a destination and so cannot be matched on.");
this.matcher = pathMatcher;
this.messageTypeMatcher = (type != null) ? new SimpMessageTypeMatcher(type) : ANY_MESSAGE;
this.pattern = pattern;
}
@Override
public boolean matches(Message<?> message) {
if (!this.messageTypeMatcher.matches(message)) {
return false;
}
String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
return destination != null && this.matcher.match(this.pattern, destination);
}
public Map<String, String> extractPathVariables(Message<?> message) {
final String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
return (destination != null) ? this.matcher.extractUriTemplateVariables(this.pattern, destination)
: Collections.emptyMap();
}
public MessageMatcher<Object> getMessageTypeMatcher() {
return this.messageTypeMatcher;
}
@Override
public String toString() {
return "SimpDestinationMessageMatcher [matcher=" + this.matcher + ", messageTypeMatcher="
+ this.messageTypeMatcher + ", pattern=" + this.pattern + "]";
}
private boolean isTypeWithDestination(SimpMessageType type) {
return type == null || SimpMessageType.MESSAGE.equals(type) || SimpMessageType.SUBSCRIBE.equals(type);
}
/**
* <p>
* Creates a new instance with the specified pattern,
* {@code SimpMessageType.SUBSCRIBE}, and {@link PathMatcher}.
* @param pattern the pattern to use
* @param matcher the {@link PathMatcher} to use.
*/
public static SimpDestinationMessageMatcher createSubscribeMatcher(String pattern, PathMatcher matcher) {
return new SimpDestinationMessageMatcher(pattern, SimpMessageType.SUBSCRIBE, matcher);
}
/**
* <p>
* Creates a new instance with the specified pattern, {@code SimpMessageType.MESSAGE},
* and {@link PathMatcher}.
* @param pattern the pattern to use
* @param matcher the {@link PathMatcher} to use.
*/
public static SimpDestinationMessageMatcher createMessageMatcher(String pattern, PathMatcher matcher) {
return new SimpDestinationMessageMatcher(pattern, SimpMessageType.MESSAGE, matcher);
}
}
| 5,943 | 34.171598 | 106 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpMessageTypeMatcher.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* A {@link MessageMatcher} that matches if the provided {@link Message} has a type that
* is the same as the {@link SimpMessageType} that was specified in the constructor.
*
* @author Rob Winch
* @since 4.0
*
*/
public class SimpMessageTypeMatcher implements MessageMatcher<Object> {
private final SimpMessageType typeToMatch;
/**
* Creates a new instance
* @param typeToMatch the {@link SimpMessageType} that will result in a match. Cannot
* be null.
*/
public SimpMessageTypeMatcher(SimpMessageType typeToMatch) {
Assert.notNull(typeToMatch, "typeToMatch cannot be null");
this.typeToMatch = typeToMatch;
}
@Override
public boolean matches(Message<?> message) {
MessageHeaders headers = message.getHeaders();
SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
return this.typeToMatch == messageType;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof SimpMessageTypeMatcher otherMatcher)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.typeToMatch, otherMatcher.typeToMatch);
}
@Override
public int hashCode() {
// Using nullSafeHashCode for proper array hashCode handling
return ObjectUtils.nullSafeHashCode(this.typeToMatch);
}
@Override
public String toString() {
return "SimpMessageTypeMatcher [typeToMatch=" + this.typeToMatch + "]";
}
}
| 2,415 | 29.974359 | 88 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/util/matcher/AbstractMessageMatcherComposite.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* Abstract {@link MessageMatcher} containing multiple {@link MessageMatcher}
*
* @since 4.0
*/
public abstract class AbstractMessageMatcherComposite<T> implements MessageMatcher<T> {
protected final Log logger = LogFactory.getLog(getClass());
/**
* @deprecated since 5.4 in favor of {@link #logger}
*/
@Deprecated
protected final Log LOGGER = this.logger;
private final List<MessageMatcher<T>> messageMatchers;
/**
* Creates a new instance
* @param messageMatchers the {@link MessageMatcher} instances to try
*/
AbstractMessageMatcherComposite(List<MessageMatcher<T>> messageMatchers) {
Assert.notEmpty(messageMatchers, "messageMatchers must contain a value");
Assert.isTrue(!messageMatchers.contains(null), "messageMatchers cannot contain null values");
this.messageMatchers = messageMatchers;
}
/**
* Creates a new instance
* @param messageMatchers the {@link MessageMatcher} instances to try
*/
@SafeVarargs
AbstractMessageMatcherComposite(MessageMatcher<T>... messageMatchers) {
this(Arrays.asList(messageMatchers));
}
public List<MessageMatcher<T>> getMessageMatchers() {
return this.messageMatchers;
}
@Override
public String toString() {
return getClass().getSimpleName() + "[messageMatchers=" + this.messageMatchers + "]";
}
}
| 2,158 | 28.175676 | 95 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/util/matcher/MessageMatcher.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import org.springframework.messaging.Message;
/**
* API for determining if a {@link Message} should be matched on.
*
* @author Rob Winch
* @since 4.0
*/
public interface MessageMatcher<T> {
/**
* Matches every {@link Message}
*/
MessageMatcher<Object> ANY_MESSAGE = new MessageMatcher<Object>() {
@Override
public boolean matches(Message<?> message) {
return true;
}
@Override
public String toString() {
return "ANY_MESSAGE";
}
};
/**
* Returns true if the {@link Message} matches, else false
* @param message the {@link Message} to match on
* @return true if the {@link Message} matches, else false
*/
boolean matches(Message<? extends T> message);
}
| 1,384 | 24.648148 | 75 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/util/matcher/AndMessageMatcher.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import java.util.List;
import org.springframework.core.log.LogMessage;
import org.springframework.messaging.Message;
/**
* {@link MessageMatcher} that will return true if all of the passed in
* {@link MessageMatcher} instances match.
*
* @since 4.0
*/
public final class AndMessageMatcher<T> extends AbstractMessageMatcherComposite<T> {
/**
* Creates a new instance
* @param messageMatchers the {@link MessageMatcher} instances to try
*/
public AndMessageMatcher(List<MessageMatcher<T>> messageMatchers) {
super(messageMatchers);
}
/**
* Creates a new instance
* @param messageMatchers the {@link MessageMatcher} instances to try
*/
@SafeVarargs
public AndMessageMatcher(MessageMatcher<T>... messageMatchers) {
super(messageMatchers);
}
@Override
public boolean matches(Message<? extends T> message) {
for (MessageMatcher<T> matcher : getMessageMatchers()) {
this.logger.debug(LogMessage.format("Trying to match using %s", matcher));
if (!matcher.matches(message)) {
this.logger.debug("Did not match");
return false;
}
}
this.logger.debug("All messageMatchers returned true");
return true;
}
}
| 1,842 | 27.796875 | 84 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/util/matcher/OrMessageMatcher.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.util.matcher;
import java.util.List;
import org.springframework.core.log.LogMessage;
import org.springframework.messaging.Message;
/**
* {@link MessageMatcher} that will return true if any of the passed in
* {@link MessageMatcher} instances match.
*
* @since 4.0
*/
public final class OrMessageMatcher<T> extends AbstractMessageMatcherComposite<T> {
/**
* Creates a new instance
* @param messageMatchers the {@link MessageMatcher} instances to try
*/
public OrMessageMatcher(List<MessageMatcher<T>> messageMatchers) {
super(messageMatchers);
}
/**
* Creates a new instance
* @param messageMatchers the {@link MessageMatcher} instances to try
*/
@SafeVarargs
public OrMessageMatcher(MessageMatcher<T>... messageMatchers) {
super(messageMatchers);
}
@Override
public boolean matches(Message<? extends T> message) {
for (MessageMatcher<T> matcher : getMessageMatchers()) {
this.logger.debug(LogMessage.format("Trying to match using %s", matcher));
if (matcher.matches(message)) {
this.logger.debug("matched");
return true;
}
}
this.logger.debug("No matches found");
return false;
}
}
| 1,815 | 27.375 | 83 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptor.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.context;
import java.util.Stack;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.ExecutorChannelInterceptor;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
/**
* <p>
* Creates a {@link ExecutorChannelInterceptor} that will obtain the
* {@link Authentication} from the specified {@link Message#getHeaders()}.
* </p>
*
* @author Rob Winch
* @since 4.0
*/
public final class SecurityContextChannelInterceptor implements ExecutorChannelInterceptor, ChannelInterceptor {
private static final ThreadLocal<Stack<SecurityContext>> originalContext = new ThreadLocal<>();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private SecurityContext empty = this.securityContextHolderStrategy.createEmptyContext();
private final String authenticationHeaderName;
private Authentication anonymous = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
/**
* Creates a new instance using the header of the name
* {@link SimpMessageHeaderAccessor#USER_HEADER}.
*/
public SecurityContextChannelInterceptor() {
this(SimpMessageHeaderAccessor.USER_HEADER);
}
/**
* Creates a new instance that uses the specified header to obtain the
* {@link Authentication}.
* @param authenticationHeaderName the header name to obtain the
* {@link Authentication}. Cannot be null.
*/
public SecurityContextChannelInterceptor(String authenticationHeaderName) {
Assert.notNull(authenticationHeaderName, "authenticationHeaderName cannot be null");
this.authenticationHeaderName = authenticationHeaderName;
}
/**
* Allows setting the Authentication used for anonymous authentication. Default is:
*
* <pre>
* new AnonymousAuthenticationToken("key", "anonymous",
* AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
* </pre>
* @param authentication the Authentication used for anonymous authentication. Cannot
* be null.
*/
public void setAnonymousAuthentication(Authentication authentication) {
Assert.notNull(authentication, "authentication cannot be null");
this.anonymous = authentication;
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
setup(message);
return message;
}
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
cleanup();
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
setup(message);
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {
cleanup();
}
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy strategy) {
this.securityContextHolderStrategy = strategy;
this.empty = this.securityContextHolderStrategy.createEmptyContext();
}
private void setup(Message<?> message) {
SecurityContext currentContext = this.securityContextHolderStrategy.getContext();
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null) {
contextStack = new Stack<>();
originalContext.set(contextStack);
}
contextStack.push(currentContext);
Object user = message.getHeaders().get(this.authenticationHeaderName);
Authentication authentication = getAuthentication(user);
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
this.securityContextHolderStrategy.setContext(context);
}
private Authentication getAuthentication(Object user) {
if ((user instanceof Authentication)) {
return (Authentication) user;
}
return this.anonymous;
}
private void cleanup() {
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null || contextStack.isEmpty()) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
return;
}
SecurityContext context = contextStack.pop();
try {
if (SecurityContextChannelInterceptor.this.empty.equals(context)) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
}
else {
this.securityContextHolderStrategy.setContext(context);
}
}
catch (Throwable ex) {
this.securityContextHolderStrategy.clearContext();
}
}
}
| 5,786 | 34.286585 | 116 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/context/AuthenticationPrincipalArgumentResolver.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.context;
import java.lang.annotation.Annotation;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Allows resolving the {@link Authentication#getPrincipal()} using the
* {@link AuthenticationPrincipal} annotation. For example, the following
* {@link Controller}:
*
* <pre>
* @Controller
* public class MyController {
* @MessageMapping("/im")
* public void im(@AuthenticationPrincipal CustomUser customUser) {
* // do something with CustomUser
* }
* }
* </pre>
*
* <p>
* Will resolve the CustomUser argument using {@link Authentication#getPrincipal()} from
* the {@link SecurityContextHolder}. If the {@link Authentication} or
* {@link Authentication#getPrincipal()} is null, it will return null. If the types do not
* match, null will be returned unless
* {@link AuthenticationPrincipal#errorOnInvalidType()} is true in which case a
* {@link ClassCastException} will be thrown.
*
* <p>
* Alternatively, users can create a custom meta annotation as shown below:
*
* <pre>
* @Target({ ElementType.PARAMETER })
* @Retention(RetentionPolicy.RUNTIME)
* @AuthenticationPrincipal
* public @interface CurrentUser {
* }
* </pre>
*
* <p>
* The custom annotation can then be used instead. For example:
*
* <pre>
* @Controller
* public class MyController {
* @MessageMapping("/im")
* public void im(@CurrentUser CustomUser customUser) {
* // do something with CustomUser
* }
* }
* </pre>
*
* @author Rob Winch
* @since 4.0
*/
public final class AuthenticationPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ExpressionParser parser = new SpelExpressionParser();
@Override
public boolean supportsParameter(MethodParameter parameter) {
return findMethodAnnotation(AuthenticationPrincipal.class, parameter) != null;
}
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication == null) {
return null;
}
Object principal = authentication.getPrincipal();
AuthenticationPrincipal authPrincipal = findMethodAnnotation(AuthenticationPrincipal.class, parameter);
String expressionToParse = authPrincipal.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(principal);
context.setVariable("this", principal);
Expression expression = this.parser.parseExpression(expressionToParse);
principal = expression.getValue(context);
}
if (principal != null && !ClassUtils.isAssignable(parameter.getParameterType(), principal.getClass())) {
if (authPrincipal.errorOnInvalidType()) {
throw new ClassCastException(principal + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return principal;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* @param annotationClass the class of the {@link Annotation} to find on the
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) {
T annotation = parameter.getParameterAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
if (annotation != null) {
return annotation;
}
}
return null;
}
}
| 6,034 | 36.955975 | 109 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/expression/MessageSecurityExpressionRoot.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.function.Supplier;
import org.springframework.messaging.Message;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.core.Authentication;
/**
* The {@link SecurityExpressionRoot} used for {@link Message} expressions.
*
* @author Rob Winch
* @author Evgeniy Cheban
* @since 4.0
*/
public class MessageSecurityExpressionRoot extends SecurityExpressionRoot {
public final Message<?> message;
public MessageSecurityExpressionRoot(Authentication authentication, Message<?> message) {
this(() -> authentication, message);
}
/**
* Creates an instance for the given {@link Supplier} of the {@link Authentication}
* and {@link Message}.
* @param authentication the {@link Supplier} of the {@link Authentication} to use
* @param message the {@link Message} to use
* @since 5.8
*/
public MessageSecurityExpressionRoot(Supplier<Authentication> authentication, Message<?> message) {
super(authentication);
this.message = message;
}
}
| 1,726 | 31.584906 | 100 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/expression/MessageAuthorizationContextSecurityExpressionHandler.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.Map;
import java.util.function.Supplier;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.messaging.Message;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.access.intercept.MessageAuthorizationContext;
/**
* An expression handler for {@link MessageAuthorizationContext}.
*
* @author Josh Cummings
* @since 5.8
*/
public final class MessageAuthorizationContextSecurityExpressionHandler
implements SecurityExpressionHandler<MessageAuthorizationContext<?>> {
private final SecurityExpressionHandler<Message<?>> delegate;
@SuppressWarnings("rawtypes")
public MessageAuthorizationContextSecurityExpressionHandler() {
this(new DefaultMessageSecurityExpressionHandler());
}
public MessageAuthorizationContextSecurityExpressionHandler(
SecurityExpressionHandler<Message<?>> expressionHandler) {
this.delegate = expressionHandler;
}
@Override
public ExpressionParser getExpressionParser() {
return this.delegate.getExpressionParser();
}
@Override
public EvaluationContext createEvaluationContext(Authentication authentication,
MessageAuthorizationContext<?> message) {
return createEvaluationContext(() -> authentication, message);
}
@Override
public EvaluationContext createEvaluationContext(Supplier<Authentication> authentication,
MessageAuthorizationContext<?> message) {
EvaluationContext context = this.delegate.createEvaluationContext(authentication, message.getMessage());
Map<String, String> variables = message.getVariables();
if (variables != null) {
for (Map.Entry<String, String> entry : variables.entrySet()) {
context.setVariable(entry.getKey(), entry.getValue());
}
}
return context;
}
}
| 2,598 | 33.653333 | 106 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/expression/DefaultMessageSecurityExpressionHandler.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.function.Supplier;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.messaging.Message;
import org.springframework.security.access.expression.AbstractSecurityExpressionHandler;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.access.expression.SecurityExpressionOperations;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
/**
* The default implementation of {@link SecurityExpressionHandler} which uses a
* {@link MessageSecurityExpressionRoot}.
*
* @param <T> the type for the body of the Message
* @author Rob Winch
* @author Evgeniy Cheban
* @since 4.0
*/
public class DefaultMessageSecurityExpressionHandler<T> extends AbstractSecurityExpressionHandler<Message<T>> {
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
@Override
public EvaluationContext createEvaluationContext(Supplier<Authentication> authentication, Message<T> message) {
MessageSecurityExpressionRoot root = createSecurityExpressionRoot(authentication, message);
StandardEvaluationContext ctx = new StandardEvaluationContext(root);
ctx.setBeanResolver(getBeanResolver());
return ctx;
}
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication,
Message<T> invocation) {
return createSecurityExpressionRoot(() -> authentication, invocation);
}
private MessageSecurityExpressionRoot createSecurityExpressionRoot(Supplier<Authentication> authentication,
Message<T> invocation) {
MessageSecurityExpressionRoot root = new MessageSecurityExpressionRoot(authentication, invocation);
root.setPermissionEvaluator(getPermissionEvaluator());
root.setTrustResolver(this.trustResolver);
root.setRoleHierarchy(getRoleHierarchy());
return root;
}
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
}
}
| 3,029 | 39.945946 | 112 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/expression/ExpressionBasedMessageSecurityMetadataSourceFactory.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.expression.Expression;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.messaging.access.intercept.DefaultMessageSecurityMetadataSource;
import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
/**
* A class used to create a {@link MessageSecurityMetadataSource} that uses
* {@link MessageMatcher} mapped to Spring Expressions.
*
* @author Rob Winch
* @since 4.0
* @deprecated Use
* {@link org.springframework.security.messaging.access.intercept.MessageMatcherDelegatingAuthorizationManager}
* instead
*/
@Deprecated
public final class ExpressionBasedMessageSecurityMetadataSourceFactory {
private ExpressionBasedMessageSecurityMetadataSourceFactory() {
}
/**
* Create a {@link MessageSecurityMetadataSource} that uses {@link MessageMatcher}
* mapped to Spring Expressions. Each entry is considered in order and only the first
* match is used.
*
* For example:
*
* <pre>
* LinkedHashMap<MessageMatcher<?>,String> matcherToExpression = new LinkedHashMap<MessageMatcher<Object>,String>();
* matcherToExpression.put(new SimDestinationMessageMatcher("/public/**"), "permitAll");
* matcherToExpression.put(new SimDestinationMessageMatcher("/admin/**"), "hasRole('ROLE_ADMIN')");
* matcherToExpression.put(new SimDestinationMessageMatcher("/topics/{name}/**"), "@someBean.customLogic(authentication, #name)");
* matcherToExpression.put(new SimDestinationMessageMatcher("/**"), "authenticated");
*
* MessageSecurityMetadataSource metadataSource = createExpressionMessageMetadataSource(matcherToExpression);
* </pre>
*
* <p>
* If our destination is "/public/hello", it would match on "/public/**" and on "/**".
* However, only "/public/**" would be used since it is the first entry. That means
* that a destination of "/public/hello" will be mapped to "permitAll".
*
* <p>
* For a complete listing of expressions see {@link MessageSecurityExpressionRoot}
* @param matcherToExpression an ordered mapping of {@link MessageMatcher} to Strings
* that are turned into an Expression using
* {@link DefaultMessageSecurityExpressionHandler#getExpressionParser()}
* @return the {@link MessageSecurityMetadataSource} to use. Cannot be null.
*/
public static MessageSecurityMetadataSource createExpressionMessageMetadataSource(
LinkedHashMap<MessageMatcher<?>, String> matcherToExpression) {
return createExpressionMessageMetadataSource(matcherToExpression,
new DefaultMessageSecurityExpressionHandler<>());
}
/**
* Create a {@link MessageSecurityMetadataSource} that uses {@link MessageMatcher}
* mapped to Spring Expressions. Each entry is considered in order and only the first
* match is used.
*
* For example:
*
* <pre>
* LinkedHashMap<MessageMatcher<?>,String> matcherToExpression = new LinkedHashMap<MessageMatcher<Object>,String>();
* matcherToExpression.put(new SimDestinationMessageMatcher("/public/**"), "permitAll");
* matcherToExpression.put(new SimDestinationMessageMatcher("/admin/**"), "hasRole('ROLE_ADMIN')");
* matcherToExpression.put(new SimDestinationMessageMatcher("/topics/{name}/**"), "@someBean.customLogic(authentication, #name)");
* matcherToExpression.put(new SimDestinationMessageMatcher("/**"), "authenticated");
*
* MessageSecurityMetadataSource metadataSource = createExpressionMessageMetadataSource(matcherToExpression);
* </pre>
*
* <p>
* If our destination is "/public/hello", it would match on "/public/**" and on "/**".
* However, only "/public/**" would be used since it is the first entry. That means
* that a destination of "/public/hello" will be mapped to "permitAll".
* </p>
*
* <p>
* For a complete listing of expressions see {@link MessageSecurityExpressionRoot}
* </p>
* @param matcherToExpression an ordered mapping of {@link MessageMatcher} to Strings
* that are turned into an Expression using
* {@link DefaultMessageSecurityExpressionHandler#getExpressionParser()}
* @param handler the {@link SecurityExpressionHandler} to use
* @return the {@link MessageSecurityMetadataSource} to use. Cannot be null.
*/
public static MessageSecurityMetadataSource createExpressionMessageMetadataSource(
LinkedHashMap<MessageMatcher<?>, String> matcherToExpression,
SecurityExpressionHandler<Message<Object>> handler) {
LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>> matcherToAttrs = new LinkedHashMap<>();
for (Map.Entry<MessageMatcher<?>, String> entry : matcherToExpression.entrySet()) {
MessageMatcher<?> matcher = entry.getKey();
String rawExpression = entry.getValue();
Expression expression = handler.getExpressionParser().parseExpression(rawExpression);
ConfigAttribute attribute = new MessageExpressionConfigAttribute(expression, matcher);
matcherToAttrs.put(matcher, Arrays.asList(attribute));
}
return new DefaultMessageSecurityMetadataSource(matcherToAttrs);
}
}
| 6,092 | 45.869231 | 145 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/expression/EvaluationContextPostProcessor.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import org.springframework.expression.EvaluationContext;
/**
* Allows post processing the {@link EvaluationContext}
*
* <p>
* This API is intentionally kept package scope as it may evolve over time.
* </p>
*
* @author Daniel Bustamante Ospina
* @since 5.2
* @deprecated Since {@link MessageExpressionVoter} is deprecated, there is no more need
* for this class
*/
@Deprecated
interface EvaluationContextPostProcessor<I> {
/**
* Allows post processing of the {@link EvaluationContext}. Implementations may return
* a new instance of {@link EvaluationContext} or modify the {@link EvaluationContext}
* that was passed in.
* @param context the original {@link EvaluationContext}
* @param invocation the security invocation object (i.e. Message)
* @return the upated context.
*/
EvaluationContext postProcess(EvaluationContext context, I invocation);
}
| 1,569 | 32.404255 | 88 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/expression/MessageExpressionConfigAttribute.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.Map;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher;
import org.springframework.util.Assert;
/**
* Simple expression configuration attribute for use in {@link Message} authorizations.
*
* @author Rob Winch
* @author Daniel Bustamante Ospina
* @since 4.0
* @deprecated Use
* {@link org.springframework.security.messaging.access.intercept.MessageMatcherDelegatingAuthorizationManager}
* instead
*/
@Deprecated
@SuppressWarnings("serial")
class MessageExpressionConfigAttribute implements ConfigAttribute, EvaluationContextPostProcessor<Message<?>> {
private final Expression authorizeExpression;
private final MessageMatcher<?> matcher;
/**
* Creates a new instance
* @param authorizeExpression the {@link Expression} to use. Cannot be null
* @param matcher the {@link MessageMatcher} used to match the messages.
*/
MessageExpressionConfigAttribute(Expression authorizeExpression, MessageMatcher<?> matcher) {
Assert.notNull(authorizeExpression, "authorizeExpression cannot be null");
Assert.notNull(matcher, "matcher cannot be null");
this.authorizeExpression = authorizeExpression;
this.matcher = matcher;
}
Expression getAuthorizeExpression() {
return this.authorizeExpression;
}
@Override
public String getAttribute() {
return null;
}
@Override
public String toString() {
return this.authorizeExpression.getExpressionString();
}
@Override
public EvaluationContext postProcess(EvaluationContext ctx, Message<?> message) {
if (this.matcher instanceof SimpDestinationMessageMatcher) {
Map<String, String> variables = ((SimpDestinationMessageMatcher) this.matcher)
.extractPathVariables(message);
for (Map.Entry<String, String> entry : variables.entrySet()) {
ctx.setVariable(entry.getKey(), entry.getValue());
}
}
return ctx;
}
}
| 2,847 | 32.116279 | 111 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/expression/MessageExpressionVoter.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.expression;
import java.util.Collection;
import org.springframework.expression.EvaluationContext;
import org.springframework.messaging.Message;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.expression.ExpressionUtils;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
/**
* Voter which handles {@link Message} authorisation decisions. If a
* {@link MessageExpressionConfigAttribute} is found, then its expression is evaluated. If
* true, {@code ACCESS_GRANTED} is returned. If false, {@code ACCESS_DENIED} is returned.
* If no {@code MessageExpressionConfigAttribute} is found, then {@code ACCESS_ABSTAIN} is
* returned.
*
* @author Rob Winch
* @author Daniel Bustamante Ospina
* @since 4.0
* @deprecated Use
* {@link org.springframework.security.messaging.access.intercept.MessageMatcherDelegatingAuthorizationManager}
* instead
*/
@Deprecated
public class MessageExpressionVoter<T> implements AccessDecisionVoter<Message<T>> {
private SecurityExpressionHandler<Message<T>> expressionHandler = new DefaultMessageSecurityExpressionHandler<>();
@Override
public int vote(Authentication authentication, Message<T> message, Collection<ConfigAttribute> attributes) {
Assert.notNull(authentication, "authentication must not be null");
Assert.notNull(message, "message must not be null");
Assert.notNull(attributes, "attributes must not be null");
MessageExpressionConfigAttribute attr = findConfigAttribute(attributes);
if (attr == null) {
return ACCESS_ABSTAIN;
}
EvaluationContext ctx = this.expressionHandler.createEvaluationContext(authentication, message);
ctx = attr.postProcess(ctx, message);
return ExpressionUtils.evaluateAsBoolean(attr.getAuthorizeExpression(), ctx) ? ACCESS_GRANTED : ACCESS_DENIED;
}
private MessageExpressionConfigAttribute findConfigAttribute(Collection<ConfigAttribute> attributes) {
for (ConfigAttribute attribute : attributes) {
if (attribute instanceof MessageExpressionConfigAttribute) {
return (MessageExpressionConfigAttribute) attribute;
}
}
return null;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return attribute instanceof MessageExpressionConfigAttribute;
}
@Override
public boolean supports(Class<?> clazz) {
return Message.class.isAssignableFrom(clazz);
}
public void setExpressionHandler(SecurityExpressionHandler<Message<T>> expressionHandler) {
Assert.notNull(expressionHandler, "expressionHandler cannot be null");
this.expressionHandler = expressionHandler;
}
}
| 3,437 | 38.068182 | 115 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/intercept/MessageSecurityMetadataSource.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import org.springframework.messaging.Message;
import org.springframework.security.access.SecurityMetadataSource;
/**
* A {@link SecurityMetadataSource} that is used for securing {@link Message}
*
* @author Rob Winch
* @since 4.0
* @see ChannelSecurityInterceptor
* @see DefaultMessageSecurityMetadataSource
* @deprecated Use {@link MessageMatcherDelegatingAuthorizationManager} instead
*/
@Deprecated
public interface MessageSecurityMetadataSource extends SecurityMetadataSource {
}
| 1,182 | 32.8 | 79 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/intercept/AuthorizationChannelInterceptor.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationEventPublisher;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
/**
* Authorizes {@link Message} resources using the provided {@link AuthorizationManager}
*
* @author Josh Cummings
* @since 5.8
*/
public final class AuthorizationChannelInterceptor implements ChannelInterceptor {
private Supplier<Authentication> authentication = getAuthentication(
SecurityContextHolder.getContextHolderStrategy());
private final Log logger = LogFactory.getLog(this.getClass());
private final AuthorizationManager<Message<?>> preSendAuthorizationManager;
private AuthorizationEventPublisher eventPublisher = new NoopAuthorizationEventPublisher();
/**
* Creates a new instance
* @param preSendAuthorizationManager the {@link AuthorizationManager} to use. Cannot
* be null.
*
*/
public AuthorizationChannelInterceptor(AuthorizationManager<Message<?>> preSendAuthorizationManager) {
Assert.notNull(preSendAuthorizationManager, "preSendAuthorizationManager cannot be null");
this.preSendAuthorizationManager = preSendAuthorizationManager;
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
this.logger.debug(LogMessage.of(() -> "Authorizing message send"));
AuthorizationDecision decision = this.preSendAuthorizationManager.check(this.authentication, message);
this.eventPublisher.publishAuthorizationEvent(this.authentication, message, decision);
if (decision == null || !decision.isGranted()) { // default deny
this.logger.debug(LogMessage.of(() -> "Failed to authorize message with authorization manager "
+ this.preSendAuthorizationManager + " and decision " + decision));
throw new AccessDeniedException("Access Denied");
}
this.logger.debug(LogMessage.of(() -> "Authorized message send"));
return message;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.authentication = getAuthentication(securityContextHolderStrategy);
}
/**
* Use this {@link AuthorizationEventPublisher} to publish the
* {@link AuthorizationManager} result.
* @param eventPublisher
*/
public void setAuthorizationEventPublisher(AuthorizationEventPublisher eventPublisher) {
Assert.notNull(eventPublisher, "eventPublisher cannot be null");
this.eventPublisher = eventPublisher;
}
private Supplier<Authentication> getAuthentication(SecurityContextHolderStrategy strategy) {
return () -> {
Authentication authentication = strategy.getContext().getAuthentication();
if (authentication == null) {
throw new AuthenticationCredentialsNotFoundException(
"An Authentication object was not found in the SecurityContext");
}
return authentication;
};
}
private static class NoopAuthorizationEventPublisher implements AuthorizationEventPublisher {
@Override
public <T> void publishAuthorizationEvent(Supplier<Authentication> authentication, T object,
AuthorizationDecision decision) {
}
}
}
| 4,745 | 38.55 | 108 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/intercept/MessageMatcherDelegatingAuthorizationManager.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorityAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpMessageTypeMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
import org.springframework.util.function.SingletonSupplier;
public final class MessageMatcherDelegatingAuthorizationManager implements AuthorizationManager<Message<?>> {
private final Log logger = LogFactory.getLog(getClass());
private final List<Entry<AuthorizationManager<MessageAuthorizationContext<?>>>> mappings;
private MessageMatcherDelegatingAuthorizationManager(
List<Entry<AuthorizationManager<MessageAuthorizationContext<?>>>> mappings) {
Assert.notEmpty(mappings, "mappings cannot be empty");
this.mappings = mappings;
}
/**
* Delegates to a specific {@link AuthorizationManager} based on a
* {@link MessageMatcher} evaluation.
* @param authentication the {@link Supplier} of the {@link Authentication} to check
* @param message the {@link Message} to check
* @return an {@link AuthorizationDecision}. If there is no {@link MessageMatcher}
* matching the message, or the {@link AuthorizationManager} could not decide, then
* null is returned
*/
@Override
public AuthorizationDecision check(Supplier<Authentication> authentication, Message<?> message) {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Authorizing message"));
}
for (Entry<AuthorizationManager<MessageAuthorizationContext<?>>> mapping : this.mappings) {
MessageMatcher<?> matcher = mapping.getMessageMatcher();
MessageAuthorizationContext<?> authorizationContext = authorizationContext(matcher, message);
if (authorizationContext != null) {
AuthorizationManager<MessageAuthorizationContext<?>> manager = mapping.getEntry();
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Checking authorization on message using %s", manager));
}
return manager.check(authentication, authorizationContext);
}
}
this.logger.trace("Abstaining since did not find matching MessageMatcher");
return null;
}
private MessageAuthorizationContext<?> authorizationContext(MessageMatcher<?> matcher, Message<?> message) {
if (!matcher.matches((Message) message)) {
return null;
}
if (matcher instanceof SimpDestinationMessageMatcher simp) {
return new MessageAuthorizationContext<>(message, simp.extractPathVariables(message));
}
if (matcher instanceof Builder.LazySimpDestinationMessageMatcher) {
Builder.LazySimpDestinationMessageMatcher path = (Builder.LazySimpDestinationMessageMatcher) matcher;
return new MessageAuthorizationContext<>(message, path.extractPathVariables(message));
}
return new MessageAuthorizationContext<>(message);
}
/**
* Creates a builder for {@link MessageMatcherDelegatingAuthorizationManager}.
* @return the new {@link Builder} instance
*/
public static Builder builder() {
return new Builder();
}
/**
* A builder for {@link MessageMatcherDelegatingAuthorizationManager}.
*/
public static final class Builder {
private final List<Entry<AuthorizationManager<MessageAuthorizationContext<?>>>> mappings = new ArrayList<>();
private Supplier<PathMatcher> pathMatcher = AntPathMatcher::new;
public Builder() {
}
/**
* Maps any {@link Message} to a security expression.
* @return the Expression to associate
*/
public Builder.Constraint anyMessage() {
return matchers(MessageMatcher.ANY_MESSAGE);
}
/**
* Maps any {@link Message} that has a null SimpMessageHeaderAccessor destination
* header (i.e. CONNECT, CONNECT_ACK, HEARTBEAT, UNSUBSCRIBE, DISCONNECT,
* DISCONNECT_ACK, OTHER)
* @return the Expression to associate
*/
public Builder.Constraint nullDestMatcher() {
return matchers(SimpDestinationMessageMatcher.NULL_DESTINATION_MATCHER);
}
/**
* Maps a {@link List} of {@link SimpDestinationMessageMatcher} instances.
* @param typesToMatch the {@link SimpMessageType} instance to match on
* @return the {@link Builder.Constraint} associated to the matchers.
*/
public Builder.Constraint simpTypeMatchers(SimpMessageType... typesToMatch) {
MessageMatcher<?>[] typeMatchers = new MessageMatcher<?>[typesToMatch.length];
for (int i = 0; i < typesToMatch.length; i++) {
SimpMessageType typeToMatch = typesToMatch[i];
typeMatchers[i] = new SimpMessageTypeMatcher(typeToMatch);
}
return matchers(typeMatchers);
}
/**
* Maps a {@link List} of {@link SimpDestinationMessageMatcher} instances without
* regard to the {@link SimpMessageType}. If no destination is found on the
* Message, then the Matcher returns false.
* @param patterns the patterns to create
* {@link org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher}
* from.
*/
public Builder.Constraint simpDestMatchers(String... patterns) {
return simpDestMatchers(null, patterns);
}
/**
* Maps a {@link List} of {@link SimpDestinationMessageMatcher} instances that
* match on {@code SimpMessageType.MESSAGE}. If no destination is found on the
* Message, then the Matcher returns false.
* @param patterns the patterns to create
* {@link org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher}
* from.
*/
public Builder.Constraint simpMessageDestMatchers(String... patterns) {
return simpDestMatchers(SimpMessageType.MESSAGE, patterns);
}
/**
* Maps a {@link List} of {@link SimpDestinationMessageMatcher} instances that
* match on {@code SimpMessageType.SUBSCRIBE}. If no destination is found on the
* Message, then the Matcher returns false.
* @param patterns the patterns to create
* {@link org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher}
* from.
*/
public Builder.Constraint simpSubscribeDestMatchers(String... patterns) {
return simpDestMatchers(SimpMessageType.SUBSCRIBE, patterns);
}
/**
* Maps a {@link List} of {@link SimpDestinationMessageMatcher} instances. If no
* destination is found on the Message, then the Matcher returns false.
* @param type the {@link SimpMessageType} to match on. If null, the
* {@link SimpMessageType} is not considered for matching.
* @param patterns the patterns to create
* {@link org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher}
* from.
* @return the {@link Builder.Constraint} that is associated to the
* {@link MessageMatcher}
*/
private Builder.Constraint simpDestMatchers(SimpMessageType type, String... patterns) {
List<MessageMatcher<?>> matchers = new ArrayList<>(patterns.length);
for (String pattern : patterns) {
MessageMatcher<Object> matcher = new LazySimpDestinationMessageMatcher(pattern, type);
matchers.add(matcher);
}
return new Builder.Constraint(matchers);
}
/**
* The {@link PathMatcher} to be used with the
* {@link Builder#simpDestMatchers(String...)}. The default is to use the default
* constructor of {@link AntPathMatcher}.
* @param pathMatcher the {@link PathMatcher} to use. Cannot be null.
* @return the {@link Builder} for further customization.
*/
public Builder simpDestPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "pathMatcher cannot be null");
this.pathMatcher = () -> pathMatcher;
return this;
}
/**
* The {@link PathMatcher} to be used with the
* {@link Builder#simpDestMatchers(String...)}. Use this method to delay the
* computation or lookup of the {@link PathMatcher}.
* @param pathMatcher the {@link PathMatcher} to use. Cannot be null.
* @return the {@link Builder} for further customization.
*/
public Builder simpDestPathMatcher(Supplier<PathMatcher> pathMatcher) {
Assert.notNull(pathMatcher, "pathMatcher cannot be null");
this.pathMatcher = pathMatcher;
return this;
}
/**
* Maps a {@link List} of {@link MessageMatcher} instances to a security
* expression.
* @param matchers the {@link MessageMatcher} instances to map.
* @return The {@link Builder.Constraint} that is associated to the
* {@link MessageMatcher} instances
*/
public Builder.Constraint matchers(MessageMatcher<?>... matchers) {
List<MessageMatcher<?>> builders = new ArrayList<>(matchers.length);
for (MessageMatcher<?> matcher : matchers) {
builders.add(matcher);
}
return new Builder.Constraint(builders);
}
public AuthorizationManager<Message<?>> build() {
return new MessageMatcherDelegatingAuthorizationManager(this.mappings);
}
/**
* Represents the security constraint to be applied to the {@link MessageMatcher}
* instances.
*/
public final class Constraint {
private final List<? extends MessageMatcher<?>> messageMatchers;
/**
* Creates a new instance
* @param messageMatchers the {@link MessageMatcher} instances to map to this
* constraint
*/
private Constraint(List<? extends MessageMatcher<?>> messageMatchers) {
Assert.notEmpty(messageMatchers, "messageMatchers cannot be null or empty");
this.messageMatchers = messageMatchers;
}
/**
* Shortcut for specifying {@link Message} instances require a particular
* role. If you do not want to have "ROLE_" automatically inserted see
* {@link #hasAuthority(String)}.
* @param role the role to require (i.e. USER, ADMIN, etc). Note, it should
* not start with "ROLE_" as this is automatically inserted.
* @return the {@link Builder} for further customization
*/
public Builder hasRole(String role) {
return access(AuthorityAuthorizationManager.hasRole(role));
}
/**
* Shortcut for specifying {@link Message} instances require any of a number
* of roles. If you do not want to have "ROLE_" automatically inserted see
* {@link #hasAnyAuthority(String...)}
* @param roles the roles to require (i.e. USER, ADMIN, etc). Note, it should
* not start with "ROLE_" as this is automatically inserted.
* @return the {@link Builder} for further customization
*/
public Builder hasAnyRole(String... roles) {
return access(AuthorityAuthorizationManager.hasAnyRole(roles));
}
/**
* Specify that {@link Message} instances require a particular authority.
* @param authority the authority to require (i.e. ROLE_USER, ROLE_ADMIN,
* etc).
* @return the {@link Builder} for further customization
*/
public Builder hasAuthority(String authority) {
return access(AuthorityAuthorizationManager.hasAuthority(authority));
}
/**
* Specify that {@link Message} instances requires any of a number
* authorities.
* @param authorities the requests require at least one of the authorities
* (i.e. "ROLE_USER","ROLE_ADMIN" would mean either "ROLE_USER" or
* "ROLE_ADMIN" is required).
* @return the {@link Builder} for further customization
*/
public Builder hasAnyAuthority(String... authorities) {
return access(AuthorityAuthorizationManager.hasAnyAuthority(authorities));
}
/**
* Specify that Messages are allowed by anyone.
* @return the {@link Builder} for further customization
*/
public Builder permitAll() {
return access((authentication, context) -> new AuthorizationDecision(true));
}
/**
* Specify that Messages are not allowed by anyone.
* @return the {@link Builder} for further customization
*/
public Builder denyAll() {
return access((authorization, context) -> new AuthorizationDecision(false));
}
/**
* Specify that Messages are allowed by any authenticated user.
* @return the {@link Builder} for further customization
*/
public Builder authenticated() {
return access(AuthenticatedAuthorizationManager.authenticated());
}
/**
* Specify that Messages are allowed by users who have authenticated and were
* not "remembered".
* @return the {@link Builder} for further customization
* @since 5.8
*/
public Builder fullyAuthenticated() {
return access(AuthenticatedAuthorizationManager.fullyAuthenticated());
}
/**
* Specify that Messages are allowed by users that have been remembered.
* @return the {@link Builder} for further customization
* @since 5.8
*/
public Builder rememberMe() {
return access(AuthenticatedAuthorizationManager.rememberMe());
}
/**
* Specify that Messages are allowed by anonymous users.
* @return the {@link Builder} for further customization
* @since 5.8
*/
public Builder anonymous() {
return access(AuthenticatedAuthorizationManager.anonymous());
}
/**
* Allows specifying that Messages are secured by an arbitrary expression
* @param authorizationManager the {@link AuthorizationManager} to secure the
* destinations
* @return the {@link Builder} for further customization
*/
public Builder access(AuthorizationManager<MessageAuthorizationContext<?>> authorizationManager) {
for (MessageMatcher<?> messageMatcher : this.messageMatchers) {
Builder.this.mappings.add(new Entry<>(messageMatcher, authorizationManager));
}
return Builder.this;
}
}
private final class LazySimpDestinationMessageMatcher implements MessageMatcher<Object> {
private final Supplier<SimpDestinationMessageMatcher> delegate;
private LazySimpDestinationMessageMatcher(String pattern, SimpMessageType type) {
this.delegate = SingletonSupplier.of(() -> {
PathMatcher pathMatcher = Builder.this.pathMatcher.get();
if (type == null) {
return new SimpDestinationMessageMatcher(pattern, pathMatcher);
}
if (SimpMessageType.MESSAGE == type) {
return SimpDestinationMessageMatcher.createMessageMatcher(pattern, pathMatcher);
}
if (SimpMessageType.SUBSCRIBE == type) {
return SimpDestinationMessageMatcher.createSubscribeMatcher(pattern, pathMatcher);
}
throw new IllegalStateException(type + " is not supported since it does not have a destination");
});
}
@Override
public boolean matches(Message<?> message) {
return this.delegate.get().matches(message);
}
Map<String, String> extractPathVariables(Message<?> message) {
return this.delegate.get().extractPathVariables(message);
}
}
}
private static final class Entry<T> {
private final MessageMatcher<?> messageMatcher;
private final T entry;
Entry(MessageMatcher requestMatcher, T entry) {
this.messageMatcher = requestMatcher;
this.entry = entry;
}
MessageMatcher<?> getMessageMatcher() {
return this.messageMatcher;
}
T getEntry() {
return this.entry;
}
}
}
| 16,287 | 36.272311 | 111 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/intercept/DefaultMessageSecurityMetadataSource.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.messaging.Message;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory;
import org.springframework.security.messaging.util.matcher.MessageMatcher;
/**
* A default implementation of {@link MessageSecurityMetadataSource} that looks up the
* {@link ConfigAttribute} instances using a {@link MessageMatcher}.
*
* <p>
* Each entry is considered in order. The first entry that matches, the corresponding
* {@code Collection<ConfigAttribute>} is returned.
* </p>
*
* @author Rob Winch
* @since 4.0
* @see ChannelSecurityInterceptor
* @see ExpressionBasedMessageSecurityMetadataSourceFactory
* @deprecated Use {@link MessageMatcherDelegatingAuthorizationManager} instead
*/
@Deprecated
public final class DefaultMessageSecurityMetadataSource implements MessageSecurityMetadataSource {
private final Map<MessageMatcher<?>, Collection<ConfigAttribute>> messageMap;
public DefaultMessageSecurityMetadataSource(
LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>> messageMap) {
this.messageMap = messageMap;
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
final Message message = (Message) object;
for (Map.Entry<MessageMatcher<?>, Collection<ConfigAttribute>> entry : this.messageMap.entrySet()) {
if (entry.getKey().matches(message)) {
return entry.getValue();
}
}
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
Set<ConfigAttribute> allAttributes = new HashSet<>();
for (Collection<ConfigAttribute> entry : this.messageMap.values()) {
allAttributes.addAll(entry);
}
return allAttributes;
}
@Override
public boolean supports(Class<?> clazz) {
return Message.class.isAssignableFrom(clazz);
}
}
| 2,783 | 32.95122 | 116 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/intercept/ChannelSecurityInterceptor.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory;
import org.springframework.util.Assert;
/**
* Performs security handling of Message resources via a ChannelInterceptor
* implementation.
* <p>
* The <code>SecurityMetadataSource</code> required by this security interceptor is of
* type {@link MessageSecurityMetadataSource}.
* <p>
* Refer to {@link AbstractSecurityInterceptor} for details on the workflow.
*
* @author Rob Winch
* @since 4.0
* @deprecated Use {@link AuthorizationChannelInterceptor} instead
*/
@Deprecated
public final class ChannelSecurityInterceptor extends AbstractSecurityInterceptor implements ChannelInterceptor {
private static final ThreadLocal<InterceptorStatusToken> tokenHolder = new ThreadLocal<>();
private final MessageSecurityMetadataSource metadataSource;
/**
* Creates a new instance
* @param metadataSource the MessageSecurityMetadataSource to use. Cannot be null.
*
* @see DefaultMessageSecurityMetadataSource
* @see ExpressionBasedMessageSecurityMetadataSourceFactory
*/
public ChannelSecurityInterceptor(MessageSecurityMetadataSource metadataSource) {
Assert.notNull(metadataSource, "metadataSource cannot be null");
this.metadataSource = metadataSource;
}
@Override
public Class<?> getSecureObjectClass() {
return Message.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.metadataSource;
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
InterceptorStatusToken token = beforeInvocation(message);
if (token != null) {
tokenHolder.set(token);
}
return message;
}
@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
InterceptorStatusToken token = clearToken();
afterInvocation(token, null);
}
@Override
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
InterceptorStatusToken token = clearToken();
finallyInvocation(token);
}
@Override
public boolean preReceive(MessageChannel channel) {
return true;
}
@Override
public Message<?> postReceive(Message<?> message, MessageChannel channel) {
return message;
}
@Override
public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
}
private InterceptorStatusToken clearToken() {
InterceptorStatusToken token = tokenHolder.get();
tokenHolder.remove();
return token;
}
}
| 3,611 | 31.25 | 116 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/access/intercept/MessageAuthorizationContext.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.access.intercept;
import java.util.Collections;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.messaging.Message;
/**
* An {@link Message} authorization context.
*
* @author Josh Cummings
* @since 5.8
*/
public final class MessageAuthorizationContext<T> {
private final Message<T> message;
private final Map<String, String> variables;
/**
* Creates an instance.
* @param message the {@link HttpServletRequest} to use
*/
public MessageAuthorizationContext(Message<T> message) {
this(message, Collections.emptyMap());
}
/**
* Creates an instance.
* @param message the {@link HttpServletRequest} to use
* @param variables a map containing key-value pairs representing extracted variable
* names and variable values
*/
public MessageAuthorizationContext(Message<T> message, Map<String, String> variables) {
this.message = message;
this.variables = variables;
}
/**
* Returns the {@link HttpServletRequest}.
* @return the {@link HttpServletRequest} to use
*/
public Message<T> getMessage() {
return this.message;
}
/**
* Returns the extracted variable values where the key is the variable name and the
* value is the variable value.
* @return a map containing key-value pairs representing extracted variable names and
* variable values
*/
public Map<String, String> getVariables() {
return this.variables;
}
}
| 2,097 | 26.605263 | 88 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/AuthenticationPrincipalArgumentResolver.java | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.handler.invocation.reactive;
import java.lang.annotation.Annotation;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.invocation.reactive.HandlerMethodArgumentResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Allows resolving the {@link Authentication#getPrincipal()} using the
* {@link AuthenticationPrincipal} annotation. For example, the following
* {@link Controller}:
*
* <pre>
* @Controller
* public class MyController {
* @MessageMapping("/im")
* public void im(@AuthenticationPrincipal CustomUser customUser) {
* // do something with CustomUser
* }
* }
* </pre>
*
* <p>
* Will resolve the CustomUser argument using {@link Authentication#getPrincipal()} from
* the {@link ReactiveSecurityContextHolder}. If the {@link Authentication} or
* {@link Authentication#getPrincipal()} is null, it will return null. If the types do not
* match, null will be returned unless
* {@link AuthenticationPrincipal#errorOnInvalidType()} is true in which case a
* {@link ClassCastException} will be thrown.
*
* <p>
* Alternatively, users can create a custom meta annotation as shown below:
*
* <pre>
* @Target({ ElementType.PARAMETER })
* @Retention(RetentionPolicy.RUNTIME)
* @AuthenticationPrincipal
* public @interface CurrentUser {
* }
* </pre>
*
* <p>
* The custom annotation can then be used instead. For example:
*
* <pre>
* @Controller
* public class MyController {
* @MessageMapping("/im")
* public void im(@CurrentUser CustomUser customUser) {
* // do something with CustomUser
* }
* }
* </pre>
*
* @author Rob Winch
* @since 5.2
*/
public class AuthenticationPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
private ExpressionParser parser = new SpelExpressionParser();
private BeanResolver beanResolver;
private ReactiveAdapterRegistry adapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
/**
* Sets the {@link BeanResolver} to be used on the expressions
* @param beanResolver the {@link BeanResolver} to use
*/
public void setBeanResolver(BeanResolver beanResolver) {
this.beanResolver = beanResolver;
}
/**
* Sets the {@link ReactiveAdapterRegistry} to be used.
* @param adapterRegistry the {@link ReactiveAdapterRegistry} to use. Cannot be null.
* Default is {@link ReactiveAdapterRegistry#getSharedInstance()}
*/
public void setAdapterRegistry(ReactiveAdapterRegistry adapterRegistry) {
Assert.notNull(adapterRegistry, "adapterRegistry cannot be null");
this.adapterRegistry = adapterRegistry;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return findMethodAnnotation(AuthenticationPrincipal.class, parameter) != null;
}
@Override
public Mono<Object> resolveArgument(MethodParameter parameter, Message<?> message) {
ReactiveAdapter adapter = this.adapterRegistry.getAdapter(parameter.getParameterType());
// @formatter:off
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.flatMap((a) -> {
Object p = resolvePrincipal(parameter, a.getPrincipal());
Mono<Object> principal = Mono.justOrEmpty(p);
return (adapter != null) ? Mono.just(adapter.fromPublisher(principal)) : principal;
});
// @formatter:on
}
private Object resolvePrincipal(MethodParameter parameter, Object principal) {
AuthenticationPrincipal authPrincipal = findMethodAnnotation(AuthenticationPrincipal.class, parameter);
String expressionToParse = authPrincipal.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(principal);
context.setVariable("this", principal);
context.setBeanResolver(this.beanResolver);
Expression expression = this.parser.parseExpression(expressionToParse);
principal = expression.getValue(context);
}
if (isInvalidType(parameter, principal)) {
if (authPrincipal.errorOnInvalidType()) {
throw new ClassCastException(principal + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return principal;
}
private boolean isInvalidType(MethodParameter parameter, Object principal) {
if (principal == null) {
return false;
}
Class<?> typeToCheck = parameter.getParameterType();
boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType());
if (isParameterPublisher) {
ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
Class<?> genericType = resolvableType.resolveGeneric(0);
if (genericType == null) {
return false;
}
typeToCheck = genericType;
}
return !ClassUtils.isAssignable(typeToCheck, principal.getClass());
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* @param annotationClass the class of the {@link Annotation} to find on the
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) {
T annotation = parameter.getParameterAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
if (annotation != null) {
return annotation;
}
}
return null;
}
}
| 7,441 | 36.21 | 109 | java |
null | spring-security-main/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/CurrentSecurityContextArgumentResolver.java | /*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.security.messaging.handler.invocation.reactive;
import java.lang.annotation.Annotation;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.invocation.reactive.HandlerMethodArgumentResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Allows resolving the {@link Authentication#getPrincipal()} using the
* {@link CurrentSecurityContext} annotation. For example, the following
* {@link Controller}:
*
* <pre>
* @Controller
* public class MyController {
* @MessageMapping("/im")
* public void im(@CurrentSecurityContext SecurityContext context) {
* // do something with context
* }
* }
* </pre>
*
* <p>
* Will resolve the SecurityContext argument using the
* {@link ReactiveSecurityContextHolder}. If the {@link SecurityContext} is empty, it will
* return null. If the types do not match, null will be returned unless
* {@link CurrentSecurityContext#errorOnInvalidType()} is true in which case a
* {@link ClassCastException} will be thrown.
*
* <p>
* Alternatively, users can create a custom meta annotation as shown below:
*
* <pre>
* @Target({ ElementType.PARAMETER })
* @Retention(RetentionPolicy.RUNTIME)
* @CurrentSecurityContext(expression = "authentication?.principal")
* public @interface CurrentUser {
* }
* </pre>
*
* <p>
* The custom annotation can then be used instead. For example:
*
* <pre>
* @Controller
* public class MyController {
* @MessageMapping("/im")
* public void im(@CurrentUser CustomUser customUser) {
* // do something with CustomUser
* }
* }
* </pre>
*
* @author Rob Winch
* @since 5.2
*/
public class CurrentSecurityContextArgumentResolver implements HandlerMethodArgumentResolver {
private ExpressionParser parser = new SpelExpressionParser();
private BeanResolver beanResolver;
private ReactiveAdapterRegistry adapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
/**
* Sets the {@link BeanResolver} to be used on the expressions
* @param beanResolver the {@link BeanResolver} to use
*/
public void setBeanResolver(BeanResolver beanResolver) {
this.beanResolver = beanResolver;
}
/**
* Sets the {@link ReactiveAdapterRegistry} to be used.
* @param adapterRegistry the {@link ReactiveAdapterRegistry} to use. Cannot be null.
* Default is {@link ReactiveAdapterRegistry#getSharedInstance()}
*/
public void setAdapterRegistry(ReactiveAdapterRegistry adapterRegistry) {
Assert.notNull(adapterRegistry, "adapterRegistry cannot be null");
this.adapterRegistry = adapterRegistry;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return findMethodAnnotation(CurrentSecurityContext.class, parameter) != null;
}
@Override
public Mono<Object> resolveArgument(MethodParameter parameter, Message<?> message) {
ReactiveAdapter adapter = this.adapterRegistry.getAdapter(parameter.getParameterType());
// @formatter:off
return ReactiveSecurityContextHolder.getContext()
.flatMap((securityContext) -> {
Object sc = resolveSecurityContext(parameter, securityContext);
Mono<Object> result = Mono.justOrEmpty(sc);
return (adapter != null) ? Mono.just(adapter.fromPublisher(result)) : result;
});
// @formatter:on
}
private Object resolveSecurityContext(MethodParameter parameter, Object securityContext) {
CurrentSecurityContext contextAnno = findMethodAnnotation(CurrentSecurityContext.class, parameter);
String expressionToParse = contextAnno.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(securityContext);
context.setVariable("this", securityContext);
context.setBeanResolver(this.beanResolver);
Expression expression = this.parser.parseExpression(expressionToParse);
securityContext = expression.getValue(context);
}
if (isInvalidType(parameter, securityContext)) {
if (contextAnno.errorOnInvalidType()) {
throw new ClassCastException(securityContext + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return securityContext;
}
private boolean isInvalidType(MethodParameter parameter, Object value) {
if (value == null) {
return false;
}
Class<?> typeToCheck = parameter.getParameterType();
boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType());
if (isParameterPublisher) {
ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
Class<?> genericType = resolvableType.resolveGeneric(0);
if (genericType == null) {
return false;
}
typeToCheck = genericType;
}
return !typeToCheck.isAssignableFrom(value.getClass());
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* @param annotationClass the class of the {@link Annotation} to find on the
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) {
T annotation = parameter.getParameterAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
if (annotation != null) {
return annotation;
}
}
return null;
}
}
| 7,333 | 36.228426 | 109 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.