Skip to content

Commit

Permalink
Merge pull request quarkusio#38376 from aloubyansky/3.2.10-backports-3
Browse files Browse the repository at this point in the history
[3.2] 3.2.10 backports 3
  • Loading branch information
aloubyansky authored Jan 25, 2024
2 parents 3c8c772 + f52b644 commit 2cabec0
Show file tree
Hide file tree
Showing 27 changed files with 632 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ static Optional<AnnotationInstance> searchPathAnnotationOnInterfaces(CombinedInd
* @param resultAcc accumulator for tail-recursion
* @return Collection of all interfaces und their parents. Never null.
*/
private static Collection<ClassInfo> getAllClassInterfaces(
static Collection<ClassInfo> getAllClassInterfaces(
CombinedIndexBuildItem index,
Collection<ClassInfo> classInfos,
List<ClassInfo> resultAcc) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
package io.quarkus.resteasy.deployment;

import static io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT;
import static io.quarkus.resteasy.deployment.RestPathAnnotationProcessor.getAllClassInterfaces;
import static io.quarkus.resteasy.deployment.RestPathAnnotationProcessor.isRestEndpointMethod;
import static io.quarkus.security.spi.SecurityTransformerUtils.hasSecurityAnnotation;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import org.jboss.logging.Logger;

import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.deployment.Capabilities;
Expand All @@ -27,10 +31,12 @@
import io.quarkus.resteasy.runtime.AuthenticationFailedExceptionMapper;
import io.quarkus.resteasy.runtime.AuthenticationRedirectExceptionMapper;
import io.quarkus.resteasy.runtime.CompositeExceptionMapper;
import io.quarkus.resteasy.runtime.EagerSecurityFilter;
import io.quarkus.resteasy.runtime.ExceptionMapperRecorder;
import io.quarkus.resteasy.runtime.ForbiddenExceptionMapper;
import io.quarkus.resteasy.runtime.JaxRsSecurityConfig;
import io.quarkus.resteasy.runtime.NotFoundExceptionMapper;
import io.quarkus.resteasy.runtime.PreventRepeatedSecurityChecksInterceptor;
import io.quarkus.resteasy.runtime.SecurityContextFilter;
import io.quarkus.resteasy.runtime.UnauthorizedExceptionMapper;
import io.quarkus.resteasy.runtime.vertx.JsonArrayReader;
Expand All @@ -48,6 +54,7 @@
public class ResteasyBuiltinsProcessor {

protected static final String META_INF_RESOURCES = "META-INF/resources";
private static final Logger LOG = Logger.getLogger(ResteasyBuiltinsProcessor.class);

@BuildStep
void setUpDenyAllJaxRs(CombinedIndexBuildItem index,
Expand All @@ -63,10 +70,42 @@ void setUpDenyAllJaxRs(CombinedIndexBuildItem index,
ClassInfo classInfo = index.getIndex().getClassByName(DotName.createSimple(className));
if (classInfo == null)
throw new IllegalStateException("Unable to find class info for " + className);
if (!hasSecurityAnnotation(classInfo)) {
for (MethodInfo methodInfo : classInfo.methods()) {
if (isRestEndpointMethod(index, methodInfo) && !hasSecurityAnnotation(methodInfo)) {
methods.add(methodInfo);
// add unannotated class endpoints as well as parent class unannotated endpoints
addAllUnannotatedEndpoints(index, classInfo, methods);

// interface endpoints implemented on resources are already in, now we need to resolve default interface
// methods as there, CDI interceptors won't work, therefore neither will our additional secured methods
Collection<ClassInfo> interfaces = getAllClassInterfaces(index, List.of(classInfo), new ArrayList<>());
if (!interfaces.isEmpty()) {
final List<MethodInfo> interfaceEndpoints = new ArrayList<>();
for (ClassInfo anInterface : interfaces) {
addUnannotatedEndpoints(index, anInterface, interfaceEndpoints);
}
// look for implementors as implementors on resource classes are secured by CDI interceptors
if (!interfaceEndpoints.isEmpty()) {
interfaceBlock: for (MethodInfo interfaceEndpoint : interfaceEndpoints) {
if (interfaceEndpoint.isDefault()) {
for (MethodInfo endpoint : methods) {
boolean nameParamsMatch = endpoint.name().equals(interfaceEndpoint.name())
&& (interfaceEndpoint.parameterTypes().equals(endpoint.parameterTypes()));
if (nameParamsMatch) {
// whether matched method is declared on class that implements interface endpoint
Predicate<DotName> isEndpointInterface = interfaceEndpoint.declaringClass()
.name()::equals;
if (endpoint.declaringClass().interfaceNames().stream().anyMatch(isEndpointInterface)) {
continue interfaceBlock;
}
}
}
String configProperty = config.denyJaxRs ? "quarkus.security.jaxrs.deny-unannotated-endpoints"
: "quarkus.security.jaxrs.default-roles-allowed";
// this is logging only as I'm a bit worried about false positives and breaking things
// for what is very much edge case
LOG.warn("Default interface method '" + interfaceEndpoint
+ "' cannot be secured with the '" + configProperty
+ "' configuration property. Please implement this method for CDI "
+ "interceptor binding to work");
}
}
}
}
Expand All @@ -83,6 +122,27 @@ void setUpDenyAllJaxRs(CombinedIndexBuildItem index,
}
}

private static void addAllUnannotatedEndpoints(CombinedIndexBuildItem index, ClassInfo classInfo,
List<MethodInfo> methods) {
if (classInfo == null) {
return;
}
addUnannotatedEndpoints(index, classInfo, methods);
if (classInfo.superClassType() != null && !classInfo.superClassType().name().equals(DotName.OBJECT_NAME)) {
addAllUnannotatedEndpoints(index, index.getIndex().getClassByName(classInfo.superClassType().name()), methods);
}
}

private static void addUnannotatedEndpoints(CombinedIndexBuildItem index, ClassInfo classInfo, List<MethodInfo> methods) {
if (!hasSecurityAnnotation(classInfo)) {
for (MethodInfo methodInfo : classInfo.methods()) {
if (isRestEndpointMethod(index, methodInfo) && !hasSecurityAnnotation(methodInfo)) {
methods.add(methodInfo);
}
}
}
}

/**
* Install the JAX-RS security provider.
*/
Expand All @@ -98,6 +158,10 @@ void setUpSecurity(BuildProducer<ResteasyJaxrsProviderBuildItem> providers,
if (capabilities.isPresent(Capability.SECURITY)) {
providers.produce(new ResteasyJaxrsProviderBuildItem(SecurityContextFilter.class.getName()));
additionalBeanBuildItem.produce(AdditionalBeanBuildItem.unremovableOf(SecurityContextFilter.class));
providers.produce(new ResteasyJaxrsProviderBuildItem(EagerSecurityFilter.class.getName()));
additionalBeanBuildItem.produce(AdditionalBeanBuildItem.unremovableOf(EagerSecurityFilter.class));
additionalBeanBuildItem
.produce(AdditionalBeanBuildItem.unremovableOf(PreventRepeatedSecurityChecksInterceptor.class));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ public class DefaultRolesAllowedJaxRsTest {
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(PermitAllResource.class, UnsecuredResource.class,
TestIdentityProvider.class,
TestIdentityController.class,
TestIdentityProvider.class, UnsecuredResourceInterface.class,
TestIdentityController.class, UnsecuredParentResource.class,
UnsecuredSubResource.class, HelloResource.class)
.addAsResource(new StringAsset("quarkus.security.jaxrs.default-roles-allowed = admin\n"),
"application.properties"));
Expand All @@ -41,6 +41,18 @@ public void shouldDenyUnannotated() {
assertStatus(path, 200, 403, 401);
}

@Test
public void shouldDenyUnannotatedOnParentClass() {
String path = "/unsecured/defaultSecurityParent";
assertStatus(path, 200, 403, 401);
}

@Test
public void shouldDenyUnannotatedOnInterface() {
String path = "/unsecured/defaultSecurityInterface";
assertStatus(path, 200, 403, 401);
}

@Test
public void shouldDenyDenyAllMethod() {
String path = "/unsecured/denyAll";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ public class DefaultRolesAllowedStarJaxRsTest {
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(PermitAllResource.class, UnsecuredResource.class,
TestIdentityProvider.class,
TestIdentityController.class,
TestIdentityProvider.class, UnsecuredParentResource.class,
TestIdentityController.class, UnsecuredResourceInterface.class,
UnsecuredSubResource.class)
.addAsResource(new StringAsset("quarkus.security.jaxrs.default-roles-allowed = **\n"),
"application.properties"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public class DenyAllJaxRsTest {
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(PermitAllResource.class, UnsecuredResource.class,
TestIdentityProvider.class,
TestIdentityController.class,
TestIdentityProvider.class, UnsecuredParentResource.class,
TestIdentityController.class, UnsecuredResourceInterface.class,
UnsecuredSubResource.class, HelloResource.class)
.addAsResource(new StringAsset("quarkus.security.jaxrs.deny-unannotated-endpoints = true\n"),
"application.properties"));
Expand Down Expand Up @@ -58,6 +58,18 @@ public void shouldDenyUnannotated() {
assertStatus(path, 403, 401);
}

@Test
public void shouldDenyUnannotatedOnParentClass() {
String path = "/unsecured/defaultSecurityParent";
assertStatus(path, 403, 401);
}

@Test
public void shouldDenyUnannotatedOnInterface() {
String path = "/unsecured/defaultSecurityInterface";
assertStatus(path, 403, 401);
}

@Test
public void shouldDenyDenyAllMethod() {
String path = "/unsecured/denyAll";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package io.quarkus.resteasy.test.security;

import jakarta.annotation.security.DenyAll;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.security.Authenticated;
import io.quarkus.security.test.utils.TestIdentityController;
import io.quarkus.security.test.utils.TestIdentityProvider;
import io.quarkus.test.QuarkusUnitTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.vertx.core.json.JsonObject;

/**
* Tests that {@link io.quarkus.security.spi.runtime.SecurityCheck}s are executed by Jakarta REST filters.
*/
public class EagerSecurityCheckTest {

@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(TestIdentityProvider.class, TestIdentityController.class, JsonResource.class,
AbstractJsonResource.class, JsonSubResource.class));

@BeforeAll
public static void setupUsers() {
TestIdentityController.resetRoles()
.add("admin", "admin", "admin")
.add("user", "user", "user");
}

@Test
public void testAuthenticated() {
testPostJson("auth", "admin", true).then().statusCode(400);
testPostJson("auth", null, true).then().statusCode(401);
testPostJson("auth", "admin", false).then().statusCode(200);
testPostJson("auth", null, false).then().statusCode(401);
}

@Test
public void testRolesAllowed() {
testPostJson("roles", "admin", true).then().statusCode(400);
testPostJson("roles", "user", true).then().statusCode(403);
testPostJson("roles", "admin", false).then().statusCode(200);
testPostJson("roles", "user", false).then().statusCode(403);
}

@Test
public void testRolesAllowedOverriddenMethod() {
testPostJson("/roles-overridden", "admin", true).then().statusCode(400);
testPostJson("/roles-overridden", "user", true).then().statusCode(403);
testPostJson("/roles-overridden", "admin", false).then().statusCode(200);
testPostJson("/roles-overridden", "user", false).then().statusCode(403);
}

@Test
public void testDenyAll() {
testPostJson("deny", "admin", true).then().statusCode(403);
testPostJson("deny", null, true).then().statusCode(401);
testPostJson("deny", "admin", false).then().statusCode(403);
testPostJson("deny", null, false).then().statusCode(401);
}

@Test
public void testDenyAllClassLevel() {
testPostJson("/sub-resource/deny-class-level-annotation", "admin", true).then().statusCode(403);
testPostJson("/sub-resource/deny-class-level-annotation", null, true).then().statusCode(401);
testPostJson("/sub-resource/deny-class-level-annotation", "admin", false).then().statusCode(403);
testPostJson("/sub-resource/deny-class-level-annotation", null, false).then().statusCode(401);
}

@Test
public void testPermitAll() {
testPostJson("permit", "admin", true).then().statusCode(400);
testPostJson("permit", null, true).then().statusCode(400);
testPostJson("permit", "admin", false).then().statusCode(200);
testPostJson("permit", null, false).then().statusCode(200);
}

@Test
public void testSubResource() {
testPostJson("/sub-resource/roles", "admin", true).then().statusCode(400);
testPostJson("/sub-resource/roles", "user", true).then().statusCode(403);
testPostJson("/sub-resource/roles", "admin", false).then().statusCode(200);
testPostJson("/sub-resource/roles", "user", false).then().statusCode(403);
}

private static Response testPostJson(String path, String username, boolean invalid) {
var req = RestAssured.given();
if (username != null) {
req = req.auth().preemptive().basic(username, username);
}
return req
.contentType(ContentType.JSON)
.body((invalid ? "}" : "") + "{\"simple\": \"obj\"}").post(path);
}

@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public static class JsonResource extends AbstractJsonResource {

@Authenticated
@Path("/auth")
@POST
public JsonObject auth(JsonObject array) {
return array.put("test", "testval");
}

@RolesAllowed("admin")
@Path("/roles")
@POST
public JsonObject roles(JsonObject array) {
return array.put("test", "testval");
}

@PermitAll
@Path("/permit")
@POST
public JsonObject permit(JsonObject array) {
return array.put("test", "testval");
}

@PermitAll
@Path("/sub-resource")
public JsonSubResource subResource() {
return new JsonSubResource();
}

@RolesAllowed("admin")
@Override
public JsonObject rolesOverridden(JsonObject array) {
return array.put("test", "testval");
}
}

@DenyAll
public static class JsonSubResource {
@RolesAllowed("admin")
@Path("/roles")
@POST
public JsonObject roles(JsonObject array) {
return array.put("test", "testval");
}

@Path("/deny-class-level-annotation")
@POST
public JsonObject denyClassLevelAnnotation(JsonObject array) {
return array.put("test", "testval");
}
}

public static abstract class AbstractJsonResource {
@DenyAll
@Path("/deny")
@POST
public JsonObject deny(JsonObject array) {
return array.put("test", "testval");
}

@Path("/roles-overridden")
@POST
public abstract JsonObject rolesOverridden(JsonObject array);
}
}
Loading

0 comments on commit 2cabec0

Please sign in to comment.