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 a config option to limit request body size #276

Merged
merged 11 commits into from
Sep 17, 2024
2 changes: 2 additions & 0 deletions polaris-server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,5 @@ logging:
archivedLogFilenamePattern: ./logs/polaris-%d.log.gz
# The maximum number of log files to archive.
archivedFileCount: 14

maxDocumentBytes: 0 # Don't set a limit
Copy link
Contributor

Choose a reason for hiding this comment

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

  1. This comment would ideally not be inline
  2. Do we really want to call this maxDocumentBytes? What is a "Document" in the context of a Polaris instance?
  3. Whatever we call it, we might put a small comment explaining what this is

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Renamed to maxRequestBodyBytes and updated/moved the comment.

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

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
Expand Down Expand Up @@ -104,6 +105,7 @@
import org.apache.polaris.service.task.TableCleanupTaskHandler;
import org.apache.polaris.service.task.TaskExecutorImpl;
import org.apache.polaris.service.task.TaskFileIOSupplier;
import org.apache.polaris.service.throttling.StreamReadConstraintsExceptionMapper;
import org.apache.polaris.service.tracing.OpenTelemetryAware;
import org.apache.polaris.service.tracing.TracingFilter;
import org.eclipse.jetty.servlets.CrossOriginFilter;
Expand Down Expand Up @@ -273,6 +275,17 @@ public void run(PolarisApplicationConfig configuration, Environment environment)
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setPropertyNamingStrategy(new PropertyNamingStrategies.KebabCaseStrategy());

long maxDocumentBytes = configuration.getMaxDocumentBytes();
if (maxDocumentBytes > 0) {
objectMapper
.getFactory()
.setStreamReadConstraints(
StreamReadConstraints.builder().maxDocumentLength(maxDocumentBytes).build());
LOGGER.info("Limiting document size to {} bytes", maxDocumentBytes);
}

environment.jersey().register(new StreamReadConstraintsExceptionMapper());
RESTSerializers.registerAll(objectMapper);
Serializers.registerSerializers(objectMapper);
environment.jersey().register(new IcebergJsonProcessingExceptionMapper());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public class PolarisApplicationConfig extends Configuration {
private String awsAccessKey;
private String awsSecretKey;
private FileIOFactory fileIOFactory;
private long maxDocumentBytes;

@JsonProperty("metaStoreManager")
public void setMetaStoreManagerFactory(MetaStoreManagerFactory metaStoreManagerFactory) {
Expand Down Expand Up @@ -146,6 +147,15 @@ public void setFeatureConfiguration(Map<String, Object> featureConfiguration) {
this.configurationStore = new DefaultConfigurationStore(featureConfiguration);
}

@JsonProperty("maxDocumentBytes")
public void setMaxDocumentBytes(long maxDocumentBytes) {
this.maxDocumentBytes = maxDocumentBytes;
}

public long getMaxDocumentBytes() {
return maxDocumentBytes;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

I think it should have a default value.

Copy link
Contributor

Choose a reason for hiding this comment

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

Checking a bit more about class StreamReadConstraints. -1 is the right default value, which means no limit.

        public Builder maxDocumentLength(long maxDocLen) {
            if (maxDocLen <= 0L) {
                maxDocLen = -1L;
            }

            this.maxDocLen = maxDocLen;
            return this;
        }

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you for pulling this up, this actually makes me more strongly interested in 0. Please see my new comment below.

Copy link
Contributor

Choose a reason for hiding this comment

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

I also find 0-as-unlimited a little confusing. I agree that if we make the default -1 it might imply that 0 is different from -1, but I also think a default of 0 is going to raise some questions.

Maybe we should just disallow 0, since StreamReadConstraints doesn't support what 0 would intuitively mean ("reject all requests")

Copy link
Contributor

Choose a reason for hiding this comment

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

From the code from StreamReadConstraints, that means both 0 and -1 are considered no limits. But I think it does make sense to have -1 for unlimited and disallow 0.

Copy link
Contributor Author

@andrew4699 andrew4699 Sep 12, 2024

Choose a reason for hiding this comment

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

Ok I updated it to default to -1, explained what -1 is, and restricted 0 with an exception/useful comment. I agree that -1 is a better indicator of "no limit" and restricting 0 solves some ambiguity.


public PolarisConfigurationStore getConfigurationStore() {
return configurationStore;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* 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.throttling;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
* Response object for errors caused by DoS-prevention throttling mechanisms, such as request size
* limits
*/
public class RequestThrottlingErrorResponse {
andrew4699 marked this conversation as resolved.
Show resolved Hide resolved
public enum Error {
Copy link
Member

Choose a reason for hiding this comment

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

Error is a name from java.lang - can you choose something different here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated

REQUEST_TOO_LARGE,
;
}

private final Error error;

@JsonCreator
public RequestThrottlingErrorResponse(@JsonProperty("error") Error error) {
this.error = error;
}

public Error getError() {
return error;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* 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.throttling;

import com.fasterxml.jackson.core.exc.StreamConstraintsException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;

/**
* Handles exceptions during the request that are a result of stream constraints such as the request
* being too large
*/
public class StreamReadConstraintsExceptionMapper
andrew4699 marked this conversation as resolved.
Show resolved Hide resolved
implements ExceptionMapper<StreamConstraintsException> {

@Override
public Response toResponse(StreamConstraintsException exception) {
return Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(
new RequestThrottlingErrorResponse(
RequestThrottlingErrorResponse.Error.REQUEST_TOO_LARGE))
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
import org.apache.polaris.service.config.PolarisApplicationConfig;
import org.apache.polaris.service.test.PolarisConnectionExtension;
import org.apache.polaris.service.test.SnowmanCredentialsExtension;
import org.apache.polaris.service.throttling.RequestThrottlingErrorResponse;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.AfterAll;
Expand Down Expand Up @@ -636,4 +637,28 @@ public void testWarehouseNotSpecified() throws IOException {
.hasMessage("Malformed request: Please specify a warehouse");
}
}

@Test
public void testRequestTooLarge() {
// The size is set to be higher than the limit in polaris-server-integrationtest.yml
Entity<PrincipalRole> largeRequest = Entity.json(new PrincipalRole("r".repeat(1000001)));

try (Response response =
EXT.client()
.target(
String.format(
"http://localhost:%d/api/management/v1/principal-roles", EXT.getLocalPort()))
.request("application/json")
.header("Authorization", "Bearer " + userToken)
.header(REALM_PROPERTY_KEY, realm)
.post(largeRequest)) {
assertThat(response)
.returns(Response.Status.BAD_REQUEST.getStatusCode(), Response::getStatus)
.matches(
r ->
r.readEntity(RequestThrottlingErrorResponse.class)
.getError()
.equals(RequestThrottlingErrorResponse.Error.REQUEST_TOO_LARGE));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,5 @@ logging:
archivedLogFilenamePattern: ./logs/iceberg-rest-%d.log.gz
# The maximum number of log files to archive.
archivedFileCount: 14

maxDocumentBytes: 1000000