You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@polaris.apache.org by ad...@apache.org on 2026/09/23 08:39:40 UTC

(polaris) branch main updated: Answer 400 for a query parameter that is not a number (#5572)

This is an automated email from the ASF dual-hosted git repository.

adutra pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/polaris.git


The following commit(s) were added to refs/heads/main by this push:
     new a919f11e51 Answer 400 for a query parameter that is not a number (#5572)
a919f11e51 is described below

commit a919f11e51ff76b5ef56633d8cb0429ff2b4c100
Author: EJ Wang <ej...@gmail.com>
AuthorDate: Wed Sep 23 01:39:34 2026 -0700

    Answer 400 for a query parameter that is not a number (#5572)
    
    A query parameter declared as a number is converted before the resource method
    runs, and JAX-RS turns a failed conversion into 404 Not Found. On a list route
    that status reads as a missing catalog or namespace, which sends the caller
    looking for the wrong problem. A ParamConverterProvider for Integer and Long now
    raises BadRequestException, which the exception mappers render as 400 with the
    usual error body, naming the parameter that was rejected. pageSize is the only
    numeric query parameter Polaris declares: it is accepted by listNamespaces,
    listTables and listViews on the Iceberg catalog API, by listPolicies and
    getApplicablePolicies on the policy API, and by listGenericTables. Readable
    values, absent values and every other parameter type keep their current
    behaviour.
---
 CHANGELOG.md                                       |   3 +
 .../http/NumericParamConverterProvider.java        | 109 ++++++++++++++
 .../http/NumericParamConverterProviderTest.java    | 148 +++++++++++++++++++
 .../service/http/NumericQueryParameterTest.java    | 158 +++++++++++++++++++++
 4 files changed, 418 insertions(+)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc17218795..fb7d9864e3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -142,6 +142,9 @@ request adding CHANGELOG notes for breaking (!) changes and possibly other secti
 
 ### Fixes
 
+- A list request whose `pageSize` is not a number now returns `400 Bad Request` naming the
+  parameter, instead of `404 Not Found`. The status is now the same on every API that accepts
+  `pageSize`.
 - Policy API: detaching a policy from a target it was never attached to now returns
   `404 Not Found` with error type `NoSuchMappingException`, as the policy API specification
   requires, instead of `500 Internal Server Error`.
diff --git a/runtime/service/src/main/java/org/apache/polaris/service/http/NumericParamConverterProvider.java b/runtime/service/src/main/java/org/apache/polaris/service/http/NumericParamConverterProvider.java
new file mode 100644
index 0000000000..931c8a4dcd
--- /dev/null
+++ b/runtime/service/src/main/java/org/apache/polaris/service/http/NumericParamConverterProvider.java
@@ -0,0 +1,109 @@
+/*
+ * 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.http;
+
+import jakarta.ws.rs.BadRequestException;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.ext.ParamConverter;
+import jakarta.ws.rs.ext.ParamConverterProvider;
+import jakarta.ws.rs.ext.Provider;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.function.Function;
+
+/**
+ * Converts {@code Integer} and {@code Long} request parameters so that a value which is not a
+ * number is answered with {@code 400 Bad Request}.
+ *
+ * <p>Jakarta RESTful Web Services 4.0, section 3.2, requires that an exception thrown while
+ * converting a parameter value be wrapped in a {@code NotFoundException} (404) when the parameter
+ * is a {@code @QueryParam}, {@code @PathParam} or {@code @MatrixParam}, and in a {@code
+ * BadRequestException} (400) when it is a {@code @HeaderParam} or {@code @CookieParam}. The
+ * runtime's own numeric converter raises {@link NumberFormatException}, so an unreadable query
+ * parameter becomes a 404. On a listing route that status reads as "this catalog or namespace does
+ * not exist", which sends the caller looking for the wrong problem.
+ *
+ * <p>The same sentence exempts a {@code WebApplicationException} from that wrapping and passes it
+ * through as thrown. {@link BadRequestException} is one, which is why throwing it here reaches the
+ * client as a 400 while a {@link NumberFormatException} cannot, whatever status the exception
+ * mappers would otherwise give an {@code IllegalArgumentException}.
+ *
+ * <p>Only the boxed types are handled. No resource declares a primitive numeric parameter, so those
+ * are left to the runtime.
+ */
+@Provider
+public class NumericParamConverterProvider implements ParamConverterProvider {
+
+  @Override
+  @SuppressWarnings("unchecked")
+  public <T> ParamConverter<T> getConverter(
+      Class<T> rawType, Type genericType, Annotation[] annotations) {
+    if (rawType == Integer.class) {
+      return (ParamConverter<T>) new NumericConverter<>(Integer::valueOf, nameOf(annotations));
+    }
+    if (rawType == Long.class) {
+      return (ParamConverter<T>) new NumericConverter<>(Long::valueOf, nameOf(annotations));
+    }
+    return null;
+  }
+
+  /**
+   * The name the caller used for this parameter, so the message can say which one was rejected, or
+   * null when the parameter is not bound from the query string.
+   */
+  private static String nameOf(Annotation[] annotations) {
+    for (Annotation annotation : annotations) {
+      if (annotation instanceof QueryParam queryParam) {
+        return queryParam.value();
+      }
+    }
+    return null;
+  }
+
+  private static final class NumericConverter<T extends Number> implements ParamConverter<T> {
+
+    private final Function<String, T> parser;
+    private final String parameterName;
+
+    private NumericConverter(Function<String, T> parser, String parameterName) {
+      this.parser = parser;
+      this.parameterName = parameterName;
+    }
+
+    @Override
+    public T fromString(String value) {
+      // A parameter the caller did not send, or sent empty, stays absent: presence is not this
+      // converter's decision.
+      if (value == null) {
+        return null;
+      }
+      try {
+        return parser.apply(value);
+      } catch (NumberFormatException e) {
+        throw new BadRequestException(
+            (parameterName == null ? "The parameter" : parameterName) + " must be an integer");
+      }
+    }
+
+    @Override
+    public String toString(T value) {
+      return String.valueOf(value);
+    }
+  }
+}
diff --git a/runtime/service/src/test/java/org/apache/polaris/service/http/NumericParamConverterProviderTest.java b/runtime/service/src/test/java/org/apache/polaris/service/http/NumericParamConverterProviderTest.java
new file mode 100644
index 0000000000..3f22634845
--- /dev/null
+++ b/runtime/service/src/test/java/org/apache/polaris/service/http/NumericParamConverterProviderTest.java
@@ -0,0 +1,148 @@
+/*
+ * 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.http;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import jakarta.ws.rs.BadRequestException;
+import jakarta.ws.rs.HeaderParam;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.ext.ParamConverter;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.UUID;
+import org.junit.jupiter.api.Test;
+
+public class NumericParamConverterProviderTest {
+
+  private final NumericParamConverterProvider provider = new NumericParamConverterProvider();
+
+  /** Source of real parameter annotations, read by reflection rather than mocked. */
+  @SuppressWarnings("unused")
+  private void annotatedParameters(
+      @QueryParam("pageSize") Integer pageSize,
+      @QueryParam("limit") Long limit,
+      @HeaderParam("X-Count") Integer headerCount,
+      Integer unannotated) {}
+
+  private static Annotation[] annotationsOf(int index) {
+    for (Method method : NumericParamConverterProviderTest.class.getDeclaredMethods()) {
+      if (method.getName().equals("annotatedParameters")) {
+        return method.getParameterAnnotations()[index];
+      }
+    }
+    throw new AssertionError("annotatedParameters not found");
+  }
+
+  private static final Annotation[] PAGE_SIZE = annotationsOf(0);
+  private static final Annotation[] LIMIT = annotationsOf(1);
+  private static final Annotation[] HEADER = annotationsOf(2);
+  private static final Annotation[] NONE = annotationsOf(3);
+
+  @Test
+  public void testConverterIsOfferedForTheBoxedNumericTypes() {
+    assertThat(provider.getConverter(Integer.class, Integer.class, PAGE_SIZE)).isNotNull();
+    assertThat(provider.getConverter(Long.class, Long.class, LIMIT)).isNotNull();
+  }
+
+  @Test
+  public void testConverterIsNotOfferedForOtherTypes() {
+    assertThat(provider.getConverter(String.class, String.class, PAGE_SIZE)).isNull();
+    assertThat(provider.getConverter(Boolean.class, Boolean.class, PAGE_SIZE)).isNull();
+    assertThat(provider.getConverter(UUID.class, UUID.class, PAGE_SIZE)).isNull();
+  }
+
+  @Test
+  public void testConverterIsNotOfferedForThePrimitiveNumericTypes() {
+    // No resource declares one, so the runtime keeps them.
+    assertThat(provider.getConverter(int.class, int.class, PAGE_SIZE)).isNull();
+    assertThat(provider.getConverter(long.class, long.class, LIMIT)).isNull();
+  }
+
+  @Test
+  public void testAReadableValueIsConverted() {
+    assertThat(provider.getConverter(Integer.class, Integer.class, PAGE_SIZE).fromString("5"))
+        .isEqualTo(5);
+    assertThat(provider.getConverter(Integer.class, Integer.class, PAGE_SIZE).fromString("-3"))
+        .isEqualTo(-3);
+    assertThat(provider.getConverter(Long.class, Long.class, LIMIT).fromString("9000000000"))
+        .isEqualTo(9000000000L);
+  }
+
+  @Test
+  public void testAnAbsentValueStaysAbsent() {
+    assertThat(provider.getConverter(Integer.class, Integer.class, PAGE_SIZE).fromString(null))
+        .isNull();
+    assertThat(provider.getConverter(Long.class, Long.class, LIMIT).fromString(null)).isNull();
+  }
+
+  @Test
+  public void testAnUnreadableValueIsRejectedByName() {
+    assertThatThrownBy(
+            () ->
+                provider.getConverter(Integer.class, Integer.class, PAGE_SIZE).fromString("large"))
+        .isInstanceOf(BadRequestException.class)
+        .hasMessage("pageSize must be an integer");
+    assertThatThrownBy(
+            () -> provider.getConverter(Long.class, Long.class, LIMIT).fromString("plenty"))
+        .isInstanceOf(BadRequestException.class)
+        .hasMessage("limit must be an integer");
+  }
+
+  @Test
+  public void testAnEmptyValueWouldBeRejectedByName() {
+    // The runtime binds an empty query value as null, so this case does not arise from the query
+    // string; it is here so the converter's own contract is complete.
+    assertThatThrownBy(
+            () -> provider.getConverter(Integer.class, Integer.class, PAGE_SIZE).fromString(""))
+        .isInstanceOf(BadRequestException.class)
+        .hasMessage("pageSize must be an integer");
+  }
+
+  @Test
+  public void testAnUnreadableValueWithoutAQueryParamNameIsRejectedGenerically() {
+    assertThatThrownBy(
+            () -> provider.getConverter(Integer.class, Integer.class, HEADER).fromString("large"))
+        .isInstanceOf(BadRequestException.class)
+        .hasMessage("The parameter must be an integer");
+    assertThatThrownBy(
+            () -> provider.getConverter(Integer.class, Integer.class, NONE).fromString("large"))
+        .isInstanceOf(BadRequestException.class)
+        .hasMessage("The parameter must be an integer");
+  }
+
+  @Test
+  public void testTheRejectionCarriesBadRequest() {
+    ParamConverter<Integer> converter =
+        provider.getConverter(Integer.class, Integer.class, PAGE_SIZE);
+    assertThatThrownBy(() -> converter.fromString("large"))
+        .asInstanceOf(
+            org.assertj.core.api.InstanceOfAssertFactories.type(BadRequestException.class))
+        .extracting(e -> e.getResponse().getStatus())
+        .isEqualTo(400);
+  }
+
+  @Test
+  public void testToStringRoundTripsTheValue() {
+    assertThat(provider.getConverter(Integer.class, Integer.class, PAGE_SIZE).toString(7))
+        .isEqualTo("7");
+    assertThat(provider.getConverter(Long.class, Long.class, LIMIT).toString(7L)).isEqualTo("7");
+  }
+}
diff --git a/runtime/service/src/test/java/org/apache/polaris/service/http/NumericQueryParameterTest.java b/runtime/service/src/test/java/org/apache/polaris/service/http/NumericQueryParameterTest.java
new file mode 100644
index 0000000000..f5890acff4
--- /dev/null
+++ b/runtime/service/src/test/java/org/apache/polaris/service/http/NumericQueryParameterTest.java
@@ -0,0 +1,158 @@
+/*
+ * 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.http;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.CoreMatchers.is;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Checks over the wire that an unreadable {@code pageSize} is answered with {@code 400 Bad Request}
+ * on every route that accepts it, and that the answers which were already correct did not move.
+ *
+ * <p>The catalog in these requests does not exist, and it does not need to: a query parameter is
+ * converted before the resource method runs, so the rejection happens whether or not the rest of
+ * the path resolves. The requests without {@code pageSize} show what the same path answers
+ * otherwise, which is how these tests tell a rejected parameter apart from a missing catalog.
+ */
+@QuarkusTest
+public class NumericQueryParameterTest {
+
+  private static final String CATALOG = "nonexistent_catalog";
+  private static final String ICEBERG = "/api/catalog/v1/" + CATALOG;
+  private static final String POLARIS = "/api/catalog/polaris/v1/" + CATALOG;
+
+  private static String token;
+
+  private static RequestSpecification authenticated() {
+    if (token == null) {
+      token =
+          given()
+              .contentType(ContentType.URLENC)
+              .formParam("grant_type", "client_credentials")
+              .formParam("scope", "PRINCIPAL_ROLE:ALL")
+              .formParam("client_id", "test-admin")
+              .formParam("client_secret", "test-secret")
+              .when()
+              .post("/api/catalog/v1/oauth/tokens")
+              .then()
+              .statusCode(200)
+              .extract()
+              .path("access_token");
+    }
+    return given().header("Authorization", "Bearer " + token);
+  }
+
+  private static void expectPageSizeRejected(String path) {
+    authenticated()
+        .when()
+        .get(path)
+        .then()
+        .statusCode(400)
+        .body("error.message", is("pageSize must be an integer"))
+        .body("error.type", is("BadRequestException"))
+        .body("error.code", is(400));
+  }
+
+  private static void expectNamespaceNotFound(String path) {
+    authenticated()
+        .when()
+        .get(path)
+        .then()
+        .statusCode(404)
+        .body("error.message", is("Namespace does not exist: ''"))
+        .body("error.type", is("NoSuchNamespaceException"))
+        .body("error.code", is(404));
+  }
+
+  @Test
+  public void testListNamespacesRejectsAnUnreadablePageSize() {
+    expectPageSizeRejected(ICEBERG + "/namespaces?pageSize=large");
+  }
+
+  @Test
+  public void testListTablesRejectsAnUnreadablePageSize() {
+    expectPageSizeRejected(ICEBERG + "/namespaces/ns/tables?pageSize=large");
+  }
+
+  @Test
+  public void testListViewsRejectsAnUnreadablePageSize() {
+    expectPageSizeRejected(ICEBERG + "/namespaces/ns/views?pageSize=large");
+  }
+
+  @Test
+  public void testListPoliciesRejectsAnUnreadablePageSize() {
+    expectPageSizeRejected(POLARIS + "/namespaces/ns/policies?pageSize=large");
+  }
+
+  @Test
+  public void testGetApplicablePoliciesRejectsAnUnreadablePageSize() {
+    expectPageSizeRejected(POLARIS + "/applicable-policies?pageSize=large");
+  }
+
+  @Test
+  public void testListGenericTablesRejectsAnUnreadablePageSize() {
+    expectPageSizeRejected(POLARIS + "/namespaces/ns/generic-tables?pageSize=large");
+  }
+
+  @Test
+  public void testAMissingCatalogIsStillNotFound() {
+    expectNamespaceNotFound(ICEBERG + "/namespaces");
+  }
+
+  @Test
+  public void testAReadablePageSizeStillReachesTheResource() {
+    expectNamespaceNotFound(ICEBERG + "/namespaces?pageSize=5");
+  }
+
+  @Test
+  public void testAnEmptyPageSizeStillReachesTheResource() {
+    // An empty value binds as if the parameter had not been sent. The converter is not consulted.
+    expectNamespaceNotFound(ICEBERG + "/namespaces?pageSize=");
+  }
+
+  @Test
+  public void testAnUnknownRouteIsStillNotFound() {
+    authenticated()
+        .when()
+        .get(ICEBERG + "/no-such-subresource")
+        .then()
+        .statusCode(404)
+        .body("error.message", is("Unable to find matching target resource method"))
+        .body("error.type", is("NotFoundException"))
+        .body("error.code", is(404));
+  }
+
+  @Test
+  public void testAPageSizeBelowTheMinimumIsStillRejectedByValidation() {
+    // The converter reads 0 successfully and hands it on. The minimum declared on this route is
+    // what refuses it, so this pins that path and the converter cannot quietly take it over.
+    authenticated()
+        .when()
+        .get(POLARIS + "/namespaces/ns/policies?pageSize=0")
+        .then()
+        .statusCode(400)
+        .body("error.type", is("ResteasyReactiveViolationException"))
+        .body("error.code", is(400));
+  }
+}