Skip to content
Merged
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
2 changes: 2 additions & 0 deletions quarkus/defaults/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ quarkus.config.mapping.validate-unknown=true

quarkus.http.access-log.enabled=true
# quarkus.http.access-log.pattern=common
# Cannot use proactive authentication since Polaris requires CDI request context for authentication
quarkus.http.auth.proactive=false
quarkus.http.body.handle-file-uploads=false
quarkus.http.limits.max-body-size=10240K

Expand Down
1 change: 1 addition & 0 deletions quarkus/service/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ dependencies {
implementation("io.quarkus:quarkus-micrometer")
implementation("io.quarkus:quarkus-micrometer-registry-prometheus")
implementation("io.quarkus:quarkus-opentelemetry")
implementation("io.quarkus:quarkus-security")
implementation("io.quarkus:quarkus-smallrye-context-propagation")

implementation(libs.jakarta.enterprise.cdi.api)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.polaris.service.quarkus.auth;

import io.quarkus.security.AuthenticationFailedException;
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.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Set;
import org.apache.polaris.core.auth.AuthenticatedPolarisPrincipal;
import org.apache.polaris.service.auth.ActiveRolesProvider;

/**
* A custom {@link SecurityIdentityAugmentor} that adds active roles to the {@link
* SecurityIdentity}. This is used to augment the identity with active roles after authentication.
*/
@ApplicationScoped
public class ActiveRolesAugmentor implements SecurityIdentityAugmentor {

@Inject ActiveRolesProvider activeRolesProvider;

@Override
public Uni<SecurityIdentity> augment(
SecurityIdentity identity, AuthenticationRequestContext context) {
if (identity.isAnonymous()) {
return Uni.createFrom().item(identity);
}
return context.runBlocking(() -> augmentWithActiveRoles(identity));
}

private SecurityIdentity augmentWithActiveRoles(SecurityIdentity identity) {
AuthenticatedPolarisPrincipal polarisPrincipal =
identity.getPrincipal(AuthenticatedPolarisPrincipal.class);
if (polarisPrincipal == null) {
throw new AuthenticationFailedException("No Polaris principal found");
}
Set<String> validRoleNames = activeRolesProvider.getActiveRoles(polarisPrincipal);
return QuarkusSecurityIdentity.builder()
.setAnonymous(false)
.setPrincipal(polarisPrincipal)
.addRoles(validRoleNames)
.addCredentials(identity.getCredentials())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: do we really need these credentials in Polaris? Just trying to avoid exposing unnecessary information :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't but in principle the idea is to augment the identity, not to decrease it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess, I commented on the wrong line 😅 but I believe there's another place in our code where we produce these credentials fro the HTTP request.

.addAttributes(identity.getAttributes())
.addPermissionChecker(identity::checkPermission)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.polaris.service.quarkus.auth;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.quarkus.security.credential.TokenCredential;
import io.quarkus.security.identity.IdentityProviderManager;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.AuthenticationRequest;
import io.quarkus.security.identity.request.TokenAuthenticationRequest;
import io.quarkus.vertx.http.runtime.security.ChallengeData;
import io.quarkus.vertx.http.runtime.security.HttpAuthenticationMechanism;
import io.quarkus.vertx.http.runtime.security.HttpCredentialTransport;
import io.quarkus.vertx.http.runtime.security.HttpSecurityUtils;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.Collections;
import java.util.Set;

/** A custom {@link HttpAuthenticationMechanism} that handles Polaris token authentication. */
@ApplicationScoped
public class PolarisAuthenticationMechanism implements HttpAuthenticationMechanism {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be under quarkus/server perhaps (and the other new auth classes)?

It might be preferable to isolate service code and auth code. Plus, downsteam projects may want to adjust how authentication is down, and adding auth-related beans to the services jar may complicate reuse 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would cause all tests to fail, since there would be no authentication mechanism present in polaris-quarkus-service.

I understand the problem, and indeed I think we should isolate authentication in a dedicated module, but I'd argue that this can be done later. After all, authentication was already being done in polaris-quarkus-service, this PR doesn't change this fact.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 to refactoring in a follow-up PR


private static final String BEARER = "Bearer";

@Override
public Uni<SecurityIdentity> authenticate(
RoutingContext context, IdentityProviderManager identityProviderManager) {

String authHeader = context.request().getHeader("Authorization");
if (authHeader == null) {
return Uni.createFrom().nullItem();
}

int spaceIdx = authHeader.indexOf(' ');
if (spaceIdx <= 0 || !authHeader.substring(0, spaceIdx).equalsIgnoreCase(BEARER)) {
return Uni.createFrom().nullItem();
}

String credential = authHeader.substring(spaceIdx + 1);
return identityProviderManager.authenticate(
HttpSecurityUtils.setRoutingContextAttribute(
new TokenAuthenticationRequest(new PolarisTokenCredential(credential)), context));
}

@Override
public Uni<ChallengeData> getChallenge(RoutingContext context) {
ChallengeData result =
new ChallengeData(
HttpResponseStatus.UNAUTHORIZED.code(), HttpHeaderNames.WWW_AUTHENTICATE, BEARER);
return Uni.createFrom().item(result);
}

@Override
public Set<Class<? extends AuthenticationRequest>> getCredentialTypes() {
return Collections.singleton(TokenAuthenticationRequest.class);
}

@Override
public Uni<HttpCredentialTransport> getCredentialTransport(RoutingContext context) {
return Uni.createFrom()
.item(new HttpCredentialTransport(HttpCredentialTransport.Type.AUTHORIZATION, BEARER));
}

static class PolarisTokenCredential extends TokenCredential {
PolarisTokenCredential(String credential) {
super(credential, "bearer");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.polaris.service.quarkus.auth;

import io.quarkus.security.AuthenticationFailedException;
import io.quarkus.security.identity.AuthenticationRequestContext;
import io.quarkus.security.identity.IdentityProvider;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.TokenAuthenticationRequest;
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;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.NotAuthorizedException;
import org.apache.polaris.core.auth.AuthenticatedPolarisPrincipal;
import org.apache.polaris.service.auth.Authenticator;
import org.apache.polaris.service.quarkus.auth.PolarisAuthenticationMechanism.PolarisTokenCredential;

/** A custom {@link IdentityProvider} that handles Polaris token authentication requests. */
@ApplicationScoped
public class PolarisIdentityProvider implements IdentityProvider<TokenAuthenticationRequest> {

@Inject Authenticator<String, AuthenticatedPolarisPrincipal> authenticator;

@Override
public Class<TokenAuthenticationRequest> getRequestType() {
return TokenAuthenticationRequest.class;
}

@Override
public Uni<SecurityIdentity> authenticate(
TokenAuthenticationRequest request, AuthenticationRequestContext context) {
if (!(request.getToken() instanceof PolarisTokenCredential)) {
return Uni.createFrom().nullItem();
}
return context.runBlocking(() -> createSecurityIdentity(request, authenticator));
}

public SecurityIdentity createSecurityIdentity(
TokenAuthenticationRequest request,
Authenticator<String, AuthenticatedPolarisPrincipal> authenticator) {
try {
AuthenticatedPolarisPrincipal principal =
authenticator
.authenticate(request.getToken().getToken())
.orElseThrow(() -> new NotAuthorizedException("Authentication failed"));
QuarkusSecurityIdentity.Builder builder =
QuarkusSecurityIdentity.builder()
.setPrincipal(principal)
.addCredential(request.getToken())
.addRoles(principal.getActivatedPrincipalRoleNames())
.addAttribute(SecurityIdentity.USER_ATTRIBUTE, principal);
RoutingContext routingContext = HttpSecurityUtils.getRoutingContextAttribute(request);
if (routingContext != null) {
builder.addAttribute(RoutingContext.class.getName(), routingContext);
}
return builder.build();
} catch (RuntimeException e) {
throw new AuthenticationFailedException(e);
}
}
}
3 changes: 2 additions & 1 deletion server-templates/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ public class {{classname}} {
@{{httpMethod}}{{#subresourceOperation}}
@Path("{{{path}}}"){{/subresourceOperation}}{{#hasConsumes}}
@Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}}
@Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}}
@Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}}{{#hasAuthMethods}}
{{#authMethods}}{{#isOAuth}}@RolesAllowed("**"){{/isOAuth}}{{/authMethods}}{{/hasAuthMethods}}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RolesAllowed("**") LGTM, however, just want to mention that we could take full control of authentication and deny all requests in the auth Mechanism (if we wanted). That would complicate the mechanisms a bit, but would provide extra certainly that no holes are left in the API.

Copy link
Contributor Author

@adutra adutra Apr 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are imho different things.

You can return a failed Uni holding an unauthorized error from an auth mechanism, but that means no other auth mechanism will be attempted. This may not be desired in Polaris, because imho we are heading towards having many auth mechanisms, so even if mechanism A cannot authenticate, maybe mechanism B can.

@RolesAllowed("**") is a way to say: please authenticate the caller before invoking this endpoint. Since proactive auth is disabled, no authentication would happen without this annotation when the endpoint is invoked.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point.

@Timed("{{metricsPrefix}}.{{baseName}}.{{nickname}}")
public Response {{nickname}}({{#isMultipart}}MultipartFormDataInput input,{{/isMultipart}}{{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{^isMultipart}}{{>formParams}},{{/isMultipart}}{{#isMultipart}}{{^isFormParam}},{{/isFormParam}}{{/isMultipart}}{{/allParams}}@Context @MeterTag(key="realm_id",expression="realmIdentifier") RealmContext realmContext,@Context SecurityContext securityContext) {
{{! Don't log form or header params in case there are secrets, e.g., OAuth tokens }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.auth.AuthenticatedPolarisPrincipal;
import org.apache.polaris.core.context.CallContext;
import org.apache.polaris.core.context.RealmContext;
import org.apache.polaris.core.entity.PolarisEntity;
import org.apache.polaris.core.entity.PolarisEntityType;
import org.apache.polaris.core.entity.PrincipalRoleEntity;
Expand All @@ -51,7 +50,7 @@
public class DefaultActiveRolesProvider implements ActiveRolesProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultActiveRolesProvider.class);

@Inject RealmContext realmContext;
@Inject CallContext callContext;
@Inject MetaStoreManagerFactory metaStoreManagerFactory;

@Override
Expand All @@ -60,13 +59,13 @@ public Set<String> getActiveRoles(AuthenticatedPolarisPrincipal principal) {
loadActivePrincipalRoles(
principal.getActivatedPrincipalRoleNames(),
principal.getPrincipalEntity(),
metaStoreManagerFactory.getOrCreateMetaStoreManager(realmContext));
metaStoreManagerFactory.getOrCreateMetaStoreManager(callContext.getRealmContext()));
return activeRoles.stream().map(PrincipalRoleEntity::getName).collect(Collectors.toSet());
}

protected List<PrincipalRoleEntity> loadActivePrincipalRoles(
Set<String> tokenRoles, PolarisEntity principal, PolarisMetaStoreManager metaStoreManager) {
PolarisCallContext polarisContext = CallContext.getCurrentContext().getPolarisCallContext();
PolarisCallContext polarisContext = callContext.getPolarisCallContext();
LoadGrantsResult principalGrantResults =
metaStoreManager.loadGrantsToGrantee(polarisContext, principal);
polarisContext
Expand Down

This file was deleted.

Loading