Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RoutingContext to Vert.x duplicated context local data so that it is accessible in the SecurityIdentityAugmentor #37795

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/src/main/asciidoc/security-customization.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,44 @@
}
----

The CDI request context activation shown in the example above wouldn't help you to access the `RoutingContext` when proactive authentication is enabled.
The following example illustrates how you can access the `RoutingContext` from the `SecurityIdentityAugmentor`:

[source,java]
----
package org.acme.security;

import io.quarkus.security.identity.AuthenticationRequestContext;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.SecurityIdentityAugmentor;
import io.quarkus.security.runtime.QuarkusSecurityIdentity;
import io.quarkus.vertx.http.runtime.security.HttpSecurityUtils;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

public class CustomSecurityIdentityAugmentor implements SecurityIdentityAugmentor {
@Override
public Uni<SecurityIdentity> augment(SecurityIdentity securityIdentity, AuthenticationRequestContext authenticationRequestContext) {
var builder = QuarkusSecurityIdentity.builder(securityIdentity);

final RoutingContext routingContext;
if (!securityIdentity.isAnonymous()) {
routingContext = HttpSecurityUtils.getRoutingContextAttribute(); <1>
} else {
routingContext = securityIdentity.getAttribute(RoutingContext.class.getName()); <2>
}

if (routingContext != null) {
// here you augment SecurityIdentity based on RoutingContext
}
return Uni.createFrom().item(builder.build());
}
}
----
<1> Quarkus puts the `RoutingContext` to Vert.x duplicated context local data so that it is available during authentication and authorization.
<2> Some authentication mechanisms like the OIDC authentication mechanism add `RoutingContext` to the `SecurityIdentity` attributes.

[[jaxrs-security-context]]

Check warning on line 342 in docs/src/main/asciidoc/security-customization.adoc

View workflow job for this annotation

GitHub Actions / Linting with Vale

[vale] reported by reviewdog 🐶 [Quarkus.Headings] Use sentence-style capitalization in 'Custom Jakarta REST SecurityContext'. Raw Output: {"message": "[Quarkus.Headings] Use sentence-style capitalization in 'Custom Jakarta REST SecurityContext'.", "location": {"path": "docs/src/main/asciidoc/security-customization.adoc", "range": {"start": {"line": 342, "column": 20}}}, "severity": "INFO"}
== Custom Jakarta REST SecurityContext

If you use Jakarta REST `ContainerRequestFilter` to set a custom Jakarta REST `SecurityContext` then make sure `ContainerRequestFilter` runs in the Jakarta REST pre-match phase by adding a `@PreMatching` annotation to it for this custom security context to be linked with Quarkus `SecurityIdentity`, for example:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,11 @@ public String admin() {
public String getSecurityIdentity() {
return currentIdentityAssociation.getIdentity().getPrincipal().getName();
}

@Path("/admin/security-identity/routing-context")
@RolesAllowed("root")
@GET
public String getSecurityIdentityPrincipal() {
return currentIdentityAssociation.getIdentity().getPrincipal().getName();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
import io.quarkus.security.test.utils.TestIdentityController;
import io.quarkus.security.test.utils.TestIdentityProvider;
import io.quarkus.test.QuarkusUnitTest;
import io.quarkus.vertx.http.runtime.security.HttpSecurityUtils;
import io.restassured.RestAssured;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

public class SecurityIdentityAugmentorTest {

Expand All @@ -44,6 +46,20 @@ public void testSecurityIdentityAugmentor() {
.body(Matchers.is("admin"));
}

@Test
public void testAccessToRoutingContext() {
RestAssured.given()
.auth().basic("admin", "admin")
.get("/roles/admin/security-identity/routing-context")
.then().statusCode(403);
RestAssured.given()
.auth().basic("admin", "admin")
.header("extra-role", "root")
.get("/roles/admin/security-identity/routing-context")
.then().statusCode(200)
.body(Matchers.is("admin"));
}

@ApplicationScoped
public static class CustomAugmentor implements SecurityIdentityAugmentor {

Expand All @@ -59,6 +75,14 @@ public Uni<SecurityIdentity> augment(SecurityIdentity identity, AuthenticationRe
Supplier<SecurityIdentity> build(SecurityIdentity identity) {
QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder(identity);
builder.addRole("admin");
RoutingContext event = HttpSecurityUtils.getRoutingContextAttribute();
if (event == null) {
throw new IllegalStateException(
"RoutingContext is expected to be present in Vert.x duplicated context local data");
}
if ("root".equals(event.request().getHeader("extra-role"))) {
builder.addRole("root");
}
return builder::build;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ public void testStringPermissionOneOfPermissionsAndActionsNonBlocking() {
RestAssured.given().auth().basic("viewer", "viewer").get("/permissions-non-blocking/admin").then().statusCode(403);
}

@Test
public void testConditionalPermissionBasedOnRoutingContext() {
RestAssured.given().auth().basic("viewer", "viewer").put("permissions/edit").then().statusCode(403);
RestAssured.given().auth().basic("viewer", "viewer").header("sudo", "edit").put("permissions/edit").then()
.statusCode(200).body(Matchers.is("edit"));
}

@Test
public void testBlockingAccessToIdentityOnIOThread() {
// invokes GET /permissions/security-identity endpoint that requires one permission: get-identity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;

Expand Down Expand Up @@ -34,6 +35,13 @@ public String admin() {
return "admin";
}

@Path("/edit")
@PermissionsAllowed("edit")
@PUT
public String edit() {
return "edit";
}

@NonBlocking
@Path("/admin/security-identity")
@PermissionsAllowed("get-identity")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.SecurityIdentityAugmentor;
import io.quarkus.security.runtime.QuarkusSecurityIdentity;
import io.quarkus.vertx.http.runtime.security.HttpSecurityUtils;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class PermissionsIdentityAugmentor implements SecurityIdentityAugmentor {
Expand Down Expand Up @@ -42,6 +44,14 @@ SecurityIdentity build(SecurityIdentity identity) {
builder.addPermissionChecker(new PermissionCheckBuilder().addPermission("read", "resource-viewer").build());
break;
}
RoutingContext event = HttpSecurityUtils.getRoutingContextAttribute();
if (event == null) {
throw new IllegalStateException(
"RoutingContext is expected to be present in Vert.x duplicated context local data");
}
if ("edit".equals(event.request().getHeader("sudo"))) {
builder.addPermissionChecker(new PermissionCheckBuilder().addPermission("edit").build());
}
return builder.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
Expand Down Expand Up @@ -95,9 +96,7 @@ public void testAuthenticationEvents() {
assertEquals(0, observer.authZFailureStorage.size());
Awaitility.await().atMost(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals(1, observer.asyncAuthNFailureEventStorage.size()));
Awaitility.await().atMost(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals(1, observer.asyncAllEventsStorage.size()));
assertEquals(1, observer.allEventsStorage.size());
assertAllEvents(1);
AuthenticationFailureEvent event = observer.asyncAuthNFailureEventStorage.get(0);
assertNull(event.getSecurityIdentity());
assertNotNull(event.getEventProperties().get(RoutingContext.class.getName()));
Expand Down Expand Up @@ -128,9 +127,7 @@ public void testAuthenticatedPolicy() {
assertNotNull(event.getEventProperties().get(RoutingContext.class.getName()));
assertEquals(PathMatchingHttpSecurityPolicy.class.getName(), event.getAuthorizationContext());
assertTrue(identity.isAnonymous());
assertEquals(3, observer.allEventsStorage.size());
Awaitility.await().atMost(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals(3, observer.asyncAllEventsStorage.size()));
assertAllEvents(3);
AuthenticationSuccessEvent authNSuccessEvent = (AuthenticationSuccessEvent) observer.allEventsStorage.get(0);
identity = authNSuccessEvent.getSecurityIdentity();
assertNotNull(identity);
Expand All @@ -143,14 +140,12 @@ public void testPermitAllPolicy() {
RestAssured.get("/permit").then().statusCode(200);
assertEquals(0, observer.authZFailureStorage.size());
assertEquals(0, observer.authNSuccessStorage.size());
assertEquals(1, observer.allEventsStorage.size());
assertEquals(1, observer.authZSuccessStorage.size());
AuthorizationSuccessEvent event = observer.authZSuccessStorage.get(0);
assertNotNull(event.getSecurityIdentity());
assertTrue(event.getSecurityIdentity().isAnonymous());
assertNotNull(event.getEventProperties().get(RoutingContext.class.getName()));
Awaitility.await().atMost(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals(1, observer.asyncAllEventsStorage.size()));
assertAllEvents(1);
}

@Test
Expand All @@ -177,24 +172,23 @@ public void testRolesPolicy() {
identity = event.getSecurityIdentity();
assertNotNull(identity);
assertEquals("test", identity.getPrincipal().getName());
assertTrue(event.getAuthorizationFailure() instanceof ForbiddenException);
assertInstanceOf(ForbiddenException.class, event.getAuthorizationFailure());
assertNotNull(event.getEventProperties().get(RoutingContext.class.getName()));
Awaitility.await().atMost(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals(4, observer.asyncAllEventsStorage.size()));
assertAllEvents(4);
}

@Test
public void testRolesPolicyAugmentation() {
RestAssured.given().auth().preemptive().basic("test", "test").get("/map-roles").then().statusCode(200);
assertEquals(0, observer.authZFailureStorage.size());
assertEquals(2, observer.allEventsStorage.size());
assertEquals(1, observer.authNSuccessStorage.size());
assertEquals(1, observer.authZSuccessStorage.size());
SecurityIdentity originalIdentity = observer.authNSuccessStorage.get(0).getSecurityIdentity();
SecurityIdentity augmentedIdentity = observer.authZSuccessStorage.get(0).getSecurityIdentity();
assertNotEquals(originalIdentity, augmentedIdentity);
assertTrue(augmentedIdentity.hasRole("admin"));
assertFalse(originalIdentity.hasRole("admin"));
assertAllEvents(2);
}

@Test
Expand All @@ -220,11 +214,9 @@ public void testDenyAllPolicy() {
assertNull(first.getAuthorizationFailure());
assertEquals(PathMatchingHttpSecurityPolicy.class.getName(), first.getAuthorizationContext());
assertNotNull(first.getEventProperties().get(RoutingContext.class.getName()));
assertTrue(second.getAuthorizationFailure() instanceof ForbiddenException);
assertInstanceOf(ForbiddenException.class, second.getAuthorizationFailure());
assertEquals(PathMatchingHttpSecurityPolicy.class.getName(), first.getAuthorizationContext());
Awaitility.await().atMost(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals(3, observer.asyncAllEventsStorage.size()));
assertEquals(3, observer.allEventsStorage.size());
assertAllEvents(3);
Awaitility.await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertEquals(1,
observer.asyncAllEventsStorage.stream().filter(se -> se instanceof AuthenticationSuccessEvent).count()));
AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) observer.asyncAllEventsStorage.stream()
Expand Down Expand Up @@ -252,11 +244,9 @@ public void testNamedCustomPolicy() {
assertNotNull(identity);
assertTrue(identity.isAnonymous());
assertNotNull(event.getEventProperties().get(RoutingContext.class.getName()));
assertEquals(2, observer.allEventsStorage.size());
assertAllEvents(2);
assertEquals(event, observer.allEventsStorage.get(1));
assertEquals(PathMatchingHttpSecurityPolicy.class.getName(), event.getAuthorizationContext());
Awaitility.await().atMost(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals(2, observer.asyncAllEventsStorage.size()));
}

@Test
Expand All @@ -279,9 +269,13 @@ public void testGlobalCustomPolicy() {
assertTrue(identity.isAnonymous());
assertNotNull(event.getEventProperties().get(RoutingContext.class.getName()));
assertTrue(event.getAuthorizationContext().contains("GlobalCustomHttpSecurityPolicy"));
assertAllEvents(2);
}

private void assertAllEvents(int expectedCount) {
assertEquals(expectedCount, observer.allEventsStorage.size());
Awaitility.await().atMost(Duration.ofSeconds(2))
.untilAsserted(() -> assertEquals(2, observer.asyncAllEventsStorage.size()));
assertEquals(2, observer.allEventsStorage.size());
.untilAsserted(() -> assertEquals(expectedCount, observer.asyncAllEventsStorage.size()));
}

@Singleton
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

import java.io.File;
import java.net.URL;
import java.security.Permission;
import java.util.function.Consumer;
import java.util.function.Function;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
Expand All @@ -12,19 +15,30 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.security.StringPermission;
import io.quarkus.security.identity.AuthenticationRequestContext;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.SecurityIdentityAugmentor;
import io.quarkus.security.runtime.QuarkusSecurityIdentity;
import io.quarkus.security.test.utils.TestIdentityController;
import io.quarkus.security.test.utils.TestIdentityProvider;
import io.quarkus.test.QuarkusUnitTest;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.vertx.http.runtime.security.HttpSecurityUtils;
import io.quarkus.vertx.http.runtime.security.QuarkusHttpUser;
import io.restassured.RestAssured;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;

public class MtlsRequestBasicAuthTest {

@TestHTTPResource(value = "/mtls", ssl = true)
URL url;

@TestHTTPResource(value = "/mtls-augmentor", ssl = true)
URL augmentorUrl;

@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
Expand Down Expand Up @@ -65,14 +79,71 @@ public void testNoClientCertBasicAuth() {
.get(url).then().statusCode(200).body(is("admin"));
}

@Test
public void testSecurityIdentityAugmentor() {
RestAssured.given()
.keyStore(new File("src/test/resources/conf/mtls/client-keystore.jks"), "password")
.trustStore(new File("src/test/resources/conf/mtls/client-truststore.jks"), "password")
.get(augmentorUrl).then().statusCode(401);
RestAssured.given()
.header("add-perm", "true")
.keyStore(new File("src/test/resources/conf/mtls/client-keystore.jks"), "password")
.trustStore(new File("src/test/resources/conf/mtls/client-truststore.jks"), "password")
.get(augmentorUrl).then().statusCode(200);
}

@ApplicationScoped
static class MyBean {

public void register(@Observes Router router) {
router.get("/mtls").handler(rc -> {
rc.response().end(QuarkusHttpUser.class.cast(rc.user()).getSecurityIdentity().getPrincipal().getName());
});
router.get("/mtls-augmentor").handler(rc -> {
if (rc.user() instanceof QuarkusHttpUser quarkusHttpUser) {
quarkusHttpUser.getSecurityIdentity().checkPermission(new StringPermission("use-mTLS"))
.subscribe().with(new Consumer<Boolean>() {
@Override
public void accept(Boolean accessGranted) {
if (accessGranted) {
rc.end();
} else {
rc.fail(401);
}
}
});
} else {
rc.fail(500);
}
});
}

}

@ApplicationScoped
static class CustomSecurityIdentityAugmentor implements SecurityIdentityAugmentor {

@Override
public Uni<SecurityIdentity> augment(SecurityIdentity securityIdentity,
AuthenticationRequestContext authenticationRequestContext) {
if (!securityIdentity.isAnonymous()
&& "CN=client,OU=cert,O=quarkus,L=city,ST=state,C=AU".equals(securityIdentity.getPrincipal().getName())) {
return Uni.createFrom().item(QuarkusSecurityIdentity.builder(securityIdentity)
.addPermissionChecker(new Function<Permission, Uni<Boolean>>() {
@Override
public Uni<Boolean> apply(Permission required) {
RoutingContext event = HttpSecurityUtils.getRoutingContextAttribute();
final boolean pass;
if (event != null) {
pass = Boolean.parseBoolean(event.request().headers().get("add-perm"));
} else {
pass = false;
}
return Uni.createFrom().item(pass);
}
}).build());
}
return Uni.createFrom().item(securityIdentity);
}
}
}
Loading
Loading