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
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.annotation.JacksonRequestConverterFunction;
import com.linecorp.armeria.server.annotation.JacksonResponseConverterFunction;
import com.linecorp.armeria.server.annotation.RequestConverterFunction;
import com.linecorp.armeria.server.docs.DocService;
import io.unitycatalog.server.auth.AllowingAuthorizer;
import io.unitycatalog.server.auth.JCasbinAuthorizer;
import io.unitycatalog.server.auth.UnityCatalogAuthorizer;
import io.unitycatalog.server.auth.decorator.AuthorizationGateConverter;
import io.unitycatalog.server.auth.decorator.UnityAccessDecorator;
import io.unitycatalog.server.auth.decorator.UnityAccessUtil;
import io.unitycatalog.server.exception.BaseException;
Expand Down Expand Up @@ -203,8 +205,8 @@ private void addApiServices(
TemporaryPathCredentialsService temporaryPathCredentialsService =
new TemporaryPathCredentialsService(storageCredentialVendor);

JacksonRequestConverterFunction requestConverterFunction =
new JacksonRequestConverterFunction(
RequestConverterFunction requestConverterFunction =
gatedJackson(
JsonMapper.builder()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build());
Expand Down Expand Up @@ -270,6 +272,17 @@ private void addApiServices(
armeriaServerBuilder, authorizer, repositories, serverProperties, storageCredentialVendor);
}

/**
* Wraps a Jackson body converter with {@link AuthorizationGateConverter}. Every annotated
* service's request converter must go through this so the PAYLOAD-source auth check fires before
* body binding. Using a wrapper (rather than registering the gate as a separate chain element per
* {@code annotatedService(...)} call) makes the gate impossible to forget when a new service is
* added.
*/
private static RequestConverterFunction gatedJackson(ObjectMapper mapper) {
return new AuthorizationGateConverter(new JacksonRequestConverterFunction(mapper));
}

private void addIcebergApiServices(
ServerBuilder armeriaServerBuilder,
ServerProperties serverProperties,
Expand All @@ -282,8 +295,7 @@ private void addIcebergApiServices(

// Add support for Iceberg REST APIs
ObjectMapper icebergMapper = IcebergObjectMapper.mapper();
JacksonRequestConverterFunction icebergRequestConverter =
new JacksonRequestConverterFunction(icebergMapper);
RequestConverterFunction icebergRequestConverter = gatedJackson(icebergMapper);
JacksonResponseConverterFunction icebergResponseConverter =
new JacksonResponseConverterFunction(icebergMapper);
MetadataService metadataService =
Expand Down Expand Up @@ -312,7 +324,7 @@ private void addDeltaApiServices(
armeriaServerBuilder.annotatedService(
BASE_PATH,
deltaApiService,
new JacksonRequestConverterFunction(deltaMapper),
gatedJackson(deltaMapper),
new JacksonResponseConverterFunction(deltaMapper));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package io.unitycatalog.server.auth.decorator;

import com.linecorp.armeria.common.AggregatedHttpRequest;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.annotation.RequestConverterFunction;
import io.unitycatalog.server.exception.BaseException;
import io.unitycatalog.server.exception.ErrorCode;
import java.lang.reflect.ParameterizedType;
import java.util.Objects;

/**
* Fail-closed wrapper that enforces {@link UnityAccessDecorator}'s PAYLOAD-source authorization
* before delegating to an inner body converter (e.g. Jackson). The decorator sets {@link
* UnityAccessDecorator#AUTH_PENDING} on entry to the PAYLOAD path and clears it only after the
* authorization evaluation succeeds; if the flag is still {@code true} when a parameter is being
* bound, {@code peekData}'s callback never fired (no body, non-JSON content-type, malformed JSON,
* trailing whitespace) and the request must be denied.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

if the flag is still {@code true} when a parameter is being

  • bound, {@code peekData}'s callback never fired (no body, non-JSON content-type, malformed JSON,
  • trailing whitespace) and the request must be denied.

https://github.com/unitycatalog/unitycatalog/pull/1494/changes#diff-b9504c8a386aa1943559c357fa7ce1fcc952f4e0f45df99b89b17807213699faR42-R45
In that case, we actually are throwing the PERMISSION_DENIED exception, which actually swallow the real malformed detailed. will that make it even worst to the developer to understand the response ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is not the perfect error message throwing out.
The priority here is security: making sure it fails with PERMISSION_DENIED instead of going through.

In a follow up PR I will deal with this malformed/incomplete body problem and get rid of the processPeekData entirely.

*
* <p>Wrapping Jackson (rather than sitting in front of it as a separate chain element) means
* services register a single converter and the gate is impossible to forget when a new annotated
* service is added.
*
* <p>Scope: gates only parameters bound via the converter chain. Endpoints with no body-bound
* parameter (pure {@code @Param}/path) don't trigger this converter, but those endpoints also don't
* use PAYLOAD locators, so the decorator never sets the flag and no gate is needed.
*/
public final class AuthorizationGateConverter implements RequestConverterFunction {

private final RequestConverterFunction delegate;

public AuthorizationGateConverter(RequestConverterFunction delegate) {
this.delegate = Objects.requireNonNull(delegate);
}

@Override
public Object convertRequest(
ServiceRequestContext ctx,
AggregatedHttpRequest request,
Class<?> expectedResultType,
ParameterizedType expectedParameterizedResultType)
throws Exception {
if (Boolean.TRUE.equals(ctx.attr(UnityAccessDecorator.AUTH_PENDING))) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

when will we set this UnityAccessDecorator.AUTH_PENDING attr in the context ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

throw new BaseException(
ErrorCode.PERMISSION_DENIED, "Authorization could not be verified for this request");
}
return delegate.convertRequest(
ctx, request, expectedResultType, expectedParameterizedResultType);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,28 @@
* <p>3. {@code @AuthorizeKey} - Works like {@code @AuthorizeResourceKey} for source selection, but
* for non-resource request values (operation mode, table type, flag, etc.) exposed directly as a
* SpEL variable instead of being mapped to a resource identifier.
*
* <p>For PAYLOAD-source locators (body-read), {@code peekData} only observes complete JSON chunks;
* anything else (no body, non-JSON content-type, malformed JSON, trailing whitespace) silently
* skips the authorization evaluation. The {@link #AUTH_PENDING} flag and {@link
* AuthorizationGateConverter} close that gap: the decorator marks the request auth-pending on
* entry to the PAYLOAD path, clears it only after authorization succeeds, and the gate converter
* denies any body-binding where the flag is still set.
*/
public class UnityAccessDecorator implements DecoratingHttpServiceFunction {

private static final Logger LOGGER = LoggerFactory.getLogger(UnityAccessDecorator.class);
private static final ObjectMapper MAPPER = new ObjectMapper();

/**
* Per-request flag: {@code true} once the decorator enters the PAYLOAD path, flipped to
* {@code false} when the authorization evaluation completes inside the peekData callback. Read by
* {@link AuthorizationGateConverter} at body-binding time: if still {@code true}, authorization
* never ran (no body chunk arrived, content-type wasn't JSON, or JSON didn't complete) and the
* request must be denied.
*/
public static final AttributeKey<Boolean> AUTH_PENDING =
AttributeKey.valueOf(UnityAccessDecorator.class, "AUTH_PENDING");
private final KeyMapper keyMapper;
private final UserRepository userRepository;

Expand Down Expand Up @@ -177,15 +194,22 @@ private HttpResponse authorizeByRequest(
resourceKeys,
nonResourceValues);

// Note that peekData only gets called for requests that actually have data (like PUT&POST)
// peekData's lambda only fires when a body chunk arrives AND processPeekData returns true
// (JSON content-type + chunk ending in '}'). Any other path (no body, non-JSON, malformed
// JSON, trailing whitespace) silently skips authorization. Mark the request auth-pending
// here and clear it only after the authorization evaluation runs; AuthorizationGateConverter
// denies any body-binding attempt where this flag is still set.
ctx.setAttr(AUTH_PENDING, true);

req = req.peekData(data -> {
// This code block is not called immediately. It is called later as part of delegate.serve()
LOGGER.debug("Authorization peekData invoked.");

peekDataHandler.processPeekData(data);
Map<SecurableType, UUID> resourceIds = mapResourceKeys(resourceKeys, nonResourceValues);
evaluateAction.beforeRequest(principal, expression, resourceIds, nonResourceValues);
if (peekDataHandler.processPeekData(data)) {
Map<SecurableType, UUID> resourceIds = mapResourceKeys(resourceKeys, nonResourceValues);
evaluateAction.beforeRequest(principal, expression, resourceIds, nonResourceValues);
ctx.setAttr(AUTH_PENDING, false);
}
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.unitycatalog.server.sdk.access;

import static io.unitycatalog.server.utils.TestUtils.assertHttpApiException;
import static io.unitycatalog.server.utils.TestUtils.assertPermissionDenied;
import static org.assertj.core.api.Assertions.assertThat;

Expand All @@ -12,6 +13,7 @@
import io.unitycatalog.client.model.SecurableType;
import io.unitycatalog.client.model.UpdateCatalog;
import io.unitycatalog.server.base.ServerConfig;
import io.unitycatalog.server.exception.ErrorCode;
import io.unitycatalog.server.persist.model.Privileges;
import io.unitycatalog.server.utils.TestUtils;
import java.util.List;
Expand Down Expand Up @@ -197,4 +199,19 @@ public void testCatalogAccess() {
.storageRoot("file:///tmp/external_location/ext_table");
assertPermissionDenied(() -> principal1CatalogsApi.createCatalog(catalogWithLoc2));
}

/**
* POST /catalogs has a PAYLOAD-source authorization locator (@AuthorizeResourceKey on the
* CreateCatalog body). A body-less request never triggers UnityAccessDecorator's peekData
* callback, so checkAuthorization is silently skipped. AuthorizationGateConverter catches this at
* body-binding time and denies the request before the handler sees it.
*/
@Test
@SneakyThrows
public void bodylessPostDeniedByAuthorizationGate() {
assertHttpApiException(
TestUtils.sendRawEmptyPost(adminConfig, "/api/2.1/unity-catalog/catalogs"),
ErrorCode.PERMISSION_DENIED,
"Authorization could not be verified for this request");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
import io.unitycatalog.server.base.ServerConfig;
import io.unitycatalog.server.exception.ErrorCode;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -128,4 +131,34 @@ public static void assertPermissionDenied(Executable executable, String contains
public static void assertPermissionDenied(Executable executable) {
assertPermissionDenied(executable, "PERMISSION_DENIED");
}

/**
* Raw-HTTP counterpart to {@link #assertApiException}. Use when the generated SDK can't reach the
* failure mode (e.g. the SDK always serializes a body, so you can't exercise body-less
* authorization paths with it).
*/
public static void assertHttpApiException(
HttpResponse<String> response, ErrorCode errorCode, String containsMessage) {
// Check the body first. When tests fail due to mismatching error, the body can tell us more.
assertThat(response.body()).contains(containsMessage).contains(errorCode.name());
assertThat(response.statusCode()).isEqualTo(errorCode.getHttpStatus().code());
}

/**
* Sends a body-less POST to the given path. The SDK always attaches a serialized body, so raw
* HTTP is the only way to reach the body-less code path (used to exercise {@link
* io.unitycatalog.server.auth.decorator.AuthorizationGateConverter}'s silent-skip denial).
*/
public static HttpResponse<String> sendRawEmptyPost(ServerConfig config, String path)
throws Exception {
HttpRequest.Builder reqBuilder =
HttpRequest.newBuilder()
.uri(URI.create(config.getServerUrl() + path))
.POST(HttpRequest.BodyPublishers.noBody());
if (config.getAuthToken() != null && !config.getAuthToken().isEmpty()) {
reqBuilder.header("Authorization", "Bearer " + config.getAuthToken());
}
return HttpClient.newHttpClient()
.send(reqBuilder.build(), HttpResponse.BodyHandlers.ofString());
}
}
Loading